repo
stringlengths 3
91
| file
stringlengths 16
152
| code
stringlengths 0
3.77M
| file_length
int64 0
3.77M
| avg_line_length
float64 0
16k
| max_line_length
int64 0
273k
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
SDR | SDR-master/DataReadout/ReadoutControls/lib/arcons_basic_gui.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'arcons_basic_gui.ui'
#
# Created: Tue Dec 11 17:40:34 2012
# by: PyQt4 UI code generator 4.8.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_arcons(object):
def setupUi(self, arcons):
arcons.setObjectName(_fromUtf8("arcons"))
arcons.setEnabled(True)
arcons.resize(860, 960)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(arcons.sizePolicy().hasHeightForWidth())
arcons.setSizePolicy(sizePolicy)
arcons.setMouseTracking(True)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(_fromUtf8("lib/Archon.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
arcons.setWindowIcon(icon)
arcons.setWindowFilePath(_fromUtf8(""))
arcons.setAnimated(True)
self.centralwidget = QtGui.QWidget(arcons)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.frame = QtGui.QFrame(self.centralwidget)
self.frame.setGeometry(QtCore.QRect(0, 0, 391, 151))
self.frame.setFrameShape(QtGui.QFrame.Box)
self.frame.setFrameShadow(QtGui.QFrame.Sunken)
self.frame.setObjectName(_fromUtf8("frame"))
self.label = QtGui.QLabel(self.frame)
self.label.setGeometry(QtCore.QRect(110, 10, 251, 21))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
font.setPointSize(18)
font.setWeight(75)
font.setBold(True)
self.label.setFont(font)
self.label.setObjectName(_fromUtf8("label"))
self.array_temp_lcd = QtGui.QLCDNumber(self.frame)
self.array_temp_lcd.setGeometry(QtCore.QRect(10, 40, 81, 41))
self.array_temp_lcd.setObjectName(_fromUtf8("array_temp_lcd"))
self.pulse_tube_temp_lcd = QtGui.QLCDNumber(self.frame)
self.pulse_tube_temp_lcd.setGeometry(QtCore.QRect(10, 90, 81, 41))
self.pulse_tube_temp_lcd.setObjectName(_fromUtf8("pulse_tube_temp_lcd"))
self.label_3 = QtGui.QLabel(self.frame)
self.label_3.setGeometry(QtCore.QRect(100, 50, 101, 21))
font = QtGui.QFont()
font.setPointSize(14)
self.label_3.setFont(font)
self.label_3.setObjectName(_fromUtf8("label_3"))
self.label_4 = QtGui.QLabel(self.frame)
self.label_4.setGeometry(QtCore.QRect(100, 90, 121, 41))
font = QtGui.QFont()
font.setPointSize(14)
self.label_4.setFont(font)
self.label_4.setObjectName(_fromUtf8("label_4"))
self.open_shutter_radioButton = QtGui.QRadioButton(self.frame)
self.open_shutter_radioButton.setEnabled(False)
self.open_shutter_radioButton.setGeometry(QtCore.QRect(240, 90, 141, 41))
font = QtGui.QFont()
font.setPointSize(14)
self.open_shutter_radioButton.setFont(font)
self.open_shutter_radioButton.setFocusPolicy(QtCore.Qt.NoFocus)
self.open_shutter_radioButton.setAutoExclusive(False)
self.open_shutter_radioButton.setObjectName(_fromUtf8("open_shutter_radioButton"))
self.cycle_fridge_radioButton = QtGui.QRadioButton(self.frame)
self.cycle_fridge_radioButton.setEnabled(False)
self.cycle_fridge_radioButton.setGeometry(QtCore.QRect(240, 40, 141, 41))
font = QtGui.QFont()
font.setPointSize(14)
self.cycle_fridge_radioButton.setFont(font)
self.cycle_fridge_radioButton.setFocusPolicy(QtCore.Qt.NoFocus)
self.cycle_fridge_radioButton.setAutoExclusive(False)
self.cycle_fridge_radioButton.setObjectName(_fromUtf8("cycle_fridge_radioButton"))
self.lineEdit = QtGui.QLineEdit(self.frame)
self.lineEdit.setGeometry(QtCore.QRect(80, 180, 113, 20))
self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
self.frame_2 = QtGui.QFrame(self.centralwidget)
self.frame_2.setGeometry(QtCore.QRect(390, 0, 471, 181))
self.frame_2.setFrameShape(QtGui.QFrame.Box)
self.frame_2.setFrameShadow(QtGui.QFrame.Sunken)
self.frame_2.setObjectName(_fromUtf8("frame_2"))
self.label_2 = QtGui.QLabel(self.frame_2)
self.label_2.setGeometry(QtCore.QRect(150, 0, 261, 41))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
font.setPointSize(18)
font.setWeight(75)
font.setBold(True)
self.label_2.setFont(font)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.compass_graphicsView = QtGui.QGraphicsView(self.frame_2)
self.compass_graphicsView.setGeometry(QtCore.QRect(70, 90, 81, 81))
self.compass_graphicsView.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.compass_graphicsView.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.compass_graphicsView.setInteractive(False)
self.compass_graphicsView.setObjectName(_fromUtf8("compass_graphicsView"))
self.label_5 = QtGui.QLabel(self.frame_2)
self.label_5.setGeometry(QtCore.QRect(10, 40, 31, 21))
font = QtGui.QFont()
font.setPointSize(10)
self.label_5.setFont(font)
self.label_5.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_5.setObjectName(_fromUtf8("label_5"))
self.label_6 = QtGui.QLabel(self.frame_2)
self.label_6.setGeometry(QtCore.QRect(10, 60, 31, 21))
font = QtGui.QFont()
font.setPointSize(10)
self.label_6.setFont(font)
self.label_6.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_6.setObjectName(_fromUtf8("label_6"))
self.label_7 = QtGui.QLabel(self.frame_2)
self.label_7.setGeometry(QtCore.QRect(170, 120, 111, 21))
font = QtGui.QFont()
font.setPointSize(10)
self.label_7.setFont(font)
self.label_7.setLayoutDirection(QtCore.Qt.RightToLeft)
self.label_7.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_7.setObjectName(_fromUtf8("label_7"))
self.label_8 = QtGui.QLabel(self.frame_2)
self.label_8.setGeometry(QtCore.QRect(180, 40, 101, 21))
font = QtGui.QFont()
font.setPointSize(10)
self.label_8.setFont(font)
self.label_8.setLayoutDirection(QtCore.Qt.RightToLeft)
self.label_8.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_8.setObjectName(_fromUtf8("label_8"))
self.label_9 = QtGui.QLabel(self.frame_2)
self.label_9.setGeometry(QtCore.QRect(180, 60, 101, 21))
font = QtGui.QFont()
font.setPointSize(10)
self.label_9.setFont(font)
self.label_9.setLayoutDirection(QtCore.Qt.RightToLeft)
self.label_9.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_9.setObjectName(_fromUtf8("label_9"))
self.label_10 = QtGui.QLabel(self.frame_2)
self.label_10.setGeometry(QtCore.QRect(150, 140, 131, 21))
font = QtGui.QFont()
font.setPointSize(10)
self.label_10.setFont(font)
self.label_10.setLayoutDirection(QtCore.Qt.RightToLeft)
self.label_10.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_10.setObjectName(_fromUtf8("label_10"))
self.label_11 = QtGui.QLabel(self.frame_2)
self.label_11.setGeometry(QtCore.QRect(150, 80, 131, 21))
font = QtGui.QFont()
font.setPointSize(10)
self.label_11.setFont(font)
self.label_11.setLayoutDirection(QtCore.Qt.RightToLeft)
self.label_11.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_11.setObjectName(_fromUtf8("label_11"))
self.label_12 = QtGui.QLabel(self.frame_2)
self.label_12.setGeometry(QtCore.QRect(170, 100, 111, 21))
font = QtGui.QFont()
font.setPointSize(10)
self.label_12.setFont(font)
self.label_12.setLayoutDirection(QtCore.Qt.RightToLeft)
self.label_12.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_12.setObjectName(_fromUtf8("label_12"))
self.status_label = QtGui.QLabel(self.frame_2)
self.status_label.setGeometry(QtCore.QRect(10, 10, 131, 21))
font = QtGui.QFont()
font.setPointSize(12)
self.status_label.setFont(font)
self.status_label.setFrameShape(QtGui.QFrame.Box)
self.status_label.setObjectName(_fromUtf8("status_label"))
self.local_time_label = QtGui.QLabel(self.frame_2)
self.local_time_label.setGeometry(QtCore.QRect(290, 140, 131, 21))
font = QtGui.QFont()
font.setPointSize(12)
self.local_time_label.setFont(font)
self.local_time_label.setFrameShape(QtGui.QFrame.Box)
self.local_time_label.setText(_fromUtf8(""))
self.local_time_label.setObjectName(_fromUtf8("local_time_label"))
self.utc_label = QtGui.QLabel(self.frame_2)
self.utc_label.setGeometry(QtCore.QRect(290, 120, 131, 21))
font = QtGui.QFont()
font.setPointSize(12)
self.utc_label.setFont(font)
self.utc_label.setFrameShape(QtGui.QFrame.Box)
self.utc_label.setText(_fromUtf8(""))
self.utc_label.setObjectName(_fromUtf8("utc_label"))
self.lst_label = QtGui.QLabel(self.frame_2)
self.lst_label.setGeometry(QtCore.QRect(290, 100, 131, 21))
font = QtGui.QFont()
font.setPointSize(12)
self.lst_label.setFont(font)
self.lst_label.setFrameShape(QtGui.QFrame.Box)
self.lst_label.setText(_fromUtf8(""))
self.lst_label.setObjectName(_fromUtf8("lst_label"))
self.airmass_label = QtGui.QLabel(self.frame_2)
self.airmass_label.setGeometry(QtCore.QRect(290, 80, 131, 21))
font = QtGui.QFont()
font.setPointSize(12)
self.airmass_label.setFont(font)
self.airmass_label.setFrameShape(QtGui.QFrame.Box)
self.airmass_label.setText(_fromUtf8(""))
self.airmass_label.setObjectName(_fromUtf8("airmass_label"))
self.az_label = QtGui.QLabel(self.frame_2)
self.az_label.setGeometry(QtCore.QRect(290, 60, 131, 21))
font = QtGui.QFont()
font.setPointSize(12)
self.az_label.setFont(font)
self.az_label.setFrameShape(QtGui.QFrame.Box)
self.az_label.setText(_fromUtf8(""))
self.az_label.setObjectName(_fromUtf8("az_label"))
self.alt_label = QtGui.QLabel(self.frame_2)
self.alt_label.setGeometry(QtCore.QRect(290, 40, 131, 21))
font = QtGui.QFont()
font.setPointSize(12)
self.alt_label.setFont(font)
self.alt_label.setFrameShape(QtGui.QFrame.Box)
self.alt_label.setText(_fromUtf8(""))
self.alt_label.setObjectName(_fromUtf8("alt_label"))
self.ra_label = QtGui.QLabel(self.frame_2)
self.ra_label.setGeometry(QtCore.QRect(50, 40, 121, 21))
font = QtGui.QFont()
font.setPointSize(12)
self.ra_label.setFont(font)
self.ra_label.setFrameShape(QtGui.QFrame.Box)
self.ra_label.setText(_fromUtf8(""))
self.ra_label.setObjectName(_fromUtf8("ra_label"))
self.dec_label = QtGui.QLabel(self.frame_2)
self.dec_label.setGeometry(QtCore.QRect(50, 60, 121, 21))
font = QtGui.QFont()
font.setPointSize(12)
self.dec_label.setFont(font)
self.dec_label.setFrameShape(QtGui.QFrame.Box)
self.dec_label.setText(_fromUtf8(""))
self.dec_label.setObjectName(_fromUtf8("dec_label"))
self.frame_3 = QtGui.QFrame(self.centralwidget)
self.frame_3.setGeometry(QtCore.QRect(0, 150, 391, 521))
self.frame_3.setFrameShape(QtGui.QFrame.Box)
self.frame_3.setFrameShadow(QtGui.QFrame.Sunken)
self.frame_3.setObjectName(_fromUtf8("frame_3"))
self.save_raw_checkBox = QtGui.QCheckBox(self.frame_3)
self.save_raw_checkBox.setEnabled(False)
self.save_raw_checkBox.setGeometry(QtCore.QRect(300, 70, 91, 21))
font = QtGui.QFont()
font.setPointSize(12)
self.save_raw_checkBox.setFont(font)
self.save_raw_checkBox.setObjectName(_fromUtf8("save_raw_checkBox"))
self.data_directory_lineEdit = QtGui.QLineEdit(self.frame_3)
self.data_directory_lineEdit.setGeometry(QtCore.QRect(110, 40, 201, 21))
self.data_directory_lineEdit.setObjectName(_fromUtf8("data_directory_lineEdit"))
self.label_14 = QtGui.QLabel(self.frame_3)
self.label_14.setGeometry(QtCore.QRect(10, 40, 91, 21))
font = QtGui.QFont()
font.setPointSize(12)
self.label_14.setFont(font)
self.label_14.setObjectName(_fromUtf8("label_14"))
self.label_16 = QtGui.QLabel(self.frame_3)
self.label_16.setGeometry(QtCore.QRect(20, 210, 91, 21))
font = QtGui.QFont()
font.setPointSize(10)
self.label_16.setFont(font)
self.label_16.setObjectName(_fromUtf8("label_16"))
self.label_13 = QtGui.QLabel(self.frame_3)
self.label_13.setGeometry(QtCore.QRect(120, 0, 241, 41))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
font.setPointSize(18)
font.setWeight(75)
font.setBold(True)
self.label_13.setFont(font)
self.label_13.setObjectName(_fromUtf8("label_13"))
self.label_15 = QtGui.QLabel(self.frame_3)
self.label_15.setGeometry(QtCore.QRect(20, 170, 111, 31))
font = QtGui.QFont()
font.setPointSize(10)
self.label_15.setFont(font)
self.label_15.setObjectName(_fromUtf8("label_15"))
self.calibrate_data_checkBox = QtGui.QCheckBox(self.frame_3)
self.calibrate_data_checkBox.setEnabled(False)
self.calibrate_data_checkBox.setGeometry(QtCore.QRect(280, 100, 121, 21))
font = QtGui.QFont()
font.setPointSize(12)
self.calibrate_data_checkBox.setFont(font)
self.calibrate_data_checkBox.setObjectName(_fromUtf8("calibrate_data_checkBox"))
self.stop_observation_pushButton = QtGui.QPushButton(self.frame_3)
self.stop_observation_pushButton.setGeometry(QtCore.QRect(200, 200, 181, 41))
font = QtGui.QFont()
font.setPointSize(10)
self.stop_observation_pushButton.setFont(font)
self.stop_observation_pushButton.setObjectName(_fromUtf8("stop_observation_pushButton"))
self.start_observation_pushButton = QtGui.QPushButton(self.frame_3)
self.start_observation_pushButton.setGeometry(QtCore.QRect(200, 140, 181, 51))
font = QtGui.QFont()
font.setPointSize(14)
self.start_observation_pushButton.setFont(font)
self.start_observation_pushButton.setObjectName(_fromUtf8("start_observation_pushButton"))
self.close_pushButton = QtGui.QPushButton(self.frame_3)
self.close_pushButton.setGeometry(QtCore.QRect(50, 460, 121, 41))
self.close_pushButton.setObjectName(_fromUtf8("close_pushButton"))
self.search_pushButton = QtGui.QPushButton(self.frame_3)
self.search_pushButton.setGeometry(QtCore.QRect(320, 40, 61, 21))
self.search_pushButton.setObjectName(_fromUtf8("search_pushButton"))
self.obs_time_spinBox = QtGui.QSpinBox(self.frame_3)
self.obs_time_spinBox.setGeometry(QtCore.QRect(120, 170, 71, 31))
font = QtGui.QFont()
font.setPointSize(12)
self.obs_time_spinBox.setFont(font)
self.obs_time_spinBox.setMaximum(99999)
self.obs_time_spinBox.setProperty(_fromUtf8("value"), 30)
self.obs_time_spinBox.setObjectName(_fromUtf8("obs_time_spinBox"))
self.remaining_time_lcdNumber = QtGui.QLCDNumber(self.frame_3)
self.remaining_time_lcdNumber.setGeometry(QtCore.QRect(120, 210, 61, 21))
self.remaining_time_lcdNumber.setObjectName(_fromUtf8("remaining_time_lcdNumber"))
self.frequency_tuneup_pushButton = QtGui.QPushButton(self.frame_3)
self.frequency_tuneup_pushButton.setEnabled(False)
self.frequency_tuneup_pushButton.setGeometry(QtCore.QRect(50, 400, 121, 51))
self.frequency_tuneup_pushButton.setObjectName(_fromUtf8("frequency_tuneup_pushButton"))
self.file_name_lineEdit = QtGui.QLineEdit(self.frame_3)
self.file_name_lineEdit.setEnabled(False)
self.file_name_lineEdit.setGeometry(QtCore.QRect(82, 70, 211, 22))
self.file_name_lineEdit.setText(_fromUtf8(""))
self.file_name_lineEdit.setObjectName(_fromUtf8("file_name_lineEdit"))
self.target_lineEdit = QtGui.QLineEdit(self.frame_3)
self.target_lineEdit.setGeometry(QtCore.QRect(100, 100, 171, 22))
self.target_lineEdit.setObjectName(_fromUtf8("target_lineEdit"))
self.label_20 = QtGui.QLabel(self.frame_3)
self.label_20.setGeometry(QtCore.QRect(10, 70, 91, 20))
font = QtGui.QFont()
font.setPointSize(12)
self.label_20.setFont(font)
self.label_20.setObjectName(_fromUtf8("label_20"))
self.label_21 = QtGui.QLabel(self.frame_3)
self.label_21.setGeometry(QtCore.QRect(10, 100, 91, 17))
font = QtGui.QFont()
font.setPointSize(12)
self.label_21.setFont(font)
self.label_21.setObjectName(_fromUtf8("label_21"))
self.frame_6 = QtGui.QFrame(self.frame_3)
self.frame_6.setGeometry(QtCore.QRect(210, 390, 141, 111))
self.frame_6.setFrameShape(QtGui.QFrame.StyledPanel)
self.frame_6.setFrameShadow(QtGui.QFrame.Raised)
self.frame_6.setObjectName(_fromUtf8("frame_6"))
self.subtract_sky_radioButton = QtGui.QRadioButton(self.frame_6)
self.subtract_sky_radioButton.setGeometry(QtCore.QRect(20, 0, 111, 31))
font = QtGui.QFont()
font.setPointSize(12)
self.subtract_sky_radioButton.setFont(font)
self.subtract_sky_radioButton.setChecked(False)
self.subtract_sky_radioButton.setAutoExclusive(False)
self.subtract_sky_radioButton.setObjectName(_fromUtf8("subtract_sky_radioButton"))
self.flat_field_radioButton = QtGui.QRadioButton(self.frame_6)
self.flat_field_radioButton.setEnabled(True)
self.flat_field_radioButton.setGeometry(QtCore.QRect(20, 20, 111, 31))
font = QtGui.QFont()
font.setPointSize(12)
self.flat_field_radioButton.setFont(font)
self.flat_field_radioButton.setCheckable(True)
self.flat_field_radioButton.setChecked(False)
self.flat_field_radioButton.setAutoExclusive(False)
self.flat_field_radioButton.setObjectName(_fromUtf8("flat_field_radioButton"))
self.int_time_spinBox = QtGui.QSpinBox(self.frame_6)
self.int_time_spinBox.setGeometry(QtCore.QRect(10, 50, 51, 22))
self.int_time_spinBox.setMaximum(9999)
self.int_time_spinBox.setProperty(_fromUtf8("value"), 1)
self.int_time_spinBox.setObjectName(_fromUtf8("int_time_spinBox"))
self.label_19 = QtGui.QLabel(self.frame_6)
self.label_19.setGeometry(QtCore.QRect(60, 50, 81, 21))
font = QtGui.QFont()
font.setPointSize(10)
self.label_19.setFont(font)
self.label_19.setObjectName(_fromUtf8("label_19"))
self.options_radioButton = QtGui.QRadioButton(self.frame_6)
self.options_radioButton.setGeometry(QtCore.QRect(10, 80, 131, 21))
font = QtGui.QFont()
font.setPointSize(9)
self.options_radioButton.setFont(font)
self.options_radioButton.setObjectName(_fromUtf8("options_radioButton"))
self.textEdit = QtGui.QTextEdit(self.frame_3)
self.textEdit.setGeometry(QtCore.QRect(10, 260, 371, 101))
self.textEdit.setObjectName(_fromUtf8("textEdit"))
self.label_27 = QtGui.QLabel(self.frame_3)
self.label_27.setGeometry(QtCore.QRect(10, 240, 151, 17))
self.label_27.setObjectName(_fromUtf8("label_27"))
self.update_description = QtGui.QPushButton(self.frame_3)
self.update_description.setGeometry(QtCore.QRect(10, 360, 141, 31))
self.update_description.setObjectName(_fromUtf8("update_description"))
self.continuous = QtGui.QCheckBox(self.frame_3)
self.continuous.setGeometry(QtCore.QRect(20, 130, 181, 41))
self.continuous.setObjectName(_fromUtf8("continuous"))
self.frame_4 = QtGui.QFrame(self.centralwidget)
self.frame_4.setGeometry(QtCore.QRect(390, 180, 471, 491))
self.frame_4.setFrameShape(QtGui.QFrame.Box)
self.frame_4.setFrameShadow(QtGui.QFrame.Sunken)
self.frame_4.setObjectName(_fromUtf8("frame_4"))
self.tv_image = QtGui.QGraphicsView(self.frame_4)
self.tv_image.setGeometry(QtCore.QRect(10, 10, 444, 464))
self.tv_image.setMouseTracking(True)
self.tv_image.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.tv_image.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.tv_image.setAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignTop)
self.tv_image.setObjectName(_fromUtf8("tv_image"))
self.frame_5 = QtGui.QFrame(self.centralwidget)
self.frame_5.setGeometry(QtCore.QRect(0, 670, 861, 231))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.frame_5.sizePolicy().hasHeightForWidth())
self.frame_5.setSizePolicy(sizePolicy)
self.frame_5.setFrameShape(QtGui.QFrame.Box)
self.frame_5.setFrameShadow(QtGui.QFrame.Sunken)
self.frame_5.setObjectName(_fromUtf8("frame_5"))
self.spectra_plot = MPL_Widget(self.frame_5)
self.spectra_plot.setGeometry(QtCore.QRect(250, 0, 491, 241))
self.spectra_plot.setObjectName(_fromUtf8("spectra_plot"))
self.pixel_number_label = QtGui.QLabel(self.frame_5)
self.pixel_number_label.setGeometry(QtCore.QRect(40, 50, 131, 31))
self.pixel_number_label.setFrameShape(QtGui.QFrame.NoFrame)
self.pixel_number_label.setAlignment(QtCore.Qt.AlignCenter)
self.pixel_number_label.setObjectName(_fromUtf8("pixel_number_label"))
self.pixelpath = QtGui.QLabel(self.frame_5)
self.pixelpath.setGeometry(QtCore.QRect(40, 90, 141, 31))
font = QtGui.QFont()
font.setPointSize(14)
self.pixelpath.setFont(font)
self.pixelpath.setFrameShape(QtGui.QFrame.Box)
self.pixelpath.setText(_fromUtf8(""))
self.pixelpath.setObjectName(_fromUtf8("pixelpath"))
self.row = QtGui.QLabel(self.frame_5)
self.row.setGeometry(QtCore.QRect(40, 150, 61, 31))
self.row.setFrameShape(QtGui.QFrame.Box)
self.row.setText(_fromUtf8(""))
self.row.setObjectName(_fromUtf8("row"))
self.label_32 = QtGui.QLabel(self.frame_5)
self.label_32.setGeometry(QtCore.QRect(40, 130, 61, 16))
self.label_32.setObjectName(_fromUtf8("label_32"))
self.col = QtGui.QLabel(self.frame_5)
self.col.setGeometry(QtCore.QRect(130, 150, 61, 31))
self.col.setFrameShape(QtGui.QFrame.Box)
self.col.setText(_fromUtf8(""))
self.col.setObjectName(_fromUtf8("col"))
self.label_34 = QtGui.QLabel(self.frame_5)
self.label_34.setGeometry(QtCore.QRect(130, 130, 61, 16))
self.label_34.setObjectName(_fromUtf8("label_34"))
self.groupBox = QtGui.QGroupBox(self.centralwidget)
self.groupBox.setGeometry(QtCore.QRect(870, 10, 171, 191))
self.groupBox.setObjectName(_fromUtf8("groupBox"))
self.drag_select_radioButton = QtGui.QRadioButton(self.groupBox)
self.drag_select_radioButton.setGeometry(QtCore.QRect(10, 30, 141, 31))
self.drag_select_radioButton.setAutoExclusive(False)
self.drag_select_radioButton.setObjectName(_fromUtf8("drag_select_radioButton"))
self.mode_buttonGroup = QtGui.QButtonGroup(arcons)
self.mode_buttonGroup.setObjectName(_fromUtf8("mode_buttonGroup"))
self.mode_buttonGroup.addButton(self.drag_select_radioButton)
self.rect_select_radioButton = QtGui.QRadioButton(self.groupBox)
self.rect_select_radioButton.setGeometry(QtCore.QRect(10, 70, 161, 21))
self.rect_select_radioButton.setChecked(True)
self.rect_select_radioButton.setAutoExclusive(False)
self.rect_select_radioButton.setObjectName(_fromUtf8("rect_select_radioButton"))
self.mode_buttonGroup.addButton(self.rect_select_radioButton)
self.rect_x_spinBox = QtGui.QSpinBox(self.groupBox)
self.rect_x_spinBox.setGeometry(QtCore.QRect(30, 90, 57, 31))
self.rect_x_spinBox.setMinimum(1)
self.rect_x_spinBox.setMaximum(32)
self.rect_x_spinBox.setProperty(_fromUtf8("value"), 1)
self.rect_x_spinBox.setObjectName(_fromUtf8("rect_x_spinBox"))
self.rect_y_spinBox = QtGui.QSpinBox(self.groupBox)
self.rect_y_spinBox.setGeometry(QtCore.QRect(110, 90, 57, 31))
self.rect_y_spinBox.setMinimum(1)
self.rect_y_spinBox.setMaximum(32)
self.rect_y_spinBox.setProperty(_fromUtf8("value"), 1)
self.rect_y_spinBox.setObjectName(_fromUtf8("rect_y_spinBox"))
self.label_23 = QtGui.QLabel(self.groupBox)
self.label_23.setGeometry(QtCore.QRect(20, 90, 16, 31))
self.label_23.setObjectName(_fromUtf8("label_23"))
self.label_24 = QtGui.QLabel(self.groupBox)
self.label_24.setGeometry(QtCore.QRect(100, 90, 16, 31))
self.label_24.setObjectName(_fromUtf8("label_24"))
self.circ_select_radioButton = QtGui.QRadioButton(self.groupBox)
self.circ_select_radioButton.setGeometry(QtCore.QRect(10, 130, 151, 21))
self.circ_select_radioButton.setAutoExclusive(False)
self.circ_select_radioButton.setObjectName(_fromUtf8("circ_select_radioButton"))
self.mode_buttonGroup.addButton(self.circ_select_radioButton)
self.circ_r_spinBox = QtGui.QSpinBox(self.groupBox)
self.circ_r_spinBox.setGeometry(QtCore.QRect(40, 150, 57, 31))
self.circ_r_spinBox.setMinimum(0)
self.circ_r_spinBox.setMaximum(16)
self.circ_r_spinBox.setProperty(_fromUtf8("value"), 0)
self.circ_r_spinBox.setObjectName(_fromUtf8("circ_r_spinBox"))
self.label_25 = QtGui.QLabel(self.groupBox)
self.label_25.setGeometry(QtCore.QRect(30, 150, 16, 31))
self.label_25.setObjectName(_fromUtf8("label_25"))
self.choose_beamimage = QtGui.QPushButton(self.centralwidget)
self.choose_beamimage.setGeometry(QtCore.QRect(1050, 770, 171, 41))
self.choose_beamimage.setObjectName(_fromUtf8("choose_beamimage"))
self.choose_bindir = QtGui.QPushButton(self.centralwidget)
self.choose_bindir.setGeometry(QtCore.QRect(1050, 740, 171, 41))
self.choose_bindir.setObjectName(_fromUtf8("choose_bindir"))
self.brightpix = QtGui.QSpinBox(self.centralwidget)
self.brightpix.setGeometry(QtCore.QRect(880, 250, 57, 25))
self.brightpix.setMaximum(2024)
self.brightpix.setProperty(_fromUtf8("value"), 50)
self.brightpix.setObjectName(_fromUtf8("brightpix"))
self.label_22 = QtGui.QLabel(self.centralwidget)
self.label_22.setGeometry(QtCore.QRect(940, 250, 121, 21))
self.label_22.setObjectName(_fromUtf8("label_22"))
self.takesky = QtGui.QPushButton(self.centralwidget)
self.takesky.setGeometry(QtCore.QRect(1050, 700, 171, 51))
self.takesky.setObjectName(_fromUtf8("takesky"))
self.frame_7 = QtGui.QFrame(self.centralwidget)
self.frame_7.setGeometry(QtCore.QRect(860, 390, 181, 511))
self.frame_7.setFrameShape(QtGui.QFrame.Box)
self.frame_7.setFrameShadow(QtGui.QFrame.Sunken)
self.frame_7.setObjectName(_fromUtf8("frame_7"))
self.label_36 = QtGui.QLabel(self.frame_7)
self.label_36.setGeometry(QtCore.QRect(30, 10, 141, 41))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
font.setPointSize(18)
font.setWeight(75)
font.setBold(True)
self.label_36.setFont(font)
self.label_36.setObjectName(_fromUtf8("label_36"))
self.cal_time = QtGui.QSpinBox(self.frame_7)
self.cal_time.setGeometry(QtCore.QRect(20, 180, 57, 25))
self.cal_time.setMaximum(10000)
self.cal_time.setObjectName(_fromUtf8("cal_time"))
self.cal_angle = QtGui.QDoubleSpinBox(self.frame_7)
self.cal_angle.setGeometry(QtCore.QRect(90, 180, 62, 25))
self.cal_angle.setMaximum(360.0)
self.cal_angle.setObjectName(_fromUtf8("cal_angle"))
self.goto_angle = QtGui.QDoubleSpinBox(self.frame_7)
self.goto_angle.setGeometry(QtCore.QRect(90, 240, 62, 25))
self.goto_angle.setObjectName(_fromUtf8("goto_angle"))
self.label_37 = QtGui.QLabel(self.frame_7)
self.label_37.setGeometry(QtCore.QRect(90, 220, 62, 17))
self.label_37.setObjectName(_fromUtf8("label_37"))
self.label_38 = QtGui.QLabel(self.frame_7)
self.label_38.setGeometry(QtCore.QRect(20, 160, 51, 21))
font = QtGui.QFont()
font.setPointSize(10)
self.label_38.setFont(font)
self.label_38.setObjectName(_fromUtf8("label_38"))
self.label_39 = QtGui.QLabel(self.frame_7)
self.label_39.setGeometry(QtCore.QRect(90, 160, 61, 21))
font = QtGui.QFont()
font.setPointSize(10)
self.label_39.setFont(font)
self.label_39.setObjectName(_fromUtf8("label_39"))
self.do_cal_button = QtGui.QPushButton(self.frame_7)
self.do_cal_button.setGeometry(QtCore.QRect(10, 120, 151, 41))
self.do_cal_button.setObjectName(_fromUtf8("do_cal_button"))
self.go_home_button = QtGui.QPushButton(self.frame_7)
self.go_home_button.setGeometry(QtCore.QRect(10, 61, 151, 41))
self.go_home_button.setObjectName(_fromUtf8("go_home_button"))
self.goto_button = QtGui.QPushButton(self.frame_7)
self.goto_button.setGeometry(QtCore.QRect(10, 220, 71, 51))
self.goto_button.setObjectName(_fromUtf8("goto_button"))
self.label_40 = QtGui.QLabel(self.frame_7)
self.label_40.setGeometry(QtCore.QRect(20, 310, 151, 41))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
font.setPointSize(18)
font.setWeight(75)
font.setBold(True)
self.label_40.setFont(font)
self.label_40.setObjectName(_fromUtf8("label_40"))
self.laser_toggle = QtGui.QCheckBox(self.frame_7)
self.laser_toggle.setGeometry(QtCore.QRect(20, 270, 111, 41))
self.laser_toggle.setObjectName(_fromUtf8("laser_toggle"))
self.laser_label = QtGui.QLabel(self.frame_7)
self.laser_label.setGeometry(QtCore.QRect(120, 270, 51, 41))
self.laser_label.setObjectName(_fromUtf8("laser_label"))
self.filter1 = QtGui.QRadioButton(self.frame_7)
self.filter1.setGeometry(QtCore.QRect(20, 350, 102, 21))
self.filter1.setAutoExclusive(False)
self.filter1.setObjectName(_fromUtf8("filter1"))
self.filter_buttonGroup = QtGui.QButtonGroup(arcons)
self.filter_buttonGroup.setObjectName(_fromUtf8("filter_buttonGroup"))
self.filter_buttonGroup.addButton(self.filter1)
self.filter2 = QtGui.QRadioButton(self.frame_7)
self.filter2.setGeometry(QtCore.QRect(20, 370, 102, 21))
self.filter2.setAutoExclusive(False)
self.filter2.setObjectName(_fromUtf8("filter2"))
self.filter_buttonGroup.addButton(self.filter2)
self.filter3 = QtGui.QRadioButton(self.frame_7)
self.filter3.setGeometry(QtCore.QRect(20, 390, 102, 21))
self.filter3.setAutoExclusive(False)
self.filter3.setObjectName(_fromUtf8("filter3"))
self.filter_buttonGroup.addButton(self.filter3)
self.filter4 = QtGui.QRadioButton(self.frame_7)
self.filter4.setGeometry(QtCore.QRect(20, 410, 102, 21))
self.filter4.setAutoExclusive(False)
self.filter4.setObjectName(_fromUtf8("filter4"))
self.filter_buttonGroup.addButton(self.filter4)
self.filter5 = QtGui.QRadioButton(self.frame_7)
self.filter5.setGeometry(QtCore.QRect(20, 430, 102, 21))
self.filter5.setAutoExclusive(False)
self.filter5.setObjectName(_fromUtf8("filter5"))
self.filter_buttonGroup.addButton(self.filter5)
self.filter6 = QtGui.QRadioButton(self.frame_7)
self.filter6.setGeometry(QtCore.QRect(20, 450, 102, 21))
self.filter6.setChecked(True)
self.filter6.setAutoExclusive(False)
self.filter6.setObjectName(_fromUtf8("filter6"))
self.filter_buttonGroup.addButton(self.filter6)
self.label_26 = QtGui.QLabel(self.centralwidget)
self.label_26.setGeometry(QtCore.QRect(1060, 810, 101, 17))
self.label_26.setObjectName(_fromUtf8("label_26"))
self.label_17 = QtGui.QLabel(self.centralwidget)
self.label_17.setGeometry(QtCore.QRect(1060, 830, 46, 13))
self.label_17.setObjectName(_fromUtf8("label_17"))
self.label_18 = QtGui.QLabel(self.centralwidget)
self.label_18.setGeometry(QtCore.QRect(1060, 863, 46, 20))
self.label_18.setObjectName(_fromUtf8("label_18"))
self.RA_lineEdit = QtGui.QLineEdit(self.centralwidget)
self.RA_lineEdit.setEnabled(False)
self.RA_lineEdit.setGeometry(QtCore.QRect(1060, 840, 113, 20))
self.RA_lineEdit.setObjectName(_fromUtf8("RA_lineEdit"))
self.Dec_lineEdit = QtGui.QLineEdit(self.centralwidget)
self.Dec_lineEdit.setEnabled(False)
self.Dec_lineEdit.setGeometry(QtCore.QRect(1060, 880, 113, 20))
self.Dec_lineEdit.setObjectName(_fromUtf8("Dec_lineEdit"))
self.label_41 = QtGui.QLabel(self.centralwidget)
self.label_41.setGeometry(QtCore.QRect(900, 210, 141, 41))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
font.setPointSize(18)
font.setWeight(75)
font.setBold(True)
self.label_41.setFont(font)
self.label_41.setObjectName(_fromUtf8("label_41"))
self.vmin = QtGui.QSpinBox(self.centralwidget)
self.vmin.setGeometry(QtCore.QRect(886, 350, 61, 25))
self.vmin.setMaximum(1000000)
self.vmin.setProperty(_fromUtf8("value"), 100)
self.vmin.setObjectName(_fromUtf8("vmin"))
self.vmax = QtGui.QSpinBox(self.centralwidget)
self.vmax.setGeometry(QtCore.QRect(960, 350, 57, 25))
self.vmax.setMaximum(1000000)
self.vmax.setProperty(_fromUtf8("value"), 1500)
self.vmax.setObjectName(_fromUtf8("vmax"))
self.label_28 = QtGui.QLabel(self.centralwidget)
self.label_28.setGeometry(QtCore.QRect(940, 280, 62, 17))
self.label_28.setObjectName(_fromUtf8("label_28"))
self.contrast_mode = QtGui.QCheckBox(self.centralwidget)
self.contrast_mode.setGeometry(QtCore.QRect(880, 300, 161, 31))
self.contrast_mode.setObjectName(_fromUtf8("contrast_mode"))
self.label_29 = QtGui.QLabel(self.centralwidget)
self.label_29.setGeometry(QtCore.QRect(890, 330, 62, 17))
font = QtGui.QFont()
font.setPointSize(12)
self.label_29.setFont(font)
self.label_29.setObjectName(_fromUtf8("label_29"))
self.label_30 = QtGui.QLabel(self.centralwidget)
self.label_30.setGeometry(QtCore.QRect(960, 330, 62, 17))
font = QtGui.QFont()
font.setPointSize(11)
self.label_30.setFont(font)
self.label_30.setObjectName(_fromUtf8("label_30"))
arcons.setCentralWidget(self.centralwidget)
self.statusbar = QtGui.QStatusBar(arcons)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
arcons.setStatusBar(self.statusbar)
self.menubar = QtGui.QMenuBar(arcons)
self.menubar.setGeometry(QtCore.QRect(0, 0, 860, 22))
self.menubar.setObjectName(_fromUtf8("menubar"))
arcons.setMenuBar(self.menubar)
self.retranslateUi(arcons)
QtCore.QObject.connect(self.close_pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), arcons.close)
QtCore.QMetaObject.connectSlotsByName(arcons)
def retranslateUi(self, arcons):
arcons.setWindowTitle(QtGui.QApplication.translate("arcons", "ARCONS", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("arcons", "ARCONS Status", None, QtGui.QApplication.UnicodeUTF8))
self.label_3.setText(QtGui.QApplication.translate("arcons", "Array Temp", None, QtGui.QApplication.UnicodeUTF8))
self.label_4.setText(QtGui.QApplication.translate("arcons", "Pulse Tube Temp", None, QtGui.QApplication.UnicodeUTF8))
self.open_shutter_radioButton.setText(QtGui.QApplication.translate("arcons", "Open Shutter", None, QtGui.QApplication.UnicodeUTF8))
self.cycle_fridge_radioButton.setText(QtGui.QApplication.translate("arcons", "Cycle Fridge", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setText(QtGui.QApplication.translate("arcons", "Telescope Status", None, QtGui.QApplication.UnicodeUTF8))
self.label_5.setText(QtGui.QApplication.translate("arcons", "RA", None, QtGui.QApplication.UnicodeUTF8))
self.label_6.setText(QtGui.QApplication.translate("arcons", "Dec", None, QtGui.QApplication.UnicodeUTF8))
self.label_7.setText(QtGui.QApplication.translate("arcons", "UTC", None, QtGui.QApplication.UnicodeUTF8))
self.label_8.setText(QtGui.QApplication.translate("arcons", "Altitude", None, QtGui.QApplication.UnicodeUTF8))
self.label_9.setText(QtGui.QApplication.translate("arcons", "Azimuth", None, QtGui.QApplication.UnicodeUTF8))
self.label_10.setText(QtGui.QApplication.translate("arcons", "Local Time", None, QtGui.QApplication.UnicodeUTF8))
self.label_11.setText(QtGui.QApplication.translate("arcons", "Airmass", None, QtGui.QApplication.UnicodeUTF8))
self.label_12.setText(QtGui.QApplication.translate("arcons", "LST", None, QtGui.QApplication.UnicodeUTF8))
self.status_label.setText(QtGui.QApplication.translate("arcons", "Status", None, QtGui.QApplication.UnicodeUTF8))
self.save_raw_checkBox.setText(QtGui.QApplication.translate("arcons", " Save Raw", None, QtGui.QApplication.UnicodeUTF8))
self.label_14.setText(QtGui.QApplication.translate("arcons", "Data Directory:", None, QtGui.QApplication.UnicodeUTF8))
self.label_16.setText(QtGui.QApplication.translate("arcons", "Remaining time:", None, QtGui.QApplication.UnicodeUTF8))
self.label_13.setText(QtGui.QApplication.translate("arcons", "SDR Control", None, QtGui.QApplication.UnicodeUTF8))
self.label_15.setText(QtGui.QApplication.translate("arcons", "Exposure Time:", None, QtGui.QApplication.UnicodeUTF8))
self.calibrate_data_checkBox.setText(QtGui.QApplication.translate("arcons", "Calibrate Data", None, QtGui.QApplication.UnicodeUTF8))
self.stop_observation_pushButton.setText(QtGui.QApplication.translate("arcons", "Stop Observation", None, QtGui.QApplication.UnicodeUTF8))
self.start_observation_pushButton.setText(QtGui.QApplication.translate("arcons", "Start Observation", None, QtGui.QApplication.UnicodeUTF8))
self.close_pushButton.setText(QtGui.QApplication.translate("arcons", "Close", None, QtGui.QApplication.UnicodeUTF8))
self.search_pushButton.setText(QtGui.QApplication.translate("arcons", "Browse", None, QtGui.QApplication.UnicodeUTF8))
self.frequency_tuneup_pushButton.setText(QtGui.QApplication.translate("arcons", "Frequency \n"
"Tune-up", None, QtGui.QApplication.UnicodeUTF8))
self.target_lineEdit.setText(QtGui.QApplication.translate("arcons", "Target", None, QtGui.QApplication.UnicodeUTF8))
self.label_20.setText(QtGui.QApplication.translate("arcons", "File name:", None, QtGui.QApplication.UnicodeUTF8))
self.label_21.setText(QtGui.QApplication.translate("arcons", "Target name:", None, QtGui.QApplication.UnicodeUTF8))
self.subtract_sky_radioButton.setText(QtGui.QApplication.translate("arcons", "Subtract Sky", None, QtGui.QApplication.UnicodeUTF8))
self.flat_field_radioButton.setText(QtGui.QApplication.translate("arcons", "Flat Field", None, QtGui.QApplication.UnicodeUTF8))
self.label_19.setText(QtGui.QApplication.translate("arcons", " Integration (s)", None, QtGui.QApplication.UnicodeUTF8))
self.options_radioButton.setText(QtGui.QApplication.translate("arcons", "Expand Controls-->", None, QtGui.QApplication.UnicodeUTF8))
self.label_27.setText(QtGui.QApplication.translate("arcons", "Additional Header Info:", None, QtGui.QApplication.UnicodeUTF8))
self.update_description.setText(QtGui.QApplication.translate("arcons", "Update in Header", None, QtGui.QApplication.UnicodeUTF8))
self.continuous.setText(QtGui.QApplication.translate("arcons", " Continuous Observing", None, QtGui.QApplication.UnicodeUTF8))
self.pixel_number_label.setText(QtGui.QApplication.translate("arcons", "Displaying Plot for\n"
" Pixel Number:", None, QtGui.QApplication.UnicodeUTF8))
self.label_32.setText(QtGui.QApplication.translate("arcons", "Row:", None, QtGui.QApplication.UnicodeUTF8))
self.label_34.setText(QtGui.QApplication.translate("arcons", "Col:", None, QtGui.QApplication.UnicodeUTF8))
self.groupBox.setTitle(QtGui.QApplication.translate("arcons", "Pixel Selection Mode", None, QtGui.QApplication.UnicodeUTF8))
self.drag_select_radioButton.setText(QtGui.QApplication.translate("arcons", "Click && Drag", None, QtGui.QApplication.UnicodeUTF8))
self.rect_select_radioButton.setText(QtGui.QApplication.translate("arcons", "Single Click Rectangle", None, QtGui.QApplication.UnicodeUTF8))
self.label_23.setText(QtGui.QApplication.translate("arcons", "x", None, QtGui.QApplication.UnicodeUTF8))
self.label_24.setText(QtGui.QApplication.translate("arcons", "y", None, QtGui.QApplication.UnicodeUTF8))
self.circ_select_radioButton.setText(QtGui.QApplication.translate("arcons", "Single Click Circle", None, QtGui.QApplication.UnicodeUTF8))
self.label_25.setText(QtGui.QApplication.translate("arcons", "r", None, QtGui.QApplication.UnicodeUTF8))
self.choose_beamimage.setText(QtGui.QApplication.translate("arcons", "Choose Beamimage", None, QtGui.QApplication.UnicodeUTF8))
self.choose_bindir.setText(QtGui.QApplication.translate("arcons", "Choose Bin Dir.", None, QtGui.QApplication.UnicodeUTF8))
self.label_22.setText(QtGui.QApplication.translate("arcons", "Saturated Pix", None, QtGui.QApplication.UnicodeUTF8))
self.takesky.setText(QtGui.QApplication.translate("arcons", "Take Sky Exposure", None, QtGui.QApplication.UnicodeUTF8))
self.label_36.setText(QtGui.QApplication.translate("arcons", "Calibration", None, QtGui.QApplication.UnicodeUTF8))
self.label_37.setText(QtGui.QApplication.translate("arcons", "Angle", None, QtGui.QApplication.UnicodeUTF8))
self.label_38.setText(QtGui.QApplication.translate("arcons", "Cal Time:", None, QtGui.QApplication.UnicodeUTF8))
self.label_39.setText(QtGui.QApplication.translate("arcons", "Cal Angle:", None, QtGui.QApplication.UnicodeUTF8))
self.do_cal_button.setText(QtGui.QApplication.translate("arcons", "Do Cal", None, QtGui.QApplication.UnicodeUTF8))
self.go_home_button.setText(QtGui.QApplication.translate("arcons", "Go Home", None, QtGui.QApplication.UnicodeUTF8))
self.goto_button.setText(QtGui.QApplication.translate("arcons", "GoTo", None, QtGui.QApplication.UnicodeUTF8))
self.label_40.setText(QtGui.QApplication.translate("arcons", "Filter Wheel", None, QtGui.QApplication.UnicodeUTF8))
self.laser_toggle.setText(QtGui.QApplication.translate("arcons", "Laser Box", None, QtGui.QApplication.UnicodeUTF8))
self.laser_label.setText(QtGui.QApplication.translate("arcons", "OFF", None, QtGui.QApplication.UnicodeUTF8))
self.filter1.setText(QtGui.QApplication.translate("arcons", "Filter 1", None, QtGui.QApplication.UnicodeUTF8))
self.filter2.setText(QtGui.QApplication.translate("arcons", "Filter 2", None, QtGui.QApplication.UnicodeUTF8))
self.filter3.setText(QtGui.QApplication.translate("arcons", "Filter 3", None, QtGui.QApplication.UnicodeUTF8))
self.filter4.setText(QtGui.QApplication.translate("arcons", "Filter 4", None, QtGui.QApplication.UnicodeUTF8))
self.filter5.setText(QtGui.QApplication.translate("arcons", "Filter 5", None, QtGui.QApplication.UnicodeUTF8))
self.filter6.setText(QtGui.QApplication.translate("arcons", "Filter 6", None, QtGui.QApplication.UnicodeUTF8))
self.label_26.setText(QtGui.QApplication.translate("arcons", "Testing Junk", None, QtGui.QApplication.UnicodeUTF8))
self.label_17.setText(QtGui.QApplication.translate("arcons", "RA", None, QtGui.QApplication.UnicodeUTF8))
self.label_18.setText(QtGui.QApplication.translate("arcons", "Dec", None, QtGui.QApplication.UnicodeUTF8))
self.RA_lineEdit.setText(QtGui.QApplication.translate("arcons", "0.0", None, QtGui.QApplication.UnicodeUTF8))
self.Dec_lineEdit.setText(QtGui.QApplication.translate("arcons", "0.0", None, QtGui.QApplication.UnicodeUTF8))
self.label_41.setText(QtGui.QApplication.translate("arcons", "Contrast", None, QtGui.QApplication.UnicodeUTF8))
self.label_28.setText(QtGui.QApplication.translate("arcons", "or", None, QtGui.QApplication.UnicodeUTF8))
self.contrast_mode.setText(QtGui.QApplication.translate("arcons", "Manually", None, QtGui.QApplication.UnicodeUTF8))
self.label_29.setText(QtGui.QApplication.translate("arcons", "Min", None, QtGui.QApplication.UnicodeUTF8))
self.label_30.setText(QtGui.QApplication.translate("arcons", "Max", None, QtGui.QApplication.UnicodeUTF8))
from mpl_pyqt4_widget import MPL_Widget
| 46,431 | 60.094737 | 148 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/testbuttons_gui.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'testbuttons_gui.ui'
#
# Created: Tue Nov 19 13:59:11 2013
# by: PyQt4 UI code generator 4.8.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(792, 167)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.pushButton = QtGui.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(70, 30, 114, 51))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.pushButton_2 = QtGui.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(200, 30, 114, 51))
self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
self.pushButton_3 = QtGui.QPushButton(self.centralwidget)
self.pushButton_3.setGeometry(QtCore.QRect(330, 30, 114, 51))
self.pushButton_3.setObjectName(_fromUtf8("pushButton_3"))
self.pushButton_4 = QtGui.QPushButton(self.centralwidget)
self.pushButton_4.setGeometry(QtCore.QRect(460, 30, 114, 51))
self.pushButton_4.setObjectName(_fromUtf8("pushButton_4"))
self.pushButton_5 = QtGui.QPushButton(self.centralwidget)
self.pushButton_5.setGeometry(QtCore.QRect(590, 30, 114, 51))
self.pushButton_5.setObjectName(_fromUtf8("pushButton_5"))
self.spinBox = QtGui.QSpinBox(self.centralwidget)
self.spinBox.setGeometry(QtCore.QRect(710, 40, 57, 31))
self.spinBox.setObjectName(_fromUtf8("spinBox"))
self.lcdNumber = QtGui.QLCDNumber(self.centralwidget)
self.lcdNumber.setGeometry(QtCore.QRect(630, 80, 91, 41))
self.lcdNumber.setObjectName(_fromUtf8("lcdNumber"))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 792, 22))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
self.pushButton.setText(QtGui.QApplication.translate("MainWindow", "1", None, QtGui.QApplication.UnicodeUTF8))
self.pushButton_2.setText(QtGui.QApplication.translate("MainWindow", "2", None, QtGui.QApplication.UnicodeUTF8))
self.pushButton_3.setText(QtGui.QApplication.translate("MainWindow", "3", None, QtGui.QApplication.UnicodeUTF8))
self.pushButton_4.setText(QtGui.QApplication.translate("MainWindow", "4", None, QtGui.QApplication.UnicodeUTF8))
self.pushButton_5.setText(QtGui.QApplication.translate("MainWindow", "Count", None, QtGui.QApplication.UnicodeUTF8))
| 3,332 | 51.078125 | 129 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/rad2altaz.py | #rad2altaz.py
#Written 9/28/10 by Seth Meeker
from numpy import *
def rad2altaz(ra, dec, lon, lat, time=None):
'''callable python program for converting RA/Dec coordinates to Alt/Az.
Inputs: Right Ascension and Declination of object
Latitude and Longitude of observing site
Time of observation (in format of python's time.gmtime() function call).
Defaults to current time if none given.
Outputs: Altitude, Azimuth, Hour Angle, and Local Sidereal Time of object
Sidereal Time calculated using J2000 epoch
'''
#calculate days since J2000
#days = days in previous years + extra days for leap years + days this year + fraction from today
years = time.tm_year - 2000
today = (time.tm_hour+(time.tm_min/60.)+(time.tm_sec/3600.))/24.
days = 365*(years-1) + (years-1)/4 + (time.tm_yday -1) + today
#calculate Local Sidereal Time from longitude and days from the epoch
LST = 100.46 + 0.985647*days + lon + 15*(today*24)
LST %= 360
#calculate Hour Angle of object
HA = LST - ra
#setup conversions from degrees to radians and radians to degrees
d2r = pi/180
r2d = 180/pi
#calculate altitude
alt = r2d*arcsin((sin(dec*d2r)*sin(lat*d2r))+(cos(dec*d2r)*cos(lat*d2r)*cos(HA*d2r)))
#calculate azimuth
A = r2d*arccos((sin(dec*d2r)-sin(alt*d2r)*sin(lat*d2r))/(cos(alt*d2r)*cos(lat*d2r)))
az = 360-A
return alt, az, LST, HA | 1,356 | 32.097561 | 98 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/HeaderGen.py | #!/usr/bin/env python
# encoding: utf-8
"""
HeaderGen.py
Call HeaderGen from ARCONS control GUI to start write of observation file.
Created by Ben Mazin on 2011-05-04.
Copyright (c) 2011 . All rights reserved.
Modified by Seth Meeker on 2011-06-02
"""
import pulses_v1 as pulses
import time,datetime,os,ephem
import numpy as np
from tables import *
filt1 = Filters(complevel=1, complib='zlib', fletcher32=False)
def BeamImage(obsfile, beammapfile, timestamp):
print "creating BeamImage and copying into observation file"
nBeamRows = 46
nBeamCols = 44
bmfile = openFile(beammapfile, 'r')
h5file = openFile(obsfile, 'a')
#read beammap in to memory to create beam image
bmap = bmfile.root.beammap.beammap.read()
#create beammap node in obs file and copy over from beam map file
bgroup = h5file.createGroup('/','beammap','Beam Map of Array')
h5file.copyNode(bmfile.getNode('/beammap/beammap'),newparent=bgroup,recursive=True)
bmfile.close()
# make beammap array - this is a 2d array (top left is 0,0. first index is column, second is row) containing a string with the name of the group holding the photon data
ca = h5file.createCArray(bgroup, 'beamimage', StringAtom(itemsize=40), (nBeamRows,nBeamCols), filters=filt1)
for i in range(len(bmap)):
rowidx = bmap[i][8]
colidx = bmap[i][6]
ca[colidx,rowidx] = 'r'+str(bmap[i][4])+'/p'+str(int(bmap[i][3]))+'/t'+str(timestamp)
#ca[rowidx,colidx] = 'r'+str(bmap[i][4])+'/p'+str(int(bmap[i][2]))+'/t'+str(timestamp)
h5file.flush()
carray = ca.read()
h5file.close()
def HeaderGen(filename,beammapfile,lt,exptime,ra,dec,alt,az,airmass,lst,passedfilt,dir="./",telescope = "Broida", target="Target",equinox=2000.0,epoch=2011.0,focus=np.nan, parallactic=np.nan, seeing=0):
#lt = time.time() #passed in call to HeaderGen
dt = datetime.datetime.utcfromtimestamp(lt)
h5f = openFile(str(dir)+'/'+str(filename), mode='w')
hdrgrp = h5f.createGroup('/','header','Group containing observation description')
hdrtable = h5f.createTable(hdrgrp, 'header', pulses.ObsHeader, "Header",filters=filt1)
w = hdrtable.row
w['target'] = target #passed in call to HeaderGen
w['datadir'] = dir
w['calfile'] = dir + 'something.h5'
w['beammappath'] = os.environ['MKID_BEAMMAP_PATH']
w['beammapfile'] = beammapfile #passed in call to HeaderGen
w['version'] = 'ARCONS Observation v2.0'
w['instrument'] = 'ARCONS v2.0 - 2024 pixel (46x44) array, 8 ROACH readout.'
w['boffile'] = os.environ['BOFFILE']
w['firmware'] = os.environ['FIRMWARE_COMMIT']
w['customFIR'] = os.environ['MKID_CUSTOM_FIR']
w['freqpath'] = os.environ['MKID_FREQ_PATH']
w['description'] = ''
w['filt'] = passedfilt
if telescope == "Palomar":
w['telescope'] = 'Palomar 200" Hale Telescope'
w['obslat'] = 33.0 + 21.0/60.0 + 21.6/3600.0 #Palomar
w['obslong'] = -1.*(116.0 + 51.0/60.0 + 46.80/3600.0) #Palomar
w['obsalt'] = 1706.0 #Palomar
if telescope == "Lick":
w['telescope'] = 'Lick 36 inch Shane Telescope'
w['obslat'] = 37.0 + 20.0/60.0 + 24.6/3600.0 #Lick
w['obslong'] = -1.*(121.0 + 38.0/60.0 + 43.80/3600.0) #Lick
w['obsalt'] = 1283.0 #Lick
if telescope == "Broida":
w['telescope'] = 'Mazin Lab, UCSB'
w['obslat'] = 34.414243 #UCSB's location according to Google Earth
w['obslong'] = -119.843009
w['obsalt'] = 100.0
if focus != np.nan:
w['focus'] = focus
if parallactic != np.nan:
w['parallactic'] = parallactic
#crab = ephem.readdb("Crab Pulsar,f|L,5:34:31.97,22:00:52.1,16.5,2000")
w['seeing'] = seeing
w['airmass'] = airmass
w['equinox'] = equinox
w['epoch'] = epoch
w['timezone'] = time.altzone/3600.0
w['localtime'] = time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime(lt))
w['unixtime'] = lt
w['utc'] = time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime(lt))
#palomar = ephem.Observer()
#palomar.long, palomar.lat = '116.0:51.0:46.80', '33.0:21.0:21.6'
#palomar.date = ephem.Date(dt)
#palomar.elevation = 1706.0
#crab.compute(palomar)
#w['ra'] = crab.ra*12.0/ephem.pi #pulled from TCS
w['ra'] = ra
#w['dec'] = crab.dec*180.0/ephem.pi #pulled from TCS
w['dec'] = dec
#w['lst'] = palomar.sidereal_time().__str__() #pulled from TCS
w['lst'] = lst
w['jd'] = ephem.julian_date(dt)
#w['alt'] = crab.alt*180.0/ephem.pi #pulled from TCS
w['alt'] = alt
#w['az'] = crab.az*180.0/ephem.pi #pulled from TCS
w['az'] = az
w['platescl'] = 0.3
#w['exptime'] = 10.0 #passed in call to HeaderGen
w['exptime'] = exptime
w.append()
h5f.close()
h5f = openFile(str(dir)+'/'+str(filename), mode='r')
print str(dir)+'/'+str(filename)
test = h5f.root.header.header.read()
print 'exptime written is ',test['exptime'][0]
h5f.close()
#BeamImage(dir+'/'+str(filename), beammapfile, lt)
| 5,066 | 37.097744 | 202 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/getSeeing.py | import numpy as np
import os
import sys
import subprocess
# get seeing log from http://nera.palomar.caltech.edu/P18_seeing/current.log
# read in last line of file and extract seeing value
# return this value
def getPalomarSeeing(verbose=False):
#set Verbose = True if you want debug messages
f="current.log"
address = "http://nera.palomar.caltech.edu/P18_seeing/%s"%f
if verbose==True:
print "Grabbing file from %s"%address
if verbose== True:
p = subprocess.Popen("wget %s"%address,shell=True)
else:
p = subprocess.Popen("wget --quiet %s"%address,shell=True)
p.communicate()
stdin,stdout = os.popen2("tail -1 %s"%f)
stdin.close()
line = stdout.readlines(); stdout.close()
if verbose==True:
print line
breakdown = line[0].split('\t')
seeing = breakdown[4]
if verbose==True:
print "Seeing = %s"%seeing
print "Deleting %s"%f
os.remove(f)
return seeing
if __name__ == "__main__":
verbose=False
if len(sys.argv)>1:
if sys.argv[1]=='v':
verbose=True
else: print "To set verbose mode use syntax:\npython getSeeing.py v"
seeing = getPalomarSeeing(verbose)
print "Got seeing as %s"%seeing
| 1,239 | 28.52381 | 76 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/make_image_v2.py | # make_image.py
# 05/30/11 version 2 updated to make image as numpy array and return mplib figure to arcons quicklook
#from data2ascii import unpack_data
from PIL import Image
from PIL import ImageDraw
from numpy import *
import matplotlib
from matplotlib.pyplot import plot, figure, show, rc, grid
import matplotlib.pyplot as plt
#will actually need intermediate work to unpack these arrays from file and pass them in
def make_image(photon_count, median_energy, color_on = True, white_pixels = .10):
'''
Updated from 08/31/10 version. Image generation will happen on GUI machine now. organize_data
will be run on SDR to pass over binary file with arrays of each pixels photon count and median energy.
Those arrays will be unpacked in GUI image generation thread, combined into cumulative arrays if we
are doing an observation, then passes arrays of photon counts and energies to make_image
'''
array_rows = 32
array_cols = 32
total_pixels = array_rows * array_cols
print "Generating image"
im = Image.new("RGB",(array_cols,array_rows))
draw = ImageDraw.ImageDraw(im)
#to get better v gradient we want to saturate brightest 10% of pixels
#make histogram out of the lengths of each pixel. Histogram peak will be at the low end
#as most pixels will be dark, thus having small "lengths" for their photon lists.
hist_counts, hist_bins = histogram(photon_count, bins=100)
brightest_pixels = 0
nbrightestcounts = 0.0
q=1
#starting at the high end of the histogram (bins containing the pixels with the most photons),
#count backwards until we get to the 5th brightest, then set that to maximum v value.
#Thus the few brighter pixels will be saturated, and the rest will be scaled to this
#5th brightest pixel.
ncounts = float(sum(photon_count))
#print "ncounts ", ncounts
cdf = array(cumsum(hist_counts*hist_bins[:-1]),dtype = float32)
#print cdf
idx = (where(cdf > (ncounts*(1.0-white_pixels))))[0][0] #where cdf has 1-white_pixels percent of max number of counts
#print idx
vmax = hist_bins[idx]
#while float(nbrightestcounts/float(ncounts)) <= white_pixels:
#brightest_pixels += hist_bins[-q]
#nbrightestcounts += hist_counts[-q]
#q+=1
#if vmax == 0: #if vmax = 0 then no pixels are illuminated
#while vmax ==0: #check through brightest pixels until one is found
#q -= 1
#vmax = pixel_hist[1][-q]
for m in range(total_pixels):
try:
if median_energy[m] >= 3.1:
hue= 300
elif median_energy[m] <= 1.9:
hue= 0
else:
hue = int(((median_energy[m]-1.9)/(3.1-1.9))*300)
except ValueError:
hue = 150 #if median energy is NaN, that pixel has no photons, so set hue to green and v will be 0
#normalize number of photons in that pixel by vmax, then *80 to give brightness
try:
v = int((photon_count[m]/vmax)*80)
if v < 0:
v=0 #after sky subtraction we may get negative counts for some pixels
except ValueError:
v=0 #if v is NaN set v to 0
if color_on == True:
s=v #scale saturation with v so brightest pixels show most color, dimmer show less color
else:
s=0 #make image black and white if color is turned off
colorstring = "hsl(%i,%i%%,%i%%)" %(hue,s,v)
imx = m%(array_cols)
#to flip image vertically use: imy = m/array_cols
imy = (array_rows - 1) - m/(array_cols)
draw.point((imx,imy),colorstring)
return im
#10/5/10 added main portion so single binary data file can be turned into an image
if __name__ == "__main__":
file = raw_input("enter binary data file name: ")
newpixel, newtime, newenergy = unpack_data(file)
imagefile = raw_input("enter image file name to save data to: ")
obs = len(newenergy)
print "creating list of each pixel's photons"
each_pixels_photons = []
lengths = []
#generate empty list for pixels to have photons dumped into
for j in range(1024):
each_pixels_photons.append([])
#search through data and place energies in right pixels
for k in range(obs):
each_pixels_photons[newpixel[k]].append(newenergy[k])
for l in range(1024):
lengths.append(len(each_pixels_photons[l]))
print "Generating image"
im = Image.new("RGB",(32,32))
draw = ImageDraw.ImageDraw(im)
#to get better v distribution we want to saturate brightest 0.5% of pixels
pixel_hist = histogram(lengths, bins=100)
photon_sum=0
q=1
while photon_sum <=4:
photon_sum += pixel_hist[0][-q]
q+=1
vmax = pixel_hist[1][-q]
for m in range(1024):
#normalize pixel's ave energy by max of 5, then multiply by 300 to give hue value between 0 and 300
median_energy = median(each_pixels_photons[m])
try:
if median_energy >= 3.1:
hue= 300
elif median_energy <= 1.9:
hue= 0
else:
hue = int(((median_energy-1.9)/(3.1-1.9))*300)
except ValueError:
hue = 150 #if median energy is NaN, that pixel has no photons, so set hue to green and v will be 0
#normalize number of photons in that pixel by vmax, then *80 to give brightness
try:
v = (len(each_pixels_photons[m])/vmax)*80
except ValueError:
v=0 #if v is NaN set v to 0
s=v #scale saturation with v so brightest pixels show most color, dimmer show less color
colorstring = "hsl(%i,%i%%,%i%%)" %(hue,s,v)
imx = m%(32)
#switch between two lines below to flip array vertically
#imy = m/array_cols
imy = (31) - m/(32)
#imy = m/(32)
draw.point((imx,imy),colorstring)
im.show()
| 5,323 | 34.258278 | 119 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/mpl_pyqt4_widget.py | #!/usr/bin/env python
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4 import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import numpy as N
class MyMplCanvas(FigureCanvas):
def __init__(self, parent=None, width = 10, height = 12, dpi = 100, sharex = None, sharey = None):
self.fig = Figure(figsize = (width, height), dpi=dpi, facecolor = '#FFFFFF')
self.ax = self.fig.add_subplot(111, sharex = sharex, sharey = sharey)
self.fig.subplots_adjust(left=0.12, bottom=0.15, right=0.97, top=0.97)
self.xtitle="Wavelength"
self.ytitle="Counts"
#self.PlotTitle = "Some Plot"
self.grid_status = True
self.xaxis_style = 'linear'
self.yaxis_style = 'linear'
self.format_labels()
self.ax.hold(True)
FigureCanvas.__init__(self, self.fig)
#self.fc = FigureCanvas(self.fig)
FigureCanvas.setSizePolicy(self,
QSizePolicy.Expanding,
QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
def format_labels(self):
#self.ax.set_title(self.PlotTitle)
self.ax.title.set_fontsize(7)
self.ax.set_xlabel(self.xtitle, fontsize = 7)
self.ax.set_ylabel(self.ytitle, fontsize = 7)
labels_x = self.ax.get_xticklabels()
labels_y = self.ax.get_yticklabels()
for xlabel in labels_x:
xlabel.set_fontsize(7)
for ylabel in labels_y:
ylabel.set_fontsize(7)
ylabel.set_color('b')
def sizeHint(self):
w, h = self.get_width_height()
return QSize(w, h)
def minimumSizeHint(self):
return QSize(10, 10)
def sizeHint(self):
w, h = self.get_width_height()
return QSize(w, h)
def minimumSizeHint(self):
return QSize(10, 10)
class MPL_Widget(QWidget):
def __init__(self, parent = None):
QWidget.__init__(self, parent)
self.canvas = MyMplCanvas()
#self.toolbar = NavigationToolbar(self.canvas, self.canvas)
self.vbox = QVBoxLayout()
self.vbox.addWidget(self.canvas)
#self.vbox.addWidget(self.toolbar)
self.setLayout(self.vbox)
| 2,089 | 28.43662 | 99 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/h5headers.py | # encoding: utf-8
"""
h5headers.py
Created as pulses.py by Ben Mazin on 2011-05-04.
Copyright (c) 2011 . All rights reserved.
"""
import numpy as np
import time
import os
from tables import *
import matplotlib
import scipy as sp
import scipy.signal
from matplotlib.pyplot import plot, figure, show, rc, grid
import matplotlib.pyplot as plt
import mpfit
class ObsHeader(IsDescription):#PyTables header for observation files
target = StringCol(80)
datadir = StringCol(80) # directory where observation data is stored
calfile = StringCol(80) # path and filename of calibration file
beammapfile = StringCol(80) # path and filename of beam map file
version = StringCol(80)
instrument = StringCol(80)
telescope = StringCol(80)
focus = StringCol(80)
parallactic = Float64Col()
ra = Float64Col()
dec = Float64Col()
alt = Float64Col()
az = Float64Col()
airmass = Float64Col()
equinox = Float64Col()
epoch = Float64Col()
obslat = Float64Col()
obslong = Float64Col()
obsalt = Float64Col()
timezone = Int32Col()
localtime = StringCol(80)
ut = Float64Col()
lst = StringCol(80)
jd = Float64Col()
platescl = Float64Col()
exptime = Int32Col()
class Photon(IsDescription):
"""The pytables derived class that holds pulse packet data on the disk.
Put in a marker pulse with at = int(time.time()) and phase = -32767 every second.
"""
at = UInt32Col() # pulse arrival time in microseconds since last sync pulse
class RawPulse(IsDescription):
"""The pytables derived class that hold raw pulse data on the disk.
"""
starttime = Float64Col() # start time of pulse data
samprate = Float32Col() # sample rate of the data in samples/sec
npoints = Int32Col() # number of data points in the pulse
f0 = Float32Col() # resonant frequency data was taken at
atten1 = Float32Col() # attenuator 1 setting data was taken at
atten2 = Float32Col() # attenuator 2 setting data was taken at
Tstart = Float32Col() # temp data was taken at
I = Float32Col(2000) # I pulse data, up to 5000 points.
Q = Float32Col(2000)
class PulseAnalysis(IsDescription): # contains final template info
flag = Int16Col() # flag for quality of template. If this could be a bad template set > 0
count = Float32Col() # number of pulses going into this template
pstart = Int16Col() # index of peak of template
phasetemplate = Float64Col(2000)
phasenoise = Float64Col(800)
phasenoiseidx = Float64Col(800)
#optfilt = Complex128(800)
# fit quantities
trise = Float32Col() # fit value of rise time
tfall = Float32Col() # fit value of fall time
# optimal filter parameters
coeff = Float32Col(100) # coefficients for the near-optimal filter
nparam = Int16Col() # number of parameters in the filter
class BeamMap(IsDescription):
roach = UInt16Col() # ROACH board number (0-15) for now!
resnum = UInt16Col() # resonator number on roach board (corresponds to res # in optimal pulse packets)
f0 = Float32Col() # resonant frequency of center of sweep (can be used to get group name)
pixel = UInt32Col() # actual pixel number - bottom left of array is 0, increasing up
xpos = Float32Col() # physical X location in mm
ypos = Float32Col() # physical Y location in mm
scale = Float32Col(3) # polynomial to convert from degrees to eV
# Make a fake observation file
def FakeObservation(obsname, start, exptime):
# simulation parameters
nroach = 4 # number of roach boards
nres = 256 # number of pixels on each roach
xpix = 32 # pixels in x dir
ypix = 32 # pixels in y dir
R = 15 # mean energy resolution
good = 0.85 # fraction of resonators that are good
#exptime = 10 # duration of fake exposure in seconds
fullobspath = obsname.split("/")
obsfile = fullobspath.pop()
obspath = "/".join(fullobspath)+"/"
h5file = openFile(obsname, mode = "r")
carray = h5file.root.beammap.beamimage.read()
h5file.close()
filt1 = Filters(complevel=1, complib='zlib', fletcher32=False) # without minimal compression the files sizes are ridiculous...
h5file = openFile(obsname, mode = "a")
''' beam map inserted from beam map file during header gen
# make beamap table
bgroup = h5file.createGroup('/','beammap','Beam Map of Array')
filt = Filters(complevel=0, complib='zlib', fletcher32=False)
filt1 = Filters(complevel=1, complib='blosc', fletcher32=False) # without minimal compression the files sizes are ridiculous...
btable = h5file.createTable(bgroup, 'beammap', BeamMap, "Table of anaylzed beam map data",filters=filt1)
w = btable.row
# make beammap array - this is a 2d array (top left is 0,0. first index is column, second is row) containing a string with the name of the group holding the photon data
ca = h5file.createCArray(bgroup, 'beamimage', StringAtom(itemsize=40), (32,32), filters=filt1)
for i in xrange(nroach):
for j in xrange(nres):
w['roach'] = i
w['resnum'] = ((41*j)%256)
w['f0'] = 3.5 + (i%2)*.512 + 0.002*j
w['pixel'] = ((41*j)%256) + 256*i
w['xpos'] = np.floor(j/16)*0.1
w['ypos'] = (j%16)*0.1
if i == 1 or i == 3:
w['ypos'] = (j%16)*0.1 + 1.6
if i == 2 or i == 3:
w['xpos'] = np.floor(j/16)*0.1 + 1.6
w.append()
colidx = int(np.floor(j/16))
rowidx = 31 - j%16
if i == 1 or i == 3:
rowidx -= 16
if i >= 2:
colidx += 16
ca[rowidx,colidx] = 'r'+str(i)+'/p'+str( ((41*j)%256) )
h5file.flush()
carray = ca.read()
'''
# load up the 32x32 image we want to simulate
sourceim = plt.imread('/Users/ourhero/Documents/python/MazinLab/Arcons/ucsblogo.png')
sourceim = sourceim[:,:,0]
# make directory structure for pulse data
dptr = []
for i in xrange(nroach):
group = h5file.createGroup('/','r'+str(i),'Roach ' + str(i))
for j in xrange(nres):
subgroup = h5file.createGroup(group,'p'+str(j))
dptr.append(subgroup)
'''
# now go in an update the beamimages array to contain the name of the actual data array
for i in xrange(32):
for j in xrange(32):
name = h5file.getNode('/',name=ca[i,j])
for leaf in name._f_walkNodes('Leaf'):
newname = ca[i,j]+'/'+leaf.name
ca[i,j] = newname
'''
# create fake photon data
#start = np.floor(time.time())
# make VLArray tables for the photon data
vlarr=[]
for i in dptr:
tmpvlarr = h5file.createVLArray(i, 't'+str(int(start)), UInt32Atom(shape=()),expectedsizeinMB=0.1,filters=filt1)
vlarr.append(tmpvlarr)
idx = np.arange(2000)
for i in xrange(exptime):
print i
t1 = time.time()
for j in vlarr:
# sky photons
nphot = 1000 + int(np.random.randn()*np.sqrt(1000))
#arrival = np.uint32(idx[:nphot]*700.0 + np.random.randn(nphot)*100.0)
arrival = np.uint64(np.random.random(nphot)*1e6)
energy = np.uint64(np.round((20.0 + np.random.random(nphot)*80.0)*20.0))
photon = np.bitwise_or( np.left_shift(energy,12), arrival )
# source photons
# figure out where this group is on the array
pgroup = j._g_getparent().__str__()
#print "printing pgroup", pgroup
ngroup = (pgroup.split(' '))[0]+'/t'+str(start)
#print "printing ngroup", ngroup
cidx = np.where(carray == ngroup[1:])
#print "printing ngroup 1:" ,ngroup[1:]
#print "printing cidx", cidx
#print sourceim[cidx]
sphot = 100.0 * (sourceim[cidx])[0]
sphot += np.sqrt(sphot)*np.random.randn()
sphot = np.uint32(sphot)
#print sphot
if sphot >= 1.0:
arrival = np.uint64(np.random.random(sphot)*1e6)
energy = np.uint64( (60.0 + np.random.randn(sphot)*3.0)*20.0 )
source = np.bitwise_or( np.left_shift(energy,12), arrival )
plist = np.concatenate((photon,source))
else:
plist = photon
#splist = np.sort(plist)
j.append(plist)
t2 = time.time()
dt = t2-t1
if t2-t1 < 1:
#delay for 1 second between creating seconds of false data
time.sleep(1-dt)
'''
idx = np.arange(2000)
for i in xrange(exptime):
print i
t1 = time.time()
for j in vlarr:
# sky photons
nphot = 1000 + int(np.random.randn()*np.sqrt(1000))
#arrival = np.uint32(idx[:nphot]*700.0 + np.random.randn(nphot)*100.0)
arrival = np.uint32(np.random.random(nphot)*1e6)
energy = np.uint32(np.round((20.0 + np.random.random(nphot)*80.0)*20.0))
photon = np.bitwise_or( np.left_shift(arrival,12), energy )
# source photons
# figure out where this group is on the array
pgroup = j._g_getparent().__str__()
ngroup = (pgroup.split(' '))[0]
cidx = np.where(carray == ngroup[1:])
#print sourceim[cidx]
sphot = 100.0 * (sourceim[cidx])[0]
sphot += np.sqrt(sphot)*np.random.randn()
sphot = np.uint32(sphot)
#print sphot
if sphot >= 1.0:
arrival = np.uint32(np.random.random(sphot)*1e6)
energy = np.uint32( (60.0 + np.random.randn(sphot)*3.0)*20.0 )
source = np.bitwise_or( np.left_shift(arrival,12), energy )
plist = np.concatenate((photon,source))
else:
plist = photon
#splist = np.sort(plist)
j.append(plist)
'''
h5file.close()
# make a preview image from obsfile
def QuickLook(obsfile,tstart,tend):
h5file = openFile(obsfile, mode = "r")
image = np.zeros((32,32))
#mask = np.repeat(np.uint32(4095),2000)
# load beamimage
bmap = h5file.root.beammap.beamimage
for i in xrange(32):
for j in xrange(32):
photons = h5file.root._f_getChild(bmap[i][j])
for k in range(tstart,tend):
#energy = np.bitwise_and( mask[:len(photons[0])],photons[0])
image[i][j] += len(photons[k])
# subtract off sky
skysub = np.float32(image - np.median(image))
h5file.close()
# display the image
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.imshow(skysub,cmap='gray', interpolation='nearest')
cbar = fig.colorbar(cax)
plt.show()
# Make a pulse template from the pulses saved in filename
def MakeTemplate(pulsedat):
# open the pulse file
h5file = openFile(pulsedat, mode = "r")
r1 = h5file.root.r1
# create the template file
tfile = openFile(pulsedat.replace('.h5','-template.h5'), mode = "w", title = "Optimal filter data file created " + time.asctime() )
tempr1 = tfile.createGroup('/','r1','ROACH 1')
# loop through pulse data
for group in r1._f_walkGroups():
if group == r1: # walkgroups returns itself as first entry, so skip it - there is probably a more elegant way!
continue
print group
# go through all the raw pulses in table and generate the template
tP=np.zeros(2000,dtype='float64')
tA=np.zeros(2000,dtype='float64')
tPf=np.zeros(2000,dtype='float64')
tAf=np.zeros(2000,dtype='float64')
noise = np.zeros(800,dtype='float64')
# read the table into memory (too slow otherwise!)
dat = group.iqpulses.read()
N = len(dat)
count = 0.0
peaklist = []
idx = np.arange(2000)*2.0
fitidx = np.concatenate((idx[:900],idx[1800:]))
# center of loop
xc = 0.0
yc = 0.0
# determine median prepulse levels for first 100 pulses
I1m = np.median(dat['I'][:100,:900])
Q1m = np.median(dat['Q'][:100,:900])
# make a prelimiary template with 1000 pulses, then a better one with all of them
if N > 1000:
N = 1000
# first pass
for j in xrange(N):
I = dat['I'][j]
Q = dat['Q'][j]
# reference all pulses to first 100 pulses (1/f removal)
I += (I1m - np.median(I[1:900]))
Q += (Q1m - np.median(Q[1:900]))
# transform to phase
P1 = np.arctan2( Q-yc, I-xc )
#P1 = numexpr.evaluate('arctan2( Q-yc, I-xc )')
# remove phase wraps and convert to degrees
P2 = np.rad2deg(np.unwrap(P1))
# subtract baseline
fit = np.poly1d(np.polyfit(fitidx,np.concatenate((P2[:900],P2[1800:])),1))
P3 = P2 - fit(idx)
# skip pulses with bad baseline subtraction
stdev = np.std(P3[:100])
if np.abs(np.mean(P3[:100])-np.mean(P3[1900:])) > stdev*2.0 :
continue
# eliminate doubles
# first pass fit all non-noise pulses
peak = np.max(P3[980:1050])
peaklist.append(peak)
if peak < 15.0 or peak > 120.0:
continue
# if peak not near the center skip
ploc = (np.where(P3 == peak))[0]
if ploc < 980 or ploc > 1020:
continue
# align pulse so peak happens at center
P4 = np.roll(P3,1000-ploc)
# normalize and add to template
tP += P4/np.max(P4)
count += 1
print 'First Pass =',int(count),'pulses'
tP /= count
tA /= count
# make a second pass through using the initial template as the kernel to determine pulse start time
peaklist = np.asarray(peaklist)
pm = np.median(peaklist[np.where(peaklist>15)])
pdev = np.std(peaklist[np.where(peaklist>15)])
print pm,'+-',pdev,'degrees'
N = len(dat)
count = 0.0
t1 = time.time()
for j in xrange(N):
I = dat['I'][j]
Q = dat['Q'][j]
# reference all pulses to first 100 pulses (1/f removal)
I += (I1m - np.median(I[1:900]))
Q += (Q1m - np.median(Q[1:900]))
# transform to phase
P1 = np.arctan2( Q-yc, I-xc )
# remove phase wraps and convert to degrees
P2 = np.rad2deg(np.unwrap(P1))
# subtract baseline - this step is slow - speed up!
fit = np.poly1d(np.polyfit(fitidx,np.concatenate((P2[:900],P2[1800:])),1))
P3 = P2 - fit(idx)
# skip pulses with bad baseline subtraction
stdev = np.std(P3[:100])
if np.abs(np.mean(P3[:100])-np.mean(P3[1900:])) > stdev*2.0 :
continue
# eliminate doubles
# Only fit pulses near the peak
conv = np.convolve(tP[900:1500],P3)
#conv = scipy.signal.fftconvolve(tP[950:1462],np.concatenate( (P3,P3[0:48]) ) )
ploc = int((np.where(conv == np.max(conv)))[0] - 1160.0)
peak = np.max(P3[1000+ploc])
#print ploc,peak
if peak < pm - 4.0*pdev or peak > pm + 4.0*pdev:
continue
# if peak not near the center skip
if ploc < -30 or ploc > 30:
continue
# align pulse so peak happens at center
P4 = np.roll(P3,-ploc)
# normalize and add to template
tPf += P4/np.max(P4)
count += 1
# compute noise PSD
noise += np.abs( np.fft.fft(np.deg2rad(P4[50:850])) )**2
t2 = time.time()
tPf /= count
noise /= count
noiseidx = np.fft.fftfreq(len(noise),d=0.000002)
print 'Second Pass =',int(count),'pulses'
print 'Pulses per second = ', N/(t2-t1)
# calculate optimal filter parameters
# save the template information in a new file
# create a group off root for each resonator that contains iq sweep, pulse template, noise, and optimal filter coefficents
pgroup = tfile.createGroup(tempr1,group._v_name, 'data to set up optimal filtering' )
group.iqsweep.copy(newparent=pgroup) # copy in IQ sweep data
#filt = Filters(complevel=5, complib='zlib', fletcher32=True)
filt = Filters(complevel=0, complib='zlib', fletcher32=False)
table = tfile.createTable(pgroup, 'opt', PulseAnalysis, "optimal filter data",filters=filt)
w = table.row
if( count < 500 or pm < 10 or pm > 150):
w['flag'] = 1
else:
w['flag'] = 0
w['count'] = count
w['pstart'] = (np.where( tPf == np.max(tPf)))[0]
w['phasetemplate'] = tPf
w['phasenoise'] = noise
w['phasenoiseidx'] = noiseidx
w.append()
break
#plot(tPf)
plot(noiseidx,noise)
show()
h5file.close()
tfile.close()
def FakeTemplateData(): # make fake data and write it to a h5 file
filename = '/Users/bmazin/Data/Projects/pytest/fakepulse2.h5'
h5file = openFile(filename, mode='w', title = "Fake Pulse file created " + time.asctime() )
r1 = h5file.createGroup('/','r1','ROACH 1')
# open IQ sweep file
sweepdat = '/Users/bmazin/Data/Projects/pytest/ps_20110505-172336.h5'
iqfile = openFile(sweepdat, mode = "r")
swp = iqfile.root.sweeps
# loop through each IQ sweep in sweepddat and create fake pulses for it
for group in swp._f_walkGroups():
if group == swp: # walkgroups returns itself as first entry, so skip it - there is probably a more elegant way!
continue
print group
pgroup = h5file.createGroup(r1,group._v_name, 'IQ pulse data' )
pname = 'iqpulses'
#filt = Filters(complevel=5, complib='zlib', fletcher32=True)
filt = Filters(complevel=0, complib='zlib', fletcher32=False)
table = h5file.createTable(pgroup, pname, RawPulse, "IQ Pulse Data",filters=filt)
p = table.row
# copy the IQ sweep data into the file
group._f_copyChildren(pgroup)
trise = 0.1
tfall = 65.0
for j in xrange(1000):
p['starttime'] = time.time()
p['samprate'] = 500000.0
p['npoints'] = 2000
p['f0'] = 3.65
p['atten1'] = 30
p['atten2'] = 0
p['Tstart'] = 0.1
I = np.zeros(2000)
Q = np.zeros(2000)
idx = np.arange(1000,dtype='float32')
I[1000:2000] = (1.0 - np.exp( -idx/trise ) ) * np.exp(-idx/tfall) * 0.25
Q[1000:2000] = (1.0 - np.exp( -idx/trise ) ) * np.exp(-idx/tfall)
I += 2.0 - np.random.normal(size=2000)*.01 # add noise
Q += np.random.normal(size=2000)*.01
# move arrival time
I = np.roll(I, int((np.random.normal()*10.0)+0.5) )
Q = np.roll(Q, int((np.random.normal()*10.0)+0.5) )
p['I'] = np.concatenate( (I,np.zeros(2000-len(I))),axis=0 )
p['Q'] = np.concatenate( (Q,np.zeros(2000-len(Q))),axis=0 )
p.append()
table.flush()
h5file.close()
iqfile.close()
#print 'Running!'
#FakeTemplateData()
#pulsedat = '/Users/bmazin/Data/Projects/pytest/fakepulse2.h5'
#MakeTemplate(pulsedat)
#fakedat = '/Users/bmazin/Data/Projects/pytest/fakeobs.h5'
#FakeObservation(fakedat)
#QuickLook(fakedat,0,10)
#print 'Done.'
| 20,906 | 36.602518 | 173 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/pulses.py | #!/usr/bin/env python
# encoding: utf-8
"""
pulses.py
Created by Ben Mazin on 2011-05-04.
Copyright (c) 2011 . All rights reserved.
"""
import numpy as np
import time
from tables import *
import matplotlib
#import scipy as sp
#import scipy.signal
from matplotlib.pyplot import plot, figure, show, rc, grid
import matplotlib.pyplot as plt
#import matplotlib.image as mpimg
#import mpfit
#import numexpr
#from iqsweep import *
class Photon(IsDescription):
"""The pytables derived class that holds pulse packet data on the disk.
Put in a marker pulse with at = int(time.time()) and phase = -32767 every second.
"""
at = UInt32Col() # pulse arrival time in microseconds since last sync pulse
# phase = Int16Col() # optimally filtered phase pulse height
class RawPulse(IsDescription):
"""The pytables derived class that hold raw pulse data on the disk.
"""
starttime = Float64Col() # start time of pulse data
samprate = Float32Col() # sample rate of the data in samples/sec
npoints = Int32Col() # number of data points in the pulse
f0 = Float32Col() # resonant frequency data was taken at
atten1 = Float32Col() # attenuator 1 setting data was taken at
atten2 = Float32Col() # attenuator 2 setting data was taken at
Tstart = Float32Col() # temp data was taken at
I = Float32Col(2000) # I pulse data, up to 5000 points.
Q = Float32Col(2000)
class PulseAnalysis(IsDescription): # contains final template info
flag = Int16Col() # flag for quality of template. If this could be a bad template set > 0
count = Float32Col() # number of pulses going into this template
pstart = Int16Col() # index of peak of template
phasetemplate = Float64Col(2000)
phasenoise = Float64Col(800)
phasenoiseidx = Float64Col(800)
#optfilt = Complex128(800)
# fit quantities
trise = Float32Col() # fit value of rise time
tfall = Float32Col() # fit value of fall time
# optimal filter parameters
coeff = Float32Col(100) # coefficients for the near-optimal filter
nparam = Int16Col() # number of parameters in the filter
class BeamMap(IsDescription):
roach = UInt16Col() # ROACH board number (0-15) for now!
resnum = UInt16Col() # resonator number on roach board (corresponds to res # in optimal pulse packets)
f0 = Float32Col() # resonant frequency of center of sweep (can be used to get group name)
pixel = UInt32Col() # actual pixel number - bottom left of array is 0, increasing up
xpos = Float32Col() # physical X location in mm
ypos = Float32Col() # physical Y location in mm
scale = Float32Col(3) # polynomial to convert from degrees to eV
class ObsHeader(IsDescription):
target = StringCol(80)
datadir = StringCol(80) # directory where observation data is stored
calfile = StringCol(80) # path and filename of calibration file
beammapfile = StringCol(80) # path and filename of beam map file
version = StringCol(80)
instrument = StringCol(80)
ra = Float64Col()
dec = Float64Col()
alt = Float64Col()
az = Float64Col()
airmass = Float64Col()
equinox = Float64Col()
epoch = Float64Col()
obslat = Float64Col()
obslong = Float64Col()
obsalt = Float64Col()
timezone = Int32Col()
localtime = StringCol(80)
ut = Float64Col()
lst = StringCol(80)
jd = Float64Col()
platescl = Float64Col()
exptime = Int32Col()
# Make a fake observation file
def FakeObservation(obsname):
# simulation parameters
nroach = 4 # number of roach boards
nres = 256 # number of pixels on each roach
xpix = 32 # pixels in x dir
ypix = 32 # pixels in y dir
R = 15 # mean energy resolution
good = 0.85 # fraction of resonators that are good
exptime = 10 # duration of fake exposure in seconds
h5file = openFile(obsname, mode = "w")
# make beamap table
bgroup = h5file.createGroup('/','beammap','Beam Map of Array')
filt = Filters(complevel=0, complib='zlib', fletcher32=False)
filt1 = Filters(complevel=1, complib='blosc', fletcher32=False) # without minimal compression the files sizes are ridiculous...
btable = h5file.createTable(bgroup, 'beammap', BeamMap, "Table of anaylzed beam map data",filters=filt1)
w = btable.row
# make beammap array - this is a 2d array (top left is 0,0. first index is column, second is row) containing a string with the name of the group holding the photon data
ca = h5file.createCArray(bgroup, 'beamimage', StringAtom(itemsize=40), (32,32), filters=filt1)
for i in xrange(nroach):
for j in xrange(nres):
w['roach'] = i
w['resnum'] = ((41*j)%256)
w['f0'] = 3.5 + (i%2)*.512 + 0.002*j
w['pixel'] = ((41*j)%256) + 256*i
w['xpos'] = np.floor(j/16)*0.1
w['ypos'] = (j%16)*0.1
if i == 1 or i == 3:
w['ypos'] = (j%16)*0.1 + 1.6
if i == 2 or i == 3:
w['xpos'] = np.floor(j/16)*0.1 + 1.6
w.append()
colidx = int(np.floor(j/16))
rowidx = 31 - j%16
if i == 1 or i == 3:
rowidx -= 16
if i >= 2:
colidx += 16
ca[rowidx,colidx] = 'r'+str(i)+'/p'+str( ((41*j)%256) )
h5file.flush()
carray = ca.read()
# load up the 32x32 image we want to simulate
sourceim = plt.imread('/Users/bmazin/Data/Projects/pytest/ucsblogo.png')
sourceim = sourceim[:,:,0]
# make directory structure for pulse data
dptr = []
for i in xrange(nroach):
group = h5file.createGroup('/','r'+str(i),'Roach ' + str(i))
for j in xrange(nres):
subgroup = h5file.createGroup(group,'p'+str(j))
dptr.append(subgroup)
# create fake photon data
start = np.floor(time.time())
# make VLArray tables for the photon data
vlarr=[]
for i in dptr:
tmpvlarr = h5file.createVLArray(i, 't'+str(int(start)), UInt32Atom(shape=()),expectedsizeinMB=0.1,filters=filt1)
vlarr.append(tmpvlarr)
idx = np.arange(2000)
for i in xrange(exptime):
print i
for j in vlarr:
# sky photons
nphot = 1000 + int(np.random.randn()*np.sqrt(1000))
#arrival = np.uint32(idx[:nphot]*700.0 + np.random.randn(nphot)*100.0)
arrival = np.uint32(np.random.random(nphot)*1e6)
energy = np.uint32(np.round((20.0 + np.random.random(nphot)*80.0)*20.0))
photon = np.bitwise_or( np.left_shift(arrival,12), energy )
# source photons
# figure out where this group is on the array
pgroup = j._g_getparent().__str__()
ngroup = (pgroup.split(' '))[0]
cidx = np.where(carray == ngroup[1:])
#print sourceim[cidx]
sphot = 100.0 * (sourceim[cidx])[0]
sphot += np.sqrt(sphot)*np.random.randn()
sphot = np.uint32(sphot)
print sphot
if sphot >= 1.0:
arrival = np.uint32(np.random.random(sphot)*1e6)
energy = np.uint32( (60.0 + np.random.randn(sphot)*3.0)*20.0 )
source = np.bitwise_or( np.left_shift(arrival,12), energy )
plist = np.concatenate((photon,source))
else:
plist = photon
#splist = np.sort(plist)
j.append(plist)
# now go in an update the beamimages array to contain the name of the actual data array
for i in xrange(32):
for j in xrange(32):
name = h5file.getNode('/',name=ca[i,j])
for leaf in name._f_walkNodes('Leaf'):
newname = ca[i,j]+'/'+leaf.name
ca[i,j] = newname
h5file.close()
# make a preview image from obsfile
def QuickLook(obsfile,tstart,tend):
h5file = openFile(obsfile, mode = "r")
image = np.zeros((32,32))
#mask = np.repeat(np.uint32(4095),2000)
# load beamimage
bmap = h5file.root.beammap.beamimage.read()
for i in xrange(32):
for j in xrange(32):
photons = h5file.root._f_getChild(bmap[i][j]).read()
for k in xrange(tstart,tend):
#energy = np.bitwise_and( mask[:len(photons[0])],photons[0])
image[i][j] += len(photons[k])
# subtract off sky
skysub = np.float32(image - np.median(image))
h5file.close()
# display the image
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.imshow(skysub,cmap='gray', interpolation='nearest')
cbar = fig.colorbar(cax)
plt.show()
# Make a pulse template from the pulses saved in filename
def MakeTemplate(pulsedat):
# open the pulse file
h5file = openFile(pulsedat, mode = "r")
r1 = h5file.root.r1
# create the template file
tfile = openFile(pulsedat.replace('.h5','-template.h5'), mode = "w", title = "Optimal filter data file created " + time.asctime() )
tempr1 = tfile.createGroup('/','r1','ROACH 1')
# loop through pulse data
for group in r1._f_walkGroups():
if group == r1: # walkgroups returns itself as first entry, so skip it - there is probably a more elegant way!
continue
print group
# go through all the raw pulses in table and generate the template
tP=np.zeros(2000,dtype='float64')
tA=np.zeros(2000,dtype='float64')
tPf=np.zeros(2000,dtype='float64')
tAf=np.zeros(2000,dtype='float64')
noise = np.zeros(800,dtype='float64')
# read the table into memory (too slow otherwise!)
dat = group.iqpulses.read()
N = len(dat)
count = 0.0
peaklist = []
idx = np.arange(2000)*2.0
fitidx = np.concatenate((idx[:900],idx[1800:]))
# center of loop
xc = 0.0
yc = 0.0
# determine median prepulse levels for first 100 pulses
I1m = np.median(dat['I'][:100,:900])
Q1m = np.median(dat['Q'][:100,:900])
# make a prelimiary template with 1000 pulses, then a better one with all of them
if N > 1000:
N = 1000
# first pass
for j in xrange(N):
I = dat['I'][j]
Q = dat['Q'][j]
# reference all pulses to first 100 pulses (1/f removal)
I += (I1m - np.median(I[1:900]))
Q += (Q1m - np.median(Q[1:900]))
# transform to phase
P1 = np.arctan2( Q-yc, I-xc )
#P1 = numexpr.evaluate('arctan2( Q-yc, I-xc )')
# remove phase wraps and convert to degrees
P2 = np.rad2deg(np.unwrap(P1))
# subtract baseline
fit = np.poly1d(np.polyfit(fitidx,np.concatenate((P2[:900],P2[1800:])),1))
P3 = P2 - fit(idx)
# skip pulses with bad baseline subtraction
stdev = np.std(P3[:100])
if np.abs(np.mean(P3[:100])-np.mean(P3[1900:])) > stdev*2.0 :
continue
# eliminate doubles
# first pass fit all non-noise pulses
peak = np.max(P3[980:1050])
peaklist.append(peak)
if peak < 15.0 or peak > 120.0:
continue
# if peak not near the center skip
ploc = (np.where(P3 == peak))[0]
if ploc < 980 or ploc > 1020:
continue
# align pulse so peak happens at center
P4 = np.roll(P3,1000-ploc)
# normalize and add to template
tP += P4/np.max(P4)
count += 1
print 'First Pass =',int(count),'pulses'
tP /= count
tA /= count
# make a second pass through using the initial template as the kernel to determine pulse start time
peaklist = np.asarray(peaklist)
pm = np.median(peaklist[np.where(peaklist>15)])
pdev = np.std(peaklist[np.where(peaklist>15)])
print pm,'+-',pdev,'degrees'
N = len(dat)
count = 0.0
t1 = time.time()
for j in xrange(N):
I = dat['I'][j]
Q = dat['Q'][j]
# reference all pulses to first 100 pulses (1/f removal)
I += (I1m - np.median(I[1:900]))
Q += (Q1m - np.median(Q[1:900]))
# transform to phase
P1 = np.arctan2( Q-yc, I-xc )
# remove phase wraps and convert to degrees
P2 = np.rad2deg(np.unwrap(P1))
# subtract baseline - this step is slow - speed up!
fit = np.poly1d(np.polyfit(fitidx,np.concatenate((P2[:900],P2[1800:])),1))
P3 = P2 - fit(idx)
# skip pulses with bad baseline subtraction
stdev = np.std(P3[:100])
if np.abs(np.mean(P3[:100])-np.mean(P3[1900:])) > stdev*2.0 :
continue
# eliminate doubles
# Only fit pulses near the peak
conv = np.convolve(tP[900:1500],P3)
#conv = scipy.signal.fftconvolve(tP[950:1462],np.concatenate( (P3,P3[0:48]) ) )
ploc = int((np.where(conv == np.max(conv)))[0] - 1160.0)
peak = np.max(P3[1000+ploc])
#print ploc,peak
if peak < pm - 4.0*pdev or peak > pm + 4.0*pdev:
continue
# if peak not near the center skip
if ploc < -30 or ploc > 30:
continue
# align pulse so peak happens at center
P4 = np.roll(P3,-ploc)
# normalize and add to template
tPf += P4/np.max(P4)
count += 1
# compute noise PSD
noise += np.abs( np.fft.fft(np.deg2rad(P4[50:850])) )**2
t2 = time.time()
tPf /= count
noise /= count
noiseidx = np.fft.fftfreq(len(noise),d=0.000002)
print 'Second Pass =',int(count),'pulses'
print 'Pulses per second = ', N/(t2-t1)
# calculate optimal filter parameters
# save the template information in a new file
# create a group off root for each resonator that contains iq sweep, pulse template, noise, and optimal filter coefficents
pgroup = tfile.createGroup(tempr1,group._v_name, 'data to set up optimal filtering' )
group.iqsweep.copy(newparent=pgroup) # copy in IQ sweep data
#filt = Filters(complevel=5, complib='zlib', fletcher32=True)
filt = Filters(complevel=0, complib='zlib', fletcher32=False)
table = tfile.createTable(pgroup, 'opt', PulseAnalysis, "optimal filter data",filters=filt)
w = table.row
if( count < 500 or pm < 10 or pm > 150):
w['flag'] = 1
else:
w['flag'] = 0
w['count'] = count
w['pstart'] = (np.where( tPf == np.max(tPf)))[0]
w['phasetemplate'] = tPf
w['phasenoise'] = noise
w['phasenoiseidx'] = noiseidx
w.append()
break
#plot(tPf)
plot(noiseidx,noise)
show()
h5file.close()
tfile.close()
def FakeTemplateData(): # make fake data and write it to a h5 file
filename = '/Users/bmazin/Data/Projects/pytest/fakepulse2.h5'
h5file = openFile(filename, mode='w', title = "Fake Pulse file created " + time.asctime() )
r1 = h5file.createGroup('/','r1','ROACH 1')
# open IQ sweep file
sweepdat = '/Users/bmazin/Data/Projects/pytest/ps_20110505-172336.h5'
iqfile = openFile(sweepdat, mode = "r")
swp = iqfile.root.sweeps
# loop through each IQ sweep in sweepddat and create fake pulses for it
for group in swp._f_walkGroups():
if group == swp: # walkgroups returns itself as first entry, so skip it - there is probably a more elegant way!
continue
print group
pgroup = h5file.createGroup(r1,group._v_name, 'IQ pulse data' )
pname = 'iqpulses'
#filt = Filters(complevel=5, complib='zlib', fletcher32=True)
filt = Filters(complevel=0, complib='zlib', fletcher32=False)
table = h5file.createTable(pgroup, pname, RawPulse, "IQ Pulse Data",filters=filt)
p = table.row
# copy the IQ sweep data into the file
group._f_copyChildren(pgroup)
trise = 0.1
tfall = 65.0
for j in xrange(1000):
p['starttime'] = time.time()
p['samprate'] = 500000.0
p['npoints'] = 2000
p['f0'] = 3.65
p['atten1'] = 30
p['atten2'] = 0
p['Tstart'] = 0.1
I = np.zeros(2000)
Q = np.zeros(2000)
idx = np.arange(1000,dtype='float32')
I[1000:2000] = (1.0 - np.exp( -idx/trise ) ) * np.exp(-idx/tfall) * 0.25
Q[1000:2000] = (1.0 - np.exp( -idx/trise ) ) * np.exp(-idx/tfall)
I += 2.0 - np.random.normal(size=2000)*.01 # add noise
Q += np.random.normal(size=2000)*.01
# move arrival time
I = np.roll(I, int((np.random.normal()*10.0)+0.5) )
Q = np.roll(Q, int((np.random.normal()*10.0)+0.5) )
p['I'] = np.concatenate( (I,np.zeros(2000-len(I))),axis=0 )
p['Q'] = np.concatenate( (Q,np.zeros(2000-len(Q))),axis=0 )
p.append()
table.flush()
h5file.close()
iqfile.close()
#print 'Running!'
#FakeTemplateData()
#pulsedat = '/Users/bmazin/Data/Projects/pytest/fakepulse2.h5'
#MakeTemplate(pulsedat)
#fakedat = '/Users/bmazin/Data/Projects/pytest/fakeobs.h5'
#FakeObservation(fakedat)
#QuickLook(fakedat,0,10)
#print 'Done.' | 18,647 | 36.596774 | 173 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/__init__.py | 0 | 0 | 0 | py |
|
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/setup.py | from distutils.core import setup
setup(name='LabJackPython',
version='8-26-2011',
description='The LabJack python module.',
url='http://www.labjack.com/support/labjackpython',
author='The LabJack crew',
package_dir = {'': 'src'},
py_modules=['LabJackPython', 'Modbus', 'u3', 'u6', 'ue9', 'u12', 'skymote']
)
| 350 | 34.1 | 81 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/src/ue9.py | """
Name: ue9.py
Desc: Defines the UE9 class, which makes working with a UE9 much easier. All of
the low-level functions for the UE9 are implemented as functions of the
UE9 class. There are also a handful additional functions which improve
upon the interface provided by the low-level functions.
To learn about the low-level functions, please see Section 5.2 of the UE9 User's Guide:
http://labjack.com/support/ue9/users-guide/5.2
"""
from LabJackPython import *
import struct, socket, select, ConfigParser
def openAllUE9():
"""
A helpful function which will open all the connected UE9s. Returns a
dictionary where the keys are the serialNumber, and the value is the device
object.
"""
returnDict = dict()
for i in range(deviceCount(9)):
d = UE9(firstFound = False, devNumber = i+1)
returnDict[str(d.serialNumber)] = d
return returnDict
def parseIpAddress(bytes):
return "%s.%s.%s.%s" % (bytes[3], bytes[2], bytes[1], bytes[0] )
def unpackInt(bytes):
return struct.unpack("<I", struct.pack("BBBB", *bytes))[0]
def unpackShort(bytes):
return struct.unpack("<H", struct.pack("BB", *bytes))[0]
DEFAULT_CAL_CONSTANTS = { "AINSlopes" : { '0' : 0.000077503, '1' : 0.000038736, '2' : 0.000019353, '3' : 0.0000096764, '8' : 0.00015629 }, "AINOffsets" : { '0' : -0.012000, '1' : -0.012000, '2' : -0.012000, '3' : -0.012000, '8' : -5.1760 }, "TempSlope" : 0.012968 }
class UE9(Device):
"""
UE9 Class for all UE9 specific low-level commands.
Example:
>>> import ue9
>>> d = ue9.UE9()
>>> print d.commConfig()
{'CommFWVersion': '1.47', ..., 'IPAddress': '192.168.1.114'}
"""
def __init__(self, debug = False, autoOpen = True, **kargs):
"""
Name: UE9.__init__(self)
Args: debug, True for debug information
Desc: Your basic constructor.
>>> myUe9 = ue9.UE9()
"""
Device.__init__(self, None, devType = 9)
self.debug = debug
self.calData = None
self.controlFWVersion = self.commFWVersion = None
if autoOpen:
self.open(**kargs)
def open(self, firstFound = True, serial = None, ipAddress = None, localId = None, devNumber = None, ethernet=False, handleOnly = False, LJSocket = None):
"""
Name: UE9.open(firstFound = True, ipAddress = None, localId = None, devNumber = None, ethernet=False)
Args: firstFound, Open the first found UE9
serial, open a UE9 with the given serial number.
ipAddress, Specify the IP Address of the UE9 you want to open
localId, Specify the localId of the UE9 you want to open
devNumber, Specify the USB dev number of the UE9
ethernet, set to true to connect over ethernet.
handleOnly, if True, LabJackPython will only open a handle
LJSocket, set to "<ip>:<port>" to connect to LJSocket
Desc: Opens the UE9.
>>> myUe9 = ue9.UE9(autoOpen = False)
>>> myUe9.open()
"""
Device.open(self, 9, Ethernet = ethernet, firstFound = firstFound, serial = serial, localId = localId, devNumber = devNumber, ipAddress = ipAddress, handleOnly = handleOnly, LJSocket = LJSocket)
def commConfig(self, LocalID = None, IPAddress = None, Gateway = None, Subnet = None, PortA = None, PortB = None, DHCPEnabled = None):
"""
Name: UE9.commConfig(LocalID = None, IPAddress = None, Gateway = None,
Subnet = None, PortA = None, PortB = None, DHCPEnabled = None)
Args: LocalID, Set the LocalID
IPAddress, Set the IPAdress
Gateway, Set the Gateway
Subnet, Set the Subnet
PortA, Set Port A
PortB, Set Port B
DHCPEnabled, True = Enabled, False = Disabled
Desc: Writes and reads various configuration settings associated
with the Comm processor. Section 5.2.1 of the User's Guide.
>>> myUe9 = ue9.UE9()
>>> myUe9.commConfig()
{'CommFWVersion': '1.47',
'DHCPEnabled': False,
'Gateway': '192.168.1.1',
'HWVersion': '1.10',
'IPAddress': '192.168.1.114',
'LocalID': 1,
'MACAddress': 'XX:XX:XX:XX:XX:XX',
'PortA': 52360,
'PortB': 52361,
'PowerLevel': 0,
'ProductID': 9,
'SerialNumber': 27121XXXX,
'Subnet': '255.255.255.0'}
"""
command = [ 0 ] * 38
#command[0] = Checksum8
command[1] = 0x78
command[2] = 0x10
command[3] = 0x01
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
#command[6] = Writemask. Set it along the way.
#command[7] = Reserved
if LocalID != None:
command[6] |= 1
command[8] = LocalID
if IPAddress != None:
command[6] |= (1 << 2)
ipbytes = IPAddress.split('.')
ipbytes = [ int(x) for x in ipbytes ]
ipbytes.reverse()
command[10:14] = ipbytes
if Gateway != None:
command[6] |= (1 << 3)
gwbytes = Gateway.split('.')
gwbytes = [ int(x) for x in gwbytes ]
gwbytes.reverse()
command[14:18] = gwbytes
if Subnet != None:
command[6] |= (1 << 4)
snbytes = Subnet.split('.')
snbytes = [ int(x) for x in snbytes ]
snbytes.reverse()
command[18:21] = snbytes
if PortA != None:
command[6] |= (1 << 5)
t = struct.pack("<H", PortA)
command[22] = ord(t[0])
command[23] = ord(t[1])
if PortB != None:
command[6] |= (1 << 5)
t = struct.pack("<H", PortB)
command[24] = ord(t[0])
command[25] = ord(t[1])
if DHCPEnabled != None:
command[6] |= (1 << 6)
if DHCPEnabled:
command[26] = 1
result = self._writeRead(command, 38, [], checkBytes = False)
if result[0] == 0xB8 and result[1] == 0xB8:
raise LabJackException("Device detected a bad checksum.")
elif result[1:4] != [ 0x78, 0x10, 0x01 ]:
raise LabJackException("Got incorrect command bytes.")
elif not verifyChecksum(result):
raise LabJackException("Checksum was incorrect.")
self.localId = result[8]
self.powerLevel = result[9]
self.ipAddress = parseIpAddress(result[10:14])
self.gateway = parseIpAddress(result[14:18])
self.subnet = parseIpAddress(result[18:22])
self.portA = struct.unpack("<H", struct.pack("BB", *result[22:24]))[0]
self.portB = struct.unpack("<H", struct.pack("BB", *result[24:26]))[0]
self.DHCPEnabled = bool(result[26])
self.productId = result[27]
macBytes = result[28:34]
self.macAddress = "%02X:%02X:%02X:%02X:%02X:%02X" % (result[33], result[32], result[31], result[30], result[29], result[28])
self.serialNumber = struct.unpack("<I", struct.pack("BBBB", result[28], result[29], result[30], 0x10))[0]
self.hwVersion = "%s.%02d" % (result[35], result[34])
self.commFWVersion = "%s.%02d" % (result[37], result[36])
self.firmwareVersion = [self.controlFWVersion, self.commFWVersion]
return { 'LocalID' : self.localId, 'PowerLevel' : self.powerLevel, 'IPAddress' : self.ipAddress, 'Gateway' : self.gateway, 'Subnet' : self.subnet, 'PortA' : self.portA, 'PortB' : self.portB, 'DHCPEnabled' : self.DHCPEnabled, 'ProductID' : self.productId, 'MACAddress' : self.macAddress, 'HWVersion' : self.hwVersion, 'CommFWVersion' : self.commFWVersion, 'SerialNumber' : self.serialNumber}
def flushBuffer(self):
"""
Name: UE9.flushBuffer()
Args: None
Desc: Resets the pointers to the stream buffer to make it empty.
>>> myUe9 = ue9.UE9()
>>> myUe9.flushBuffer()
"""
command = [ 0x08, 0x08 ]
self._writeRead(command, 2, [], False)
def discoveryUDP(self):
"""
Name: UE9.discoveryUDP()
Args: None
Desc: Sends a UDP Broadcast packet and returns a dictionary of the
result. The dictionary contains all the things that are in the
commConfig dictionary.
>>> myUe9 = ue9.UE9()
>>> myUe9.discoveryUDP()
{'192.168.1.114': {'CommFWVersion': '1.47', ... },
'192.168.1.209': {'CommFWVersion': '1.47', ... }}
"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
host = '255.255.255.255'
port = 52362
addr = (host,port)
sndBuffer = [0] * 6
sndBuffer[0] = 0x22
sndBuffer[1] = 0x78
sndBuffer[2] = 0x00
sndBuffer[3] = 0xA9
sndBuffer[4] = 0x00
sndBuffer[5] = 0x00
packFormat = "B" * len(sndBuffer)
tempString = struct.pack(packFormat, *sndBuffer)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.sendto(tempString, addr)
inputs = [s]
ue9s = {}
listen = True
while listen:
#We will wait 2 seconds for a response from a Ue9
rs,ws,es = select.select(inputs, [], [], 1)
listen = False
for r in rs:
if r is s:
data,addr = s.recvfrom(38)
ue9s[addr[0]] = data
listen = True
s.close()
for ip, data in ue9s.items():
data = list(struct.unpack("B"*38, data))
ue9 = { 'LocalID' : data[8], 'PowerLevel' : data[9] , 'IPAddress' : parseIpAddress(data[10:14]), 'Gateway' : parseIpAddress(data[14:18]), 'Subnet' : parseIpAddress(data[18:23]), 'PortA' : struct.unpack("<H", struct.pack("BB", *data[22:24]))[0], 'PortB' : struct.unpack("<H", struct.pack("BB", *data[24:26]))[0], 'DHCPEnabled' : bool(data[26]), 'ProductID' : data[27], 'MACAddress' : "%02X:%02X:%02X:%02X:%02X:%02X" % (data[33], data[32], data[31], data[30], data[29], data[28]), 'SerialNumber' : struct.unpack("<I", struct.pack("BBBB", data[28], data[29], data[30], 0x10))[0], 'HWVersion' : "%s.%02d" % (data[35], data[34]), 'CommFWVersion' : "%s.%02d" % (data[37], data[36])}
ue9s[ip] = ue9
return ue9s
def controlConfig(self, PowerLevel = None, FIODir = None, FIOState = None, EIODir = None, EIOState = None, CIODirection = None, CIOState = None, MIODirection = None, MIOState = None, DoNotLoadDigitalIODefaults = None, DAC0Enable = None, DAC0 = None, DAC1Enable = None, DAC1 = None):
"""
Name: UE9.controlConfig(PowerLevel = None, FIODir = None,
FIOState = None, EIODir = None,
EIOState = None, CIODirection = None, CIOState = None,
MIODirection = None, MIOState = None,
DoNotLoadDigitalIODefaults = None, DAC0Enable = None,
DAC0 = None, DAC1Enable = None, DAC1 = None)
Args: PowerLevel, 0 = Fixed High, 48 MHz, 1 = Fixed low, 6 MHz
FIODir, Direction of FIOs
FIOState, State of FIOs
EIODir, Direction of EIOs
EIOState, State of EIOs
CIODirection, Direction of CIOs (max of 4)
CIOState, State of CIOs (max of 4)
MIODirection, Direction of MIOs (max of 3)
MIOState, Direction of MIOs (max of 3)
DoNotLoadDigitalIODefaults, Set True, to not load the defaults
DAC0Enable, True = DAC0 Enabled, False = DAC0 Disabled
DAC0, The default value for DAC0
DAC1Enable, True = DAC1 Enabled, False = DAC1 Disabled
DAC1, The default value for DAC1
Desc: Configures various parameters associated with the Control
processor. Affects only the power-up values, not current
state. See section 5.3.2 of the User's Guide.
>>> myUe9 = ue9.UE9()
>>> myUe9.controlConfig()
{'CIODirection': 0,
'CIOState': 0,
'ControlBLVersion': '1.12',
'ControlFWVersion': '1.97',
'DAC0': 0,
'DAC0 Enabled': False,
'DAC1': 0,
'DAC1 Enabled': False,
'EIODir': 0,
'EIOState': 0,
'FIODir': 0,
'FIOState': 0,
'HiRes Flag': False,
'MIODirection': 0,
'MIOState': 0,
'PowerLevel': 0,
'ResetSource': 119}
"""
command = [ 0 ] * 18
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x06
command[3] = 0x08
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
#command[6] = Writemask. Set it along the way.
if PowerLevel != None:
command[6] |= 1
command[7] = PowerLevel
if FIODir != None:
command[6] |= (1 << 1)
command[8] = FIODir
if FIOState != None:
command[6] |= (1 << 1)
command[9] = FIOState
if EIODir != None:
command[6] |= (1 << 1)
command[10] = EIODir
if EIOState != None:
command[6] |= (1 << 1)
command[11] = EIOState
if CIODirection != None:
command[6] |= (1 << 1)
command[12] = ( CIODirection & 0xf) << 4
if CIOState != None:
command[6] |= (1 << 1)
command[12] |= ( CIOState & 0xf )
if DoNotLoadDigitalIODefaults != None:
command[6] |= (1 << 1)
if DoNotLoadDigitalIODefaults:
command[13] |= (1 << 7)
if MIODirection != None:
command[6] |= (1 << 1)
command[13] |= ( MIODirection & 7 ) << 4
if MIOState != None:
command[6] |= (1 << 1)
command[13] |= ( MIOState & 7 )
if DAC0Enable != None:
command[6] |= (1 << 2)
if DAC0Enable:
command[15] = (1 << 7)
if DAC0 != None:
command[6] |= (1 << 2)
command[14] = DAC0 & 0xff
command[15] |= (DAC0 >> 8 ) & 0xf
if DAC1Enable != None:
command[6] |= (1 << 2)
if DAC1Enable:
command[17] = (1 << 7)
if DAC1 != None:
command[6] |= (1 << 2)
command[16] = DAC1 & 0xff
command[17] |= (DAC1 >> 8 ) & 0xf
result = self._writeRead(command, 24, [ 0xF8, 0x09, 0x08 ])
self.powerLevel = result[7]
self.controlFWVersion = "%s.%02d" % (result[10], result[9])
self.firmwareVersion = [self.controlFWVersion, self.commFWVersion]
self.controlBLVersion = "%s.%02d" % (result[12], result[11])
self.hiRes = bool(result[13] & 1)
self.deviceName = 'UE9'
if self.hiRes:
self.deviceName = 'UE9-Pro'
return { 'PowerLevel' : self.powerLevel, 'ResetSource' : result[8], 'ControlFWVersion' : self.controlFWVersion, 'ControlBLVersion' : self.controlBLVersion, 'HiRes Flag' : self.hiRes, 'FIODir' : result[14], 'FIOState' : result[15], 'EIODir' : result[16], 'EIOState' : result[17], 'CIODirection' : (result[18] >> 4) & 0xf, 'CIOState' : result[18] & 0xf, 'MIODirection' : (result[19] >> 4) & 7, 'MIOState' : result[19] & 7, 'DAC0 Enabled' : bool(result[21] >> 7 & 1), 'DAC0' : (result[21] & 0xf) + result[20], 'DAC1 Enabled' : bool(result[23] >> 7 & 1), 'DAC1' : (result[23] & 0xf) + result[22], 'DeviceName' : self.deviceName }
def feedback(self, FIOMask = 0, FIODir = 0, FIOState = 0, EIOMask = 0, EIODir = 0, EIOState = 0, CIOMask = 0, CIODirection = 0, CIOState = 0, MIOMask = 0, MIODirection = 0, MIOState = 0, DAC0Update = False, DAC0Enabled = False, DAC0 = 0, DAC1Update = False, DAC1Enabled = False, DAC1 = 0, AINMask = 0, AIN14ChannelNumber = 0, AIN15ChannelNumber = 0, Resolution = 0, SettlingTime = 0, AIN1_0_BipGain = 0, AIN3_2_BipGain = 0, AIN5_4_BipGain = 0, AIN7_6_BipGain = 0, AIN9_8_BipGain = 0, AIN11_10_BipGain = 0, AIN13_12_BipGain = 0, AIN15_14_BipGain = 0):
"""
Name: UE9.feedback(FIOMask = 0, FIODir = 0, FIOState = 0,
EIOMask = 0, EIODir = 0, EIOState = 0, CIOMask = 0,
CIODirection = 0, CIOState = 0, MIOMask = 0, MIODirection = 0,
MIOState = 0, DAC0Update = False, DAC0Enabled = None,
DAC0 = None, DAC1Update = False, DAC1Enabled = None, DAC1 = None,
AINMask = 0, AIN14ChannelNumber = 0, AIN15ChannelNumber = 0,
Resolution = 0, SettlingTime = 0, AIN1_0_BipGain = 0,
AIN3_2_BipGain = 0, AIN5_4_BipGain = 0, AIN7_6_BipGain = 0,
AIN9_8_BipGain = 0, AIN11_10_BipGain = 0, AIN13_12_BipGain = 0,
AIN15_14_BipGain = 0)
Args: See section 5.3.3 of the User's Guide
Desc: A very useful function that writes/reads almost every I/O on the
LabJack UE9. See section 5.3.3 of the User's Guide.
>>> myUe9 = ue9.UE9()
>>> myUe9.feedback()
{'AIN0': 0, ...
'TimerB': 0,
'TimerC': 0}
"""
command = [ 0 ] * 34
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x0E
command[3] = 0x00
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = FIOMask
command[7] = FIODir
command[8] = FIOState
command[9] = EIOMask
command[10] = EIODir
command[11] = EIOState
command[12] = CIOMask
command[13] = (CIODirection & 0xf) << 4
command[13] |= (CIOState & 0xf)
command[14] = MIOMask
command[15] = (MIODirection & 7) << 4
command[15] |= (MIOState & 7 )
if DAC0Update:
if DAC0Enabled:
command[17] = 1 << 7
command[17] |= 1 << 6
command[16] = DAC0 & 0xff
command[17] |= (DAC0 >> 8) & 0xf
if DAC0Update:
if DAC0Enabled:
command[19] = 1 << 7
command[19] |= 1 << 6
command[18] = DAC0 & 0xff
command[19] |= (DAC0 >> 8) & 0xf
command[20] = AINMask & 0xff
command[21] = (AINMask >> 8) & 0xff
command[22] = AIN14ChannelNumber
command[23] = AIN15ChannelNumber
command[24] = Resolution
command[25] = SettlingTime
command[26] = AIN1_0_BipGain
command[27] = AIN3_2_BipGain
command[28] = AIN5_4_BipGain
command[29] = AIN7_6_BipGain
command[30] = AIN9_8_BipGain
command[31] = AIN11_10_BipGain
command[32] = AIN13_12_BipGain
command[33] = AIN15_14_BipGain
result = self._writeRead(command, 64, [ 0xF8, 0x1D, 0x00], checkBytes = False)
returnDict = { 'FIODir' : result[6], 'FIOState' : result[7], 'EIODir' : result[8], 'EIOState' : result[9], 'CIODir' : (result[10] >> 4) & 0xf, 'CIOState' : result[10] & 0xf, 'MIODir' : (result[11] >> 4) & 7, 'MIOState' : result[11] & 7, 'Counter0' : unpackInt(result[44:48]), 'Counter1' : unpackInt(result[48:52]), 'TimerA' : unpackInt(result[52:56]), 'TimerB' : unpackInt(result[56:60]), 'TimerC' : unpackInt(result[60:]) }
"""
'AIN0' : b2c(unpackShort(result[12:14])), 'AIN1' : unpackShort(result[14:16]), 'AIN2' : unpackShort(result[16:18]), 'AIN3' : unpackShort(result[18:20]), 'AIN4' : unpackShort(result[20:22]), 'AIN5' : unpackShort(result[22:24]), 'AIN6' : unpackShort(result[24:26]), 'AIN7' : unpackShort(result[26:28]), 'AIN8' : unpackShort(result[28:30]), 'AIN9' : unpackShort(result[30:32]), 'AIN10' : unpackShort(result[32:34]), 'AIN11' : unpackShort(result[34:36]), 'AIN12' : unpackShort(result[36:38]), 'AIN13' : unpackShort(result[38:40]), 'AIN14' : unpackShort(result[40:42]), 'AIN15' : unpackShort(result[42:44]),
"""
b2c = self.binaryToCalibratedAnalogVoltage
g = 0
for i in range(16):
bits = unpackShort(result[(12+(2*i)):(14+(2*i))])
if i%2 == 0:
gain = command[26 + g] & 0xf
else:
gain = (command[26 + g] >> 4) & 0xf
g += 1
returnDict["AIN%s" % i] = b2c(bits, gain)
return returnDict
digitalPorts = [ 'FIO', 'EIO', 'CIO', 'MIO' ]
def singleIO(self, IOType, Channel, Dir = None, BipGain = None, State = None, Resolution = None, DAC = 0, SettlingTime = 0):
"""
Name: UE9.singleIO(IOType, Channel, Dir = None, BipGain = None, State = None, Resolution = None, DAC = 0, SettlingTime = 0)
Args: See section 5.3.4 of the User's Guide
Desc: An alternative to Feedback, is this function which writes or
reads a single output or input. See section 5.3.4 of the User's
Guide.
>>> myUe9 = ue9.UE9()
>>> myUe9.singleIO(1, 0, Dir = 1, State = 0)
{'FIO0 Direction': 1, 'FIO0 State': 0}
"""
command = [ 0 ] * 8
#command[0] = Checksum8
command[1] = 0xA3
command[2] = IOType
command[3] = Channel
if IOType == 0:
#Digital Bit Read
pass
elif IOType == 1:
#Digital Bit Write
if Dir == None or State == None:
raise LabJackException("Need to specify a direction and state")
command[4] = Dir
command[5] = State
elif IOType == 2:
#Digital Port Read
pass
elif IOType == 3:
#Digital Port Write
if Dir == None or State == None:
raise LabJackException("Need to specify a direction and state")
command[4] = Dir
command[5] = State
elif IOType == 4:
#Analog In
if BipGain == None or Resolution == None or SettlingTime == None:
raise LabJackException("Need to specify a BipGain, Resolution, and SettlingTime")
command[4] = BipGain
command[5] = Resolution
command[6] = SettlingTime
elif IOType == 5:
#Analog Out
if DAC == None:
raise LabJackException("Need to specify a DAC Value")
command[4] = DAC & 0xff
command[5] = (DAC >> 8) & 0xf
result = self._writeRead(command, 8, [ 0xA3 ], checkBytes = False)
if result[2] == 0:
#Digital Bit Read
return { "FIO%s State" % result[3] : result[5], "FIO%s Direction" % result[3] : result[4] }
elif result[2] == 1:
#Digital Bit Write
return { "FIO%s State" % result[3] : result[5], "FIO%s Direction" % result[3] : result[4] }
elif result[2] == 2:
#Digital Port Read
return { "%s Direction" % self.digitalPorts[result[3]] : result[4], "%s State" % self.digitalPorts[result[3]] : result [5] }
elif result[2] == 3:
#Digital Port Write
return { "%s Direction" % self.digitalPorts[result[3]] : result[4], "%s State" % self.digitalPorts[result[3]] : result [5] }
elif result[2] == 4:
#Analog In
ain = float((result[6] << 16) + (result[5] << 8) + result[4]) / 256
return { "AIN%s" % result[3] : ain }
elif result[2] == 5:
#Analog Out
dac = (result[6] << 16) + (result[5] << 8) + result[4]
return { "DAC%s" % result[3] : dac }
def timerCounter(self, TimerClockDivisor=0, UpdateConfig=False, NumTimersEnabled=0, Counter0Enabled=False, Counter1Enabled=False, TimerClockBase=LJ_tcSYS, ResetTimer0=False, ResetTimer1=False, ResetTimer2=False, ResetTimer3=False, ResetTimer4=False, ResetTimer5=False, ResetCounter0=False, ResetCounter1=False, Timer0Mode=None, Timer0Value=None, Timer1Mode=None, Timer1Value=None, Timer2Mode=None, Timer2Value=None, Timer3Mode=None, Timer3Value=None, Timer4Mode=None, Timer4Value=None, Timer5Mode=None, Timer5Value=None):
"""
Name: UE9.timerCounter(TimerClockDivisor=0, UpdateConfig=False,
NumTimersEnabled=0, Counter0Enabled=False,
Counter1Enabled=True, TimerClockBase=LJ_tcSYS,
ResetTimer0=False, ResetTimer1=False,
ResetTimer2=False, ResetTimer3=False,
ResetTimer4=False, ResetTimer5=False,
ResetCounter0=False, ResetCounter1=False,
Timer0Mode=None, Timer0Value=None,
Timer1Mode=None, Timer1Value=None,
Timer2Mode=None, Timer2Value=None,
Timer3Mode=None, Timer3Value=None,
Timer4Mode=None, Timer4Value=None,
Timer5Mode=None, Timer5Value=None)
Args: TimerClockDivisor, The timer clock is divided by this value, or
divided by 256 if this value is 0. The
UpdateConfig bit must be set to change this
parameter.
UpdateConfig, If true, counters and timers are re-configured by
this call. If false, the timer/counter configuration
will remain the same.
NumTimersEnabled, The number of timers enabled
TimerClockBase, The determines the timer base clock which is used
by all output mode timers. The choices are a fixed
750 kHz clock source, or the system clock. The UE9
is by default in high power mode which means the
system clock is fixed at 48 MHz. The UpdateConfig
bit must be set to change this parameter.
ResetTimer#, Resets the specified timer
ResetCounter#, Resets the specified counter
Timer#Mode, These values are only updated if the UpdateConfig
parameter is True. See section 5.3.5 in the User's
Guide for values to pass to configure a timer.
Timer#Value, Only updates if UpdateReset is True. The meaning of
this parameter varies with the timer mode. See
Section 2.10 for further information.
Desc: Enables, configures, and reads the counters and timers. See
section 5.3.5 of the User's Guide for more information.
>>> dev = UE9()
>>> dev.timerCounter()
{'Counter0Enabled': False, 'Timer5Enabled': False, 'Timer0Enabled': False, 'Timer1': 0, 'Timer4': 0, 'Timer3Enabled': False, 'Timer4Enabled': False, 'Timer5': 0, 'Counter1Enabled': False, 'Timer3': 0, 'Timer2': 0, 'Timer1Enabled': False, 'Timer0': 0, 'Timer2Enabled': False}
"""
command = [ 0 ] * 30
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x0C
command[3] = 0x18
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = TimerClockDivisor
# Create EnableMask
if UpdateConfig:
command[7] = 128 | NumTimersEnabled
if Counter0Enabled: command[7] = command[7] | 8
if Counter1Enabled: command[7] = command[7] | 16
else: UpdateConfig = 0
# Configure clock base
command[8] = TimerClockBase
# Configure UpdateReset
if ResetTimer0: command[9] = 1
if ResetTimer1: command[9] = command[9] | 2
if ResetTimer2: command[9] = command[9] | 4
if ResetTimer3: command[9] = command[9] | 8
if ResetTimer4: command[9] = command[9] | 16
if ResetTimer5: command[9] = command[9] | 32
if ResetCounter0: command[9] = command[9] | 64
if ResetCounter1: command[9] = command[9] | 128
# Configure timers and counters if we are updating the configuration
if UpdateConfig:
if NumTimersEnabled >= 1:
if Timer0Mode == None: raise LabJackException("Need to specify a mode for Timer0")
if Timer0Value == None: raise LabJackException("Need to specify a value for Timer0")
command[10] = Timer0Mode
command[11] = Timer0Value & 0xff
command[12] = (Timer0Value >> 8) & 0xff
if NumTimersEnabled >= 2:
if Timer1Mode == None: raise LabJackException("Need to specify a mode for Timer1")
if Timer1Value == None: raise LabJackException("Need to specify a value for Timer1")
command[13] = Timer1Mode
command[14] = Timer1Value & 0xff
command[15] = (Timer1Value >> 8) & 0xff
if NumTimersEnabled >= 3:
if Timer2Mode == None: raise LabJackException("Need to specify a mode for Timer2")
if Timer2Value == None: raise LabJackException("Need to specify a value for Timer2")
command[16] = Timer2Mode
command[17] = Timer2Value & 0xff
command[18] = (Timer2Value >> 8) & 0xff
if NumTimersEnabled >= 4:
if Timer3Mode == None: raise LabJackException("Need to specify a mode for Timer3")
if Timer3Value == None: raise LabJackException("Need to specify a value for Timer3")
command[19] = Timer3Mode
command[20] = Timer3Value & 0xff
command[21] = (Timer3Value >> 8) & 0xff
if NumTimersEnabled >= 5:
if Timer4Mode == None: raise LabJackException("Need to specify a mode for Timer4")
if Timer4Value == None: raise LabJackException("Need to specify a value for Timer4")
command[22] = Timer4Mode
command[23] = Timer4Value & 0xff
command[24] = (Timer4Value >> 8) & 0xff
if NumTimersEnabled == 6:
if Timer5Mode == None: raise LabJackException("Need to specify a mode for Timer5")
if Timer5Value == None: raise LabJackException("Need to specify a value for Timer5")
command[25] = Timer5Mode
command[26] = Timer5Value & 0xff
command[27] = (Timer5Value >> 8) & 0xff
if NumTimersEnabled > 7: raise LabJackException("Only a maximum of 5 timers can be enabled")
command[28] = 0#command[28] = Counter0Mode
command[29] = 0#command[29] = Counter1Mode
result = self._writeRead(command, 40, [ 0xF8, 0x11, 0x18 ])
# Parse the results
returnValue = {}
for i in range(0,6):
returnValue["Timer" + str(i) + "Enabled"] = result[7] >> i & 1 == 1
for i in range(0,2):
returnValue["Counter" + str(i) + "Enabled"] = result[7] >> i + 6 & 1 == 1
for i in range(0, 6):
returnValue["Timer" + str(i)] = unpackInt(result[8+i*4:12+i*4])
for i in range(0,2):
counterValue = [0]
counterValue.extend(result[32+i*4:35+i*4])
returnValue["Counter" + str(i)] = unpackInt(counterValue)
return returnValue
def readMem(self, BlockNum):
"""
Name: UE9.readMem(BlockNum)
Args: BlockNum, which block to read
ReadCal, set to True to read the calibration data
Desc: Reads 1 block (128 bytes) from the non-volatile user or
calibration memory. Please read section 5.3.10 of the user's
guide before you do something you may regret.
>>> myUE9 = UE9()
>>> myUE9.readMem(0)
[ < userdata stored in block 0 > ]
NOTE: Do not call this function while streaming.
"""
command = [ 0 ] * 8
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x01
command[3] = 0x2A
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = 0x00
command[7] = BlockNum
result = self._writeRead(command, 136, [ 0xF8, 0x41, 0x2A ])
return result[8:]
def writeMem(self, BlockNum, Data):
"""
Name: UE9.writeMem(BlockNum, Data, WriteCal=False)
Args: BlockNum, which block to write
Data, a list of bytes to write
Desc: Writes 1 block (128 bytes) from the non-volatile user or
calibration memory. Please read section 5.3.11 of the user's
guide before you do something you may regret.
>>> myUE9 = UE9()
>>> myUE9.writeMem(0, [ < userdata to be stored in block 0 > ])
NOTE: Do not call this function while streaming.
"""
if not isinstance(Data, list):
raise LabJackException("Data must be a list of bytes")
command = [ 0 ] * 136
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x41
command[3] = 0x28
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = 0x00
command[7] = BlockNum
command[8:] = Data
self._writeRead(command, 8, [0xF8, 0x01, command[3]])
def eraseMem(self, EraseCal=False):
"""
Name: UE9.eraseMem(EraseCal=False)
Args: EraseCal, set to True to erase the calibration memory.
Desc: The UE9 uses flash memory that must be erased before writing.
Please read section 5.2.12 of the user's guide before you do
something you may regret.
>>> myUE9 = UE9()
>>> myUE9.eraseMem()
NOTE: Do not call this function while streaming.
"""
command = [ 0 ] * 8
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x01
command[3] = 0x29
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
if EraseCal:
command[6] = 0x4C
command[7] = 0x4A
else:
command[6] = 0x00
command[7] = 0x00
self._writeRead(command, 8, [0xF8, 0x01, command[3]])
def watchdogConfig(self, ResetCommonTimeout = False, ResetControlonTimeout = False, UpdateDigitalIOB = False, UpdateDigitalIOA = False, UpdateDAC1onTimeout = False, UpdateDAC0onTimeout = False, TimeoutPeriod = 60, DIOConfigA = 0, DIOConfigB = 0, DAC0Enabled = False, DAC0 = 0, DAC1Enabled = False, DAC1 = 0):
command = [ 0 ] * 16
command[1] = 0xF8
command[2] = 0x05
command[3] = 0x09
if ResetCommonTimeout:
command[7] |= (1 << 6)
if ResetControlonTimeout:
command[7] |= (1 << 5)
if UpdateDigitalIOB:
command[7] |= (1 << 4)
if UpdateDigitalIOA:
command[7] |= (1 << 3)
if UpdateDAC1onTimeout:
command[7] |= (1 << 1)
if UpdateDAC0onTimeout:
command[7] |= (1 << 0)
t = struct.pack("<H", TimeoutPeriod)
command[8] = ord(t[0])
command[9] = ord(t[1])
command[10] = DIOConfigA
command[11] = DIOConfigB
command[12] = DAC0 & 0xff
command[13] = (int(DAC0Enabled) << 7) + (DAC0 & 0xf)
command[14] = DAC1 & 0xff
command[15] = (int(DAC1Enabled) << 7) + (DAC1 & 0xf)
result = self._writeRead(command, 8, [0xF8, 0x01, 0x09])
return { 'UpdateDAC0onTimeout' : bool(result[7]& 1), 'UpdateDAC1onTimeout' : bool((result[7] >> 1) & 1), 'UpdateDigitalIOBonTimeout' : bool((result[7] >> 3) & 1), 'UpdateDigitalIOBonTimeout' : bool((result[7] >> 4) & 1), 'ResetControlOnTimeout' : bool((result[7] >> 5) & 1), 'ResetCommOnTimeout' : bool((result[7] >> 6) & 1) }
def watchdogRead(self):
"""
Name: UE9.watchdogRead()
Args: None
Desc: Reads the current watchdog settings.
"""
command = [ 0 ] * 6
command[1] = 0xF8
command[2] = 0x00
command[3] = 0x09
command = setChecksum8(command, 6)
result = self._writeRead(command, 16, [0xF8, 0x05, 0x09], checksum = False)
return { 'UpdateDAC0onTimeout' : bool(result[7]& 1), 'UpdateDAC1onTimeout' : bool((result[7] >> 1) & 1), 'UpdateDigitalIOBonTimeout' : bool((result[7] >> 3) & 1), 'UpdateDigitalIOBonTimeout' : bool((result[7] >> 4) & 1), 'ResetControlOnTimeout' : bool((result[7] >> 5) & 1), 'ResetCommOnTimeout' : bool((result[7] >> 6) & 1), 'TimeoutPeriod' : struct.unpack('<H', struct.pack("BB", *result[8:10]))[0], 'DIOConfigA' : result[10], 'DIOConfigB' : result[11], 'DAC0' : struct.unpack('<H', struct.pack("BB", *result[8:10]))[0], 'DAC1' : struct.unpack('<H', struct.pack("BB", *result[8:10]))[0] }
SPIModes = { 'A' : 0, 'B' : 1, 'C' : 2, 'D' : 3 }
def spi(self, SPIBytes, AutoCS=True, DisableDirConfig = False, SPIMode = 'A', SPIClockFactor = 0, CSPINNum = 1, CLKPinNum = 0, MISOPinNum = 3, MOSIPinNum = 2):
"""
Name: UE9.spi(SPIBytes, AutoCS=True, DisableDirConfig = False,
SPIMode = 'A', SPIClockFactor = 0, CSPINNum = 1,
CLKPinNum = 0, MISOPinNum = 3, MOSIPinNum = 2)
Args: SPIBytes, a list of bytes to be transferred.
See Section 5.3.16 of the user's guide.
Desc: Sends and receives serial data using SPI synchronous
communication.
"""
print SPIBytes
if not isinstance(SPIBytes, list):
raise LabJackException("SPIBytes MUST be a list of bytes")
numSPIBytes = len(SPIBytes)
oddPacket = False
if numSPIBytes%2 != 0:
SPIBytes.append(0)
numSPIBytes = numSPIBytes + 1
oddPacket = True
command = [ 0 ] * (13 + numSPIBytes)
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 4 + (numSPIBytes/2)
command[3] = 0x3A
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
if AutoCS:
command[6] |= (1 << 7)
if DisableDirConfig:
command[6] |= (1 << 6)
command[6] |= ( self.SPIModes[SPIMode] & 3 )
command[7] = SPIClockFactor
#command[8] = Reserved
command[9] = CSPINNum
command[10] = CLKPinNum
command[11] = MISOPinNum
command[12] = MOSIPinNum
command[13] = numSPIBytes
if oddPacket:
command[13] = numSPIBytes - 1
command[14:] = SPIBytes
result = self._writeRead(command, 8+numSPIBytes, [ 0xF8, 1+(numSPIBytes/2), 0x3A ])
return result[8:]
def asynchConfig(self, Update = True, UARTEnable = True, DesiredBaud = 9600):
"""
Name: UE9.asynchConfig(Update = True, UARTEnable = True,
DesiredBaud = 9600)
Args: See section 5.3.17 of the User's Guide.
Desc: Configures the U3 UART for asynchronous communication.
returns a dictionary:
{
'Update' : True means new parameters were written
'UARTEnable' : True means the UART is enabled
'BaudFactor' : The baud factor being used
}
"""
command = [ 0 ] * 10
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x02
command[3] = 0x14
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
#command[6] = 0x00
if Update:
command[7] |= ( 1 << 7 )
if UARTEnable:
command[7] |= ( 1 << 6 )
BaudFactor = (2**16) - 48000000/(2 * DesiredBaud)
t = struct.pack("<H", BaudFactor)
command[8] = ord(t[0])
command[9] = ord(t[1])
result = self._writeRead(command, 10, [0xF8, 0x02, 0x14])
returnDict = {}
if ( ( result[7] >> 7 ) & 1 ):
returnDict['Update'] = True
else:
returnDict['Update'] = False
if ( ( result[7] >> 6 ) & 1):
returnDict['UARTEnable'] = True
else:
returnDict['UARTEnable'] = False
returnDict['BaudFactor'] = struct.unpack("<H", struct.pack("BB", *result[8:]))[0]
return returnDict
def asynchTX(self, AsynchBytes):
"""
Name: UE9.asynchTX(AsynchBytes)
Args: AsynchBytes, must be a list of bytes to transfer.
Desc: Sends bytes to the U3 UART which will be sent asynchronously on
the transmit line. See section 5.3.18 of the user's guide.
returns a dictionary:
{
'NumAsynchBytesSent' : Number of Asynch Bytes Sent
'NumAsynchBytesInRXBuffer' : How many bytes are currently in the
RX buffer.
}
"""
if not isinstance(AsynchBytes, list):
raise LabJackException("AsynchBytes must be a list")
numBytes = len(AsynchBytes)
oddPacket = False
if numBytes%2 != 0:
AsynchBytes.append(0)
numBytes = numBytes+1
oddPacket = True
command = [ 0 ] * ( 8 + numBytes)
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 1 + ( numBytes/2 )
command[3] = 0x15
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
#command[6] = 0x00
command[7] = numBytes
if oddPacket:
command[7] = numBytes - 1
command[8:] = AsynchBytes
result = self._writeRead(command, 10, [0xF8, 0x02, 0x15])
return { 'NumAsynchBytesSent' : result[7], 'NumAsynchBytesInRXBuffer' : result[8] }
def asynchRX(self, Flush = False):
"""
Name: UE9.asynchRX(Flush = False)
Args: Flush, Set to True to flush
Desc: Reads the oldest 32 bytes from the U3 UART RX buffer
(received on receive terminal). The buffer holds 256 bytes. See
section 5.3.19 of the User's Guide.
returns a dictonary:
{
'AsynchBytes' : List of received bytes
'NumAsynchBytesInRXBuffer' : Number of AsynchBytes are in the RX
Buffer.
}
"""
command = [ 0 ] * 8
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x01
command[3] = 0x16
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
#command[6] = 0x00
if Flush:
command[7] = 1
result = self._writeRead(command, 40, [0xF8, 0x11, 0x16])
return { 'AsynchBytes' : result[8:], 'NumAsynchBytesInRXBuffer' : result[7] }
def i2c(self, Address, I2CBytes, EnableClockStretching = False, NoStopWhenRestarting = False, ResetAtStart = False, SpeedAdjust = 0, SDAPinNum = 1, SCLPinNum = 0, NumI2CBytesToReceive = 0, AddressByte = None):
"""
Name: UE9.i2c(Address, I2CBytes, ResetAtStart = False, EnableClockStretching = False, SpeedAdjust = 0, SDAPinNum = 0, SCLPinNum = 1, NumI2CBytesToReceive = 0, AddressByte = None)
Args: Address, the address (not shifted over)
I2CBytes, must be a list of bytes to send.
See section 5.3.20 of the user's guide.
AddressByte, The address as you would put it in the lowlevel
packet. Overrides Address. Optional
Desc: Sends and receives serial data using I2C synchronous
communication.
"""
if not isinstance(I2CBytes, list):
raise LabJackException("I2CBytes must be a list")
numBytes = len(I2CBytes)
oddPacket = False
if numBytes%2 != 0:
I2CBytes.append(0)
numBytes = numBytes + 1
oddPacket = True
command = [ 0 ] * (14 + numBytes)
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 4 + (numBytes/2)
command[3] = 0x3B
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
if ResetAtStart:
command[6] |= (1 << 1)
if NoStopWhenRestarting:
command[6] |= (1 << 2)
if EnableClockStretching:
command[6] |= (1 << 3)
command[7] = SpeedAdjust
command[8] = SDAPinNum
command[9] = SCLPinNum
if AddressByte != None:
command[10] = AddressByte
else:
command[10] = Address << 1
command[12] = numBytes
if oddPacket:
command[12] = numBytes-1
command[13] = NumI2CBytesToReceive
command[14:] = I2CBytes
oddResponse = False
if NumI2CBytesToReceive%2 != 0:
NumI2CBytesToReceive = NumI2CBytesToReceive+1
oddResponse = True
result = self._writeRead(command, 12+NumI2CBytesToReceive, [0xF8, (3+(NumI2CBytesToReceive/2)), 0x3B])
if len(result) > 12:
if oddResponse:
return { 'AckArray' : result[8:12], 'I2CBytes' : result[12:-1] }
else:
return { 'AckArray' : result[8:12], 'I2CBytes' : result[12:] }
else:
return { 'AckArray' : result[8:], 'I2CBytes' : [] }
def sht1x(self, DataPinNum = 0, ClockPinNum = 1, SHTOptions = 0xc0):
"""
Name: UE9.sht1x(DataPinNum = 0, ClockPinNum = 1, SHTOptions = 0xc0)
Args: DataPinNum, Which pin is the Data line
ClockPinNum, Which line is the Clock line
SHTOptions (and proof people read documentation):
bit 7 = Read Temperature
bit 6 = Read Realtive Humidity
bit 2 = Heater. 1 = on, 0 = off
bit 1 = Reserved at 0
bit 0 = Resolution. 1 = 8 bit RH, 12 bit T; 0 = 12 RH, 14 bit T
Desc: Reads temperature and humidity from a Sensirion SHT1X sensor.
Section 5.3.21 of the User's Guide.
"""
command = [ 0 ] * 10
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x02
command[3] = 0x39
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = DataPinNum
command[7] = ClockPinNum
#command[8] = Reserved
command[9] = SHTOptions
result = self._writeRead(command, 16, [ 0xF8, 0x05, 0x39])
val = (result[11]*256) + result[10]
temp = -39.60 + 0.01*val
val = (result[14]*256) + result[13]
humid = -4 + 0.0405*val + -.0000028*(val*val)
humid = (temp - 25)*(0.01 + 0.00008*val) + humid
return { 'StatusReg' : result[8], 'StatusCRC' : result[9], 'Temperature' : temp, 'TemperatureCRC' : result[12], 'Humidity' : humid, 'HumidityCRC' : result[15] }
def getAIN(self, channel, BipGain = 0x00, Resolution = 12, SettlingTime = 0):
"""
Name: UE9.getAIN(channel, BipGain = 0x00, Resolution = 12,
SettlingTime = 0)
"""
bits = self.singleIO(4, channel, BipGain = BipGain, Resolution = Resolution, SettlingTime = SettlingTime )
return self.binaryToCalibratedAnalogVoltage(bits["AIN%s"%channel], BipGain)
def getTemperature(self):
"""
Name: UE9.getTemperature()
"""
if self.calData is None:
self.getCalibrationData()
bits = self.singleIO(4, 133, BipGain = 0x00, Resolution = 12, SettlingTime = 0 )
return self.binaryToCalibratedAnalogTemperature(bits["AIN133"])
def binaryToCalibratedAnalogVoltage(self, bits, gain):
""" Name: UE9.binaryToCalibratedAnalogVoltage( bits, gain )
Args: bits, the binary value to be converted
gain, the gain used. Please use the values from 5.3.3 of the
UE9's user's guide.
Desc: Converts the binary value returned from Feedback and SingleIO
to a calibrated, analog voltage.
>>> print d.singleIO(4, 1, BipGain = 0x01, Resolution = 12 )
{'AIN1': 65520.0}
>>> print d.binaryToCalibratedAnalogVoltage(65520.0, 0x01)
2.52598272
"""
if self.calData is not None:
slope = self.calData['AINSlopes'][str(gain)]
offset = self.calData['AINOffsets'][str(gain)]
else:
slope = DEFAULT_CAL_CONSTANTS['AINSlopes'][str(gain)]
offset = DEFAULT_CAL_CONSTANTS['AINOffsets'][str(gain)]
return (bits * slope) + offset
def binaryToCalibratedAnalogTemperature(self, bits):
if self.calData is not None:
return bits * self.calData['TempSlope']
else:
return bits * DEFAULT_CAL_CONSTANTS['TempSlope']
def getCalibrationData(self):
""" Name: UE9.getCalibrationData()
Args: None
Desc: Reads the calibration constants off the UE9, and stores them
for use with binaryToCalibratedAnalogVoltage.
Note: Please note that this function calls controlConfig to check
if the device is a UE9 or not. It also makes calls to
readMem, so please don't call this while streaming.
"""
# Insure that we know if we are dealing with a Pro or not.
self.controlConfig()
results = dict()
ainslopes = { '0' : None, '1' : None, '2' : None, '3' : None, '8' : None }
ainoffsets = { '0' : None, '1' : None, '2' : None, '3' : None, '8' : None }
dacslopes = { '0' : None, '1' : None }
dacoffsets = { '0' : None, '1' : None }
tempslope = None
memBlock = self.readMem(0)
ainslopes['0'] = toDouble(memBlock[:8])
ainoffsets['0'] = toDouble(memBlock[8:16])
ainslopes['1'] = toDouble(memBlock[16:24])
ainoffsets['1'] = toDouble(memBlock[24:32])
ainslopes['2'] = toDouble(memBlock[32:40])
ainoffsets['2'] = toDouble(memBlock[40:48])
ainslopes['3'] = toDouble(memBlock[48:56])
ainoffsets['3'] = toDouble(memBlock[56:])
memBlock = self.readMem(1)
ainslopes['8'] = toDouble(memBlock[:8])
ainoffsets['8'] = toDouble(memBlock[8:16])
# Read DAC and Temperature slopes
memBlock = self.readMem(2)
dacslopes['0'] = toDouble(memBlock[:8])
dacoffsets['0'] = toDouble(memBlock[8:16])
dacslopes['1'] = toDouble(memBlock[16:24])
dacoffsets['1'] = toDouble(memBlock[24:32])
tempslope = toDouble(memBlock[32:40])
if self.deviceName.endswith("Pro"):
memBlock = self.readMem(3)
ainslopes['0'] = toDouble(memBlock[:8])
ainoffsets['0'] = toDouble(memBlock[8:16])
memBlock = self.readMem(4)
ainslopes['8'] = toDouble(memBlock[:8])
ainoffsets['8'] = toDouble(memBlock[8:16])
self.calData = { "AINSlopes" : ainslopes, "AINOffsets" : ainoffsets, 'TempSlope' : tempslope, "DACSlopes" : dacslopes, "DACOffsets" : dacoffsets }
return self.calData
def readDefaultsConfig(self):
"""
Name: UE9.readDefaultsConfig( )
Args: None
Desc: Reads the power-up defaults stored in flash.
"""
results = dict()
defaults = self.readDefaults(0)
results['FIODirection'] = defaults[4]
results['FIOState'] = defaults[5]
results['EIODirection'] = defaults[6]
results['EIOState'] = defaults[7]
results['CIODirection'] = defaults[8]
results['CIOState'] = defaults[9]
results['MIODirection'] = defaults[10]
results['MIOState'] = defaults[11]
results['ConfigWriteMask'] = defaults[16]
results['NumOfTimersEnable'] = defaults[17]
results['CounterMask'] = defaults[18]
results['PinOffset'] = defaults[19]
defaults = self.readDefaults(1)
results['ClockSource'] = defaults[0]
results['Divisor'] = defaults[1]
results['TMR0Mode'] = defaults[16]
results['TMR0ValueL'] = defaults[17]
results['TMR0ValueH'] = defaults[18]
results['TMR1Mode'] = defaults[20]
results['TMR1ValueL'] = defaults[21]
results['TMR1ValueH'] = defaults[22]
results['TMR2Mode'] = defaults[24]
results['TMR2ValueL'] = defaults[25]
results['TMR2ValueH'] = defaults[26]
results['TMR3Mode'] = defaults[28]
results['TMR3ValueL'] = defaults[29]
results['TMR3ValueH'] = defaults[30]
defaults = self.readDefaults(2)
results['TMR4Mode'] = defaults[0]
results['TMR4ValueL'] = defaults[1]
results['TMR4ValueH'] = defaults[2]
results['TMR5Mode'] = defaults[4]
results['TMR5ValueL'] = defaults[5]
results['TMR5ValueH'] = defaults[6]
results['DAC0'] = struct.unpack( ">H", struct.pack("BB", *defaults[16:18]) )[0]
results['DAC1'] = struct.unpack( ">H", struct.pack("BB", *defaults[20:22]) )[0]
defaults = self.readDefaults(3)
for i in range(14):
results["AIN%sRes" % i] = defaults[i]
results["AIN%sBPGain" % i] = defaults[i+16]
defaults = self.readDefaults(4)
for i in range(14):
results["AIN%sSettling" % i] = defaults[i]
return results
def exportConfig(self):
"""
Name: UE9.exportConfig( )
Args: None
Desc: Takes the current configuration and puts it into a ConfigParser
object. Useful for saving the setup of your UE9.
"""
# Make a new configuration file
parser = ConfigParser.SafeConfigParser()
# Change optionxform so that options preserve their case.
parser.optionxform = str
# Local Id and name
self.commConfig()
self.controlConfig()
section = "Identifiers"
parser.add_section(section)
parser.set(section, "Local ID", str(self.localId))
parser.set(section, "Name", str(self.getName()))
parser.set(section, "Device Type", str(self.devType))
parser.set(section, "MAC Address", str(self.macAddress))
# Comm Config settings
section = "Communication"
parser.add_section(section)
parser.set(section, "DHCPEnabled", str(self.DHCPEnabled))
parser.set(section, "IP Address", str(self.ipAddress))
parser.set(section, "Subnet", str(self.subnet))
parser.set(section, "Gateway", str(self.gateway))
parser.set(section, "PortA", str(self.portA))
parser.set(section, "PortB", str(self.portB))
# FIO Direction / State
section = "FIOs"
parser.add_section(section)
parser.set(section, "FIO Directions", str( self.readRegister(6750) ))
parser.set(section, "FIO States", str( self.readRegister(6700) ))
parser.set(section, "EIO Directions", str( self.readRegister(6751) ))
parser.set(section, "EIO States", str( self.readRegister(6701) ))
parser.set(section, "CIO Directions", str( self.readRegister(6752) ))
parser.set(section, "CIO States", str( self.readRegister(6702) ))
#parser.set(section, "MIOs Directions", str( self.readRegister(50591) ))
#parser.set(section, "MIOs States", str( self.readRegister(50591) ))
# DACs
section = "DACs"
parser.add_section(section)
dac0 = self.readRegister(5000)
dac0 = max(dac0, 0)
dac0 = min(dac0, 5)
parser.set(section, "DAC0", "%0.2f" % dac0)
dac1 = self.readRegister(5002)
dac1 = max(dac1, 0)
dac1 = min(dac1, 5)
parser.set(section, "DAC1", "%0.2f" % dac1)
# Timer Clock Configuration
section = "Timer Clock Speed Configuration"
parser.add_section(section)
parser.set(section, "TimerClockBase", str(self.readRegister(7000)))
parser.set(section, "TimerClockDivisor", str(self.readRegister(7002)))
# Timers / Counters
section = "Timers And Counters"
parser.add_section(section)
nte = self.readRegister(50501)
cm = self.readRegister(50502)
ec0 = bool( cm & 1 )
ec1 = bool( (cm >> 1) & 1 )
parser.set(section, "NumberTimersEnabled", str(nte) )
parser.set(section, "Counter0Enabled", str(ec0) )
parser.set(section, "Counter1Enabled", str(ec1) )
for i in range(nte):
mode, value = self.readRegister(7100 + (i*2), numReg = 2, format = ">HH")
parser.set(section, "Timer%s Mode" % i, str(mode))
parser.set(section, "Timer%s Value" % i, str(value))
return parser
def loadConfig(self, configParserObj):
"""
Name: UE9.loadConfig( configParserObj )
Args: configParserObj, A Config Parser object to load in
Desc: Takes a configuration and updates the UE9 to match it.
"""
parser = configParserObj
# Set Identifiers:
section = "Identifiers"
if parser.has_section(section):
if parser.has_option(section, "device type"):
if parser.getint(section, "device type") != self.devType:
raise Exception("Not a UE9 Config file.")
if parser.has_option(section, "local id"):
self.commConfig( LocalID = parser.getint(section, "local id"))
if parser.has_option(section, "name"):
self.setName( parser.get(section, "name") )
# Comm Config settings
section = "Communication"
if parser.has_section(section):
DHCPEnabled = None
ipAddress = None
subnet = None
gateway = None
portA = None
portB = None
if parser.has_option(section, "DHCPEnabled"):
DHCPEnabled = parser.getboolean(section, "DHCPEnabled")
if parser.has_option(section, "ipAddress"):
ipAddress = parser.get(section, "ipAddress")
if parser.has_option(section, "subnet"):
subnet = parser.get(section, "subnet")
if parser.has_option(section, "gateway"):
gateway = parser.get(section, "gateway")
if parser.has_option(section, "portA"):
portA = parser.getint(section, "portA")
if parser.has_option(section, "portB"):
portB = parser.getint(section, "portB")
self.commConfig( DHCPEnabled = DHCPEnabled, IPAddress = ipAddress, Subnet = subnet, Gateway = gateway, PortA = portA, PortB = portB )
# Set FIOs:
section = "FIOs"
if parser.has_section(section):
fiodirs = 0
eiodirs = 0
ciodirs = 0
fiostates = 0
eiostates = 0
ciostates = 0
if parser.has_option(section, "fios directions"):
fiodirs = parser.getint(section, "fios directions")
if parser.has_option(section, "eios directions"):
eiodirs = parser.getint(section, "eios directions")
if parser.has_option(section, "cios directions"):
ciodirs = parser.getint(section, "cios directions")
if parser.has_option(section, "fios states"):
fiostates = parser.getint(section, "fios states")
if parser.has_option(section, "eios states"):
eiostates = parser.getint(section, "eios states")
if parser.has_option(section, "cios states"):
ciostates = parser.getint(section, "cios states")
bitmask = 0xff00
# FIO State/Dir
self.writeRegister(6700, bitmask + fiostates )
self.writeRegister(6750, bitmask + fiodirs )
# EIO State/Dir
self.writeRegister(6701, bitmask + eiostates )
self.writeRegister(6751, bitmask + eiodirs )
# CIO State/Dir
self.writeRegister(6702, bitmask + ciostates )
self.writeRegister(6752, bitmask + ciodirs )
# Set DACs:
section = "DACs"
if parser.has_section(section):
if parser.has_option(section, "dac0"):
self.writeRegister(5000, parser.getfloat(section, "dac0"))
if parser.has_option(section, "dac1"):
self.writeRegister(5002, parser.getfloat(section, "dac1"))
# Set Timer Clock Configuration
section = "Timer Clock Speed Configuration"
if parser.has_section(section):
if parser.has_option(section, "timerclockbase"):
self.writeRegister(7000, parser.getint(section, "timerclockbase"))
if parser.has_option(section, "timerclockdivisor"):
self.writeRegister(7002, parser.getint(section, "timerclockbase"))
# Set Timers / Counters
section = "Timers And Counters"
if parser.has_section(section):
nte = 0
if parser.has_option(section, "NumberTimersEnabled"):
nte = parser.getint(section, "NumberTimersEnabled")
self.writeRegister(50501, nte)
if parser.has_option(section, "Counter0Enabled"):
cm = (self.readRegister(50502) & 2) # 0b10
c0e = parser.getboolean(section, "Counter0Enabled")
self.writeRegister(50502, cm + int(c0e))
if parser.has_option(section, "Counter1Enabled"):
cm = (self.readRegister(50502) & 1) # 0b01
c1e = parser.getboolean(section, "Counter1Enabled")
self.writeRegister(50502, (int(c1e) << 1) + 1)
mode = None
value = None
for i in range(nte):
if parser.has_option(section, "timer%s mode"):
mode = parser.getint(section, "timer%s mode")
if parser.has_option(section, "timer%s value"):
value = parser.getint(section, "timer%s mode")
self.writeRegister(7100 + (i*2), [mode, value])
| 64,151 | 40.361702 | 688 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/src/skymote.py | """
Name: bridge.py
Desc: Provides a Bridge and Mote class for working with SkyMote bridges and
motes.
"""
from LabJackPython import *
if os.name == "nt":
if skymoteLib is None:
raise ImportError("Couldn't load liblabjackusb.dll. Please install, and try again.")
def serialToDotHex(serial):
bytes = struct.unpack("BBBBBBBB", struct.pack(">Q", serial))
line = ""
for i in range(7):
line += "%02x:" % bytes[i]
line += "%02x" % bytes[7]
return line
def dotHexToSerial(dothex):
bytes = [ int(i, 16) for i in dothex.split(":") ]
serial = 0
for i, byte in enumerate(bytes):
serial += byte << (8 * (7-i))
return serial
class Bridge(Device):
"""
Bridge class for working with wireless bridges
>>> import bridge
>>> d = bridge.Bridge()
"""
# ------------------ Object Functions ------------------
# These functions are part of object interaction in python
def __init__(self, handle = None, autoOpen = True, **kargs):
Device.__init__(self, None, devType = 0x501)
self.handle = handle
if 'localId' in kargs:
self.localId = kargs['localId']
else:
self.localId = None
if 'serial' in kargs:
self.serialNumber = int(kargs['serial'])
self.serialString = serialToDotHex(self.serialNumber)
else:
self.serialNumber = None
self.serialString = None
self.ethernetFWVersion = None
self.usbFWVersion = None
self.deviceName = "SkyMote Bridge"
self.devType = 0x501
self.unitId = 0
self.debug = True
self.modbusPrependZeros = False
self.nameCache = None
if autoOpen:
self.open(**kargs)
def open(self, firstFound = True, serial = None, devNumber = None, handleOnly = False, LJSocket = "localhost:6000"): #"
Device.open(self, 0x501, firstFound = firstFound, localId = None, serial = serial, devNumber = devNumber, handleOnly = handleOnly, LJSocket = LJSocket)
def read(self, numBytes, stream = False, modbus = False):
result = Device.read(self, 64, stream, modbus)
return result[:numBytes]
def spontaneous(self):
while True:
try:
packet = self.read(64, stream = True)
localId = packet[6]
packet = struct.pack("B"*len(packet), *packet)
transId = struct.unpack(">H", packet[0:2])[0]
report = struct.unpack(">HBBfHH"+"f"*8, packet[9:53])
results = dict()
results['unitId'] = localId
results['transId'] = transId
results['RxLQI'] = report[1]
results['TxLQI'] = report[2]
results['Battery'] = report[3]
results['Temp'] = report[6]
results['Light'] = report[7]
results['Bump'] = report[4]
results['Sound'] = report[11]
yield results
except socket.timeout:
# Our read timed out, but keep going.
pass
def readRegister(self, addr, numReg = None, format = None, unitId = None):
if unitId is None:
return Device.readRegister(self, addr, numReg, format, self.unitId)
else:
return Device.readRegister(self, addr, numReg, format, unitId)
def writeRegister(self, addr, value, unitId = None):
if unitId is None:
return Device.writeRegister(self, addr, value, unitId = self.unitId)
else:
return Device.writeRegister(self, addr, value, unitId = unitId)
# ------------------ Convenience Functions ------------------
# These functions call read register for you.
def readSerialNumber(self):
self.serialNumber = self.readRegister(65104, numReg = 4, format = ">Q")
self.serialString = serialToDotHex(self.serialNumber)
return self.serialNumber
def readNumberOfMotes(self):
return self.readRegister(59200, numReg = 2, format = '>I')
def ethernetFirmwareVersion(self):
left, right = self.readRegister(56000, format = '>BB')
self.ethernetFWVersion = "%s.%02d" % (left, right)
return "%s.%02d" % (left, right)
def usbFirmwareVersion(self):
left, right = self.readRegister(57000, format = '>BB')
self.usbFWVersion = "%s.%02d" % (left, right)
return "%s.%02d" % (left, right)
def mainFirmwareVersion(self):
left, right = self.readRegister(65006, format = ">BB")
self.mainFWVersion = "%s.%02d" % (left, right)
return "%s.%02d" % (left, right)
def energyScan(self):
return self.readRegister(59410, numReg = 8, format = ">"+"B"*16)
def getNetworkPassword(self):
results = self.readRegister(50120, numReg = 8, format = ">"+"B"*16)
returnDict = dict()
returnDict['enabled'] = True if results[0] != 0 else False
returnDict['password'] = struct.pack("B"*15, *results[1:])
return returnDict
def setNetworkPassword(self, password, enable = True):
if len(password) > 15:
password = password[:15]
if len(password) < 15:
password += "\x00" * ( 15 - len(password) )
byteList = list(struct.unpack("B" * 15, password))
if enable:
byteList = [ 1 ] + byteList
else:
byteList = [ 0 ] + byteList
byteList = list(struct.unpack(">"+"H" * 8, struct.pack("B"*16, *byteList)))
self.writeRegister(50120, byteList)
def usbBufferStatus(self):
return self.readRegister(57001)
def numUSBRX(self):
return self.readRegister(57002, numReg = 2, format = '>I')
def numUSBTX(self):
return self.readRegister(57004, numReg = 2, format = '>I')
def numPIBRX(self):
return self.readRegister(57006, numReg = 2, format = '>I')
def numPIBTX(self):
return self.readRegister(57008, numReg = 2, format = '>I')
def lastUsbError(self):
return self.readRegister(57010)
def dmOverflows(self):
return self.readRegister(57011)
def numPibTos(self):
return self.readRegister(57014)
def numUsbTos(self):
return self.readRegister(57015)
def vUsb(self):
return self.readRegister(57050, numReg = 2, format = '>f')
def vJack(self):
return self.readRegister(57052, numReg = 2, format = '>f')
def vSt(self):
return self.readRegister(57054, numReg = 2, format = '>f')
# ------------------ Mote Functions ------------------
# These functions help you work with the motes.
def numMotes(self):
return self.readRegister(59200, numReg = 2, format = '>I')
def listMotes(self):
numMotes = self.readRegister(59200, numReg = 2, format = '>I')
if numMotes == 0:
return []
connectedMotes = []
unitIds = self.readRegister(59202, numReg = numMotes, format = ">" + "H" *numMotes )
if isinstance(unitIds, list):
for unitId in unitIds:
connectedMotes.append(Mote(self, unitId))
return connectedMotes
else:
return [Mote(self, unitIds)]
def makeMote(self, unitId):
return Mote(self, unitId)
class Mote(object):
# ------------------ Object Functions ------------------
# These functions are part of object interaction in python
def __init__(self, bridge, unitId):
self.bridge = bridge
self.unitId = unitId
self.productName = "SkyMote Mote"
self.nickname = None
self.checkinInterval = None
self.processInterval = 1000
self.mainFWVersion = None
self.devType = None
self.serialNumber = None
self.serialString = None
def __repr__(self):
return str(self)
def __str__(self):
return "<Mote Object with ID = %s>" % self.unitId
def readRegister(self, addr, numReg = None, format = None):
return self.bridge.readRegister(addr, numReg = numReg, format = format, unitId = self.unitId)
def writeRegister(self, addr, value):
return self.bridge.writeRegister(addr, value, unitId = self.unitId)
def getName(self):
"""
Name: Device.getName()
Args: None
Desc: Returns the name of a device.
Always returns a unicode string.
Works as of the following firmware versions:
U6 - 1.00
U3 - 1.22
UE9 - 2.00
>>> d = u3.U3()
>>> d.open()
>>> d.getName()
u'My LabJack U3'
"""
name = list(self.readRegister(58000, format='B'*48, numReg = 24))
if name[1] == 3:
# Old style string
name = "My %s" % self.productName
print "Old UTF-16 name detected, replacing with %s" % name
self.setName(name)
name = name.decode("UTF-8")
else:
try:
end = name.index(0x00)
name = struct.pack("B"*end, *name[:end]).decode("UTF-8")
except ValueError:
name = "My %s" % self.productName
print "Improperly formatted name detected, replacing with %s" % name
self.setName(name)
name = name.decode("UTF-8")
return name
def setName(self, name = "My LabJack U3"):
"""
Name: Device.setName(name = ""My LabJack U3")
Args: name, the name you'd like to assign the the U3
Desc: Writes a new name to the device.
Names a limited to 30 characters or less.
Works as of the following firmware versions:
U6 - 1.00
U3 - 1.22
UE9 - 2.00
>>> d = u3.U3()
>>> d.open()
>>> d.getName()
u'My LabJack U3'
>>> d.setName("Johann")
>>> d.getName()
u'Johann'
"""
strLen = len(name)
if strLen > 47:
raise LabJackException("The name is too long, must be less than 48 characters.")
newname = name.encode('UTF-8')
bl = list(struct.unpack("B"*strLen, newname)) + [0x00]
strLen += 1
if strLen%2 != 0:
bl = bl + [0x00]
strLen += 1
bl = struct.unpack(">"+"H"*(strLen/2), struct.pack("B" * strLen, *bl))
self.writeRegister(58000, list(bl))
name = property(getName, setName)
def getUnitId(self):
self.unitId = self.readRegister(65103)
return self.unitId
def setUnitId(self, unitId):
self.writeRegister(65103, unitId)
self.unitId = unitId
return True
def close(self):
self.bridge = None
def mainFirmwareVersion(self):
left, right = self.readRegister(65006, format = ">BB")
self.mainFWVersion = "%s.%02d" % (left, right)
return "%s.%02d" % (left, right)
# ------------------ Convenience Functions ------------------
# These functions call read register for you.
def readSerialNumber(self):
self.serialNumber = self.readRegister(65104, numReg = 4, format = ">Q")
self.serialString = serialToDotHex(self.serialNumber)
return self.serialNumber
def startRapidMode(self, minutes = 3):
# Sends the command to put a bridge in rapid mode.
self.writeRegister(59990, minutes)
def stopRapidMode(self):
# Sends the command to disable rapid mode.
self.startRapidMode(0)
def setCheckinInterval(self, milliseconds=1000, processInterval = None):
if processInterval is None:
processInterval = self.processInterval
self.processInterval = processInterval
bytes = list(struct.unpack(">HHHH", struct.pack(">II", processInterval, milliseconds)))
self.writeRegister(50100, bytes)
def readCheckinInterval(self):
self.checkinInterval = self.readRegister(50102)
return self.checkinInterval
def readProcessInterval(self):
self.processInterval = self.readRegister(50100)
return self.processInterval
def sensorSweep(self):
"""
Performs a sweep of all the sensors on the sensor mote.
"""
rxLqi, txLqi, battery, temp, light, motion, sound = self.readRegister(12000, numReg = 14, format = ">" + "f"*7)
results = dict()
results['RxLQI'] = rxLqi
results['TxLQI'] = txLqi
results['Battery'] = battery
results['Temp'] = temp
results['Light'] = light
results['Motion'] = motion
results['Sound'] = sound
return results
def panId(self):
return self.readRegister(50000)
def sleepTime(self):
return self.readRegister(50100, numReg = 2, format = ">I")
def getNetworkPassword(self):
results = self.readRegister(50120, numReg = 8, format = ">"+"B"*16)
returnDict = dict()
returnDict['enabled'] = True if results[0] != 0 else False
returnDict['password'] = struct.pack("B"*15, *results[1:])
return returnDict
def setNetworkPassword(self, password, enable = True):
if len(password) > 15:
password = password[:15]
if len(password) < 15:
password += "\x00" * ( 15 - len(password) )
byteList = list(struct.unpack("B" * 15, password))
if enable:
byteList = [ 1 ] + byteList
else:
byteList = [ 0 ] + byteList
byteList = list(struct.unpack(">"+"H" * 8, struct.pack("B"*16, *byteList)))
print "Writing:", byteList
self.writeRegister(50120, byteList) | 14,404 | 32.422274 | 159 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/src/mirrorGoToAngle.py | """
mirrorGoHome.py was written to send the 8711HV digital rotary servo
to the home position and turn off the laser box with the Labjack U3-HV
if need be.
author: Danica Marsden August 13, 2012
"""
import u3, time, sys
#u3.listAll(3)
# Open the LabJack
#d = u3.U3(debug = True)
d = u3.U3()
# Configure
d.configU3()
#print d.configU3()
#print d.configIO()
home = 0.467 # 0 degrees
endpt = 0.8095 # 145 degrees
center = 0.62891 # corresponds to 1.52ms "on"/high
rangeOfServo = 145. # degrees
if (len(sys.argv) < 2):
print "Syntax is: >>> python mirrorGoToAngle.py <angle [degrees]>"
sys.exit(1)
angleReq = float(sys.argv[1]) # Note: motion is CCW!
if (angleReq > rangeOfServo):
print "Need to specify an angle <= ", rangeOfServo
sys.exit(1)
if (angleReq < 0.):
print "Need to specify an angle >= 0"
sys.exit(1)
dutyReq = ((endpt-home)/rangeOfServo)*angleReq + home
# Set the timer clock to be 48 MHz/divisor with a divisor of 3
d.configTimerClock(TimerClockBase = 6, TimerClockDivisor = 3)
# Enable the timer, at FIO4
d.configIO(TimerCounterPinOffset = 4, NumberOfTimersEnabled = 1)
# Configure the timer for 16 bit PWM, with a duty cycle of a given %, where duty
# cycle is the amount of time "off"/down. This creates an overall PWM frequency
# of ~244.1Hz (4.1ms period) with (1 - dutyCycle)*4.1 ms "on"/high.
baseValue = 65536
dutyCycle = dutyReq
d.getFeedback( u3.Timer0Config(TimerMode = 0, Value = int(baseValue*dutyCycle)) )
d.getFeedback(u3.DAC16(Dac=0, Value = 0x0))
# Close the device
d.close
| 1,595 | 25.163934 | 81 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/src/test_arcons.py | """
test commands for the Labjack U3-HV.
author: Danica Marsden August 6, 2012
"""
import u3, time
# Open the LabJack
d = u3.U3(debug = True)
# Configure
d.configU3()
print d.configU3()
print d.configIO()
#
# Control the status LED:
#
d.getFeedback(u3.LED(0))
d.getFeedback(u3.LED(1))
#
# Example with DAC0 hotwired to AIN0:
#
DAC0_REGISTER = 5000
# Set DAC0 to 1.5 V
d.writeRegister(DAC0_REGISTER, 1.5)
# Read value
AIN0_REGISTER = 0
d.readRegister(AIN0_REGISTER)
# Set DAC0 to 0.5 V
d.writeRegister(DAC0_REGISTER, .5)
d.readRegister(AIN0_REGISTER)
#
# Set DAC output levels another way:
#
d.getFeedback(u3.DAC16(Dac=0, Value = 0x7fff)) # ~2.5V = 1/2 of 0xffff
d.getFeedback(u3.DAC16(Dac=1, Value = 0xffff)) # ~4.95V
d.getFeedback(u3.DAC16(Dac=0, Value = 0x0))
d.getFeedback(u3.DAC16(Dac=1, Value = 0x0))
# Close the device
d.close
| 893 | 14.964286 | 71 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/src/laserBoxControl.py | """
laserBoxControl.py was written to turn Marty's laser box on/off
with the Labjack U3-HV.
The laser box 1PPS signal should be tied to DAC1.
author: Danica Marsden September 5, 2012
"""
import u3, time, sys
#u3.listAll(3)
# Open the LabJack
#d = u3.U3(debug = True)
d = u3.U3()
# Configure
d.configU3()
DAC1_Register = 5002
FIO6_Register = 6106
FIO7_Register = 6107
FIO6_State = 6006
FIO7_State = 6007
# Set FIO6 and 7 to digital output
d.writeRegister(FIO6_Register,1)
d.writeRegister(FIO7_Register,1)
#print d.configU3()
#print d.configIO()
#onval = 0xffff
#offval = 0x0
#onval = 5.0
#offval = 0.0
if (len(sys.argv) < 3):
print "Syntax is: >>> python laserBoxControl.py <'on' or 'off'> <'blue' or 'red' or 'ir'>"
sys.exit(1)
#if (len(sys.argv) < 2):
# print "Syntax is: >>> python laserBoxControl.py <'on' or 'off'>"
# sys.exit(1)
actionReq = sys.argv[1]
laserReq = sys.argv[2]
if ((actionReq != 'on') * (actionReq != 'off')):
print "Syntax is: >>> python laserBoxControl.py <'on' or 'off'> <'blue' or 'red' or 'ir'>"
#print "Syntax is: >>> python laserBoxControl.py <'on' or 'off'>"
sys.exit(1)
if ((laserReq != 'blue')*(laserReq != 'red')*(laserReq != 'ir')):
print "Syntax is: >>> python laserBoxControl.py <'on' or 'off'> <'blue' or 'red' or 'ir'>"
sys.exit(1)
if (actionReq == 'on'):
if (laserReq == 'blue'):
d.writeRegister(DAC1_Register, 5.0)
if (laserReq == 'red'):
d.writeRegister(FIO6_State, 1)
if (laserReq == 'ir'):
d.writeRegister(FIO7_State, 1)
if (actionReq == 'off'):
if (laserReq == 'blue'):
d.writeRegister(DAC1_Register, 0.0)
if (laserReq == 'red'):
d.writeRegister(FIO6_State, 0)
if (laserReq == 'ir'):
d.writeRegister(FIO7_State, 0)
#print "Turning lasers ", actionReq
print "Turning ", laserReq, " laser ", actionReq
# Close the device
d.close
| 1,931 | 23.15 | 95 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/src/u12.py | """
Name: u12.py
Desc: Defines the U12 class, which makes working with a U12 much easier. The
functions of the U12 class are divided into two categories: UW and
low-level.
Most of the UW functions are exposed as functions of the U12 class. With
the exception of the "e" functions, UW functions are Windows only. The "e"
functions will work with both the UW and the Exodriver. Therefore, people
wishing to write cross-platform code should restrict themselves to using
only the "e" functions. The UW functions are described in Section 4 of the
U12 User's Guide:
http://labjack.com/support/u12/users-guide/4
All low-level functions of the U12 class begin with the word
raw. For example, the low-level function Counter can be called with
U12.rawCounter(). Currently, low-level functions are limited to the
Exodriver (Linux and Mac OS X). You can find descriptions of the low-level
functions in Section 5 of the U12 User's Guide:
http://labjack.com/support/u12/users-guide/5
"""
import platform
import ctypes
import os, atexit
import math
from time import time
import struct
WINDOWS = "Windows"
ON_WINDOWS = (os.name == 'nt')
class U12Exception(Exception):
"""Custom Exception meant for dealing specifically with U12 Exceptions.
Error codes are either going to be a LabJackUD error code or a -1. The -1 implies
a python wrapper specific error.
def __init__(self, ec = 0, errorString = ''):
self.errorCode = ec
self.errorString = errorString
if not self.errorString:
#try:
self.errorString = getErrorString(ec)
#except:
# self.errorString = str(self.errorCode)
def __str__(self):
return self.errorString
"""
pass
class BitField(object):
"""
Provides a method for working with bit fields.
>>> bf = BitField()
>>> print bf
[ bit7 = 0, bit6 = 0, bit5 = 0, bit4 = 0, bit3 = 0, bit2 = 0, bit1 = 0, bit0 = 0 ]
You can use attribute accessing for easy bit flipping:
>>> bf.bit4 = 1
>>> bf.bit7 = 1
>>> print bf
[ bit7 = 1, bit6 = 0, bit5 = 0, bit4 = 1, bit3 = 0, bit2 = 0, bit1 = 0, bit0 = 0 ]
You can also use list-style accessing. Counting starts on the left:
>>> print bf[0] # List index 0 is bit7
1
>>> print bf[3] # List index 3 is bit4
1
List-style slicing:
>>> print bf[3:]
[1, 0, 0, 0, 0]
List-style setting bits works as you would expect:
>>> bf[1] = 1
>>> print bf
[ bit7 = 1, bit6 = 1, bit5 = 0, bit4 = 1, bit3 = 0, bit2 = 0, bit1 = 0, bit0 = 0 ]
It provides methods for going to and from bytes:
>>> bf = BitField(123)
>>> print bf
[ bit7 = 0, bit6 = 1, bit5 = 1, bit4 = 1, bit3 = 1, bit2 = 0, bit1 = 1, bit0 = 1 ]
>>> bf = BitField()
>>> bf.fromByte(123) # Modifies bf in place
>>> print bf
[ bit7 = 0, bit6 = 1, bit5 = 1, bit4 = 1, bit3 = 1, bit2 = 0, bit1 = 1, bit0 = 1 ]
>>> bf.bit4 = 0
>>> print bf.asByte()
107
You can iterate of the raw bits ( 1 and 0 Vs. '1' and '0') easily:
>>> for i in bf:
... print i
0
1
1
0
1
0
1
1
You can also iterate over the labels and their data values using items():
>>> for label, data in bf.items():
... print label, data
bit7 0
bit6 1
bit5 1
bit4 0
bit3 1
bit2 0
bit1 1
bit0 1
As an added bonus, it can also be cast as an int or hex:
>>> int(bf)
107
>>> hex(bf)
'0x6b'
See the description of the __init__ method for setting the label parameters. """
def __init__(self, rawByte = None, labelPrefix = "bit", labelList = None, zeroLabel = "0", oneLabel = "1"):
"""
Name: BitField.__init__(rawByte = None, labelPrefix = "bit",
labelList = None, zeroLabel = "0",
oneLabel = "1")
Args: rawByte, a value to set the bit field values to.
labelPrefix, what should go before the labels in labelList
labelList, a list of labels to apply to each bit. If None, it
gets set to range(7,-1,-1).
zeroLabel, bits with a value of 0 will have this label
oneLabel, bits with a value of 1 will have this label
Desc: Creates a new bitfield and sets up the labels.
With out any arguments, you get a bit field that looks like this:
>>> bf = BitField()
>>> print bf
[ bit7 = 0, bit6 = 0, bit5 = 0, bit4 = 0, bit3 = 0, bit2 = 0, bit1 = 0,
bit0 = 0 ]
To make the labels, it iterates over all the labelList and adds the
labelPrefix to them. If you have less than 8 labels, then your bit field
will only work up to that many bits.
To make a BitField with labels for FIO0-7 you can do the following:
>>> bf = BitField(labelPrefix = "FIO")
>>> print bf
[ FIO7 = 0, FIO6 = 0, FIO5 = 0, FIO4 = 0, FIO3 = 0, FIO2 = 0, FIO1 = 0,
FIO0 = 0 ]
The labels don't have to be numbers, for example:
>>> names = [ "Goodreau", "Jerri", "Selena", "Allan", "Tania",
"Kathrine", "Jessie", "Zelma" ]
>>> bf = BitField( labelPrefix = "", labelList = names)
>>> print bf
[ Goodreau = 0, Jerri = 0, Selena = 0, Allan = 0, Tania = 0,
Kathrine = 0, Jessie = 0, Zelma = 0 ]
You can change the display value of zero and one to be whatever you
want. For example, if you have a BitField that represents FIO0-7
directions:
>>> dirs = BitField(rawByte = 5, labelPrefix = "FIO",
zeroLabel = "Output", oneLabel = "Input")
>>> print dirs
[ FIO7 = Output, FIO6 = Output, FIO5 = Output, FIO4 = Output,
FIO3 = Output, FIO2 = Input, FIO1 = Output, FIO0 = Input ]
Note, that when you access the value, you will get 1 or 0, not "Input"
or "Output. For example:
>>> print dirs.FIO3
0
"""
# Do labels first, so that self.something = something works.
self.__dict__['labels'] = []
self.labelPrefix = labelPrefix
if labelList is None:
self.labelList = range(8)
else:
self.labelList = list(reversed(labelList))
self.zeroLabel = zeroLabel
self.oneLabel = oneLabel
self.rawValue = 0
self.rawBits = [ 0 ] * 8
self.data = [ self.zeroLabel ] * 8
items = min(8, len(self.labelList))
for i in reversed(range(items)):
self.labels.append("%s%s" % (self.labelPrefix, self.labelList[i]))
if rawByte is not None:
self.fromByte(rawByte)
def fromByte(self, raw):
"""
Name: BitField.fromByte(raw)
Args: raw, the raw byte to make the BitField.
Desc: Takes a byte, and modifies self to match.
>>> bf = BitField()
>>> bf.fromByte(123) # Modifies bf in place
>>> print bf
[ bit7 = 0, bit6 = 1, bit5 = 1, bit4 = 1, bit3 = 1, bit2 = 0, bit1 = 1,
bit0 = 1 ]
"""
self.rawValue = raw
self.rawBits = []
self.data = []
items = min(8, len(self.labelList))
for i in reversed(range(items)):
self.rawBits.append( ((raw >> (i)) & 1) )
self.data.append(self.oneLabel if bool(((raw >> (i)) & 1)) else self.zeroLabel)
def asByte(self):
"""
Name: BitField.asByte()
Args: None
Desc: Returns the value of the bitfield as a byte.
>>> bf = BitField()
>>> bf.fromByte(123) # Modifies bf in place
>>> bf.bit4 = 0
>>> print bf.asByte()
107
"""
byteVal = 0
for i, v in enumerate(reversed(self.rawBits)):
byteVal += ( 1 << i ) * v
return byteVal
def asBin(self):
result = "0b"
for i in self.rawBits:
result += "%s" % i
return result
def __len__(self):
return len(self.data)
def __repr__(self):
result = "["
for i in range(len(self.data)):
result += " %s = %s (%s)," % (self.labels[i], self.data[i], self.rawBits[i])
result = result.rstrip(',')
result += " ]"
return "<BitField object: %s >" % result
def __str__(self):
result = "["
for i in range(len(self.data)):
result += " %s = %s," % (self.labels[i], self.data[i])
result = result.rstrip(',')
result += " ]"
return result
def __getattr__(self, label):
try:
i = self.labels.index(label)
return self.rawBits[i]
except ValueError:
raise AttributeError(label)
def __setattr__(self, label, value):
try:
i = self.labels.index(label)
self.rawBits[i] = int(bool(value))
self.data[i] = self.oneLabel if bool(value) else self.zeroLabel
except ValueError:
self.__dict__[label] = value
def __getitem__(self, key):
return self.rawBits[key]
def __setitem__(self, key, value):
self.rawBits[key] = int(bool(value))
self.data[key] = self.oneLabel if bool(value) else self.zeroLabel
def __iter__(self):
return iter(self.rawBits)
def items(self):
"""
Name: BitField.items()
Args: None
Desc: Returns a list of tuples where the first item is the label and the
second is the string value, like "High" or "Input"
>>> dirs = BitField(rawByte = 5, labelPrefix = "FIO",
zeroLabel = "Output", oneLabel = "Input")
>>> print dirs
[ FIO7 = Output, FIO6 = Output, FIO5 = Output, FIO4 = Output,
FIO3 = Output, FIO2 = Input, FIO1 = Output, FIO0 = Input ]
>>> for label, data in dirs.items():
... print label, data
...
FIO7 Output
FIO6 Output
FIO5 Output
FIO4 Output
FIO3 Output
FIO2 Input
FIO1 Output
FIO0 Input
"""
return zip(self.labels, self.data)
def __int__(self):
return self.asByte()
def __hex__(self):
return hex(self.asByte())
def __add__(self, other):
"""
A helper to prevent having to test if a variable is a bitfield or int.
"""
return other + self.asByte()
def errcheck(ret, func, args):
if ret == -1:
try:
ec = ctypes.get_errno()
raise U12Exception("Exodriver returned error number %s" % ec)
except AttributeError:
raise U12Exception("Exodriver returned an error, but LabJackPython is unable to read the error code. Upgrade to Python 2.6 for this functionality.")
else:
return ret
def _loadLinuxSo():
try:
l = ctypes.CDLL("liblabjackusb.so", use_errno=True)
except TypeError:
l = ctypes.CDLL("liblabjackusb.so")
l.LJUSB_Stream.errcheck = errcheck
l.LJUSB_Read.errcheck = errcheck
return l
def _loadMacDylib():
try:
l = ctypes.CDLL("liblabjackusb.dylib", use_errno=True)
except TypeError:
l = ctypes.CDLL("liblabjackusb.dylib")
l.LJUSB_Stream.errcheck = errcheck
l.LJUSB_Read.errcheck = errcheck
return l
staticLib = None
if os.name == 'posix':
try:
staticLib = _loadLinuxSo()
except OSError, e:
pass # We may be on Mac.
except Exception, e:
raise U12Exception("Could not load the Linux SO for some reason other than it not being installed. Ethernet connectivity only.\n\n The error was: %s" % e)
try:
if staticLib is None:
staticLib = _loadMacDylib()
except OSError, e:
raise U12Exception("Could not load the Exodriver driver. Ethernet connectivity only.\n\nCheck that the Exodriver is installed, and the permissions are set correctly.\nThe error message was: %s" % e)
except Exception, e:
raise U12Exception("Could not load the Mac Dylib for some reason other than it not being installed. Ethernet connectivity only.\n\n The error was: %s" % e)
else:
try:
staticLib = ctypes.windll.LoadLibrary("ljackuw")
except:
raise Exception, "Could not load LabJack UW driver."
class U12(object):
"""
U12 Class for all U12 specific commands.
u12 = U12()
"""
def __init__(self, id = -1, serialNumber = None, debug = False):
self.id = id
self.serialNumber = serialNumber
self.deviceName = "U12"
self.streaming = False
self.handle = None
self.debug = debug
self._autoCloseSetup = False
if not ON_WINDOWS:
# Save some variables to save state.
self.pwmAVoltage = 0
self.pwmBVoltage = 0
self.open(id, serialNumber)
def open(self, id = -1, serialNumber = None):
"""
Opens the U12.
The Windows UW driver opens the device every time a function is called.
The Exodriver, however, works like the UD family of devices and returns
a handle. On Windows, this method does nothing. On Mac OS X and Linux,
this method acquires a device handle and saves it to the U12 object.
"""
if ON_WINDOWS:
pass
else:
if self.debug: print "open called"
devType = ctypes.c_ulong(1)
openDev = staticLib.LJUSB_OpenDevice
openDev.restype = ctypes.c_void_p
if serialNumber is not None:
numDevices = staticLib.LJUSB_GetDevCount(devType)
for i in range(numDevices):
handle = openDev(i+1, 0, devType)
if handle != 0 and handle is not None:
self.handle = ctypes.c_void_p(handle)
try:
serial = self.rawReadSerial()
except Exception:
serial = self.rawReadSerial()
if serial == int(serialNumber):
break
else:
self.close()
if self.handle is None:
raise U12Exception("Couldn't find a U12 with a serial number matching %s" % serialNumber)
elif id != -1:
numDevices = staticLib.LJUSB_GetDevCount(devType)
for i in range(numDevices):
handle = openDev(i+1, 0, devType)
if handle != 0 and handle is not None:
self.handle = ctypes.c_void_p(handle)
try:
unitId = self.rawReadLocalId()
except Exception:
unitId = self.rawReadLocalId()
if unitId == int(id):
break
else:
self.close()
if self.handle is None:
raise U12Exception("Couldn't find a U12 with a local ID matching %s" % id)
elif id == -1:
handle = openDev(1, 0, devType)
if handle == 0 or handle is None:
raise Exception("Couldn't open a U12. Check that one is connected and try again.")
else:
self.handle = ctypes.c_void_p(handle)
# U12 ignores first command, so let's write a command.
command = [ 0 ] * 8
command[5] = 0x57 # 0b01010111
try:
self.write(command)
self.read()
except:
pass
self.id = self.rawReadLocalId()
else:
raise Exception("Invalid combination of parameters.")
if not self._autoCloseSetup:
# Only need to register auto-close once per device.
atexit.register(self.close)
self._autoCloseSetup = True
def close(self):
if ON_WINDOWS:
pass
else:
staticLib.LJUSB_CloseDevice(self.handle)
self.handle = None
def write(self, writeBuffer):
if ON_WINDOWS:
pass
else:
if self.handle is None:
raise U12Exception("The U12's handle is None. Please open a U12 with open()")
if self.debug: print "Writing:", hexWithoutQuotes(writeBuffer)
newA = (ctypes.c_byte*len(writeBuffer))(0)
for i in range(len(writeBuffer)):
newA[i] = ctypes.c_byte(writeBuffer[i])
writeBytes = staticLib.LJUSB_Write(self.handle, ctypes.byref(newA), len(writeBuffer))
if(writeBytes != len(writeBuffer)):
raise U12Exception( "Could only write %s of %s bytes." % (writeBytes, len(writeBuffer) ) )
return writeBuffer
def read(self, numBytes = 8):
if ON_WINDOWS:
pass
else:
if self.handle is None:
raise U12Exception("The U12's handle is None. Please open a U12 with open()")
newA = (ctypes.c_byte*numBytes)()
readBytes = staticLib.LJUSB_Read(self.handle, ctypes.byref(newA), numBytes)
# return a list of integers in command/response mode
result = [(newA[i] & 0xff) for i in range(readBytes)]
if self.debug: print "Received:", hexWithoutQuotes(result)
return result
# Low-level helpers
def rawReadSerial(self):
"""
Name: U12.rawReadSerial()
Args: None
Desc: Reads the serial number from internal memory.
Returns: The U12's serial number as an integer.
Example:
>>> import u12
>>> d = u12.U12()
>>> print d.rawReadSerial()
10004XXXX
"""
results = self.rawReadRAM()
return struct.unpack(">I", struct.pack("BBBB", results['DataByte3'], results['DataByte2'], results['DataByte1'], results['DataByte0']))[0]
def rawReadLocalId(self):
"""
Name: U12.rawReadLocalId()
Args: None
Desc: Reads the Local ID from internal memory.
Returns: The U12's Local ID as an integer.
Example:
>>> import u12
>>> d = u12.U12()
>>> print d.rawReadLocalId()
0
"""
results = self.rawReadRAM(0x08)
return results['DataByte0']
# Begin Section 5 Functions
def rawAISample(self, channel0PGAMUX = 8, channel1PGAMUX = 9, channel2PGAMUX = 10, channel3PGAMUX = 11, UpdateIO = False, LEDState = True, IO3toIO0States = 0, EchoValue = 0):
"""
Name: U12.rawAISample(channel0PGAMUX = 8, channel1PGAMUX = 9,
channel2PGAMUX = 10, channel3PGAMUX = 11,
UpdateIO = False, LEDState = True,
IO3toIO0States = 0, EchoValue = 0)
Args: channel0PGAMUX, A byte that contains channel0 information
channel1PGAMUX, A byte that contains channel1 information
channel2PGAMUX, A byte that contains channel2 information
channel3PGAMUX, A byte that contains channel3 information
IO3toIO0States, A byte that represents the states of IO0 to IO3
UpdateIO, If true, set IO0 to IO 3 to match IO3toIO0States
LEDState, Turns the status LED on or off.
EchoValue, Sometimes, you want what you put in.
Desc: Collects readings from 4 analog inputs. It can also toggle the
status LED and update the state of the IOs. See Section 5.1 of
the User's Guide.
By default it will read AI0-3 (single-ended).
Returns: A dictionary with the following keys:
PGAOvervoltage, A bool representing if the U12 detected overvoltage
IO3toIO0States, a BitField representing the state of IO0 to IO3
Channel0-3, the analog voltage for the channel
EchoValue, a repeat of the value passed in.
Example:
>>> import u12
>>> d = u12.U12()
>>> d.rawAISample()
{
'IO3toIO0States':
<BitField object: [ IO3 = Low (0), IO2 = Low (0),
IO1 = Low (0), IO0 = Low (0) ] >,
'Channel0': 1.46484375,
'Channel1': 1.4501953125,
'Channel2': 1.4599609375,
'Channel3': 1.4306640625,
'PGAOvervoltage': False,
'EchoValue': 0
}
"""
command = [ 0 ] * 8
# Bits 6-4: PGA for 1st Channel
# Bits 3-0: MUX command for 1st Channel
command[0] = int(channel0PGAMUX)
tempNum = command[0] & 7 # 7 = 0b111
channel0Number = tempNum if (command[0] & 0xf) > 7 else tempNum+8
channel0Gain = (command[0] >> 4) & 7 # 7 = 0b111
command[1] = int(channel1PGAMUX)
tempNum = command[1] & 7 # 7 = 0b111
channel1Number = tempNum if (command[1] & 0xf) > 7 else tempNum+8
channel1Gain = (command[1] >> 4) & 7 # 7 = 0b111
command[2] = int(channel2PGAMUX)
tempNum = command[2] & 7 # 7 = 0b111
channel2Number = tempNum if (command[2] & 0xf) > 7 else tempNum+8
channel2Gain = (command[2] >> 4) & 7 # 7 = 0b111
command[3] = int(channel3PGAMUX)
tempNum = command[3] & 7 # 7 = 0b111
channel3Number = tempNum if (command[3] & 0xf) > 7 else tempNum+8
channel3Gain = (command[3] >> 4) & 7 # 7 = 0b111
# Bit 1: Update IO
# Bit 0: LED State
bf = BitField()
bf.bit1 = int(UpdateIO)
bf.bit0 = int(LEDState)
command[4] = int(bf)
# Bit 7-4: 1100 (Command/Response)
# Bit 3-0: Bits for IO3 through IO0 States
bf.fromByte(0)
bf.bit7 = 1
bf.bit6 = 1
bf.fromByte( int(bf) | int(IO3toIO0States) )
command[5] = int(bf)
command[7] = EchoValue
self.write(command)
results = self.read()
bf = BitField()
bf.fromByte(results[0])
if bf.bit7 != 1 or bf.bit6 != 0:
raise U12Exception("Expected a AIStream response, got %s instead." % results[0])
returnDict = {}
returnDict['EchoValue'] = results[1]
returnDict['PGAOvervoltage'] = bool(bf.bit4)
returnDict['IO3toIO0States'] = BitField(results[0], "IO", range(3, -1, -1), "Low", "High")
channel0 = (results[2] >> 4) & 0xf
channel1 = (results[2] & 0xf)
channel2 = (results[5] >> 4) & 0xf
channel3 = (results[5] & 0xf)
channel0 = (channel0 << 8) + results[3]
returnDict['Channel0'] = self.bitsToVolts(channel0Number, channel0Gain, channel0)
channel1 = (channel1 << 8) + results[4]
returnDict['Channel1'] = self.bitsToVolts(channel1Number, channel1Gain, channel1)
channel2 = (channel2 << 8) + results[6]
returnDict['Channel2'] = self.bitsToVolts(channel2Number, channel2Gain, channel2)
channel3 = (channel3 << 8) + results[7]
returnDict['Channel3'] = self.bitsToVolts(channel3Number, channel3Gain, channel3)
return returnDict
def rawDIO(self, D15toD8Directions = 0, D7toD0Directions = 0, D15toD8States = 0, D7toD0States = 0, IO3toIO0DirectionsAndStates = 0, UpdateDigital = False):
"""
Name: U12.rawDIO(D15toD8Directions = 0, D7toD0Directions = 0,
D15toD8States = 0, D7toD0States = 0,
IO3toIO0DirectionsAndStates = 0, UpdateDigital = 1)
Args: D15toD8Directions, A byte where 0 = Output, 1 = Input for D15-8
D7toD0Directions, A byte where 0 = Output, 1 = Input for D7-0
D15toD8States, A byte where 0 = Low, 1 = High for D15-8
D7toD0States, A byte where 0 = Low, 1 = High for D7-0
IO3toIO0DirectionsAndStates, Bits 7-4: Direction, 3-0: State
UpdateDigital, True if you want to update the IO/D line. False to
False to just read their values.
Desc: This commands reads the direction and state of all the digital
I/O. See Section 5.2 of the U12 User's Guide.
By default, it just reads the directions and states.
Returns: A dictionary with the following keys:
D15toD8Directions, a BitField representing the directions of D15-D8
D7toD0Directions, a BitField representing the directions of D7-D0.
D15toD8States, a BitField representing the states of D15-D8.
D7toD0States, a BitField representing the states of D7-D0.
IO3toIO0States, a BitField representing the states of IO3-IO0.
D15toD8OutputLatchStates, BitField of output latch states for D15-8
D7toD0OutputLatchStates, BitField of output latch states for D7-0
Example:
>>> import u12
>>> d = u12.U12()
>>> d.rawDIO()
{
'D15toD8Directions':
<BitField object: [ D15 = Input (1), D14 = Input (1),
D13 = Input (1), D12 = Input (1),
D11 = Input (1), D10 = Input (1),
D9 = Input (1), D8 = Input (1) ] >,
'D7toD0Directions':
<BitField object: [ D7 = Input (1), D6 = Input (1), D5 = Input (1),
D4 = Input (1), D3 = Input (1), D2 = Input (1),
D1 = Input (1), D0 = Input (1) ] >,
'D15toD8States':
<BitField object: [ D15 = Low (0), D14 = Low (0), D13 = Low (0),
D12 = Low (0), D11 = Low (0), D10 = Low (0),
D9 = Low (0), D8 = Low (0) ] >,
'D7toD0States':
<BitField object: [ D7 = Low (0), D6 = Low (0), D5 = Low (0),
D4 = Low (0), D3 = Low (0), D2 = Low (0),
D1 = Low (0), D0 = Low (0) ] >,
'IO3toIO0States':
<BitField object: [ IO3 = Low (0), IO2 = Low (0), IO1 = Low (0),
IO0 = Low (0) ] >,
'D15toD8OutputLatchStates':
<BitField object: [ D15 = 0 (0), D14 = 0 (0), D13 = 0 (0),
D12 = 0 (0), D11 = 0 (0), D10 = 0 (0),
D9 = 0 (0), D8 = 0 (0) ] >,
'D7toD0OutputLatchStates':
<BitField object: [ D7 = 0 (0), D6 = 0 (0), D5 = 0 (0), D4 = 0 (0),
D3 = 0 (0), D2 = 0 (0), D1 = 0 (0),
D0 = 0 (0) ] >
}
"""
command = [ 0 ] * 8
# Bits for D15 through D8 Direction
command[0] = int(D15toD8Directions)
# Bits for D7 through D0 Direction ( 0 = Output, 1 = Input)
command[1] = int(D7toD0Directions)
# Bits for D15 through D8 State ( 0 = Low, 1 = High)
command[2] = int(D15toD8States)
# Bits for D7 through D0 State ( 0 = Low, 1 = High)
command[3] = int(D7toD0States)
# Bits 7-4: Bits for IO3 through IO0 Direction
# Bits 3-0: Bits for IO3 through IO0 State
command[4] = int(IO3toIO0DirectionsAndStates)
# 01X10111 (DIO)
command[5] = 0x57 # 0b01010111
# Bit 0: Update Digital
command[6] = int(bool(UpdateDigital))
#XXXXXXXX
# command[7] = XXXXXXXX
self.write(command)
results = self.read()
returnDict = {}
if results[0] != 87:
raise U12Exception("Expected a DIO response, got %s instead." % results[0])
returnDict['D15toD8States'] = BitField(results[1], "D", range(15, 7, -1), "Low", "High")
returnDict['D7toD0States'] = BitField(results[2], "D", range(7, -1, -1), "Low", "High")
returnDict['D15toD8Directions'] = BitField(results[4], "D", range(15, 7, -1), "Output", "Input")
returnDict['D7toD0Directions'] = BitField(results[5], "D", range(7, -1, -1), "Output", "Input")
returnDict['D15toD8OutputLatchStates'] = BitField(results[6], "D", range(15, 7, -1))
returnDict['D7toD0OutputLatchStates'] = BitField(results[7], "D", range(7, -1, -1))
returnDict['IO3toIO0States'] = BitField((results[3] >> 4), "IO", range(3, -1, -1), "Low", "High")
return returnDict
def rawCounter(self, StrobeEnabled = False, ResetCounter = False):
"""
Name: U12.rawCounter(StrobeEnabled = False, ResetCounter = False)
Args: StrobeEnable, set to True to enable strobe.
ResetCounter, set to True to reset the counter AFTER reading.
Desc: This command controls and reads the 32-bit counter. See
Section 5.3 of the User's Guide.
Returns: A dictionary with the following keys:
D15toD8States, a BitField representing the states of D15-D8.
D7toD0States, a BitField representing the states of D7-D0.
IO3toIO0States, a BitField representing the states of IO3-IO0.
Counter, the value of the counter
Example:
>>> import u12
>>> d = u12.U12()
>>> d.rawCounter()
{
'D15toD8States':
<BitField object: [ D15 = Low (0), D14 = Low (0), D13 = Low (0),
D12 = Low (0), D11 = Low (0), D10 = Low (0),
D9 = Low (0), D8 = Low (0) ] >,
'D7toD0States':
<BitField object: [ D7 = Low (0), D6 = Low (0), D5 = Low (0),
D4 = Low (0), D3 = Low (0), D2 = Low (0),
D1 = Low (0), D0 = Low (0) ] >,
'IO3toIO0States':
<BitField object: [ IO3 = Low (0), IO2 = Low (0), IO1 = Low (0),
IO0 = Low (0) ] >,
'Counter': 0
}
"""
command = [ 0 ] * 8
bf = BitField()
bf.bit1 = int(StrobeEnabled)
bf.bit0 = int(ResetCounter)
command[0] = int(bf)
bf.fromByte(0)
bf.bit6 = 1
bf.bit4 = 1
bf.bit1 = 1
command[5] = int(bf)
self.write(command)
results = self.read()
returnDict = {}
if results[0] != command[5]:
raise U12Exception("Expected a Counter response, got %s instead." % results[0])
returnDict['D15toD8States'] = BitField(results[1], "D", range(15, 7, -1), "Low", "High")
returnDict['D7toD0States'] = BitField(results[2], "D", range(7, -1, -1), "Low", "High")
returnDict['IO3toIO0States'] = BitField((results[3] >> 4), "IO", range(3, -1, -1), "Low", "High")
counter = results[7]
counter += results[6] << 8
counter += results[5] << 16
counter += results[4] << 24
returnDict['Counter'] = counter
return returnDict
def rawCounterPWMDIO(self, D15toD8Directions = 0, D7toD0Directions = 0, D15toD8States = 0, D7toD0States = 0, IO3toIO0DirectionsAndStates = 0, ResetCounter = False, UpdateDigital = 0, PWMA = 0, PWMB = 0):
"""
Name: U12.rawCounterPWMDIO( D15toD8Directions = 0, D7toD0Directions = 0,
D15toD8States = 0, D7toD0States = 0,
IO3toIO0DirectionsAndStates = 0,
ResetCounter = False, UpdateDigital = 0,
PWMA = 0, PWMB = 0)
Args: D15toD8Directions, A byte where 0 = Output, 1 = Input for D15-8
D7toD0Directions, A byte where 0 = Output, 1 = Input for D7-0
D15toD8States, A byte where 0 = Low, 1 = High for D15-8
D7toD0States, A byte where 0 = Low, 1 = High for D7-0
IO3toIO0DirectionsAndStates, Bits 7-4: Direction, 3-0: State
ResetCounter, If True, reset the counter after reading.
UpdateDigital, True if you want to update the IO/D line. False to
False to just read their values.
PWMA, Voltage to set AO0 to output.
PWMB, Voltage to set AO1 to output.
Desc: This command controls all 20 digital I/O, and the 2 PWM outputs.
The response provides the state of all I/O and the current count.
See Section 5.4 of the User's Guide.
By default, sets the AOs to 0 and reads the states and counters.
Returns: A dictionary with the following keys:
D15toD8States, a BitField representing the states of D15-D8.
D7toD0States, a BitField representing the states of D7-D0.
IO3toIO0States, a BitField representing the states of IO3-IO0.
Counter, the value of the counter
Example:
>>> import u12
>>> d = u12.U12()
>>> d.rawCounterPWMDIO()
{
'D15toD8States':
<BitField object: [ D15 = Low (0), D14 = Low (0), D13 = Low (0),
D12 = Low (0), D11 = Low (0), D10 = Low (0),
D9 = Low (0), D8 = Low (0) ] >,
'D7toD0States':
<BitField object: [ D7 = Low (0), D6 = Low (0), D5 = Low (0),
D4 = Low (0), D3 = Low (0), D2 = Low (0),
D1 = Low (0), D0 = Low (0) ] >,
'IO3toIO0States':
<BitField object: [ IO3 = Low (0), IO2 = Low (0),
IO1 = Low (0), IO0 = Low (0) ] >,
'Counter': 0
}
"""
command = [ 0 ] * 8
# Bits for D15 through D8 Direction
command[0] = int(D15toD8Directions)
# Bits for D7 through D0 Direction ( 0 = Output, 1 = Input)
command[1] = int(D7toD0Directions)
# Bits for D15 through D8 State ( 0 = Low, 1 = High)
command[2] = int(D15toD8States)
# Bits for D7 through D0 State ( 0 = Low, 1 = High)
command[3] = int(D7toD0States)
# Bits 7-4: Bits for IO3 through IO0 Direction
# Bits 3-0: Bits for IO3 through IO0 State
command[4] = int(IO3toIO0DirectionsAndStates)
bf = BitField()
bf.bit5 = int(ResetCounter)
bf.bit4 = int(UpdateDigital)
binPWMA = int((1023 * (float(PWMA)/5.0)))
binPWMB = int((1023 * (float(PWMB)/5.0)))
bf2 = BitField()
bf2.fromByte( binPWMA & 3 ) # 3 = 0b11
bf.bit3 = bf2.bit1
bf.bit2 = bf2.bit0
bf2.fromByte( binPWMB & 3 ) # 3 = 0b11
bf.bit1 = bf2.bit1
bf.bit0 = bf2.bit0
command[5] = int(bf)
command[6] = (binPWMA >> 2) & 0xff
command[7] = (binPWMB >> 2) & 0xff
self.write(command)
results = self.read()
returnDict = {}
returnDict['D15toD8States'] = BitField(results[1], "D", range(15, 7, -1), "Low", "High")
returnDict['D7toD0States'] = BitField(results[2], "D", range(7, -1, -1), "Low", "High")
returnDict['IO3toIO0States'] = BitField((results[3] >> 4), "IO", range(3, -1, -1), "Low", "High")
counter = results[7]
counter += results[6] << 8
counter += results[5] << 16
counter += results[4] << 24
returnDict['Counter'] = counter
return returnDict
def rawAIBurst(self, channel0PGAMUX = 8, channel1PGAMUX = 9, channel2PGAMUX = 10, channel3PGAMUX = 11, NumberOfScans = 8, TriggerIONum = 0, TriggerState = 0, UpdateIO = False, LEDState = True, IO3ToIO0States = 0, FeatureReports = False, TriggerOn = False, SampleInterval = 15000):
"""
Name: U12.rawAIBurst( channel0PGAMUX = 8, channel1PGAMUX = 9,
channel2PGAMUX = 10, channel3PGAMUX = 11,
NumberOfScans = 8, TriggerIONum = 0,
TriggerState = 0, UpdateIO = False,
LEDState = True, IO3ToIO0States = 0,
FeatureReports = False, TriggerOn = False,
SampleInterval = 15000 )
Args: channel0PGAMUX, A byte that contains channel0 information
channel1PGAMUX, A byte that contains channel1 information
channel2PGAMUX, A byte that contains channel2 information
channel3PGAMUX, A byte that contains channel3 information
NumberOfScans, The number of scans you wish to take. Rounded up
to a power of 2.
TriggerIONum, IO to trigger burst on.
TriggerState, State to trigger on.
UpdateIO, True if you want to update the IO/D line. False to
False to just read their values.
LEDState, Turns the status LED on or off.
IO3ToIO0States, 4 bits for IO3-0 states
FeatureReports, Use feature reports, or not.
TriggerOn, Use trigger to start acquisition.
SampleInterval, = int(6000000.0/(ScanRate * NumberOfChannels))
must be greater than (or equal to) 733.
Desc: After receiving a AIBurst command, the LabJack collects 4
channels at the specified data rate, and puts data in the buffer.
This continues until the buffer is full, at which time the
LabJack starts sending the data to the host. Data is sent to the
host 1 scan at a time while checking for a command from the host.
If a command is received the burst operation is canceled and the
command is executed normally. If the LED is enabled, it blinks at
4 Hz while waiting for a trigger, is off during acquisition,
blinks at about 8 Hz during data delivery, and is set on when
done or stopped. See Section 5.5 of the User's Guide.
This function sends the AIBurst command, then reads all the
responses. Separating the write and read is not currently
supported (like in the UW driver).
By default, it does single-ended readings on AI0-4 at 100Hz for 8
scans.
Returns: A dictionary with the following keys:
Channel0-3, A list of the readings on the channels
PGAOvervoltages, A list of the over-voltage flags
IO3toIO0State, A list of the IO states
IterationCounters, A list of the values of the iteration counter
Backlogs, value*256 = number of packets in the backlog.
BufferOverflowOrChecksumErrors, If True and Backlog = 31,
then a buffer overflow occurred. If
True and Backlog = 0, then Checksum
error occurred.
Example:
>>> import u12
>>> d = u12.U12()
>>> d.rawAIBurst()
{
'Channel0': [1.484375, 1.513671875, ... , 1.46484375],
'Channel1': [1.455078125, 1.455078125, ... , 1.455078125],
'Channel2': [1.46484375, 1.474609375, ... , 1.46484375],
'Channel3': [1.435546875, 1.42578125, ... , 1.435546875],
'PGAOvervoltages': [False, False, ..., False],
'IO3toIO0States':
[<BitField object: [ IO3 = Low (0), IO2 = Low (0), IO1 = Low (0),
IO0 = Low (0) ] >, ... ],
'IterationCounters': [0, 1, 2, 3, 4, 5, 6, 0],
'Backlogs': [0, 0, 0, 0, 0, 0, 0, 0],
'BufferOverflowOrChecksumErrors': [False, False, ... , False]
}
"""
command = [ 0 ] * 8
# Bits 6-4: PGA for 1st Channel
# Bits 3-0: MUX command for 1st Channel
command[0] = int(channel0PGAMUX)
tempNum = command[0] & 7 # 7 = 0b111
channel0Number = tempNum if (command[0] & 0xf) > 7 else tempNum+8
channel0Gain = (command[0] >> 4) & 7 # 7 = 0b111
command[1] = int(channel1PGAMUX)
tempNum = command[1] & 7 # 7 = 0b111
channel1Number = tempNum if (command[1] & 0xf) > 7 else tempNum+8
channel1Gain = (command[1] >> 4) & 7 # 7 = 0b111
command[2] = int(channel2PGAMUX)
tempNum = command[2] & 7 # 7 = 0b111
channel2Number = tempNum if (command[2] & 0xf) > 7 else tempNum+8
channel2Gain = (command[2] >> 4) & 7 # 7 = 0b111
command[3] = int(channel3PGAMUX)
tempNum = command[3] & 7 # 7 = 0b111
channel3Number = tempNum if (command[3] & 0xf) > 7 else tempNum+8
channel3Gain = (command[3] >> 4) & 7 # 7 = 0b111
if NumberOfScans > 1024 or NumberOfScans < 8:
raise U12Exception("The number of scans must be between 1024 and 8 (inclusive)")
NumScansExponentMod = 10 - int(math.ceil(math.log(NumberOfScans, 2)))
NumScans = 2 ** (10 - NumScansExponentMod)
bf = BitField( rawByte = (NumScansExponentMod << 5) )
# bits 4-3: IO to Trigger on
bf.bit2 = 0
bf.bit1 = int(bool(UpdateIO))
bf.bit0 = int(bool(LEDState))
command[4] = int(bf)
bf2 = BitField(rawByte = int(IO3ToIO0States))
#Bits 7-4: 1010 (Start Burst)
bf2.bit7 = 1
bf2.bit5 = 1
command[5] = int(bf2)
if SampleInterval < 733:
raise U12Exception("SampleInterval must be greater than 733.")
bf3 = BitField( rawByte = ((SampleInterval >> 8) & 0xf) )
bf3.bit7 = int(bool(FeatureReports))
bf3.bit6 = int(bool(TriggerOn))
command[6] = int(bf3)
command[7] = SampleInterval & 0xff
self.write(command)
resultsList = []
for i in range(NumScans):
resultsList.append(self.read())
returnDict = {}
returnDict['BufferOverflowOrChecksumErrors'] = list()
returnDict['PGAOvervoltages'] = list()
returnDict['IO3toIO0States'] = list()
returnDict['IterationCounters'] = list()
returnDict['Backlogs'] = list()
returnDict['Channel0'] = list()
returnDict['Channel1'] = list()
returnDict['Channel2'] = list()
returnDict['Channel3'] = list()
for results in resultsList:
bf = BitField(rawByte = results[0])
if bf.bit7 != 1 or bf.bit6 != 0:
raise U12Exception("Expected a AIBurst response, got %s instead." % results[0])
returnDict['BufferOverflowOrChecksumErrors'].append(bool(bf.bit5))
returnDict['PGAOvervoltages'].append(bool(bf.bit4))
returnDict['IO3toIO0States'].append(BitField(results[0], "IO", range(3, -1, -1), "Low", "High"))
returnDict['IterationCounters'].append((results[1] >> 5))
returnDict['Backlogs'].append(results[1] & 0xf)
channel0 = (results[2] >> 4) & 0xf
channel1 = (results[2] & 0xf)
channel2 = (results[5] >> 4) & 0xf
channel3 = (results[5] & 0xf)
channel0 = (channel0 << 8) + results[3]
returnDict['Channel0'].append(self.bitsToVolts(channel0Number, channel0Gain, channel0))
channel1 = (channel1 << 8) + results[4]
returnDict['Channel1'].append(self.bitsToVolts(channel1Number, channel1Gain, channel1))
channel2 = (channel2 << 8) + results[6]
returnDict['Channel2'].append(self.bitsToVolts(channel2Number, channel2Gain, channel2))
channel3 = (channel3 << 8) + results[7]
returnDict['Channel3'].append(self.bitsToVolts(channel3Number, channel3Gain, channel3))
return returnDict
def rawAIContinuous(self, channel0PGAMUX = 8, channel1PGAMUX = 9, channel2PGAMUX = 10, channel3PGAMUX = 11, FeatureReports = False, CounterRead = False, UpdateIO = False, LEDState = True, IO3ToIO0States = 0, SampleInterval = 15000):
"""
Currently in development.
The function is mostly implemented, but is currently too slow to be
useful.
"""
command = [ 0 ] * 8
# Bits 6-4: PGA for 1st Channel
# Bits 3-0: MUX command for 1st Channel
command[0] = int(channel0PGAMUX)
tempNum = command[0] & 7 # 7 = 0b111
channel0Number = tempNum if (command[0] & 0xf) > 7 else tempNum+8
channel0Gain = (command[0] >> 4) & 7 # 7 = 0b111
command[1] = int(channel1PGAMUX)
tempNum = command[1] & 7 # 7 = 0b111
channel1Number = tempNum if (command[1] & 0xf) > 7 else tempNum+8
channel1Gain = (command[1] >> 4) & 7 # 7 = 0b111
command[2] = int(channel2PGAMUX)
tempNum = command[2] & 7 # 7 = 0b111
channel2Number = tempNum if (command[2] & 0xf) > 7 else tempNum+8
channel2Gain = (command[2] >> 4) & 7 # 7 = 0b111
command[3] = int(channel3PGAMUX)
tempNum = command[3] & 7 # 7 = 0b111
channel3Number = tempNum if (command[3] & 0xf) > 7 else tempNum+8
channel3Gain = (command[3] >> 4) & 7 # 7 = 0b111
bf = BitField()
bf.bit7 = int(bool(FeatureReports))
bf.bit6 = int(bool(CounterRead))
bf.bit1 = int(bool(UpdateIO))
bf.bit0 = int(bool(LEDState))
command[4] = int(bf)
# Bits 7-4: 1001 (Start Continuous)
bf2 = BitField( rawByte = int(IO3ToIO0States) )
bf2.bit7 = 1
bf2.bit4 = 1
command[5] = int(bf2)
command[6] = ( SampleInterval >> 8)
command[7] = SampleInterval & 0xff
byte0bf = BitField()
returnDict = dict()
self.write(command)
while True:
results = self.read()
byte0bf.fromByte(results[0])
returnDict['Byte0'] = byte0bf
returnDict['IterationCounter'] = (results[1] >> 5)
returnDict['Backlog'] = results[1] & 0xf
yield returnDict
def rawPulseout(self, B1 = 10, C1 = 2, B2 = 10, C2 = 2, D7ToD0PulseSelection = 1, ClearFirst = False, NumberOfPulses = 5):
"""
Name: U12.rawPulseout( B1 = 10, C1 = 2, B2 = 10, C2 = 2,
D7ToD0PulseSelection = 1, ClearFirst = False,
NumberOfPulses = 5)
Args: B1, the B component of the first half cycle
C1, the C component of the first half cycle
B2, the B component of the second half cycle
C2, the C component of the second half cycle
D7ToD0PulseSelection, which D lines to pulse.
ClearFirst, True = Start Low.
NumberOfPulses, the number of pulses
Desc: This command creates pulses on any, or all, of D0-D7. The desired
D lines must be set to output with some other function. See
Section 5.7 of the User's Guide.
By default, pulses D0 5 times at 400us high, then 400 us low.
Returns: None
Example:
Have a jumper wire connected from D0 to CNT.
>>> import u12
>>> d = u12.U12()
>>> d.rawDIO(D7toD0Directions = 0, UpdateDigital = True)
>>> d.rawCounter(ResetCounter = True)
>>> d.rawPulseout(ClearFirst = True)
>>> print d.rawCounter()
{ 'IO3toIO0States': ... ,
'Counter': 5,
'D7toD0States': ... ,
'D15toD8States': ...
}
"""
command = [ 0 ] * 8
command[0] = B1
command[1] = C1
command[2] = B2
command[3] = C2
command[4] = int(D7ToD0PulseSelection)
# 01100100 (Pulseout)
bf = BitField()
bf.bit6 = 1
bf.bit5 = 1
bf.bit2 = 1
command[5] = int(bf)
bf2 = BitField( rawByte = ( NumberOfPulses >> 8 ) )
bf2.bit7 = int(bool(ClearFirst))
command[6] = int(bf2)
command[7] = NumberOfPulses & 0xff
self.write(command)
results = self.read()
if command[5] != results[5]:
raise U12Exception("Expected Pulseout response, got %s instead." % results[5])
if results[4] != 0:
errors = BitField(rawByte = command[4], labelPrefix = "D", zeroLabel = "Ok", oneLabel = "Error")
raise U12Exception("D7-D0 Direction error detected: %s" % errors)
return None
def rawReset(self):
"""
Name: U12.rawReset()
Desc: Sits in an infinite loop until micro watchdog timeout after about
2 seconds. See Section 5.8 of the User's Guide.
Note: The function will close the device after it has written the
command.
Returns: None
Example:
>>> import u12
>>> d = u12.U12()
>>> d.rawReset()
"""
command = [ 0 ] * 8
# 0b01011111 ( Reset )
bf = BitField()
bf.bit6 = 1
bf.bit4 = 1
bf.bit3 = 1
bf.bit2 = 1
bf.bit1 = 1
bf.bit0 = 1
command[5] = int(bf)
self.write(command)
self.close()
def rawReenumerate(self):
"""
Name: U12.rawReenumerate()
Desc: Detaches from the USB, reloads config parameters, and then
reattaches so the device can be re-enumerated. See Section 5.9 of
the User's Guide.
Note: The function will close the device after it has written the
command.
Returns: None
Example:
>>> import u12
>>> d = u12.U12()
>>> d.rawReenumerate()
"""
command = [ 0 ] * 8
# 0b01000000 (Re-Enumerate)
bf = BitField()
bf.bit6 = 1
command[5] = int(bf)
self.write(command)
self.close()
def rawWatchdog(self, IgnoreCommands = False, D0Active = False, D0State = False, D1Active = False, D1State = False, D8Active = False, D8State = False, ResetOnTimeout = False, WatchdogActive = False, Timeout = 60):
"""
Name: U12.rawWatchdog( IgnoreCommands = False, D0Active = False,
D0State = False, D1Active = False,
D1State = False, D8Active = False,
D8State = False, ResetOnTimeout = False,
WatchdogActive = False, Timeout = 60)
Desc: Sets the settings for the watchdog, or just reads the firmware
version of the U12. See section 5.10 of the User's Guide.
By defaults, just reads the firmware version.
Returns: A dictionary with the following keys:
FirmwareVersion, the firmware version of the U12.
Example:
>>> import u12
>>> d = u12.U12()
>>> print d.rawWatchdog()
{'FirmwareVersion': '1.10'}
"""
command = [ 0 ] * 8
command[0] = int(bool(IgnoreCommands))
bf = BitField()
bf.bit7 = int(D0Active)
bf.bit6 = int(D0State)
bf.bit5 = int(D1Active)
bf.bit4 = int(D1State)
bf.bit3 = int(D8Active)
bf.bit2 = int(D8State)
bf.bit1 = int(ResetOnTimeout)
bf.bit0 = int(WatchdogActive)
command[4] = int(bf)
# 01X1X011 (Watchdog)
bf2 = BitField()
bf2.bit6 = 1
bf2.bit4 = 1
bf2.bit1 = 1
bf2.bit0 = 1
command[5] = int(bf2)
# Timeout is increments of 2^16 cycles.
# 2^16 cycles is about 0.01 seconds.
binTimeout = int((float(Timeout) / 0.01))
command[6] = ( binTimeout >> 8 ) & 0xff
command[7] = binTimeout & 0xff
self.write(command)
results = self.read()
returnDict = dict()
returnDict['FirmwareVersion'] = "%s.%.2d" % (results[0], results[1])
return returnDict
def rawReadRAM(self, Address = 0):
"""
Name: U12.rawReadRAM(Address = 0)
Args: Address, the starting address to read from
Desc: Reads 4 bytes out of the U12's internal memory. See section 5.11
of the User's Guide.
By default, reads the bytes that make up the serial number.
Returns: A dictionary with the following keys:
DataByte0, the data byte at Address - 0
DataByte1, the data byte at Address - 1
DataByte2, the data byte at Address - 2
DataByte3, the data byte at Address - 3
Example:
>>> import u12, struct
>>> d = u12.U12()
>>> r = d.rawReadRAM()
>>> print r
{'DataByte3': 5, 'DataByte2': 246, 'DataByte1': 139, 'DataByte0': 170}
>>> bytes = [ r['DataByte3'], r['DataByte2'], r['DataByte1'], r['DataByte0'] ]
>>> print struct.unpack(">I", struct.pack("BBBB", *bytes))[0]
100043690
"""
command = [ 0 ] * 8
# 01010000 (Read RAM)
bf = BitField()
bf.bit6 = 1
bf.bit4 = 1
command[5] = int(bf)
command[6] = (Address >> 8) & 0xff
command[7] = Address & 0xff
self.write(command)
results = self.read()
if results[0] != int(bf):
raise U12Exception("Expected ReadRAM response, got %s" % results[0])
if (results[6] != command[6]) or (results[7] != command[7]):
receivedAddress = (results[6] << 8) + results[7]
raise U12Exception("Wanted address %s got address %s" % (Address, receivedAddress))
returnDict = dict()
returnDict['DataByte3'] = results[1]
returnDict['DataByte2'] = results[2]
returnDict['DataByte1'] = results[3]
returnDict['DataByte0'] = results[4]
return returnDict
def rawWriteRAM(self, Data, Address):
"""
Name: U12.rawWriteRAM(Data, Address)
Args: Data, a list of 4 bytes to write to memory.
Address, the starting address to write to.
Desc: Writes 4 bytes to the U12's internal memory. See section 5.13 of
the User's Guide.
No default behavior, you must pass Data and Address.
Returns: A dictionary with the following keys:
DataByte0, the data byte at Address - 0
DataByte1, the data byte at Address - 1
DataByte2, the data byte at Address - 2
DataByte3, the data byte at Address - 3
Example:
>>> import u12
>>> d = u12.U12()
>>> print d.rawWriteRAM([1, 2, 3, 4], 0x200)
{'DataByte3': 4, 'DataByte2': 3, 'DataByte1': 2, 'DataByte0': 1}
"""
command = [ 0 ] * 8
if not isinstance(Data, list) or len(Data) > 4:
raise U12Exception("Data wasn't a list, or was too long.")
Data.reverse()
command[:len(Data)] = Data
# 01010001 (Write RAM)
bf = BitField()
bf.bit6 = 1
bf.bit4 = 1
bf.bit0 = 1
command[5] = int(bf)
command[6] = (Address >> 8) & 0xff
command[7] = Address & 0xff
self.write(command)
results = self.read()
if results[0] != int(bf):
raise U12Exception("Expected ReadRAM response, got %s" % results[0])
if (results[6] != command[6]) or (results[7] != command[7]):
receivedAddress = (results[6] << 8) + results[7]
raise U12Exception("Wanted address %s got address %s" % (Address, receivedAddress))
returnDict = dict()
returnDict['DataByte3'] = results[1]
returnDict['DataByte2'] = results[2]
returnDict['DataByte1'] = results[3]
returnDict['DataByte0'] = results[4]
return returnDict
def rawAsynch(self, Data, AddDelay = False, TimeoutActive = False, SetTransmitEnable = False, PortB = False, NumberOfBytesToWrite = 0, NumberOfBytesToRead = 0):
"""
Name: U12.rawAsynch(Data, AddDelay = False, TimeoutActive = False,
SetTransmitEnable = False, PortB = False,
NumberOfBytesToWrite = 0, NumberOfBytesToRead = 0)
Args: Data, A list of bytes to write.
AddDelay, True to add a 1 bit delay between each transmit byte.
TimeoutActive, True to enable timeout for the receive phase.
SetTransmitEnable, True to set Transmit Enable to high during
transmit and low during receive.
PortB, True to use PortB instead of PortA.
NumberOfBytesToWrite, Number of bytes to write.
NumberOfBytesToRead, Number of bytes to read.
Desc: Requires firmware V1.1 or higher. This function writes and then
reads half-duplex asynchronous data on 1 of two pairs of D lines.
See section 5.13 of the User's Guide.
Returns: A dictionary with the following keys,
DataByte0-3, the first four data bytes read over the RX line
ErrorFlags, a BitField representing the error flags.
Example:
>>> import u12
>>> d = u12.U12()
>>> # Set the full and half A,B,C to 9600
>>> d.rawWriteRAM([0, 1, 1, 200], 0x073)
>>> d.rawWriteRAM([5, 1, 2, 48], 0x076)
>>> print d.rawAsynch([1, 2, 3, 4], NumberOfBytesToWrite = 4, NumberOfBytesToRead = 4)
{
'DataByte3': 4,
'DataByte2': 3,
'DataByte1': 2,
'DataByte0': 1,
'ErrorFlags': <BitField object: [ Timeout Error Flag = 0 (0), ... ] >
}
"""
command = [ 0 ] * 8
if not isinstance(Data, list) or len(Data) > 4:
raise U12Exception("Data wasn't a list, or was too long.")
NumberOfBytesToWrite = NumberOfBytesToRead & 0xff
NumberOfBytesToRead = NumberOfBytesToRead & 0xff
if NumberOfBytesToWrite > 18:
raise U12Exception("Can only write 18 or fewer bytes at a time.")
if NumberOfBytesToRead > 18:
raise U12Exception("Can only read 18 or fewer bytes at a time.")
Data.reverse()
command[:len(Data)] = Data
bf = BitField()
bf.bit3 = int(bool(AddDelay))
bf.bit2 = int(bool(TimeoutActive))
bf.bit1 = int(bool(SetTransmitEnable))
bf.bit0 = int(bool(PortB))
command[4] = int(bf)
#01100001 (Asynch)
bf2 = BitField()
bf2.bit6 = 1
bf2.bit5 = 1
bf2.bit0 = 1
command[5] = int(bf2)
command[6] = NumberOfBytesToWrite
command[7] = NumberOfBytesToRead
self.write(command)
results = self.read()
if command[5] != results[5]:
raise U12Exception("Expected Asynch response, got %s instead." % results[5])
returnDict = dict()
returnDict['DataByte3'] = results[0]
returnDict['DataByte2'] = results[1]
returnDict['DataByte1'] = results[2]
returnDict['DataByte0'] = results[3]
bfLabels = ["Timeout Error Flag", "STRT Error Flag", "FRM Error Flag", "RXTris Error Flag", "TETris Error Flag", "TXTris Error Flag"]
bf = BitField( rawByte = results[4], labelPrefix = "", labelList = bfLabels )
returnDict["ErrorFlags"] = bf
return returnDict
SPIModes = ['A', 'B', 'C', 'D']
def rawSPI(self, Data, AddMsDelay = False, AddHundredUsDelay = False, SPIMode = 'A', NumberOfBytesToWriteRead = 0, ControlCS = False, StateOfActiveCS = False, CSLineNumber = 0):
"""
Name: U12.rawSPI( Data, AddMsDelay = False, AddHundredUsDelay = False,
SPIMode = 'A', NumberOfBytesToWriteRead = 0,
ControlCS = False, StateOfActiveCS = False,
CSLineNumber = 0)
Args: Data, A list of four bytes to write using SPI
AddMsDelay, If True, a 1 ms delay is added between each bit
AddHundredUsDelay, if True, 100us delay is added
SPIMode, 'A', 'B', 'C', or 'D'
NumberOfBytesToWriteRead, number of bytes to write and read.
ControlCS, D0-D7 is automatically controlled as CS. The state and
direction of CS is only tested if control is enabled.
StateOfActiveCS, Active state for CS line.
CSLineNumber, D line to use as CS if enabled (0-7).
Desc: This function performs SPI communication. See Section 5.14 of the
User's Guide.
Returns: A dictionary with the following keys,
DataByte0-3, the first four data bytes read
ErrorFlags, a BitField representing the error flags.
Example:
>>> import u12
>>> d = u12.U12()
>>> d.rawSPI([1,2,3,4], NumberOfBytesToWriteRead = 4)
{
'DataByte3': 4,
'DataByte2': 3,
'DataByte1': 2,
'DataByte0': 1,
'ErrorFlags':
<BitField object: [ CSStateTris Error Flag = 0 (0), ... ] >
}
"""
command = [ 0 ] * 8
if not isinstance(Data, list) or len(Data) > 4:
raise U12Exception("Data wasn't a list, or was too long.")
NumberOfBytesToWriteRead = NumberOfBytesToWriteRead & 0xff
if NumberOfBytesToWriteRead == 0:
NumberOfBytesToWriteRead = len(Data)
if NumberOfBytesToWriteRead > 18 or NumberOfBytesToWriteRead < 1:
raise U12Exception("Can only read/write 1 to 18 bytes at a time.")
Data.reverse()
command[:len(Data)] = Data
bf = BitField()
bf.bit7 = int(bool(AddMsDelay))
bf.bit6 = int(bool(AddHundredUsDelay))
modeIndex = self.SPIModes.index(SPIMode)
bf[7-modeIndex] = 1
command[4] = int(bf)
# 01100010 (SPI)
bf2 = BitField()
bf2.bit6 = 1
bf2.bit5 = 1
bf2.bit1 = 1
command[5] = int(bf2)
command[6] = NumberOfBytesToWriteRead
bf3 = BitField(rawByte = CSLineNumber)
bf3.bit7 = int(bool(ControlCS))
bf3.bit6 = int(bool(StateOfActiveCS))
command[7] = int(bf3)
self.write(command)
results = self.read()
if results[5] != command[5]:
raise U12Exception("Expected SPI response, got %s instead." % results[5])
returnDict = dict()
returnDict['DataByte3'] = results[0]
returnDict['DataByte2'] = results[1]
returnDict['DataByte1'] = results[2]
returnDict['DataByte0'] = results[3]
bfLabels = ["CSStateTris Error Flag", "SCKTris Error Flag", "MISOTris Error Flag", "MOSITris Error Flag"]
bf = BitField( rawByte = results[4], labelPrefix = "", labelList = bfLabels )
returnDict["ErrorFlags"] = bf
return returnDict
def rawSHT1X(self, Data = [3,0,0,0], WaitForMeasurementReady = True, IssueSerialReset = False, Add1MsDelay = False, Add300UsDelay = False, IO3State = 1, IO2State = 1, IO3Direction = 1, IO2Direction = 1, NumberOfBytesToWrite = 1, NumberOfBytesToRead = 3):
"""
Name: U12.rawSHT1X( Data = [3, 0, 0, 0],
WaitForMeasurementReady = True,
IssueSerialReset = False, Add1MsDelay = False,
Add300UsDelay = False, IO3State = 1, IO2State = 1,
IO3Direction = 1, IO2Direction = 1,
NumberOfBytesToWrite = 1, NumberOfBytesToRead = 3)
Args: Data, a list of bytes to write to the SHT.
WaitForMeasurementReady, Wait for the measurement ready signal.
IssueSerialReset, perform a serial reset
Add1MsDelay, adds 1ms delay
Add300UsDelay, adds a 300us delay
IO3State, sets the state of IO3
IO2State, sets the state of IO2
IO3Direction, sets the direction of IO3 ( 1 = Output )
IO2Direction, sets the direction of IO3 ( 1 = Output )
NumberOfBytesToWrite, how many bytes to write
NumberOfBytesToRead, how may bytes to read back
Desc: Sends and receives data from a SHT1X T/RH sensor from Sensirion.
See Section 5.15 of the User's Guide.
By default, reads the temperature from the SHT.
Returns: A dictionary with the following keys,
DataByte0-3, the four data bytes read
ErrorFlags, a BitField representing the error flags.
Example:
Uses an EI-1050 Temp/Humidity probe wired as follows:
Data ( Green ) -> IO0
Clock ( White ) -> IO1
Ground ( Black ) -> GND
Power ( Red ) -> +5V
Enable ( Brown ) -> IO2
>>> import u12
>>> d = u12.U12()
>>> results = d.rawSHT1X()
>>> print results
{
'DataByte3': 0,
'DataByte2': 69,
'DataByte1': 48,
'DataByte0': 25,
'ErrorFlags':
<BitField object: [ Serial Reset Error Flag = 0 (0), ... ] >
}
>>> tempC = (results['DataByte0'] * 256 ) + results['DataByte1']
>>> tempC = (tempC * 0.01) - 40
>>> print tempC
24.48
>>> results = d.rawSHT1X(Data = [5,0,0,0])
>>> print results
{
'DataByte3': 0,
'DataByte2': 200,
'DataByte1': 90,
'DataByte0': 2,
'ErrorFlags':
<BitField object: [ Serial Reset Error Flag = 0 (0), ... ] >
}
>>> sorh = (results['DataByte0'] * 256 ) + results['DataByte1']
>>> rhlinear = (-0.0000028*sorh*sorh)+(0.0405*sorh)-4.0
>>> rh = ((tempC-25.0)*(0.01+(0.00008*sorh)))+rhlinear
>>> print rh
19.3360256
"""
command = [ 0 ] * 8
if NumberOfBytesToWrite != 0:
if not isinstance(Data, list) or len(Data) > 4:
raise U12Exception("Data wasn't a list, or was too long.")
Data.reverse()
command[:len(Data)] = Data
if max(NumberOfBytesToWrite, NumberOfBytesToRead) > 4:
raise U12Exception("Can only read/write up to 4 bytes at a time.")
bf = BitField()
bf.bit7 = int(bool(WaitForMeasurementReady))
bf.bit6 = int(bool(IssueSerialReset))
bf.bit5 = int(bool(Add1MsDelay))
bf.bit4 = int(bool(Add300UsDelay))
bf.bit3 = int(bool(IO3State))
bf.bit2 = int(bool(IO2State))
bf.bit1 = int(bool(IO3Direction))
bf.bit0 = int(bool(IO2Direction))
command[4] = int(bf)
# 01101000 (SHT1X)
bf2 = BitField()
bf2.bit6 = 1
bf2.bit5 = 1
bf2.bit3 = 1
command[5] = int(bf2)
command[6] = NumberOfBytesToWrite
command[7] = NumberOfBytesToRead
self.write(command)
results = self.read()
if results[5] != command[5]:
raise U12Exception("Expected SHT1x response, got %s instead." % results[5])
returnDict = dict()
returnDict['DataByte3'] = results[0]
returnDict['DataByte2'] = results[1]
returnDict['DataByte1'] = results[2]
returnDict['DataByte0'] = results[3]
bfLabels = ["Serial Reset Error Flag", "Measurement Ready Error Flag", "Ack Error Flag"]
bf = BitField( rawByte = results[4], labelPrefix = "", labelList = bfLabels )
returnDict["ErrorFlags"] = bf
return returnDict
def eAnalogIn(self, channel, idNum = None, demo=0, gain=0):
"""
Name: U12.eAnalogIn(channel, idNum = None, demo=0, gain=0)
Args: See section 4.1 of the User's Guide
Desc: This is a simplified version of AISample. Reads the voltage from 1 analog input
>>> import u12
>>> d = u12.U12()
>>> d.eAnalogIn(0)
{'overVoltage': 0, 'idnum': 1, 'voltage': 1.435546875}
"""
if idNum is None:
idNum = self.id
if ON_WINDOWS:
ljid = ctypes.c_long(idNum)
ad0 = ctypes.c_long(999)
ad1 = ctypes.c_float(999)
ecode = staticLib.EAnalogIn(ctypes.byref(ljid), demo, channel, gain, ctypes.byref(ad0), ctypes.byref(ad1))
if ecode != 0: raise U12Exception(ecode)
return {"idnum":ljid.value, "overVoltage":ad0.value, "voltage":ad1.value}
else:
# Bits 6-4: PGA for 1st Channel
# Bits 3-0: MUX command for 1st Channel
channel0PGAMUX = ( ( gain & 7 ) << 4)
channel0PGAMUX += channel-8 if channel > 7 else channel+8
results = self.rawAISample(channel0PGAMUX = channel0PGAMUX)
return {"idnum" : self.id, "overVoltage" : int(results['PGAOvervoltage']), 'voltage' : results['Channel0']}
def eAnalogOut(self, analogOut0, analogOut1, idNum = None, demo=0):
"""
Name: U12.eAnalogOut(analogOut0, analogOut1, idNum = None, demo=0)
Args: See section 4.2 of the User's Guide
Desc: This is a simplified version of AOUpdate. Sets the voltage of both analog outputs.
>>> import u12
>>> d = u12.U12()
>>> d.eAnalogOut(2, 2)
{'idnum': 1}
"""
if idNum is None:
idNum = self.id
if ON_WINDOWS:
ljid = ctypes.c_long(idNum)
ecode = staticLib.EAnalogOut(ctypes.byref(ljid), demo, ctypes.c_float(analogOut0), ctypes.c_float(analogOut1))
if ecode != 0: raise U12Exception(ecode)
return {"idnum":ljid.value}
else:
if analogOut0 < 0:
analogOut0 = self.pwmAVoltage
if analogOut1 < 0:
analogOut1 = self.pwmBVoltage
self.rawCounterPWMDIO(PWMA = analogOut0, PWMB = analogOut1)
self.pwmAVoltage = analogOut0
self.pwmBVoltage = analogOut1
return {"idnum": self.id}
def eCount(self, idNum = None, demo = 0, resetCounter = 0):
"""
Name: U12.eCount(idNum = None, demo = 0, resetCounter = 0)
Args: See section 4.3 of the User's Guide
Desc: This is a simplified version of Counter. Reads & resets the counter (CNT).
>>> import u12
>>> d = u12.U12()
>>> d.eCount()
{'count': 1383596032.0, 'ms': 251487257.0}
"""
# Check id num
if idNum is None:
idNum = self.id
if ON_WINDOWS:
ljid = ctypes.c_long(idNum)
count = ctypes.c_double()
ms = ctypes.c_double()
ecode = staticLib.ECount(ctypes.byref(ljid), demo, resetCounter, ctypes.byref(count), ctypes.byref(ms))
if ecode != 0: raise U12Exception(ecode)
return {"idnum":ljid.value, "count":count.value, "ms":ms.value}
else:
results = self.rawCounter( ResetCounter = resetCounter)
return {"idnum":self.id, "count":results['Counter'], "ms": (time() * 1000)}
def eDigitalIn(self, channel, idNum = None, demo = 0, readD=0):
"""
Name: U12.eDigitalIn(channel, idNum = None, demo = 0, readD=0)
Args: See section 4.4 of the User's Guide
Desc: This is a simplified version of DigitalIO that reads the state of
one digital input. Also configures the requested pin to input and
leaves it that way.
>>> import u12
>>> d = u12.U12()
>>> d.eDigitalIn(0)
{'state': 0, 'idnum': 1}
"""
# Check id num
if idNum is None:
idNum = self.id
if ON_WINDOWS:
ljid = ctypes.c_long(idNum)
state = ctypes.c_long(999)
ecode = staticLib.EDigitalIn(ctypes.byref(ljid), demo, channel, readD, ctypes.byref(state))
if ecode != 0: raise U12Exception(ecode)
return {"idnum":ljid.value, "state":state.value}
else:
oldstate = self.rawDIO()
if readD:
if channel > 7:
channel = channel-7
direction = BitField(rawByte = oldstate['D15toD8Directions'])
direction[7-channel] = 1
results = self.rawDIO(D15toD8Directions = direction, UpdateDigital = True)
state = results["D15toD8States"][7-channel]
else:
direction = BitField(rawByte = oldstate['D7toD0Directions'])
direction[7-channel] = 1
results = self.rawDIO(D7ToD0Directions = direction, UpdateDigital = True)
state = results["D15toD8States"][7-channel]
else:
results = self.rawDIO(IO3toIO0DirectionsAndStates = 255, UpdateDigital = True)
state = results["IO3toIO0States"][3-channel]
return {"idnum" : self.id, "state" : state}
def eDigitalOut(self, channel, state, idNum = None, demo = 0, writeD=0):
"""
Name: U12.eDigitalOut(channel, state, idNum = None, demo = 0, writeD=0)
Args: See section 4.5 of the User's Guide
Desc: This is a simplified version of DigitalIO that sets/clears the
state of one digital output. Also configures the requested pin to
output and leaves it that way.
>>> import u12
>>> d = u12.U12()
>>> d.eDigitalOut(0, 1)
{idnum': 1}
"""
# Check id num
if idNum is None:
idNum = self.id
if ON_WINDOWS:
ljid = ctypes.c_long(idNum)
ecode = staticLib.EDigitalOut(ctypes.byref(ljid), demo, channel, writeD, state)
if ecode != 0: raise U12Exception(ecode)
return {"idnum":ljid.value}
else:
oldstate = self.rawDIO()
if writeD:
if channel > 7:
channel = channel-7
direction = BitField(rawByte = int(oldstate['D15toD8Directions']))
direction[7-channel] = 0
states = BitField(rawByte = int(oldstate['D15toD8States']))
states[7-channel] = state
self.rawDIO(D15toD8Directions = direction, D15toD8States = state, UpdateDigital = True)
else:
direction = BitField(rawByte = int(oldstate['D7toD0Directions']))
direction[7-channel] = 0
states = BitField(rawByte = int(oldstate['D7toD0States']))
states[7-channel] = state
self.rawDIO(D7toD0Directions = direction, D7toD0States = states, UpdateDigital = True)
else:
bf = BitField()
bf[7-(channel+4)] = 0
bf[7-channel] = state
self.rawDIO(IO3toIO0DirectionsAndStates = bf, UpdateDigital = True)
return {"idnum" : self.id}
def aiSample(self, numChannels, channels, idNum=None, demo=0, stateIOin=0, updateIO=0, ledOn=0, gains=[0, 0, 0, 0], disableCal=0):
"""
Name: U12.aiSample(channels, idNum=None, demo=0, stateIOin=0, updateIO=0, ledOn=0, gains=[0, 0, 0, 0], disableCal=0)
Args: See section 4.6 of the User's Guide
Desc: Reads the voltages from 1,2, or 4 analog inputs. Also controls/reads the 4 IO ports.
>>> dev = U12()
>>> dev.aiSample(2, [0, 1])
{'stateIO': [0, 0, 0, 0], 'overVoltage': 0, 'idnum': 1, 'voltages': [1.4208984375, 1.4306640625]}
"""
# Check id num
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
# Check to make sure that everything is checked
if not isIterable(channels): raise TypeError("channels must be iterable")
if not isIterable(gains): raise TypeError("gains must be iterable")
if len(channels) < numChannels: raise ValueError("channels must have atleast numChannels elements")
if len(gains) < numChannels: raise ValueError("gains must have atleast numChannels elements")
# Convert lists to arrays and create other ctypes
channelsArray = listToCArray(channels, ctypes.c_long)
gainsArray = listToCArray(gains, ctypes.c_long)
overVoltage = ctypes.c_long(999)
longArrayType = (ctypes.c_long * 4)
floatArrayType = (ctypes.c_float * 4)
voltages = floatArrayType(0, 0, 0, 0)
stateIOin = ctypes.c_long(stateIOin)
ecode = staticLib.AISample(ctypes.byref(idNum), demo, ctypes.byref(stateIOin), updateIO, ledOn, numChannels, ctypes.byref(channelsArray), ctypes.byref(gainsArray), disableCal, ctypes.byref(overVoltage), ctypes.byref(voltages))
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value, "stateIO":stateIOin.value, "overVoltage":overVoltage.value, "voltages":voltages[0:numChannels]}
def aiBurst(self, numChannels, channels, scanRate, numScans, idNum=None, demo=0, stateIOin=0, updateIO=0, ledOn=0, gains=[0, 0, 0, 0], disableCal=0, triggerIO=0, triggerState=0, timeout=1, transferMode=0):
"""
Name: U12.aiBurst(numChannels, channels, scanRate, numScans, idNum=None, demo=0, stateIOin=[0, 0, 0, 0], updateIO=0, ledOn=0, gains=[0, 0, 0, 0], disableCal=0, triggerIO=0, triggerState=0, timeout=1, transferMode=0)
Args: See section 4.7 of the User's Guide
Desc: Reads a specified number of scans (up to 4096) at a specified scan rate (up to 8192 Hz) from 1,2, or 4 analog inputs
>>> dev = U12()
>>> dev.aiBurst(1, [0], 400, 10)
{'overVoltage': 0, 'scanRate': 400.0, 'stateIOout': <u12.c_long_Array_4096 object at 0x00DB4BC0>, 'idnum': 1, 'voltages': <u12.c_float_Array_4096_Array_4 object at 0x00DB4B70>}
"""
# Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
# check list sizes
if len(channels) < numChannels: raise ValueError("channels must have atleast numChannels elements")
if len(gains) < numChannels: raise ValueError("gains must have atleast numChannels elements")
# Convert lists to arrays and create other ctypes
channelsArray = listToCArray(channels, ctypes.c_long)
gainsArray = listToCArray(gains, ctypes.c_long)
scanRate = ctypes.c_float(scanRate)
pointerArray = (ctypes.c_void_p * 4)
arr4096_type = ctypes.c_float * 4096
voltages_type = arr4096_type * 4
voltages = voltages_type()
stateIOout = (ctypes.c_long * 4096)()
overVoltage = ctypes.c_long(999)
ecode = staticLib.AIBurst(ctypes.byref(idNum), demo, stateIOin, updateIO, ledOn, numChannels, ctypes.byref(channelsArray), ctypes.byref(gainsArray), ctypes.byref(scanRate), disableCal, triggerIO, triggerState, numScans, timeout, ctypes.byref(voltages), ctypes.byref(stateIOout), ctypes.byref(overVoltage), transferMode)
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value, "scanRate":scanRate.value, "voltages":voltages, "stateIOout":stateIOout, "overVoltage":overVoltage.value}
def aiStreamStart(self, numChannels, channels, scanRate, idNum=None, demo=0, stateIOin=0, updateIO=0, ledOn=0, gains=[0, 0, 0, 0], disableCal=0, readCount=0):
"""
Name: U12.aiStreamStart(numChannels, channels, scanRate, idNum=None, demo=0, stateIOin=0, updateIO=0, ledOn=0, gains=[0, 0, 0, 0], disableCal=0, readCount=0)
Args: See section 4.8 of the User's Guide
Desc: Starts a hardware timed continuous acquisition
>>> dev = U12()
>>> dev.aiStreamStart(1, [0], 200)
{'scanRate': 200.0, 'idnum': 1}
"""
# Configure return type
staticLib.AIStreamStart.restype = ctypes.c_long
# check list sizes
if len(channels) < numChannels: raise ValueError("channels must have atleast numChannels elements")
if len(gains) < numChannels: raise ValueError("gains must have atleast numChannels elements")
#if len(stateIOin) < 4: raise ValueError("stateIOin must have atleast 4 elements")
# Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
# Convert lists to arrays and create other ctypes
channelsArray = listToCArray(channels, ctypes.c_long)
gainsArray = listToCArray(gains, ctypes.c_long)
scanRate = ctypes.c_float(scanRate)
ecode = staticLib.AIStreamStart(ctypes.byref(idNum), demo, stateIOin, updateIO, ledOn, numChannels, ctypes.byref(channelsArray), ctypes.byref(gainsArray), ctypes.byref(scanRate), disableCal, 0, readCount)
if ecode != 0: raise U12Exception(ecode) # TODO: Switch this out for exception
# The ID number must be saved for AIStream
self.id = idNum.value
self.streaming = True
return {"idnum":idNum.value, "scanRate":scanRate.value}
def aiStreamRead(self, numScans, localID=None, timeout=1):
"""
Name: U12.aiStreamRead(numScans, localID=None, timeout=1)
Args: See section 4.9 of the User's Guide
Desc: Waits for a specified number of scans to be available and reads them.
>>> dev = U12()
>>> dev.aiStreamStart(1, [0], 200)
>>> dev.aiStreamRead(10)
{'overVoltage': 0, 'ljScanBacklog': 0, 'stateIOout': <u12.c_long_Array_4096 object at 0x00DF4AD0>, 'reserved': 0, 'voltages': <u12.c_float_Array_4096_Array_4 object at 0x00DF4B20>}
"""
# Check to make sure that we are streaming
if not self.streaming:
raise U12Exception(-1, "Streaming has not started")
# Check id number
if localID is None:
localID = self.id
# Create arrays and other ctypes
arr4096_type = ctypes.c_float * 4096
voltages_type = arr4096_type * 4
voltages = voltages_type()
stateIOout = (ctypes.c_long * 4096)()
reserved = ctypes.c_long(0)
ljScanBacklog = ctypes.c_long(99999)
overVoltage = ctypes.c_long(999)
ecode = staticLib.AIStreamRead(localID, numScans, timeout, ctypes.byref(voltages), ctypes.byref(stateIOout), ctypes.byref(reserved), ctypes.byref(ljScanBacklog), ctypes.byref(overVoltage))
if ecode != 0: raise U12Exception(ecode) # TODO: Switch this out for exception
return {"voltages":voltages, "stateIOout":stateIOout, "reserved":reserved.value, "ljScanBacklog":ljScanBacklog.value, "overVoltage":overVoltage.value}
def aiStreamClear(self, localID=None):
"""
Name: U12.aiClear()
Args: See section 4.10 of the User's Guide
Desc: This function stops the continuous acquisition. It should be called once when finished with the stream.
>>> dev = U12()
>>> dev.aiStreamStart(1, [0], 200)
>>> dev.aiStreamRead(10)
>>> dev.aiStreamClear()
"""
# Check to make sure that we are streaming
if not self.streaming:
raise U12Exception(-1, "Streaming has not started")
# Check id number
if localID is None:
localID = self.id
ecode = staticLib.AIStreamClear(localID)
if ecode != 0: raise U12Exception(ecode) # TODO: Switch this out for exception
def aoUpdate(self, idNum=None, demo=0, trisD=None, trisIO=None, stateD=None, stateIO=None, updateDigital=0, resetCounter=0, analogOut0=0, analogOut1=0):
"""
Name: U12.aoUpdate()
Args: See section 4.11 of the User's Guide
Desc: Sets the voltages of the analog outputs. Also controls/reads all 20 digital I/O and the counter.
>>> dev = U12()
>>> dev.aoUpdate()
>>> {'count': 2, 'stateIO': 3, 'idnum': 1, 'stateD': 0}
"""
# Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
# Check tris and state arguments
if updateDigital > 0:
if trisD is None: raise ValueError("keyword argument trisD must be set")
if trisIO is None: raise ValueError("keyword argument trisIO must be set")
if stateD is None: raise ValueError("keyword argument stateD must be set")
if stateIO is None: raise ValueError("keyword argument stateIO must be set")
# Create ctypes
if stateD is None: stateD = ctypes.c_long(0)
else: stateD = ctypes.c_long(stateD)
if stateIO is None: stateIO = ctypes.c_long(0)
else: stateIO = ctypes.c_long(stateIO)
count = ctypes.c_ushort(999)
# Create arrays and other ctypes
ecode = staticLib.AOUpdate(ctypes.byref(idNum), demo, trisD, trisIO, ctypes.byref(stateD), ctypes.byref(stateIO), updateDigital, resetCounter, ctypes.byref(count), ctypes.c_float(analogOut0), ctypes.c_float(analogOut1))
if ecode != 0: raise U12Exception(ecode) # TODO: Switch this out for exception
return {"idnum":idNum.value, "stateD":stateD.value, "stateIO":stateIO.value, "count":count.value}
def asynchConfig(self, fullA, fullB, fullC, halfA, halfB, halfC, idNum=None, demo=None, timeoutMult=1, configA=0, configB=0, configTE=0):
"""
Name: U12.asynchConfig(fullA, fullB, fullC, halfA, halfB, halfC, idNum=None, demo=None, timeoutMult=1, configA=0, configB=0, configTE=0)
Args: See section 4.12 of the User's Guide
Desc: Requires firmware V1.1 or higher. This function writes to the asynch registers and sets the direction of the D lines (input/output) as needed.
>>> dev = U12()
>>> dev.asynchConfig(96,1,1,22,2,1)
>>> {'idNum': 1}
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
ecode = staticLib.AsynchConfig(ctypes.byref(idNum), demo, timeoutMult, configA, configB, configTE, fullA, fullB, fullC, halfA, halfB, halfC)
if ecode != 0: raise U12Exception(ecode) # TODO: Switch this out for exception
return {"idNum":idNum.value}
def asynch(self, baudrate, data, idNum=None, demo=0, portB=0, enableTE=0, enableTO=0, enableDel=0, numWrite=0, numRead=0):
"""
Name: U12.asynchConfig(fullA, fullB, fullC, halfA, halfB, halfC, idNum=None, demo=None, timeoutMult=1, configA=0, configB=0, configTE=0)
Args: See section 4.13 of the User's Guide
Desc: Requires firmware V1.1 or higher. This function writes to the asynch registers and sets the direction of the D lines (input/output) as needed.
>>> dev = U12()
>>> dev.asynch(96,1,1,22,2,1)
>>> dev.asynch(19200, [0, 0])
>>> {'data': <u12.c_long_Array_18 object at 0x00DEFB70>, 'idnum': <type 'long'>}
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
# Check size of data
if len(data) > 18: raise ValueError("data can not be larger than 18 elements")
# Make data 18 elements large
dataArray = [0] * 18
for i in range(0, len(data)):
dataArray[i] = data[i]
print dataArray
dataArray = listToCArray(dataArray, ctypes.c_long)
ecode = staticLib.Asynch(ctypes.byref(idNum), demo, portB, enableTE, enableTO, enableDel, baudrate, numWrite, numRead, ctypes.byref(dataArray))
if ecode != 0: raise U12Exception(ecode) # TODO: Switch this out for exception
return {"idnum":long, "data":dataArray}
GainMapping = [ 1.0, 2.0, 4.0, 5.0, 8.0, 10.0, 16.0, 20.0 ]
def bitsToVolts(self, chnum, chgain, bits):
"""
Name: U12.bitsToVolts(chnum, chgain, bits)
Args: See section 4.14 of the User's Guide
Desc: Converts a 12-bit (0-4095) binary value into a LabJack voltage. No hardware communication is involved.
>>> dev = U12()
>>> dev.bitsToVolts(0, 0, 2662)
>>> {'volts': 2.998046875}
"""
if ON_WINDOWS:
volts = ctypes.c_float()
ecode = staticLib.BitsToVolts(chnum, chgain, bits, ctypes.byref(volts))
if ecode != 0: print ecode
return volts.value
else:
if chnum < 8:
return ( float(bits) * 20.0 / 4096.0 ) - 10.0
else:
volts = ( float(bits) * 40.0 / 4096.0 ) - 20.0
return volts / self.GainMapping[chgain]
def voltsToBits(self, chnum, chgain, volts):
"""
Name: U12.voltsToBits(chnum, chgain, bits)
Args: See section 4.15 of the User's Guide
Desc: Converts a voltage to it's 12-bit (0-4095) binary representation. No hardware communication is involved.
>>> dev = U12()
>>> dev.voltsToBits(0, 0, 3)
>>> {'bits': 2662}
"""
if ON_WINDOWS:
bits = ctypes.c_long(999)
ecode = staticLib.VoltsToBits(chnum, chgain, ctypes.c_float(volts), ctypes.byref(bits))
if ecode != 0: raise U12Exception(ecode)
return bits.value
else:
pass
#*bits = RoundFL((volts+10.0F)/(20.0F/4096.0F));
def counter(self, idNum=None, demo=0, resetCounter=0, enableSTB=1):
"""
Name: U12.counter(idNum=None, demo=0, resetCounter=0, enableSTB=1)
Args: See section 4.15 of the User's Guide
Desc: Converts a voltage to it's 12-bit (0-4095) binary representation. No hardware communication is involved.
>>> dev = U12()
>>> dev.counter(0, 0, 3)
>>> {'bits': 2662}
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
# Create ctypes
stateD = ctypes.c_long(999)
stateIO = ctypes.c_long(999)
count = ctypes.c_ulong(999)
print idNum
ecode = staticLib.Counter(ctypes.byref(idNum), demo, ctypes.byref(stateD), ctypes.byref(stateIO), resetCounter, enableSTB, ctypes.byref(count))
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value, "stateD": stateD.value, "stateIO":stateIO.value, "count":count.value}
def digitalIO(self, idNum=None, demo=0, trisD=None, trisIO=None, stateD=None, stateIO=None, updateDigital=0):
"""
Name: U12.digitalIO(idNum=None, demo=0, trisD=None, trisIO=None, stateD=None, stateIO=None, updateDigital=0)
Args: See section 4.17 of the User's Guide
Desc: Reads and writes to all 20 digital I/O.
>>> dev = U12()
>>> dev.digitalIO()
>>> {'stateIO': 0, 'stateD': 0, 'idnum': 1, 'outputD': 0, 'trisD': 0}
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
# Check tris and state parameters
if updateDigital > 0:
if trisD is None: raise ValueError("keyword argument trisD must be set")
if trisIO is None: raise ValueError("keyword argument trisIO must be set")
if stateD is None: raise ValueError("keyword argument stateD must be set")
if stateIO is None: raise ValueError("keyword argument stateIO must be set")
# Create ctypes
if trisD is None: trisD = ctypes.c_long(999)
else:trisD = ctypes.c_long(trisD)
if stateD is None:stateD = ctypes.c_long(999)
else: stateD = ctypes.c_long(stateD)
if stateIO is None: stateIO = ctypes.c_long(0)
else: stateIO = ctypes.c_long(stateIO)
outputD = ctypes.c_long(999)
# Check trisIO
if trisIO is None: trisIO = 0
ecode = staticLib.DigitalIO(ctypes.byref(idNum), demo, ctypes.byref(trisD), trisIO, ctypes.byref(stateD), ctypes.byref(stateIO), updateDigital, ctypes.byref(outputD))
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value, "trisD":trisD.value, "stateD":stateD.value, "stateIO":stateIO.value, "outputD":outputD.value}
def getDriverVersion(self):
"""
Name: U12.getDriverVersion()
Args: See section 4.18 of the User's Guide
Desc: Returns the version number of ljackuw.dll. No hardware communication is involved.
>>> dev = U12()
>>> dev.getDriverVersion()
>>> 1.21000003815
"""
staticLib.GetDriverVersion.restype = ctypes.c_float
return staticLib.GetDriverVersion()
def getFirmwareVersion(self, idNum=None):
"""
Name: U12.getErrorString(idnum=None)
Args: See section 4.20 of the User's Guide
Desc: Retrieves the firmware version from the LabJack's processor
>>> dev = U12()
>>> dev.getFirmwareVersion()
>>> Unkown error
"""
# Check ID number
if idNum is None: idNum = self.id
idNum = ctypes.c_long(idNum)
staticLib.GetFirmwareVersion.restype = ctypes.c_float
firmware = staticLib.GetFirmwareVersion(ctypes.byref(idNum))
if firmware > 512: raise U12Exception(firmware-512)
return {"idnum" : idNum.value, "firmware" : firmware}
def getWinVersion(self):
"""
Name: U12.getErrorString()
Args: See section 4.21 of the User's Guide
Desc: Uses a Windows API function to get the OS version
>>> dev = U12()
>>> dev.getWinVersion()
>>> {'majorVersion': 5L, 'minorVersion': 1L, 'platformID': 2L, 'buildNumber': 2600L, 'servicePackMajor': 2L, 'servicePackMinor': 0L}
"""
# Create ctypes
majorVersion = ctypes.c_ulong()
minorVersion = ctypes.c_ulong()
buildNumber = ctypes.c_ulong()
platformID = ctypes.c_ulong()
servicePackMajor = ctypes.c_ulong()
servicePackMinor = ctypes.c_ulong()
ecode = staticLib.GetWinVersion(ctypes.byref(majorVersion), ctypes.byref(minorVersion), ctypes.byref(buildNumber), ctypes.byref(platformID), ctypes.byref(servicePackMajor), ctypes.byref(servicePackMinor))
if ecode != 0: raise U12Exception(ecode)
return {"majorVersion":majorVersion.value, "minorVersion":minorVersion.value, "buildNumber":buildNumber.value, "platformID":platformID.value, "servicePackMajor":servicePackMajor.value, "servicePackMinor":servicePackMinor.value}
def listAll(self):
"""
Name: U12.listAll()
Args: See section 4.22 of the User's Guide
Desc: Searches the USB for all LabJacks, and returns the serial number and local ID for each
>>> dev = U12()
>>> dev.listAll()
>>> {'serialnumList': <u12.c_long_Array_127 object at 0x00E2AD50>, 'numberFound': 1, 'localIDList': <u12.c_long_Array_127 object at 0x00E2ADA0>}
"""
# Create arrays and ctypes
productIDList = listToCArray([0]*127, ctypes.c_long)
serialnumList = listToCArray([0]*127, ctypes.c_long)
localIDList = listToCArray([0]*127, ctypes.c_long)
powerList = listToCArray([0]*127, ctypes.c_long)
arr127_type = ctypes.c_long * 127
calMatrix_type = arr127_type * 20
calMatrix = calMatrix_type()
reserved = ctypes.c_long()
numberFound = ctypes.c_long()
ecode = staticLib.ListAll(ctypes.byref(productIDList), ctypes.byref(serialnumList), ctypes.byref(localIDList), ctypes.byref(powerList), ctypes.byref(calMatrix), ctypes.byref(numberFound), ctypes.byref(reserved), ctypes.byref(reserved))
if ecode != 0: raise U12Exception(ecode)
return {"serialnumList": serialnumList, "localIDList":localIDList, "numberFound":numberFound.value}
def localID(self, localID, idNum=None):
"""
Name: U12.localID(localID, idNum=None)
Args: See section 4.23 of the User's Guide
Desc: Changes the local ID of a specified LabJack
>>> dev = U12()
>>> dev.localID(1)
>>> {'idnum':1}
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
ecode = staticLib.LocalID(ctypes.byref(idNum), localID)
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value}
def noThread(self, noThread, idNum=None):
"""
Name: U12.localID(noThread, idNum=None)
Args: See section 4.24 of the User's Guide
Desc: This function is needed when interfacing TestPoint to the LabJack DLL on Windows 98/ME
>>> dev = U12()
>>> dev.noThread(1)
>>> {'idnum':1}
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
ecode = staticLib.NoThread(ctypes.byref(idNum), noThread)
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value}
def pulseOut(self, bitSelect, numPulses, timeB1, timeC1, timeB2, timeC2, idNum=None, demo=0, lowFirst=0):
"""
Name: U12.pulseOut(bitSelect, numPulses, timeB1, timeC1, timeB2, timeC2, idNum=None, demo=0, lowFirst=0)
Args: See section 4.25 of the User's Guide
Desc: This command creates pulses on any/all of D0-D7
>>> dev = U12()
>>> dev.pulseOut(0, 1, 1, 1, 1, 1)
>>> {'idnum':1}
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
ecode = staticLib.PulseOut(ctypes.byref(idNum), demo, lowFirst, bitSelect, numPulses, timeB1, timeC1, timeB2, timeC2)
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value}
def pulseOutStart(self, bitSelect, numPulses, timeB1, timeC1, timeB2, timeC2, idNum=None, demo=0, lowFirst=0):
"""
Name: U12.pulseOutStart(bitSelect, numPulses, timeB1, timeC1, timeB2, timeC2, idNum=None, demo=0, lowFirst=0)
Args: See section 4.26 of the User's Guide
Desc: PulseOutStart and PulseOutFinish are used as an alternative to PulseOut (See PulseOut for more information)
>>> dev = U12()
>>> dev.pulseOutStart(0, 1, 1, 1, 1, 1)
>>> {'idnum':1}
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
ecode = staticLib.PulseOutStart(ctypes.byref(idNum), demo, lowFirst, bitSelect, numPulses, timeB1, timeC1, timeB2, timeC2)
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value}
def pulseOutFinish(self, timeoutMS, idNum=None, demo=0):
"""
Name: U12.pulseOutFinish(timeoutMS, idNum=None, demo=0)
Args: See section 4.27 of the User's Guide
Desc: See PulseOutStart for more information
>>> dev = U12()
>>> dev.pulseOutStart(0, 1, 1, 1, 1, 1)
>>> dev.pulseOutFinish(100)
>>> {'idnum':1}
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
ecode = staticLib.PulseOutFinish(ctypes.byref(idNum), demo, timeoutMS)
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value}
def pulseOutCalc(self, frequency):
"""
Name: U12.pulseOutFinish(frequency)
Args: See section 4.28 of the User's Guide
Desc: This function can be used to calculate the cycle times for PulseOut or PulseOutStart.
>>> dev = U12()
>>> dev.pulseOutCalc(100)
>>> {'frequency': 100.07672882080078, 'timeB': 247, 'timeC': 1}
"""
# Create ctypes
frequency = ctypes.c_float(frequency)
timeB = ctypes.c_long(0)
timeC = ctypes.c_long(0)
ecode = staticLib.PulseOutCalc(ctypes.byref(frequency), ctypes.byref(timeB), ctypes.byref(timeC))
if ecode != 0: raise U12Exception(ecode)
return {"frequency":frequency.value, "timeB":timeB.value, "timeC":timeC.value}
def reEnum(self, idNum=None):
"""
Name: U12.reEnum(idNum=None)
Args: See section 4.29 of the User's Guide
Desc: Causes the LabJack to electrically detach from and re-attach to the USB so it will re-enumerate
>>> dev = U12()
>>> dev.reEnum()
>>> {'idnum': 1}
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
ecode = staticLib.ReEnum(ctypes.byref(idNum))
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value}
def reset(self, idNum=None):
"""
Name: U12.reset(idNum=None)
Args: See section 4.30 of the User's Guide
Desc: Causes the LabJack to reset after about 2 seconds
>>> dev = U12()
>>> dev.reset()
>>> {'idnum': 1}
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
ecode = staticLib.Reset(ctypes.byref(idNum))
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value}
def resetLJ(self, idNum=None):
"""
Name: U12.resetLJ(idNum=None)
Args: See section 4.30 of the User's Guide
Desc: Causes the LabJack to reset after about 2 seconds
>>> dev = U12()
>>> dev.resetLJ()
>>> {'idnum': 1}
"""
return reset(idNum)
def sht1X(self, idNum=None, demo=0, softComm=0, mode=0, statusReg=0):
"""
Name: U12.sht1X(idNum=None, demo=0, softComm=0, mode=0, statusReg=0)
Args: See section 4.31 of the User's Guide
Desc: This function retrieves temperature and/or humidity readings from an SHT1X sensor.
>>> dev = U12()
>>> dev.sht1X()
>>> {'tempC': 24.69999885559082, 'rh': 39.724445343017578, 'idnum': 1, 'tempF': 76.459999084472656}
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
# Create ctypes
tempC = ctypes.c_float(0)
tempF = ctypes.c_float(0)
rh = ctypes.c_float(0)
ecode = staticLib.SHT1X(ctypes.byref(idNum), demo, softComm, mode, statusReg, ctypes.byref(tempC), ctypes.byref(tempF), ctypes.byref(rh))
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value, "tempC":tempC.value, "tempF":tempF.value, "rh":rh.value}
def shtComm(self, numWrite, numRead, datatx, idNum=None, softComm=0, waitMeas=0, serialReset=0, dataRate=0):
"""
Name: U12.shtComm(numWrite, numRead, datatx, idNum=None, softComm=0, waitMeas=0, serialReset=0, dataRate=0)
Args: See section 4.32 of the User's Guide
Desc: Low-level public function to send and receive up to 4 bytes to from an SHT1X sensor
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
# Check size of datatx
if len(datatx) != 4: raise ValueError("datatx must have exactly 4 elements")
# Create ctypes
datatx = listToCArray(datatx, ctypes.c_ubyte)
datarx = (ctypes.c_ubyte * 4)((0) * 4)
ecode = staticLib.SHTComm(ctypes.byref(idNum), softComm, waitMeas, serialReset, dataRate, numWrite, numRead, ctypes.byref(datatx), ctypes.byref(datarx))
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value, "datarx":datarx}
def shtCRC(self, numWrite, numRead, datatx, datarx, statusReg=0):
"""
Name: U12.shtCRC(numWrite, numRead, datatx, datarx, statusReg=0)
Args: See section 4.33 of the User's Guide
Desc: Checks the CRC on an SHT1X communication
"""
# Create ctypes
datatx = listToCArray(datatx, ctypes.c_ubyte)
datarx = listToCArray(datarx, ctypes.c_ubyte)
return staticLib.SHTCRC(statusReg, numWrite, numRead, ctypes.byref(datatx), ctypes.byref(datarx))
def synch(self, mode, numWriteRead, data, idNum=None, demo=0, msDelay=0, husDelay=0, controlCS=0, csLine=None, csState=0, configD=0):
"""
Name: U12.synch(mode, numWriteRead, data, idNum=None, demo=0, msDelay=0, husDelay=0, controlCS=0, csLine=None, csState=0, configD=0)
Args: See section 4.35 of the User's Guide
Desc: This function retrieves temperature and/or humidity readings from an SHT1X sensor.
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
if controlCS > 0 and csLine is None: raise ValueError("csLine must be specified")
# Make sure data is 18 elements
cData = [0] * 18
for i in range(0, len(data)):
cData[i] = data[i]
cData = listToCArray(cData, ctypes.c_long)
ecode = staticLib.Synch(ctypes.byref(idNum), demo, mode, msDelay, husDelay, controlCS, csLine, csState, configD, numWriteRead, ctypes.byref(cData))
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value, "data":cData}
def watchdog(self, active, timeout, activeDn, stateDn, idNum=None, demo=0, reset=0):
"""
Name: U12.watchdog(active, timeout, activeDn, stateDn, idNum=None, demo=0, reset=0)
Args: See section 4.35 of the User's Guide
Desc: Controls the LabJack watchdog function.
>>> dev = U12()
>>> dev.watchdog(1, 1, [0, 0, 0], [0, 0, 0])
>>> {'idnum': 1}
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
if len(activeDn) is not 3: raise ValueError("activeDn must have 3 elements")
if len(stateDn) is not 3: raise Value("stateDn must have 3 elements")
ecode = staticLib.Watchdog(ctypes.byref(idNum), demo, active, timeout, reset, activeDn[0], activeDn[1], activeDn[2], stateDn[0], stateDn[1], stateDn[2])
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value}
def readMem(self, address, idnum = None):
"""
Name: U12.readMem(address, idnum=None)
Args: See section 4.36 of the User's Guide
Desc: Reads 4 bytes from a specified address in the LabJack's nonvolatile memory
>>> dev = U12()
>>> dev.readMem(0)
>>> [5, 246, 16, 59]
"""
if address is None:
raise Exception, "Must give an Address."
if idnum is None:
idnum = self.id
ljid = ctypes.c_ulong(idnum)
ad0 = ctypes.c_ulong()
ad1 = ctypes.c_ulong()
ad2 = ctypes.c_ulong()
ad3 = ctypes.c_ulong()
ec = staticLib.ReadMem(ctypes.byref(ljid), ctypes.c_long(address), ctypes.byref(ad3), ctypes.byref(ad2), ctypes.byref(ad1), ctypes.byref(ad0))
if ec != 0: raise U12Exception(ec)
addr = [0] * 4
addr[0] = int(ad3.value & 0xff)
addr[1] = int(ad2.value & 0xff)
addr[2] = int(ad1.value & 0xff)
addr[3] = int(ad0.value & 0xff)
return addr
def writeMem(self, address, data, idnum=None, unlocked=False):
"""
Name: U12.writeMem(self, address, data, idnum=None, unlocked=False)
Args: See section 4.37 of the User's Guide
Desc: Writes 4 bytes to the LabJack's 8,192 byte nonvolatile memory at a specified address.
>>> dev = U12()
>>> dev.writeMem(0, [5, 246, 16, 59])
>>> 1
"""
if address is None or data is None:
raise Exception, "Must give both an Address and data."
if type(data) is not list or len(data) != 4:
raise Exception, "Data must be a list and have a length of 4"
if idnum is None:
idnum = self.id
ljid = ctypes.c_ulong(idnum)
ec = staticLib.WriteMem(ctypes.byref(ljid), int(unlocked), address, data[3] & 0xff, data[2] & 0xff, data[1] & 0xff, data[0] & 0xff)
if ec != 0: raise U12Exception(ec)
return ljid.value
def LJHash(self, hashStr, size):
outBuff = (ctypes.c_char * 16)()
retBuff = ''
staticLib = ctypes.windll.LoadLibrary("ljackuw")
ec = staticLib.LJHash(ctypes.cast(hashStr, ctypes.POINTER(ctypes.c_char)),
size,
ctypes.cast(outBuff, ctypes.POINTER(ctypes.c_char)),
0)
if ec != 0: raise U12Exception(ec)
for i in range(16):
retBuff += outBuff[i]
return retBuff
def isIterable(var):
try:
iter(var)
return True
except:
return False
def listToCArray(list, dataType):
arrayType = dataType * len(list)
array = arrayType()
for i in range(0,len(list)):
array[i] = list[i]
return array
def cArrayToList(array):
list = []
for item in array:
list.append(item)
return list
def getErrorString(errorcode):
"""
Name: U12.getErrorString(errorcode)
Args: See section 4.19 of the User's Guide
Desc: Converts a LabJack errorcode, returned by another function, into a string describing the error. No hardware communication is involved.
>>> dev = U12()
>>> dev.getErrorString(1)
>>> Unkown error
"""
errorString = ctypes.c_char_p(" "*50)
staticLib.GetErrorString(errorcode, errorString)
return errorString.value
def hexWithoutQuotes(l):
""" Return a string listing hex without all the single quotes.
>>> l = range(10)
>>> print hexWithoutQuotes(l)
[0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9]
"""
return str([hex (i) for i in l]).replace("'", "")
| 114,714 | 37.456252 | 327 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/src/mirrorServo.py | """
mirrorServo.py was written to control the 8711HV digital rotary servo
and Marty's laser box with the Labjack U3-HV for the wavelength
calibration setup.
The laser box 1PPS signal should be tied to DAC0, and the signal for
the servo is FIO4, routed through a single supply opamp to ensure
high enough voltage on the signal line.
author: Danica Marsden August 6, 2012
"""
import u3, time, sys
#u3.listAll(3)
# Open the LabJack
#d = u3.U3(debug = True)
d = u3.U3()
# Configure
d.configU3()
#print d.configU3()
#print d.configIO()
home = 0.467 # 0 degrees
endpt = 0.8095 # 145 degrees
center = 0.62891 # corresponds to 1.52ms "on"/high
rangeOfServo = 145. # degrees
maxTime = 5. * 60. # 5 minutes
if (len(sys.argv) < 3):
print "Syntax is: >>> python mirrorServo.py <angle [degrees]> <time [s]>"
sys.exit(1)
angleReq = float(sys.argv[1]) # Note: motion is CCW!
if (angleReq > rangeOfServo):
print "Need to specify an angle <= ", rangeOfServo
sys.exit(1)
if (angleReq < 0.):
print "Need to specify an angle >= 0"
sys.exit(1)
dutyReq = ((endpt-home)/rangeOfServo)*angleReq + home
#print dutyReq
#**************hardcoding "home" which may *****************************
# not = 0 depending on telescope config => fix!!!
newhomeang = 40
newhomeReq = ((endpt-home)/rangeOfServo)*newhomeang + home
home = newhomeReq
waitTime = 1
calObsTime = float(sys.argv[2])
if (calObsTime > maxTime):
print "Need to specify a time <= 5 minutes"
sys.exit(1)
if (calObsTime < 0.):
print "Need to specify a time >= 0"
sys.exit(1)
# Set the timer clock to be 48 MHz/divisor with a divisor of 3
d.configTimerClock(TimerClockBase = 6, TimerClockDivisor = 3)
# Enable the timer, at FIO4
d.configIO(TimerCounterPinOffset = 4, NumberOfTimersEnabled = 1)
# Configure the timer for 16 bit PWM, with a duty cycle of a given %, where duty
# cycle is the amount of time "off"/down. This creates an overall PWM frequency
# of ~244.1Hz (4.1ms period) with (1 - dutyCycle)*4.1 ms "on"/high.
baseValue = 65536
dutyCycle = home
d.getFeedback( u3.Timer0Config(TimerMode = 0, Value = int(baseValue*dutyCycle)) )
d.getFeedback(u3.DAC16(Dac=0, Value = 0x0))
# Wait at home
time.sleep(waitTime)
# Update the duty cycle and apply for the specified time
print "Turning lasers on"
dutyCycle = dutyReq
d.getFeedback( u3.Timer0( Value = int(baseValue*dutyCycle), UpdateReset = True ) )
d.getFeedback(u3.DAC16(Dac=0, Value = 0xffff))
time.sleep(calObsTime)
# Go home, turn off laser
print "Turning lasers off"
dutyCycle = home
d.getFeedback( u3.Timer0( Value = int(baseValue*dutyCycle), UpdateReset = True ) )
d.getFeedback(u3.DAC16(Dac=0, Value = 0x0))
# Close the device
d.close
| 2,773 | 24.218182 | 82 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/src/SignalFilterWheel.py | """
SignalFilterWheel.py was written to send a LabView filter wheel an active low
pulse over BNC to move it one filter position.
author: Seth Meeker August 29, 2012
"""
import u3, time, sys
def SignalFilterWheel():
basevoltage = 4.5
triggervoltage = 0.0
# Open the LabJack
d = u3.U3()
# Configure
d.configU3()
DAC0_REGISTER = 5000
d.writeRegister(DAC0_REGISTER, basevoltage)
#print "Switched voltage to " + str(basevoltage)
time.sleep(0.5)
d.writeRegister(DAC0_REGISTER, triggervoltage)
#print "Switched voltage to " + str(triggervoltage)
time.sleep(0.5)
d.writeRegister(DAC0_REGISTER,basevoltage)
#print "Switched voltage to " + str(basevoltage)
#time.sleep(0.5)
d.close
if __name__ == '__main__':
SignalFilterWheel()
| 869 | 21.894737 | 80 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/src/LabJackPython.py | """
Multi-Platform Python wrapper that implements functions from the LabJack
Windows UD Driver, and the Exodriver.
This python wrapper is intended to make working with your LabJack device easy. The functions contained in this module are helper and device agnostic functions. This module provides the base Device class which the U3, U6, and UE9 classes inherit from.
A typical user should start with their device's module, such as u3.py.
"""
# We use the 'with' keyword to manage the thread-safe device lock. It's built-in on 2.6; 2.5 requires an import.
from __future__ import with_statement
import collections
import ctypes
import os
import struct
from decimal import Decimal
import socket
import Modbus
import atexit # For auto-closing devices
import threading # For a thread-safe device lock
LABJACKPYTHON_VERSION = "8-26-2011"
SOCKET_TIMEOUT = 3
LJSOCKET_TIMEOUT = 62
BROADCAST_SOCKET_TIMEOUT = 1
MAX_USB_PACKET_LENGTH = 64
NUMBER_OF_UNIQUE_LABJACK_PRODUCT_IDS = 5
class LabJackException(Exception):
"""Custom Exception meant for dealing specifically with LabJack Exceptions.
Error codes are either going to be a LabJackUD error code or a -1. The -1 implies
a python wrapper specific error.
WINDOWS ONLY
If errorString is not specified then errorString is set by errorCode
"""
def __init__(self, ec = 0, errorString = ''):
self.errorCode = ec
self.errorString = errorString
if not self.errorString:
try:
pString = ctypes.create_string_buffer(256)
staticLib.ErrorToString(ctypes.c_long(self.errorCode), ctypes.byref(pString))
self.errorString = pString.value
except:
self.errorString = str(self.errorCode)
def __str__(self):
return self.errorString
# Raised when a low-level command raises an error.
class LowlevelErrorException(LabJackException): pass
# Raised when the return value of OpenDevice is null.
class NullHandleException(LabJackException):
def __init__(self):
self.errorString = "Couldn't open device. Please check that the device you are trying to open is connected."
def errcheck(ret, func, args):
"""
Whenever a function is called through ctypes, the return value is passed to
this function to be checked for errors.
Support for errno didn't come until 2.6, so Python 2.5 people should
upgrade.
"""
if ret == -1:
try:
ec = ctypes.get_errno()
raise LabJackException(ec, "Exodriver returned error number %s" % ec)
except AttributeError:
raise LabJackException(-1, "Exodriver returned an error, but LabJackPython is unable to read the error code. Upgrade to Python 2.6 for this functionality.")
else:
return ret
def _loadLinuxSo():
"""
Attempts to load the liblabjackusb.so for Linux.
"""
try:
l = ctypes.CDLL("liblabjackusb.so", use_errno=True)
except TypeError:
l = ctypes.CDLL("liblabjackusb.so")
l.LJUSB_Stream.errcheck = errcheck
l.LJUSB_Read.errcheck = errcheck
return l
def _loadMacDylib():
"""
Attempts to load the liblabjackusb.dylib for Mac OS X.
"""
try:
l = ctypes.CDLL("liblabjackusb.dylib", use_errno=True)
except TypeError:
l = ctypes.CDLL("liblabjackusb.dylib")
l.LJUSB_Stream.errcheck = errcheck
l.LJUSB_Read.errcheck = errcheck
return l
def _loadLibrary():
"""_loadLibrary()
Returns a ctypes dll pointer to the library.
"""
if(os.name == 'posix'):
try:
return _loadLinuxSo()
except OSError, e:
pass # We may be on Mac.
except Exception, e:
raise LabJackException("Could not load the Linux SO for some reason other than it not being installed. Ethernet connectivity only.\n\n The error was: %s" % e)
try:
return _loadMacDylib()
except OSError, e:
raise LabJackException("Could not load the Exodriver driver. Ethernet connectivity only.\n\nCheck that the Exodriver is installed, and the permissions are set correctly.\nThe error message was: %s" % e)
except Exception, e:
raise LabJackException("Could not load the Mac Dylib for some reason other than it not being installed. Ethernet connectivity only.\n\n The error was: %s" % e)
if(os.name == 'nt'):
try:
return ctypes.windll.LoadLibrary("labjackud")
except Exception, e:
raise LabJackException("Could not load labjackud driver. Ethernet connectivity availability only.\n\n The error was: %s" % e)
try:
staticLib = _loadLibrary()
except LabJackException, e:
print "%s: %s" % ( type(e), e )
staticLib = None
# Attempt to load the windows Skymote library.
try:
skymoteLib = ctypes.windll.LoadLibrary("liblabjackusb")
except:
skymoteLib = None
class Device(object):
"""Device(handle, localId = None, serialNumber = None, ipAddress = "", type = None)
Creates a simple 0 with the following functions:
write(writeBuffer) -- Writes a buffer.
writeRegister(addr, value) -- Writes a value to a modbus register
read(numBytes) -- Reads until a packet is received.
readRegister(addr, numReg = None, format = None) -- Reads a modbus register.
ping() -- Pings the device. Returns true if communication worked.
close() -- Closes the device.
reset() -- Resets the device.
"""
def __init__(self, handle, localId = None, serialNumber = None, ipAddress = "", devType = None):
# Not saving the handle as a void* causes many problems on 64-bit machines.
if isinstance(handle, int):
self.handle = ctypes.c_void_p(handle)
else:
self.handle = handle
self.localId = localId
self.serialNumber = serialNumber
self.ipAddress = ipAddress
self.devType = devType
self.debug = False
self.streamConfiged = False
self.streamStarted = False
self.streamPacketOffset = 0
self._autoCloseSetup = False
self.modbusPrependZeros = True
self.deviceLock = threading.Lock()
self.deviceName = "LabJack"
def _writeToLJSocketHandle(self, writeBuffer, modbus):
#if modbus is True and self.modbusPrependZeros:
# writeBuffer = [ 0, 0 ] + writeBuffer
packFormat = "B" * len(writeBuffer)
tempString = struct.pack(packFormat, *writeBuffer)
if modbus:
self.handle.modbusSocket.send(tempString)
else:
self.handle.crSocket.send(tempString)
return writeBuffer
def _writeToUE9TCPHandle(self, writeBuffer, modbus):
packFormat = "B" * len(writeBuffer)
tempString = struct.pack(packFormat, *writeBuffer)
if modbus is True:
self.handle.modbus.send(tempString)
else:
self.handle.data.send(tempString)
return writeBuffer
def _writeToExodriver(self, writeBuffer, modbus):
if modbus is True and self.modbusPrependZeros:
writeBuffer = [ 0, 0 ] + writeBuffer
newA = (ctypes.c_byte*len(writeBuffer))(0)
for i in range(len(writeBuffer)):
newA[i] = ctypes.c_byte(writeBuffer[i])
writeBytes = staticLib.LJUSB_Write(self.handle, ctypes.byref(newA), len(writeBuffer))
if(writeBytes != len(writeBuffer)):
raise LabJackException( "Could only write %s of %s bytes." % (writeBytes, len(writeBuffer) ) )
return writeBuffer
def _writeToUDDriver(self, writeBuffer, modbus):
if self.devType == 0x501:
newA = (ctypes.c_byte*len(writeBuffer))(0)
for i in range(len(writeBuffer)):
newA[i] = ctypes.c_byte(writeBuffer[i])
writeBytes = skymoteLib.LJUSB_IntWrite(self.handle, 1, ctypes.byref(newA), len(writeBuffer))
if(writeBytes != len(writeBuffer)):
raise LabJackException( "Could only write %s of %s bytes." % (writeBytes, len(writeBuffer) ) )
else:
if modbus is True and self.devType == 9:
dataWords = len(writeBuffer)
writeBuffer = [0, 0xF8, 0, 0x07, 0, 0] + writeBuffer #modbus low-level function
if dataWords % 2 != 0:
dataWords = (dataWords+1)/2
writeBuffer.append(0)
else:
dataWords = dataWords/2
writeBuffer[2] = dataWords
setChecksum(writeBuffer)
elif modbus is True and self.modbusPrependZeros:
writeBuffer = [ 0, 0 ] + writeBuffer
eGetRaw(self.handle, LJ_ioRAW_OUT, 0, len(writeBuffer), writeBuffer)
return writeBuffer
def write(self, writeBuffer, modbus = False, checksum = True):
"""write([writeBuffer], modbus = False)
Writes the data contained in writeBuffer to the device. writeBuffer must be a list of
bytes.
"""
if self.handle is None:
raise LabJackException("The device handle is None.")
if checksum:
setChecksum(writeBuffer)
if(isinstance(self.handle, LJSocketHandle)):
wb = self._writeToLJSocketHandle(writeBuffer, modbus)
elif(isinstance(self.handle, UE9TCPHandle)):
wb = self._writeToUE9TCPHandle(writeBuffer, modbus)
else:
if os.name == 'posix':
wb = self._writeToExodriver(writeBuffer, modbus)
elif os.name == 'nt':
wb = self._writeToUDDriver(writeBuffer, modbus)
if self.debug: print "Sent: ", hexWithoutQuotes(wb)
def read(self, numBytes, stream = False, modbus = False):
"""read(numBytes, stream = False, modbus = False)
Blocking read until a packet is received.
"""
readBytes = 0
if self.handle is None:
raise LabJackException("The device handle is None.")
if(isinstance(self.handle, LJSocketHandle)):
return self._readFromLJSocketHandle(numBytes, modbus, stream)
elif(isinstance(self.handle, UE9TCPHandle)):
return self._readFromUE9TCPHandle(numBytes, stream, modbus)
else:
if(os.name == 'posix'):
return self._readFromExodriver(numBytes, stream, modbus)
elif os.name == 'nt':
return self._readFromUDDriver(numBytes, stream, modbus)
def _readFromLJSocketHandle(self, numBytes, modbus, spont = False):
"""
Reads from LJSocket. Returns the result as a list.
"""
if modbus:
rcvString = self.handle.modbusSocket.recv(numBytes)
elif spont:
rcvString = self.handle.spontSocket.recv(numBytes)
else:
rcvString = self.handle.crSocket.recv(numBytes)
readBytes = len(rcvString)
packFormat = "B" * readBytes
rcvDataBuff = struct.unpack(packFormat, rcvString)
return list(rcvDataBuff)
def _readFromUE9TCPHandle(self, numBytes, stream, modbus):
if stream is True:
rcvString = self.handle.stream.recv(numBytes)
else:
if modbus is True:
rcvString = self.handle.modbus.recv(numBytes)
else:
rcvString = self.handle.data.recv(numBytes)
readBytes = len(rcvString)
packFormat = "B" * readBytes
rcvDataBuff = struct.unpack(packFormat, rcvString)
return list(rcvDataBuff)
def _readFromExodriver(self, numBytes, stream, modbus):
newA = (ctypes.c_byte*numBytes)()
if(stream):
readBytes = staticLib.LJUSB_Stream(self.handle, ctypes.byref(newA), numBytes)
if readBytes == 0:
return ''
# return the byte string in stream mode
return struct.pack('b' * readBytes, *newA)
else:
readBytes = staticLib.LJUSB_Read(self.handle, ctypes.byref(newA), numBytes)
# return a list of integers in command/response mode
return [(newA[i] & 0xff) for i in range(readBytes)]
def _readFromUDDriver(self, numBytes, stream, modbus):
if self.devType == 0x501:
newA = (ctypes.c_byte*numBytes)()
readBytes = skymoteLib.LJUSB_IntRead(self.handle, 0x81, ctypes.byref(newA), numBytes)
return [(newA[i] & 0xff) for i in range(readBytes)]
else:
if modbus is True and self.devType == 9:
tempBuff = [0] * (8 + numBytes + numBytes%2)
eGetBuff = list()
eGetBuff = eGetRaw(self.handle, LJ_ioRAW_IN, 0, len(tempBuff), tempBuff)[1]
#parse the modbus response out (reponse is the Modbus extended low=level function)
retBuff = list()
if len(eGetBuff) >= 9 and eGetBuff[1] == 0xF8 and eGetBuff[3] == 0x07:
#figuring out the length of the modbus response
mbSize = len(eGetBuff) - 8
if len(eGetBuff) >= 14:
mbSize = min(mbSize, eGetBuff[13] + 6)
i = min(mbSize, numBytes)
i = max(i, 0)
retBuff = eGetBuff[8:8+i] #getting the response only
return retBuff
tempBuff = [0] * numBytes
if stream:
return eGetRaw(self.handle, LJ_ioRAW_IN, 1, numBytes, tempBuff)[1]
return eGetRaw(self.handle, LJ_ioRAW_IN, 0, numBytes, tempBuff)[1]
def readRegister(self, addr, numReg = None, format = None, unitId = None):
""" Reads a specific register from the device and returns the value.
Requires Modbus.py
readHoldingRegister(addr, numReg = None, format = None)
addr: The address you would like to read
numReg: Number of consecutive addresses you would like to read
format: the unpack format of the returned value ( '>f' or '>I')
Modbus is supported for UE9s over USB from Comm Firmware 1.50 and above.
"""
pkt, numBytes = self._buildReadRegisterPacket(addr, numReg, unitId)
response = self._modbusWriteRead(pkt, numBytes)
return self._parseReadRegisterResponse(response, numBytes, addr, format, numReg)
def _buildReadRegisterPacket(self, addr, numReg, unitId):
"""
self._buildReadRegisterPacket(addr, numReg)
Builds a raw modbus "Read Register" packet to be written to a device
returns a tuple:
( < Packet as a list >, < number of bytes to read > )
"""
# Calculates the number of registers for that request, or if numReg is
# specified, checks that it is a valid number.
numReg = Modbus.calcNumberOfRegisters(addr, numReg = numReg)
pkt = Modbus.readHoldingRegistersRequest(addr, numReg = numReg, unitId = unitId)
pkt = [ ord(c) for c in pkt ]
numBytes = 9 + (2 * int(numReg))
return (pkt, numBytes)
def _parseReadRegisterResponse(self, response, numBytes, addr, format, numReg = None):
"""
self._parseReadRegisterReponse(reponse, numBytes, addr, format)
Takes a "Read Register" response and converts it to a value
returns the value
"""
if len(response) != numBytes:
raise LabJackException(9001, "Got incorrect number of bytes from device. Expected %s bytes, got %s bytes. The packet recieved was: %s" % (numBytes, len(response),response))
if isinstance(response, list):
packFormat = ">" + "B" * numBytes
response = struct.pack(packFormat, *response)
if format == None:
format = Modbus.calcFormat(addr, numReg)
value = Modbus.readHoldingRegistersResponse(response, payloadFormat=format)
return value
def writeRegister(self, addr, value, unitId = None):
"""
Writes a value to a register. Returns the value to be written, if successful.
Requires Modbus.py
writeRegister(self, addr, value)
addr: The address you want to write to.
value: The value, or list of values, you want to write.
if you cannot write to that register, a LabJackException is raised.
Modbus is not supported for UE9's over USB. If you try it, a LabJackException is raised.
"""
pkt, numBytes = self._buildWriteRegisterPacket(addr, value, unitId)
response = self._modbusWriteRead(pkt, numBytes)
return self._parseWriteRegisterResponse(response, pkt, value)
def _buildWriteRegisterPacket(self, addr, value, unitId):
"""
self._buildWriteRegisterPacket(addr, value)
Builds a raw modbus "Write Register" packet to be written to a device
returns a tuple:
( < Packet as a list >, < number of bytes to read > )
"""
if type(value) is list:
return self._buildWriteMultipleRegisters(addr, value, unitId)
fmt = Modbus.calcFormat(addr)
if fmt != '>H':
return self._buildWriteFloatToRegister(addr, value, unitId, fmt)
request = Modbus.writeRegisterRequest(addr, value, unitId)
request = [ ord(c) for c in request ]
numBytes = 12
return request, numBytes
def _buildWriteFloatToRegister(self, addr, value, unitId, fmt = '>f'):
numReg = 2
if not isinstance(value, int) and not isinstance(value, float):
raise TypeError("Value must be a float or int.")
# Function, Address, Num Regs, Byte count, Data
payload = struct.pack('>BHHB', 0x10, addr, 0x02, 0x04) + struct.pack(fmt, value)
request = Modbus._buildHeaderBytes(length = len(payload)+1, unitId = unitId)
request += payload
request = [ ord(c) for c in request ]
numBytes = 12
return (request, numBytes)
def _buildWriteMultipleRegisters(self, startAddr, values, unitId = None):
request = Modbus.writeRegistersRequest(startAddr, values, unitId)
request = [ ord(c) for c in request ]
numBytes = 12
return (request, numBytes)
def _parseWriteRegisterResponse(self, response, request, value):
response = list(response)
if request[2] != 0 and request[3] != 0:
protoID = (request[2] << 8) + request[3]
raise Modbus.ModbusException("Got an unexpected protocol ID: %s (expected 0). Please make sure that you have the latest firmware. UE9s need a Comm Firmware of 1.50 or greater.\n\nThe packet you received: %s" % (protoID, hexWithoutQuotes(response)))
if request[7] != response[7]:
raise LabJackException(9002, "Modbus error number %s raised while writing to register. Make sure you're writing to an address that allows writes.\n\nThe packet you received: %s" % (response[8], hexWithoutQuotes(response)))
return value
def setDIOState(IOnum, state):
value = (int(state) & 0x01)
self.writeRegister(6000+IOnum, value)
return True
def _modbusWriteRead(self, request, numBytes):
with self.deviceLock:
self.write(request, modbus = True, checksum = False)
try:
result = self.read(numBytes, modbus = True)
if self.debug: print "Response: ", hexWithoutQuotes(result)
return result
except LabJackException:
self.write(request, modbus = True, checksum = False)
result = self.read(numBytes, modbus = True)
if self.debug: print "Response: ", hexWithoutQuotes(result)
return result
def _checkCommandBytes(self, results, commandBytes):
"""
Checks all the stuff from a command
"""
size = len(commandBytes)
if len(results) == 0:
raise LabJackException("Got a zero length packet.")
elif results[0] == 0xB8 and results[1] == 0xB8:
raise LabJackException("Device detected a bad checksum.")
elif results[1:(size+1)] != commandBytes:
raise LabJackException("Got incorrect command bytes.\nExpected: %s\nGot: %s\nFull packet: %s" % (hexWithoutQuotes(commandBytes), hexWithoutQuotes(results[1:(size+1)]), hexWithoutQuotes(results)))
elif not verifyChecksum(results):
raise LabJackException("Checksum was incorrect.")
elif results[6] != 0:
raise LowlevelErrorException(results[6], "\nThe %s returned an error:\n %s" % (self.deviceName , lowlevelErrorToString(results[6])) )
def _writeRead(self, command, readLen, commandBytes, checkBytes = True, stream=False, checksum = True):
# Acquire the device lock.
with self.deviceLock:
self.write(command, checksum = checksum)
result = self.read(readLen, stream=False)
if self.debug: print "Response: ", hexWithoutQuotes(result)
if checkBytes:
self._checkCommandBytes(result, commandBytes)
return result
def ping(self):
try:
if self.devType == LJ_dtUE9:
writeBuffer = [0x70, 0x70]
self.write(writeBuffer)
try:
self.read(2)
except LabJackException:
self.write(writeBuffer)
self.read(2)
return True
if self.devType == LJ_dtU3:
writeBuffer = [0, 0xf8, 0x01, 0x2a, 0, 0, 0, 0]
writeBuffer = setChecksum(writeBuffer)
self.write(writeBuffer)
self.read(40)
return True
return False
except Exception, e:
print e
return False
def open(self, devType, Ethernet=False, firstFound = True, serial = None, localId = None, devNumber = None, ipAddress = None, handleOnly = False, LJSocket = None):
"""
Device.open(devType, Ethernet=False, firstFound = True, serial = None, localId = None, devNumber = None, ipAddress = None, handleOnly = False, LJSocket = None)
Open a device of type devType.
"""
if self.handle is not None:
raise LabJackException(9000,"Open called on a device with a handle. Please close the device, and try again. Your device is probably already open.\nLook for lines of code that look like this:\nd = u3.U3()\nd.open() # Wrong! Device is already open.")
ct = LJ_ctUSB
if Ethernet:
ct = LJ_ctETHERNET
if LJSocket is not None:
ct = LJ_ctLJSOCKET
d = None
if devNumber:
d = openLabJack(devType, ct, firstFound = False, devNumber = devNumber, handleOnly = handleOnly, LJSocket = LJSocket)
elif serial:
d = openLabJack(devType, ct, firstFound = False, pAddress = serial, handleOnly = handleOnly, LJSocket = LJSocket)
elif localId:
d = openLabJack(devType, ct, firstFound = False, pAddress = localId, handleOnly = handleOnly, LJSocket = LJSocket)
elif ipAddress:
d = openLabJack(devType, ct, firstFound = False, pAddress = ipAddress, handleOnly = handleOnly, LJSocket = LJSocket)
elif LJSocket:
d = openLabJack(devType, ct, handleOnly = handleOnly, LJSocket = LJSocket)
elif firstFound:
d = openLabJack(devType, ct, firstFound = True, handleOnly = handleOnly, LJSocket = LJSocket)
else:
raise LabJackException("You must use first found, or give a localId, devNumber, or IP Address")
self.handle = d.handle
if not handleOnly:
self._loadChangedIntoSelf(d)
self._registerAtExitClose()
def _loadChangedIntoSelf(self, d):
for key, value in d.changed.items():
self.__setattr__(key, value)
def _registerAtExitClose(self):
if not self._autoCloseSetup:
# Only need to register auto-close once per device.
atexit.register(self.close)
self._autoCloseSetup = True
def close(self):
"""close()
This function is not specifically supported in the LabJackUD driver
for Windows and so simply calls the UD function Close. For Mac and unix
drivers, this function MUST be performed when finished with a device.
The reason for this close is because there can not be more than one program
with a given device open at a time. If a device is not closed before
the program is finished it may still be held open and unable to be used
by other programs until properly closed.
For Windows, Linux, and Mac
"""
if isinstance(self.handle, UE9TCPHandle) or isinstance(self.handle, LJSocketHandle):
self.handle.close()
elif os.name == 'posix':
staticLib.LJUSB_CloseDevice(self.handle)
elif self.devType == 0x501:
skymoteLib.LJUSB_CloseDevice(self.handle)
self.handle = None
def reset(self):
"""Reset the LabJack device.
For Windows, Linux, and Mac
Sample Usage:
>>> u3 = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
>>> u3.reset()
@type None
@param Function takes no arguments
@rtype: None
@return: Function returns nothing.
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
ec = staticLib.ResetLabJack(self.handle)
if ec != 0: raise LabJackException(ec)
elif os.name == 'posix':
sndDataBuff = [0] * 4
#Make the reset packet
sndDataBuff[0] = 0x9B
sndDataBuff[1] = 0x99
sndDataBuff[2] = 0x02
try:
self.write(sndDataBuff)
rcvDataBuff = self.read(4)
if(len(rcvDataBuff) != 4):
raise LabJackException(0, "Unable to reset labJack 2")
except Exception, e:
raise LabJackException(0, "Unable to reset labjack: %s" % str(e))
def breakupPackets(self, packets, numBytesPerPacket):
"""
Name: Device.breakupPackets
Args: packets, a string or list of packets
numBytesPerPacket, how big each packe is
Desc: This function will break up a list into smaller chunks and return
each chunk one at a time.
>>> l = range(15)
>>> for packet in d.breakupPackets(l, 5):
... print packet
[ 0, 1, 2, 3, 4 ]
[ 5, 6, 7, 8, 9 ]
[ 10, 11, 12, 13, 14]
"""
start, end = 0, numBytesPerPacket
while end <= len(packets):
yield packets[start:end]
start, end = end, end + numBytesPerPacket
def samplesFromPacket(self, packet):
"""
Name: Device.samplesFromPacket
Args: packet, a packet of stream data
Desc: This function breaks a packet into all the two byte samples it
contains and returns them one at a time.
>>> packet = range(16) # fake packet with 1 sample in it
>>> for sample in d.samplesFromPacket(packet):
... print sample
[ 12, 13 ]
"""
HEADER_SIZE = 12
FOOTER_SIZE = 2
BYTES_PER_PACKET = 2
l = str(packet)
l = l[HEADER_SIZE:]
l = l[:-FOOTER_SIZE]
while len(l) > 0:
yield l[:BYTES_PER_PACKET]
l = l[BYTES_PER_PACKET:]
def streamStart(self):
"""
Name: Device.streamStart()
Args: None
Desc: Starts streaming on the device.
Note: You must call streamConfig() before calling this function.
"""
if not self.streamConfiged:
raise LabJackException("Stream must be configured before it can be started.")
if self.streamStarted:
raise LabJackException("Stream already started.")
command = [ 0xA8, 0xA8 ]
results = self._writeRead(command, 4, [], False, False, False)
if results[2] != 0:
raise LowlevelErrorException(results[2], "StreamStart returned an error:\n %s" % lowlevelErrorToString(results[2]) )
self.streamStarted = True
def streamData(self, convert=True):
"""
Name: Device.streamData()
Args: convert, should the packets be converted as they are read.
set to False to get much faster speeds, but you will
have to process the results later.
Desc: Reads stream data from a LabJack device. See our stream example
to get an idea of how this function should be called. The return
value of streamData is a dictionary with the following keys:
* errors: The number of errors in this block.
* numPackets: The number of USB packets collected to return this
block.
* missed: The number of readings that were missed because of
buffer overflow on the LabJack.
* firstPacket: The PacketCounter value in the first USB packet.
* result: The raw bytes returned from read(). The only way to get
data if called with convert = False.
* AINi, where i is an entry in the passed in PChannels. If called
with convert = True, this is a list of all the readings
in this block.
Note: You must start the stream by calling streamStart() before calling
this function.
"""
if not self.streamStarted:
raise LabJackException("Please start streaming before reading.")
numBytes = 14 + (self.streamSamplesPerPacket * 2)
while True:
result = self.read(numBytes * self.packetsPerRequest, stream = True)
if len(result) == 0:
yield None
continue
numPackets = len(result) // numBytes
errors = 0
missed = 0
firstPacket = ord(result[10])
for i in range(numPackets):
e = ord(result[11+(i*numBytes)])
if e != 0:
errors += 1
if self.debug and e != 60 and e != 59: print e
if e == 60:
missed += struct.unpack('<I', result[6+(i*numBytes):10+(i*numBytes)] )[0]
returnDict = dict(numPackets = numPackets, result = result, errors = errors, missed = missed, firstPacket = firstPacket )
if convert:
returnDict.update(self.processStreamData(result, numBytes = numBytes))
yield returnDict
def streamStop(self):
"""
Name: Device.streamStop()
Args: None
Desc: Stops streaming on the device.
"""
command = [ 0xB0, 0xB0 ]
results = self._writeRead(command, 4, [], False, False, False)
if results[2] != 0:
raise LowlevelErrorException(results[2], "StreamStop returned an error:\n %s" % lowlevelErrorToString(results[2]) )
self.streamStarted = False
def getName(self):
"""
Name: Device.getName()
Args: None
Desc: Returns the name of a device.
Always returns a unicode string.
Works as of the following firmware versions:
U6 - 1.00
U3 - 1.22
UE9 - 2.00
>>> d = u3.U3()
>>> d.open()
>>> d.getName()
u'My LabJack U3'
"""
name = list(self.readRegister(58000, format='B'*48, numReg = 24))
if name[1] == 3:
# Old style string
name = "My %s" % self.deviceName
if self.debug: print "Old UTF-16 name detected, replacing with %s" % name
self.setName(name)
name = name.decode("UTF-8")
else:
try:
end = name.index(0x00)
name = struct.pack("B"*end, *name[:end]).decode("UTF-8")
except ValueError:
name = "My %s" % self.deviceName
if self.debug: print "Invalid name detected, replacing with %s" % name
self.setName(name)
name = name.decode("UTF-8")
return name
def setName(self, name = "My LabJack U3"):
"""
Name: Device.setName(name = ""My LabJack U3")
Args: name, the name you'd like to assign the the U3
Desc: Writes a new name to the device.
Names a limited to 30 characters or less.
Works as of the following firmware versions:
U6 - 1.00
U3 - 1.22
UE9 - 2.00
>>> d = u3.U3()
>>> d.open()
>>> d.getName()
u'My LabJack U3'
>>> d.setName("Johann")
>>> d.getName()
u'Johann'
"""
strLen = len(name)
if strLen > 47:
raise LabJackException("The name is too long, must be less than 48 characters.")
newname = name.encode('UTF-8')
bl = list(struct.unpack("B"*strLen, newname)) + [0x00]
strLen += 1
if strLen%2 != 0:
bl = bl + [0x00]
strLen += 1
bl = struct.unpack(">"+"H"*(strLen/2), struct.pack("B" * strLen, *bl))
self.writeRegister(58000, list(bl))
name = property(getName, setName)
def setDefaults(self, SetToFactoryDefaults = False):
"""
Name: Device.setDefaults(SetToFactoryDefaults = False)
Args: SetToFactoryDefaults, set to True reset to factory defaults.
Desc: Executing this function causes the current or last used values
(or the factory defaults) to be stored in flash as the power-up
defaults.
>>> myU6 = U6()
>>> myU6.setDefaults()
"""
command = [ 0 ] * 8
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x01
command[3] = 0x0E
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = 0xBA
command[7] = 0x26
if SetToFactoryDefaults:
command[6] = 0x82
command[7] = 0xC7
self._writeRead(command, 8, [ 0xF8, 0x01, 0x0E ] )
def setToFactoryDefaults(self):
return self.setDefaults(SetToFactoryDefaults = True)
validDefaultBlocks = range(8)
def readDefaults(self, BlockNum, ReadCurrent = False):
"""
Name: Device.readDefaults(BlockNum)
Args: BlockNum, which block to read. Must be 0-7.
ReadCurrent, True = read current configuration
Desc: Reads the power-up defaults from flash.
>>> myU6 = U6()
>>> myU6.readDefaults(0)
[ 0, 0, ... , 0]
"""
if BlockNum not in self.validDefaultBlocks:
raise LabJackException("Defaults must be in range 0-7")
byte7 = (int(bool(ReadCurrent)) << 7) + BlockNum
command = [ 0, 0xF8, 0x01, 0x0E, 0, 0, 0, byte7 ]
result = self._writeRead(command, 40, [ 0xF8, 0x11, 0x0E ])
return result[8:]
def readCurrent(self, BlockNum):
self.readDefaults(BlockNum, ReadCurrent = True)
def loadGenericDevice(self, device):
""" Take a generic Device object, and loads it into the current object.
The generic Device is consumed in the process.
"""
self.handle = device.handle
self._loadChangedIntoSelf(device)
self._registerAtExitClose()
device = None
# --------------------- BEGIN LabJackPython ---------------------------------
def setChecksum(command):
"""Returns a command with checksums places in the proper locations
For Windows, Mac, and Linux
Sample Usage:
>>> from LabJackPython import *
>>> command = [0] * 12
>>> command[1] = 0xf8
>>> command[2] = 0x03
>>> command[3] = 0x0b
>>> command = SetChecksum(command)
>>> command
[7, 248, 3, 11, 0, 0, 0, 0, 0, 0, 0, 0]
@type command: List
@param command: The command by which to calculate the checksum
@rtype: List
@return: A command list with checksums in the proper locations.
"""
if len(command) < 8:
raise LabJackException("Command does not contain enough bytes.")
try:
a = command[1]
a = (a & 0x78) >> 3
#Check if the command is an extended command
if a == 15:
command = setChecksum16(command)
command = setChecksum8(command, 6)
return command
else:
command = setChecksum8(command, len(command))
return command
except LabJackException, e:
raise e
except Exception, e:
raise LabJackException("SetChecksum Exception:" + str(e))
def verifyChecksum(buffer):
"""Verifies the checksum of a given buffer using the traditional U3/UE9 Command Structure.
"""
buff0 = buffer[0]
buff4 = buffer[4]
buff5 = buffer[5]
tempBuffer = setChecksum(buffer)
if (buff0 == tempBuffer[0]) and (buff4 == tempBuffer[4]) \
and (buff5 == tempBuffer[5]):
return True
return False
# 1 = LJ_ctUSB
def listAll(deviceType, connectionType = 1):
"""listAll(deviceType, connectionType) -> [[local ID, Serial Number, IP Address], ...]
Searches for all devices of a given type over a given connection type and returns a list
of all devices found.
WORKS on WINDOWS, MAC, UNIX
"""
if connectionType == LJ_ctLJSOCKET:
ipAddress, port = deviceType.split(":")
port = int(port)
serverSocket = socket.socket()
serverSocket.connect((ipAddress, port))
serverSocket.settimeout(10)
f = serverSocket.makefile(bufsize = 0)
f.write("scan\r\n")
l = f.readline().strip()
try:
status, numLines = l.split(' ')
except ValueError:
raise Exception("Got invalid line from server: %s" % l)
if status.lower().startswith('ok'):
lines = []
marked = None
for i in range(int(numLines)):
l = f.readline().strip()
dev = parseline(l)
lines.append(dev)
f.close()
serverSocket.close()
#print "Result of scan:"
#print lines
return lines
if deviceType == 12:
if U12DriverPresent():
u12Driver = ctypes.windll.LoadLibrary("ljackuw")
# Setup all the ctype arrays
pSerialNumbers = (ctypes.c_long * 127)(0)
pIDs = (ctypes.c_long * 127)(0)
pProdID = (ctypes.c_long * 127)(0)
pPowerList = (ctypes.c_long * 127)(0)
pCalMatrix = (ctypes.c_long * 2540)(0)
pNumFound = ctypes.c_long()
pFcdd = ctypes.c_long(0)
pHvc = ctypes.c_long(0)
#Output dictionary
deviceList = {}
ec = u12Driver.ListAll(ctypes.cast(pProdID, ctypes.POINTER(ctypes.c_long)),
ctypes.cast(pSerialNumbers, ctypes.POINTER(ctypes.c_long)),
ctypes.cast(pIDs, ctypes.POINTER(ctypes.c_long)),
ctypes.cast(pPowerList, ctypes.POINTER(ctypes.c_long)),
ctypes.cast(pCalMatrix, ctypes.POINTER(ctypes.c_long)),
ctypes.byref(pNumFound),
ctypes.byref(pFcdd),
ctypes.byref(pHvc))
if ec != 0: raise LabJackException(ec)
for i in range(pNumFound.value):
deviceList[pSerialNumbers[i]] = { 'SerialNumber' : pSerialNumbers[i], 'Id' : pIDs[i], 'ProdId' : pProdID[i], 'powerList' : pPowerList[i] }
return deviceList
else:
return {}
if(os.name == 'nt'):
if deviceType == 0x501:
if skymoteLib is None:
raise ImportError("Couldn't load liblabjackusb.dll. Please install, and try again.")
num = skymoteLib.LJUSB_GetDevCount(0x501)
deviceList = dict()
for i in range(num):
try:
device = openLabJack(0x501, 1, firstFound = False, pAddress = None, devNumber = i+1)
device.close()
deviceList[str(device.serialNumber)] = device.__dict__
except LabJackException:
pass
return deviceList
pNumFound = ctypes.c_long()
pSerialNumbers = (ctypes.c_long * 128)()
pIDs = (ctypes.c_long * 128)()
pAddresses = (ctypes.c_double * 128)()
#The actual return variables so the user does not have to use ctypes
serialNumbers = []
ids = []
addresses = []
ec = staticLib.ListAll(deviceType, connectionType,
ctypes.byref(pNumFound),
ctypes.cast(pSerialNumbers, ctypes.POINTER(ctypes.c_long)),
ctypes.cast(pIDs, ctypes.POINTER(ctypes.c_long)),
ctypes.cast(pAddresses, ctypes.POINTER(ctypes.c_long)))
if ec != 0 and ec != 1010: raise LabJackException(ec)
deviceList = dict()
for i in xrange(pNumFound.value):
if pSerialNumbers[i] != 1010:
deviceValue = dict(localId = pIDs[i], serialNumber = pSerialNumbers[i], ipAddress = DoubleToStringAddress(pAddresses[i]), devType = deviceType)
deviceList[pSerialNumbers[i]] = deviceValue
return deviceList
if(os.name == 'posix'):
if deviceType == LJ_dtUE9:
return __listAllUE9Unix(connectionType)
if deviceType == LJ_dtU3:
return __listAllU3Unix()
if deviceType == 6:
return __listAllU6Unix()
if deviceType == 0x501:
return __listAllBridgesUnix()
def isHandleValid(handle):
if(os.name == 'nt'):
return True
else:
return staticLib.LJUSB_IsHandleValid(handle)
def deviceCount(devType = None):
"""Returns the number of devices connected. """
if(os.name == 'nt'):
if devType is None:
numdev = len(listAll(3))
numdev += len(listAll(9))
numdev += len(listAll(6))
if skymoteLib is not None:
numdev += len(listAll(0x501))
return numdev
else:
return len(listAll(devType))
else:
if devType == None:
numdev = staticLib.LJUSB_GetDevCount(3)
numdev += staticLib.LJUSB_GetDevCount(9)
numdev += staticLib.LJUSB_GetDevCount(6)
numdev += staticLib.LJUSB_GetDevCount(0x501)
return numdev
else:
return staticLib.LJUSB_GetDevCount(devType)
def getDevCounts():
if os.name == "nt":
# Right now there is no good way to count all the U12s on a Windows box
return { 3 : len(listAll(3)), 6 : len(listAll(6)), 9 : len(listAll(9)), 1 : 0, 0x501 : len(listAll(0x501))}
else:
devCounts = (ctypes.c_uint*NUMBER_OF_UNIQUE_LABJACK_PRODUCT_IDS)()
devIds = (ctypes.c_uint*NUMBER_OF_UNIQUE_LABJACK_PRODUCT_IDS)()
n = ctypes.c_uint(NUMBER_OF_UNIQUE_LABJACK_PRODUCT_IDS)
r = staticLib.LJUSB_GetDevCounts(ctypes.byref(devCounts), ctypes.byref(devIds), n)
returnDict = dict()
for i in range(NUMBER_OF_UNIQUE_LABJACK_PRODUCT_IDS):
returnDict[int(devIds[i])] = int(devCounts[i])
return returnDict
def openAllLabJacks():
if os.name == "nt":
# Windows doesn't provide a nice way to open all the devices.
devs = dict()
devs[3] = listAll(3)
devs[6] = listAll(6)
devs[9] = listAll(9)
devs[0x501] = listAll(0x501)
devices = list()
for prodId, numConnected in devs.items():
for i, serial in enumerate(numConnected.keys()):
d = Device(None, devType = prodId)
if prodId == 0x501:
d.open(prodId, devNumber = i)
d = _makeDeviceFromHandle(d.handle, prodId)
else:
d.open(prodId, serial = serial)
d = _makeDeviceFromHandle(d.handle, prodId)
devices.append(d)
else:
maxHandles = 10
devHandles = (ctypes.c_void_p*maxHandles)()
devIds = (ctypes.c_uint*maxHandles)()
n = ctypes.c_uint(maxHandles)
numOpened = staticLib.LJUSB_OpenAllDevices(ctypes.byref(devHandles), ctypes.byref(devIds), n)
devices = list()
for i in range(numOpened):
devices.append(_makeDeviceFromHandle(devHandles[i], int(devIds[i])))
return devices
def _openLabJackUsingLJSocket(deviceType, firstFound, pAddress, LJSocket, handleOnly ):
if LJSocket is not '':
ip, port = LJSocket.split(":")
port = int(port)
handle = LJSocketHandle(ip, port, deviceType, firstFound, pAddress)
else:
handle = LJSocketHandle('localhost', 6000, deviceType, firstFound, pAddress)
return handle
def _openLabJackUsingUDDriver(deviceType, connectionType, firstFound, pAddress, devNumber ):
if devNumber is not None:
devs = listAll(deviceType)
pAddress = devs.keys()[(devNumber-1)]
handle = ctypes.c_long()
pAddress = str(pAddress)
ec = staticLib.OpenLabJack(deviceType, connectionType,
pAddress, firstFound, ctypes.byref(handle))
if ec != 0: raise LabJackException(ec)
devHandle = handle.value
return devHandle
def _openLabJackUsingExodriver(deviceType, firstFound, pAddress, devNumber):
devType = ctypes.c_ulong(deviceType)
openDev = staticLib.LJUSB_OpenDevice
openDev.restype = ctypes.c_void_p
if(devNumber != None):
handle = openDev(devNumber, 0, devType)
if handle <= 0:
raise NullHandleException()
return handle
elif(firstFound):
handle = openDev(1, 0, devType)
if handle <= 0:
print "handle: %s" % handle
raise NullHandleException()
return handle
else:
numDevices = staticLib.LJUSB_GetDevCount(deviceType)
for i in range(numDevices):
handle = openDev(i + 1, 0, devType)
try:
if handle <= 0:
raise NullHandleException()
device = _makeDeviceFromHandle(handle, deviceType)
except:
continue
if device.localId == pAddress or device.serialNumber == pAddress or device.ipAddress == pAddress:
return device
else:
device.close()
raise LabJackException(LJE_LABJACK_NOT_FOUND)
def _openUE9OverEthernet(firstFound, pAddress, devNumber):
if firstFound is not True and pAddress is not None:
#Check if valid IP address and attempt to get TCP handle
try:
socket.inet_aton(pAddress)
return UE9TCPHandle(pAddress)
except:
pass
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.settimeout(BROADCAST_SOCKET_TIMEOUT)
sndDataBuff = [0] * 6
sndDataBuff[0] = 0x22
sndDataBuff[1] = 0x78
sndDataBuff[3] = 0xa9
outBuff = ""
for item in sndDataBuff:
outBuff += chr(item)
s.sendto(outBuff, ("255.255.255.255", 52362))
try:
count = 1
while True:
rcvDataBuff = s.recv(128)
rcvDataBuff = [ord(val) for val in rcvDataBuff]
if verifyChecksum(rcvDataBuff):
#Parse the packet
macAddress = rcvDataBuff[28:34]
macAddress.reverse()
# The serial number is four bytes:
# 0x10 and the last three bytes of the MAC address
serialBytes = chr(0x10)
for j in macAddress[3:]:
serialBytes += chr(j)
serialNumber = struct.unpack(">I", serialBytes)[0]
#Parse out the IP address
ipAddress = ""
for j in range(13, 9, -1):
ipAddress += str(int(rcvDataBuff[j]))
ipAddress += "."
ipAddress = ipAddress[0:-1]
#Local ID
localId = rcvDataBuff[8] & 0xff
# Check if we have found the device we are looking for.
# pAddress represents either Local ID, Serial Number, or the
# IP Address. This is so there are no conflicting identifiers.
if firstFound \
or devNumber == count \
or pAddress in [localId, serialNumber, ipAddress]:
handle = UE9TCPHandle(ipAddress)
return handle
count += 1
else:
# Got a bad checksum.
pass
except LabJackException, e:
raise LabJackException(LJE_LABJACK_NOT_FOUND, "%s" % e)
except:
raise LabJackException("LJE_LABJACK_NOT_FOUND: Couldn't find the specified LabJack.")
def _openWirelessBridgeOnWindows(firstFound, pAddress, devNumber):
if skymoteLib is None:
raise ImportError("Couldn't load liblabjackusb.dll. Please install, and try again.")
devType = ctypes.c_ulong(0x501)
openDev = skymoteLib.LJUSB_OpenDevice
openDev.restype = ctypes.c_void_p
if(devNumber != None):
handle = openDev(devNumber, 0, devType)
if handle <= 0:
raise NullHandleException()
return handle
elif(firstFound):
handle = openDev(1, 0, devType)
if handle <= 0:
raise NullHandleException()
return handle
else:
raise LabjackException("Bridges don't have identifiers yet.")
if handleOnly:
raise LabjackException("Can't use handleOnly with an id.")
numDevices = skymoteLib.LJUSB_GetDevCount(deviceType)
for i in range(numDevices):
handle = openDev(i + 1, 0, devType)
try:
if handle <= 0:
raise NullHandleException()
device = _makeDeviceFromHandle(handle, deviceType)
except:
continue
if device.localId == pAddress or device.serialNumber == pAddress or device.ipAddress == pAddress:
return device
else:
device.close()
raise LabJackException(LJE_LABJACK_NOT_FOUND)
#Windows, Linux, and Mac
def openLabJack(deviceType, connectionType, firstFound = True, pAddress = None, devNumber = None, handleOnly = False, LJSocket = None):
"""openLabJack(deviceType, connectionType, firstFound = True, pAddress = 1, LJSocket = None)
Note: On Windows, Ue9 over Ethernet, pAddress MUST be the IP address.
"""
rcvDataBuff = []
handle = None
if connectionType == LJ_ctLJSOCKET:
# LJSocket handles work indepenent of OS
handle = _openLabJackUsingLJSocket(deviceType, firstFound, pAddress, LJSocket, handleOnly )
elif os.name == 'posix' and connectionType == LJ_ctUSB:
# Linux/Mac need to work in the low level driver.
handle = _openLabJackUsingExodriver(deviceType, firstFound, pAddress, devNumber)
if isinstance( handle, Device ):
return handle
elif os.name == 'nt':
#If windows operating system then use the UD Driver
if deviceType == 0x501:
handle = _openWirelessBridgeOnWindows(firstFound, pAddress, devNumber)
handle = ctypes.c_void_p(handle)
elif staticLib is not None:
handle = _openLabJackUsingUDDriver(deviceType, connectionType, firstFound, pAddress, devNumber )
elif connectionType == LJ_ctETHERNET and deviceType == LJ_dtUE9 :
handle = _openUE9OverEthernet(firstFound, pAddress, devNumber)
if not handleOnly:
return _makeDeviceFromHandle(handle, deviceType)
else:
return Device(handle, devType = deviceType)
def _makeDeviceFromHandle(handle, deviceType):
""" A helper function to get set all the info about a device from a handle"""
device = Device(handle, devType = deviceType)
device.changed = dict()
if(deviceType == LJ_dtUE9):
sndDataBuff = [0] * 38
sndDataBuff[0] = 0x89
sndDataBuff[1] = 0x78
sndDataBuff[2] = 0x10
sndDataBuff[3] = 0x01
try:
device.write(sndDataBuff, checksum = False)
rcvDataBuff = device.read(38)
# Local ID
device.localId = rcvDataBuff[8] & 0xff
# MAC Address
device.macAddress = "%02X:%02X:%02X:%02X:%02X:%02X" % (rcvDataBuff[33], rcvDataBuff[32], rcvDataBuff[31], rcvDataBuff[30], rcvDataBuff[29], rcvDataBuff[28])
# Parse out serial number
device.serialNumber = struct.unpack("<I", struct.pack("BBBB", rcvDataBuff[28], rcvDataBuff[29], rcvDataBuff[30], 0x10))[0]
#Parse out the IP address
device.ipAddress = "%s.%s.%s.%s" % (rcvDataBuff[13], rcvDataBuff[12], rcvDataBuff[11], rcvDataBuff[10] )
# Comm FW Version
device.commFWVersion = "%s.%02d" % (rcvDataBuff[37], rcvDataBuff[36])
device.changed['localId'] = device.localId
device.changed['macAddress'] = device.macAddress
device.changed['serialNumber'] = device.serialNumber
device.changed['ipAddress'] = device.ipAddress
device.changed['commFWVersion'] = device.commFWVersion
except Exception, e:
device.close()
raise e
elif deviceType == LJ_dtU3:
sndDataBuff = [0] * 26
sndDataBuff[0] = 0x0b
sndDataBuff[1] = 0xf8
sndDataBuff[2] = 0x0a
sndDataBuff[3] = 0x08
try:
device.write(sndDataBuff, checksum = False)
rcvDataBuff = device.read(38)
except LabJackException, e:
device.close()
raise e
device.localId = rcvDataBuff[21] & 0xff
serialNumber = struct.pack("<BBBB", *rcvDataBuff[15:19])
device.serialNumber = struct.unpack('<I', serialNumber)[0]
device.ipAddress = ""
device.firmwareVersion = "%d.%02d" % (rcvDataBuff[10], rcvDataBuff[9])
device.hardwareVersion = "%d.%02d" % (rcvDataBuff[14], rcvDataBuff[13])
device.versionInfo = rcvDataBuff[37]
device.deviceName = 'U3'
if device.versionInfo == 1:
device.deviceName += 'B'
elif device.versionInfo == 2:
device.deviceName += '-LV'
elif device.versionInfo == 18:
device.deviceName += '-HV'
device.changed['localId'] = device.localId
device.changed['serialNumber'] = device.serialNumber
device.changed['ipAddress'] = device.ipAddress
device.changed['firmwareVersion'] = device.firmwareVersion
device.changed['versionInfo'] = device.versionInfo
device.changed['deviceName'] = device.deviceName
device.changed['hardwareVersion'] = device.hardwareVersion
elif deviceType == 6:
command = [ 0 ] * 26
command[1] = 0xF8
command[2] = 0x0A
command[3] = 0x08
try:
device.write(command)
rcvDataBuff = device.read(38)
except LabJackException, e:
device.close()
raise e
device.localId = rcvDataBuff[21] & 0xff
serialNumber = struct.pack("<BBBB", *rcvDataBuff[15:19])
device.serialNumber = struct.unpack('<I', serialNumber)[0]
device.ipAddress = ""
device.firmwareVersion = "%s.%02d" % (rcvDataBuff[10], rcvDataBuff[9])
device.bootloaderVersion = "%s.%02d" % (rcvDataBuff[12], rcvDataBuff[11])
device.hardwareVersion = "%s.%02d" % (rcvDataBuff[14], rcvDataBuff[13])
device.versionInfo = rcvDataBuff[37]
device.deviceName = 'U6'
if device.versionInfo == 12:
device.deviceName = 'U6-Pro'
device.changed['localId'] = device.localId
device.changed['serialNumber'] = device.serialNumber
device.changed['ipAddress'] = device.ipAddress
device.changed['firmwareVersion'] = device.firmwareVersion
device.changed['versionInfo'] = device.versionInfo
device.changed['deviceName'] = device.deviceName
device.changed['hardwareVersion'] = device.hardwareVersion
device.changed['bootloaderVersion'] = device.bootloaderVersion
elif deviceType == 0x501:
pkt, readlen = device._buildReadRegisterPacket(65104, 4, 0)
device.modbusPrependZeros = False
device.write(pkt, modbus = True, checksum = False)
for i in range(5):
try:
serial = None
response = device.read(64, False, True)
serial = device._parseReadRegisterResponse(response[:readlen], readlen, 65104, '>Q', numReg = 4)
break
except Modbus.ModbusException:
pass
if serial is None:
raise LabJackException("Error reading serial number.")
device.serialNumber = serial
device.localId = 0
device.deviceName = "SkyMote Bridge"
device.changed['localId'] = device.localId
device.changed['deviceName'] = device.deviceName
device.changed['serialNumber'] = device.serialNumber
return device
def AddRequest(Handle, IOType, Channel, Value, x1, UserData):
"""AddRequest(handle, ioType, channel, value, x1, userData)
Windows Only
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
v = ctypes.c_double(Value)
ud = ctypes.c_double(UserData)
ec = staticLib.AddRequest(Handle, IOType, Channel, v, x1, ud)
if ec != 0: raise LabJackException(ec)
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def AddRequestS(Handle, pIOType, Channel, Value, x1, UserData):
"""Add a request to the LabJackUD request stack
For Windows
Sample Usage to get the AIN value from channel 0:
>>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
>>> AddRequestS(u3Handle,"LJ_ioGET_AIN", 0, 0.0, 0, 0.0)
>>> Go()
>>> value = GetResult(u3Handle, LJ_ioGET_AIN, 0)
>>> print "Value:" + str(value)
Value:0.366420765873
@type Handle: number
@param Handle: Handle to the LabJack device.
@type IOType: String
@param IOType: IO Request to the LabJack.
@type Channel: number
@param Channel: Channel for the IO request.
@type Value: number
@param Value: Used for some requests
@type x1: number
@param x1: Used for some requests
@type UserData: number
@param UserData: Used for some requests
@rtype: None
@return: Function returns nothing.
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
v = ctypes.c_double(Value)
ud = ctypes.c_double(UserData)
ec = staticLib.AddRequestS(Handle, pIOType, Channel,
v, x1, ud)
if ec != 0: raise LabJackException(ec)
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def AddRequestSS(Handle, pIOType, pChannel, Value, x1, UserData):
"""Add a request to the LabJackUD request stack
For Windows
Sample Usage to get the AIN value from channel 0:
>>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
>>> AddRequestSS(u3Handle,"LJ_ioGET_CONFIG", "LJ_chFIRMWARE_VERSION", 0.0, 0, 0.0)
>>> Go()
>>> value = GetResultS(u3Handle, "LJ_ioGET_CONFIG", LJ_chFIRMWARE_VERSION)
>>> print "Value:" + str(value)
Value:1.27
@type Handle: number
@param Handle: Handle to the LabJack device.
@type IOType: String
@param IOType: IO Request to the LabJack.
@type Channel: String
@param Channel: Channel for the IO request.
@type Value: number
@param Value: Used for some requests
@type x1: number
@param x1: Used for some requests
@type UserData: number
@param UserData: Used for some requests
@rtype: None
@return: Function returns nothing.
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
v = ctypes.c_double(Value)
ud = ctypes.c_double(UserData)
ec = staticLib.AddRequestSS(Handle, pIOType, pChannel,
v, x1, ud)
if ec != 0: raise LabJackException(ec)
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def Go():
"""Complete all requests currently on the LabJackUD request stack
For Windows Only
Sample Usage:
>>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
>>> AddRequestSS(u3Handle,"LJ_ioGET_CONFIG", "LJ_chFIRMWARE_VERSION", 0.0, 0, 0.0)
>>> Go()
>>> value = GetResultS(u3Handle, "LJ_ioGET_CONFIG", LJ_chFIRMWARE_VERSION)
>>> print "Value:" + str(value)
Value:1.27
@rtype: None
@return: Function returns nothing.
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
ec = staticLib.Go()
if ec != 0: raise LabJackException(ec)
else:
raise LabJackException("Function only supported for Windows")
#Windows
def GoOne(Handle):
"""Performs the next request on the LabJackUD request stack
For Windows Only
Sample Usage:
>>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
>>> AddRequestSS(u3Handle,"LJ_ioGET_CONFIG", "LJ_chFIRMWARE_VERSION", 0.0, 0, 0.0)
>>> GoOne(u3Handle)
>>> value = GetResultS(u3Handle, "LJ_ioGET_CONFIG", LJ_chFIRMWARE_VERSION)
>>> print "Value:" + str(value)
Value:1.27
@type Handle: number
@param Handle: Handle to the LabJack device.
@rtype: None
@return: Function returns nothing.
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
ec = staticLib.GoOne(Handle)
if ec != 0: raise LabJackException(ec)
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def eGet(Handle, IOType, Channel, pValue, x1):
"""Perform one call to the LabJack Device
eGet is equivilent to an AddRequest followed by a GoOne.
For Windows Only
Sample Usage:
>>> eGet(u3Handle, LJ_ioGET_AIN, 0, 0, 0)
0.39392614550888538
@type Handle: number
@param Handle: Handle to the LabJack device.
@type IOType: number
@param IOType: IO Request to the LabJack.
@type Channel: number
@param Channel: Channel for the IO request.
@type Value: number
@param Value: Used for some requests
@type x1: number
@param x1: Used for some requests
@rtype: number
@return: Returns the value requested.
- value
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
pv = ctypes.c_double(pValue)
#ppv = ctypes.pointer(pv)
ec = staticLib.eGet(Handle, IOType, Channel, ctypes.byref(pv), x1)
#staticLib.eGet.argtypes = [ctypes.c_long, ctypes.c_long, ctypes.c_long, ctypes.c_double, ctypes.c_long]
#ec = staticLib.eGet(Handle, IOType, Channel, pValue, x1)
if ec != 0: raise LabJackException(ec)
#print "EGet:" + str(ppv)
#print "Other:" + str(ppv.contents)
return pv.value
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
#Raw method -- Used because x1 is an output
def eGetRaw(Handle, IOType, Channel, pValue, x1):
"""Perform one call to the LabJack Device as a raw command
eGetRaw is equivilent to an AddRequest followed by a GoOne.
For Windows Only
Sample Usage (Calling a echo command):
>>> sendBuff = [0] * 2
>>> sendBuff[0] = 0x70
>>> sendBuff[1] = 0x70
>>> eGetRaw(ue9Handle, LJ_ioRAW_OUT, 0, len(sendBuff), sendBuff)
(2.0, [112, 112])
@type Handle: number
@param Handle: Handle to the LabJack device.
@type IOType: number
@param IOType: IO Request to the LabJack.
@type Channel: number
@param Channel: Channel for the IO request.
@type pValue: number
@param Value: Length of the buffer.
@type x1: number
@param x1: Buffer to send.
@rtype: Tuple
@return: The tuple (numBytes, returnBuffer)
- numBytes (number)
- returnBuffer (List)
@raise LabJackException:
"""
ec = 0
x1Type = "int"
if os.name == 'nt':
digitalConst = [35, 36, 37, 45]
pv = ctypes.c_double(pValue)
#If IOType is digital then call eget with x1 as a long
if IOType in digitalConst:
ec = staticLib.eGet(Handle, IOType, Channel, ctypes.byref(pv), x1)
else: #Otherwise as an array
try:
#Verify x1 is an array
if len(x1) < 1:
raise LabJackException(0, "x1 is not a valid variable for the given IOType")
except Exception:
raise LabJackException(0, "x1 is not a valid variable for the given IOType")
#Initialize newA
newA = None
if type(x1[0]) == int:
newA = (ctypes.c_byte*len(x1))()
for i in range(0, len(x1), 1):
newA[i] = ctypes.c_byte(x1[i])
else:
x1Type = "float"
newA = (ctypes.c_double*len(x1))()
for i in range(0, len(x1), 1):
newA[i] = ctypes.c_double(x1[i])
ec = staticLib.eGet(Handle, IOType, Channel, ctypes.byref(pv), ctypes.byref(newA))
if IOType == LJ_ioRAW_IN and Channel == 1:
# We return the raw byte string if we are streaming
x1 = struct.pack('b' * len(x1), *newA)
elif IOType == LJ_ioRAW_IN and Channel == 0:
x1 = [0] * int(pv.value)
for i in range(len(x1)):
x1[i] = newA[i] & 0xff
else:
x1 = [0] * len(x1)
for i in range(len(x1)):
x1[i] = newA[i]
if(x1Type == "int"):
x1[i] = x1[i] & 0xff
if ec != 0: raise LabJackException(ec)
return pv.value, x1
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def eGetS(Handle, pIOType, Channel, pValue, x1):
"""Perform one call to the LabJack Device
eGet is equivilent to an AddRequest followed by a GoOne.
For Windows Only
Sample Usage:
>>> eGet(u3Handle, "LJ_ioGET_AIN", 0, 0, 0)
0.39392614550888538
@type Handle: number
@param Handle: Handle to the LabJack device.
@type pIOType: String
@param pIOType: IO Request to the LabJack.
@type Channel: number
@param Channel: Channel for the IO request.
@type Value: number
@param Value: Used for some requests
@type x1: number
@param x1: Used for some requests
@rtype: number
@return: Returns the value requested.
- value
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
pv = ctypes.c_double(pValue)
ec = staticLib.eGetS(Handle, pIOType, Channel, ctypes.byref(pv), x1)
if ec != 0: raise LabJackException(ec)
return pv.value
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def eGetSS(Handle, pIOType, pChannel, pValue, x1):
"""Perform one call to the LabJack Device
eGet is equivilent to an AddRequest followed by a GoOne.
For Windows Only
Sample Usage:
>>> eGetSS(u3Handle,"LJ_ioGET_CONFIG", "LJ_chFIRMWARE_VERSION", 0, 0)
1.27
@type Handle: number
@param Handle: Handle to the LabJack device.
@type pIOType: String
@param pIOType: IO Request to the LabJack.
@type Channel: String
@param Channel: Channel for the IO request.
@type Value: number
@param Value: Used for some requests
@type x1: number
@param x1: Used for some requests
@rtype: number
@return: Returns the value requested.
- value
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
pv = ctypes.c_double(pValue)
ec = staticLib.eGetSS(Handle, pIOType, pChannel, ctypes.byref(pv), x1)
if ec != 0: raise LabJackException(ec)
return pv.value
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
#Not currently implemented
def eGetRawS(Handle, pIOType, Channel, pValue, x1):
"""Function not yet implemented.
For Windows only.
"""
pass
#Windows
def ePut(Handle, IOType, Channel, Value, x1):
"""Put one value to the LabJack device
ePut is equivilent to an AddRequest followed by a GoOne.
For Windows Only
Sample Usage:
>>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
>>> eGet(u3Handle, LJ_ioGET_CONFIG, LJ_chLOCALID, 0, 0)
0.0
>>> ePut(u3Handle, LJ_ioPUT_CONFIG, LJ_chLOCALID, 8, 0)
>>> eGet(u3Handle, LJ_ioGET_CONFIG, LJ_chLOCALID, 0, 0)
8.0
@type Handle: number
@param Handle: Handle to the LabJack device.
@type IOType: number
@param IOType: IO Request to the LabJack.
@type Channel: number
@param Channel: Channel for the IO request.
@type Value: number
@param Value: Used for some requests
@type x1: number
@param x1: Used for some requests
@rtype: None
@return: Function returns nothing.
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
pv = ctypes.c_double(Value)
ec = staticLib.ePut(Handle, IOType, Channel, pv, x1)
if ec != 0: raise LabJackException(ec)
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def ePutS(Handle, pIOType, Channel, Value, x1):
"""Put one value to the LabJack device
ePut is equivilent to an AddRequest followed by a GoOne.
For Windows Only
Sample Usage:
>>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
>>> eGet(u3Handle, LJ_ioGET_CONFIG, LJ_chLOCALID, 0, 0)
0.0
>>> ePutS(u3Handle, "LJ_ioPUT_CONFIG", LJ_chLOCALID, 8, 0)
>>> eGet(u3Handle, LJ_ioGET_CONFIG, LJ_chLOCALID, 0, 0)
8.0
@type Handle: number
@param Handle: Handle to the LabJack device.
@type IOType: String
@param IOType: IO Request to the LabJack.
@type Channel: number
@param Channel: Channel for the IO request.
@type Value: number
@param Value: Used for some requests
@type x1: number
@param x1: Used for some requests
@rtype: None
@return: Function returns nothing.
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
pv = ctypes.c_double(Value)
ec = staticLib.ePutS(Handle, pIOType, Channel, pv, x1)
if ec != 0: raise LabJackException(ec)
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def ePutSS(Handle, pIOType, pChannel, Value, x1):
"""Put one value to the LabJack device
ePut is equivilent to an AddRequest followed by a GoOne.
For Windows Only
Sample Usage:
>>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
>>> eGet(u3Handle, LJ_ioGET_CONFIG, LJ_chLOCALID, 0, 0)
0.0
>>> ePutSS(u3Handle, "LJ_ioPUT_CONFIG", "LJ_chLOCALID", 8, 0)
>>> eGet(u3Handle, LJ_ioGET_CONFIG, LJ_chLOCALID, 0, 0)
8.0
@type Handle: number
@param Handle: Handle to the LabJack device.
@type IOType: String
@param IOType: IO Request to the LabJack.
@type Channel: String
@param Channel: Channel for the IO request.
@type Value: number
@param Value: Used for some requests
@type x1: number
@param x1: Used for some requests
@rtype: None
@return: Function returns nothing.
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
pv = ctypes.c_double(Value)
ec = staticLib.ePutSS(Handle, pIOType, pChannel, pv, x1)
if ec != 0: raise LabJackException(ec)
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def GetResult(Handle, IOType, Channel):
"""Put one value to the LabJack device
ePut is equivilent to an AddRequest followed by a GoOne.
For Windows Only
Sample Usage:
>>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
>>> AddRequestSS(u3Handle,"LJ_ioGET_CONFIG", "LJ_chFIRMWARE_VERSION", 0.0, 0, 0.0)
>>> GoOne(u3Handle)
>>> value = GetResult(u3Handle, LJ_ioGET_CONFIG, LJ_chFIRMWARE_VERSION)
>>> print "Value:" + str(value)
Value:1.27
@type Handle: number
@param Handle: Handle to the LabJack device.
@type IOType: number
@param IOType: IO Request to the LabJack.
@type Channel: number
@param Channel: Channel for the IO request.
@rtype: number
@return: The value requested.
- value
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
pv = ctypes.c_double()
ec = staticLib.GetResult(Handle, IOType, Channel, ctypes.byref(pv))
if ec != 0: raise LabJackException(ec)
return pv.value
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def GetResultS(Handle, pIOType, Channel):
"""Put one value to the LabJack device
ePut is equivilent to an AddRequest followed by a GoOne.
For Windows Only
Sample Usage:
>>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
>>> AddRequestSS(u3Handle,"LJ_ioGET_CONFIG", "LJ_chFIRMWARE_VERSION", 0.0, 0, 0.0)
>>> GoOne(u3Handle)
>>> value = GetResultS(u3Handle, "LJ_ioGET_CONFIG", LJ_chFIRMWARE_VERSION)
>>> print "Value:" + str(value)
Value:1.27
@type Handle: number
@param Handle: Handle to the LabJack device.
@type pIOType: String
@param pIOType: IO Request to the LabJack.
@type Channel: number
@param Channel: Channel for the IO request.
@rtype: number
@return: The value requested.
- value
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
pv = ctypes.c_double()
ec = staticLib.GetResultS(Handle, pIOType, Channel, ctypes.byref(pv))
if ec != 0: raise LabJackException(ec)
return pv.value
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def GetResultSS(Handle, pIOType, pChannel):
"""Put one value to the LabJack device
ePut is equivilent to an AddRequest followed by a GoOne.
For Windows Only
Sample Usage:
>>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
>>> AddRequestSS(u3Handle,"LJ_ioGET_CONFIG", "LJ_chFIRMWARE_VERSION", 0.0, 0, 0.0)
>>> GoOne(u3Handle)
>>> value = GetResultSS(u3Handle, "LJ_ioGET_CONFIG", "LJ_chFIRMWARE_VERSION")
>>> print "Value:" + str(value)
Value:1.27
@type Handle: number
@param Handle: Handle to the LabJack device.
@type pIOType: String
@param pIOType: IO Request to the LabJack.
@type Channel: String
@param Channel: Channel for the IO request.
@rtype: number
@return: The value requested.
- value
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
pv = ctypes.c_double()
ec = staticLib.GetResultS(Handle, pIOType, pChannel, ctypes.byref(pv))
if ec != 0: raise LabJackException(ec)
return pv.value
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def GetFirstResult(Handle):
"""List All LabJack devices of a specific type over a specific connection type.
For Windows only.
Sample Usage (Shows getting the localID (8) and firmware version (1.27) of a U3 device):
>>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
>>> AddRequest(u3Handle, LJ_ioGET_CONFIG, LJ_chLOCALID, 0, 0, 0)
>>> AddRequest(u3Handle, LJ_ioGET_CONFIG, LJ_chFIRMWARE_VERSION, 0, 0, 0)
>>> Go()
>>> GetFirstResult(u3Handle)
(1001, 0, 8.0, 0, 0.0)
>>> GetNextResult(u3Handle)
(1001, 11, 1.27, 0, 0.0)
@type DeviceType: number
@param DeviceType: The LabJack device.
@type ConnectionType: number
@param ConnectionType: The connection method (Ethernet/USB).
@rtype: Tuple
@return: The tuple (ioType, channel, value, x1, userData)
- ioType (number): The io of the result.
- serialNumber (number): The channel of the result.
- value (number): The requested result.
- x1 (number): Used only in certain requests.
- userData (number): Used only in certain requests.
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
pio = ctypes.c_long()
pchan = ctypes.c_long()
pv = ctypes.c_double()
px = ctypes.c_long()
pud = ctypes.c_double()
ec = staticLib.GetFirstResult(Handle, ctypes.byref(pio),
ctypes.byref(pchan), ctypes.byref(pv),
ctypes.byref(px), ctypes.byref(pud))
if ec != 0: raise LabJackException(ec)
return pio.value, pchan.value, pv.value, px.value, pud.value
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def GetNextResult(Handle):
"""List All LabJack devices of a specific type over a specific connection type.
For Windows only.
Sample Usage (Shows getting the localID (8) and firmware version (1.27) of a U3 device):
>>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
>>> AddRequest(u3Handle, LJ_ioGET_CONFIG, LJ_chLOCALID, 0, 0, 0)
>>> AddRequest(u3Handle, LJ_ioGET_CONFIG, LJ_chFIRMWARE_VERSION, 0, 0, 0)
>>> Go()
>>> GetFirstResult(u3Handle)
(1001, 0, 8.0, 0, 0.0)
>>> GetNextResult(u3Handle)
(1001, 11, 1.27, 0, 0.0)
@type DeviceType: number
@param DeviceType: The LabJack device.
@type ConnectionType: number
@param ConnectionType: The connection method (Ethernet/USB).
@rtype: Tuple
@return: The tuple (ioType, channel, value, x1, userData)
- ioType (number): The io of the result.
- serialNumber (number): The channel of the result.
- value (number): The requested result.
- x1 (number): Used only in certain requests.
- userData (number): Used only in certain requests.
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
pio = ctypes.c_long()
pchan = ctypes.c_long()
pv = ctypes.c_double()
px = ctypes.c_long()
pud = ctypes.c_double()
ec = staticLib.GetNextResult(Handle, ctypes.byref(pio),
ctypes.byref(pchan), ctypes.byref(pv),
ctypes.byref(px), ctypes.byref(pud))
if ec != 0: raise LabJackException(ec)
return pio.value, pchan.value, pv.value, px.value, pud.value
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def DoubleToStringAddress(number):
"""Converts a number (base 10) to an IP string.
For Windows
Sample Usage:
>>> DoubleToStringAddress(3232235985)
'192.168.1.209'
@type number: number
@param number: Number to be converted.
@rtype: String
@return: The IP string converted from the number (base 10).
@raise LabJackException:
"""
number = int(number)
address = "%i.%i.%i.%i" % ((number >> 8*3 & 0xFF), (number >> 8*2 & 0xFF), (number >> 8 & 0xFF), (number & 0xFF))
return address
def StringToDoubleAddress(pString):
"""Converts an IP string to a number (base 10).
Sample Usage:
>>> StringToDoubleAddress("192.168.1.209")
3232235985L
@type pString: String
@param pString: String to be converted.
@rtype: number
@return: The number (base 10) that represents the IP string.
@raise LabJackException:
"""
parts = pString.split('.')
if len(parts) is not 4:
raise LabJackException(0, "IP address not correctly formatted")
try:
value = (int(parts[0]) << 8*3) + (int(parts[1]) << 8*2) + (int(parts[2]) << 8) + int(parts[3])
except ValueError:
raise LabJackException(0, "IP address not correctly formatted")
return value
#Windows
def StringToConstant(pString):
"""Converts an LabJackUD valid string to its constant value.
For Windows
Sample Usage:
>>> StringToConstant("LJ_dtU3")
3
@type pString: String
@param pString: String to be converted.
@rtype: number
@return: The number (base 10) that represents the LabJackUD string.
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
a = ctypes.create_string_buffer(pString, 256)
return staticLib.StringToConstant(a)
else:
raise LabJackException(0, "Function only supported for Windows")
# To hold all the error codes and what they mean:
ERROR_TO_STRING_DICT = dict()
ERROR_TO_STRING_DICT['1'] = ("SCRATCH_WRT_FAIL", "")
ERROR_TO_STRING_DICT['2'] = ("SCRATCH_ERASE_FAIL", "")
ERROR_TO_STRING_DICT['3'] = ("DATA_BUFFER_OVERFLOW", "")
ERROR_TO_STRING_DICT['4'] = ("ADC0_BUFFER_OVERFLOW", "")
ERROR_TO_STRING_DICT['5'] = ("FUNCTION_INVALID", "")
ERROR_TO_STRING_DICT['6'] = ("SWDT_TIME_INVALID", "This error is caused when an invalid time was passed to the watchdog.")
ERROR_TO_STRING_DICT['7'] = ("XBR_CONFIG_ERROR", "")
ERROR_TO_STRING_DICT['16'] = ("FLASH_WRITE_FAIL", "For some reason, the LabJack was unable to write the specified page of its internal flash.")
ERROR_TO_STRING_DICT['17'] = ("FLASH_ERASE_FAIL", "For some reason, the LabJack was unable to erase the specified page of its internal flash.")
ERROR_TO_STRING_DICT['18'] = ("FLASH_JMP_FAIL", "For some reason, the LabJack was unable to jump to a different section of flash. This may be an indication the flash is corrupted.")
ERROR_TO_STRING_DICT['19'] = ("FLASH_PSP_TIMEOUT", "")
ERROR_TO_STRING_DICT['20'] = ("FLASH_ABORT_RECEIVED", "")
ERROR_TO_STRING_DICT['21'] = ("FLASH_PAGE_MISMATCH", "")
ERROR_TO_STRING_DICT['22'] = ("FLASH_BLOCK_MISMATCH", "")
ERROR_TO_STRING_DICT['23'] = ("FLASH_PAGE_NOT_IN_CODE_AREA", "Usually, this error is raised when you try to write new firmware before upgrading the bootloader.")
ERROR_TO_STRING_DICT['24'] = ("MEM_ILLEGAL_ADDRESS", "")
ERROR_TO_STRING_DICT['25'] = ("FLASH_LOCKED", "Tried to write to flash before unlocking it.")
ERROR_TO_STRING_DICT['26'] = ("INVALID_BLOCK", "")
ERROR_TO_STRING_DICT['27'] = ("FLASH_ILLEGAL_PAGE", "")
ERROR_TO_STRING_DICT['28'] = ("FLASH_TOO_MANY_BYTES", "")
ERROR_TO_STRING_DICT['29'] = ("FLASH_INVALID_STRING_NUM", "")
ERROR_TO_STRING_DICT['40'] = ("SHT1x_COMM_TIME_OUT", "LabJack never received the ACK it was expecting from the SHT. This is usually due to incorrect wiring. Double check that all wires are securely connected to the correct pins.")
ERROR_TO_STRING_DICT['41'] = ("SHT1x_NO_ACK", "")
ERROR_TO_STRING_DICT['42'] = ("SHT1x_CRC_FAILED", "")
ERROR_TO_STRING_DICT['43'] = ("SHT1x_TOO_MANY_W_BYTES", "")
ERROR_TO_STRING_DICT['44'] = ("SHT1x_TOO_MANY_R_BYTES", "")
ERROR_TO_STRING_DICT['45'] = ("SHT1x_INVALID_MODE", "")
ERROR_TO_STRING_DICT['46'] = ("SHT1x_INVALID_LINE", "")
ERROR_TO_STRING_DICT['48'] = ("STREAM_IS_ACTIVE", "This error is raised when you call StreamStart after the stream has already been started.")
ERROR_TO_STRING_DICT['49'] = ("STREAM_TABLE_INVALID", "")
ERROR_TO_STRING_DICT['50'] = ("STREAM_CONFIG_INVALID", "")
ERROR_TO_STRING_DICT['52'] = ("STREAM_NOT_RUNNING", "This error is raised when you call StopStream after the stream has already been stopped.")
ERROR_TO_STRING_DICT['53'] = ("STREAM_INVALID_TRIGGER", "")
ERROR_TO_STRING_DICT['54'] = ("STREAM_ADC0_BUFFER_OVERFLOW", "")
ERROR_TO_STRING_DICT['55'] = ("STREAM_SCAN_OVERLAP", "This error is raised when a scan interrupt is fired before the LabJack has completed the previous scan. The most common cause of this error is a configuration with a high sampling rate and a large number of channels.")
ERROR_TO_STRING_DICT['56'] = ("STREAM_SAMPLE_NUM_INVALID", "")
ERROR_TO_STRING_DICT['57'] = ("STREAM_BIPOLAR_GAIN_INVALID", "")
ERROR_TO_STRING_DICT['58'] = ("STREAM_SCAN_RATE_INVALID", "")
ERROR_TO_STRING_DICT['59'] = ("STREAM_AUTORECOVER_ACTIVE", "This error is to inform you that the autorecover feature has been activated. Autorecovery is usually triggered by not reading data fast enough from the LabJack.")
ERROR_TO_STRING_DICT['60'] = ("STREAM_AUTORECOVER_REPORT", "This error marks the packet as an autorecovery report packet which contains how many packets were lost.")
ERROR_TO_STRING_DICT['63'] = ("STREAM_AUTORECOVER_OVERFLOW", "")
ERROR_TO_STRING_DICT['64'] = ("TIMER_INVALID_MODE", "")
ERROR_TO_STRING_DICT['65'] = ("TIMER_QUADRATURE_AB_ERROR", "")
ERROR_TO_STRING_DICT['66'] = ("TIMER_QUAD_PULSE_SEQUENCE", "")
ERROR_TO_STRING_DICT['67'] = ("TIMER_BAD_CLOCK_SOURCE", "")
ERROR_TO_STRING_DICT['68'] = ("TIMER_STREAM_ACTIVE", "")
ERROR_TO_STRING_DICT['69'] = ("TIMER_PWMSTOP_MODULE_ERROR", "")
ERROR_TO_STRING_DICT['70'] = ("TIMER_SEQUENCE_ERROR", "")
ERROR_TO_STRING_DICT['71'] = ("TIMER_LINE_SEQUENCE_ERROR", "")
ERROR_TO_STRING_DICT['72'] = ("TIMER_SHARING_ERROR", "")
ERROR_TO_STRING_DICT['80'] = ("EXT_OSC_NOT_STABLE", "")
ERROR_TO_STRING_DICT['81'] = ("INVALID_POWER_SETTING", "")
ERROR_TO_STRING_DICT['82'] = ("PLL_NOT_LOCKED", "")
ERROR_TO_STRING_DICT['96'] = ("INVALID_PIN", "")
ERROR_TO_STRING_DICT['97'] = ("PIN_CONFIGURED_FOR_ANALOG", "This error is raised when you try to do a digital operation on a pin that's configured for analog. Use a command like ConfigIO to set the pin to digital.")
ERROR_TO_STRING_DICT['98'] = ("PIN_CONFIGURED_FOR_DIGITAL", "This error is raised when you try to do an analog operation on a pin which is configured for digital. Use a command like ConfigIO to set the pin to analog.")
ERROR_TO_STRING_DICT['99'] = ("IOTYPE_SYNCH_ERROR", "")
ERROR_TO_STRING_DICT['100'] = ("INVALID_OFFSET", "")
ERROR_TO_STRING_DICT['101'] = ("IOTYPE_NOT_VALID", "")
ERROR_TO_STRING_DICT['102'] = ("TC_PIN_OFFSET_MUST_BE_4-8", "This error is raised when you try to configure the Timer/Counter pin offset to be 0-3.")
def lowlevelErrorToString( errorcode ):
"""Converts a low-level errorcode into a string.
"""
try:
name, advice = ERROR_TO_STRING_DICT[str(errorcode)]
except KeyError:
name = "UNKNOWN_ERROR"
advice = "Unrecognized error code (%s)" % errorcode
if advice is not "":
msg = "%s (%s)\n%s" % (name, errorcode, advice)
else:
msg = "%s (%s)" % (name, errorcode)
return msg
#Windows
def ErrorToString(ErrorCode):
"""Converts an LabJackUD valid error code to a String.
For Windows
Sample Usage:
>>> ErrorToString(1007)
'LabJack not found'
@type ErrorCode: number
@param ErrorCode: Valid LabJackUD error code.
@rtype: String
@return: The string that represents the valid LabJackUD error code
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
pString = ctypes.create_string_buffer(256)
staticLib.ErrorToString(ctypes.c_long(ErrorCode), ctypes.byref(pString))
return pString.value
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows, Linux, and Mac
def GetDriverVersion():
"""Converts an LabJackUD valid error code to a String.
For Windows, Linux, and Mac
Sample Usage:
>>> GetDriverVersion()
2.64
>>> GetDriverVersion()
Mac
@rtype: number/String
@return: Value of the driver version as a String
- For Mac machines the return type is "Mac"
- For Windows and Linux systems the return type is a number that represents the driver version
"""
if os.name == 'nt':
staticLib.GetDriverVersion.restype = ctypes.c_float
return str(staticLib.GetDriverVersion())
elif os.name == 'posix':
staticLib.LJUSB_GetLibraryVersion.restype = ctypes.c_float
return "%.2f" % staticLib.LJUSB_GetLibraryVersion()
#Windows
def TCVoltsToTemp(TCType, TCVolts, CJTempK):
"""Converts a thermo couple voltage reading to an appropriate temperature reading.
For Windows
Sample Usage:
>>> TCVoltsToTemp(LJ_ttK, 0.003141592, 297.038889)
373.13353222244825
@type TCType: number
@param TCType: The type of thermo couple used.
@type TCVolts: number
@param TCVolts: The voltage reading from the thermo couple
@type CJTempK: number
@param CJTempK: The cold junction temperature reading in Kelvin
@rtype: number
@return: The thermo couples temperature reading
- pTCTempK
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
pTCTempK = ctypes.c_double()
ec = staticLib.TCVoltsToTemp(ctypes.c_long(TCType), ctypes.c_double(TCVolts),
ctypes.c_double(CJTempK), ctypes.byref(pTCTempK))
if ec != 0: raise LabJackException(ec)
return pTCTempK.value
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def Close():
"""Resets the driver and closes all open handles.
For Windows
Sample Usage:
>>> Close()
@rtype: None
@return: The function returns nothing.
"""
opSys = os.name
if(opSys == 'nt'):
staticLib = ctypes.windll.LoadLibrary("labjackud")
staticLib.Close()
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows, Linux and Mac
def DriverPresent():
try:
ctypes.windll.LoadLibrary("labjackud")
return True
except:
try:
ctypes.cdll.LoadLibrary("liblabjackusb.so")
return True
except:
try:
ctypes.cdll.LoadLibrary("liblabjackusb.dylib")
return True
except:
return False
return False
return False
def U12DriverPresent():
try:
ctypes.windll.LoadLibrary("ljackuw")
return True
except:
return False
#Windows only
def LJHash(hashStr, size):
"""An approximation of the md5 hashing algorithms.
For Windows
An approximation of the md5 hashing algorithm. Used
for authorizations on UE9 version 1.73 and higher and u3
version 1.35 and higher.
@type hashStr: String
@param hashStr: String to be hashed.
@type size: number
@param size: Amount of bytes to hash from the hashStr
@rtype: String
@return: The hashed string.
"""
print "Hash String:" + str(hashStr)
outBuff = (ctypes.c_char * 16)()
retBuff = ''
staticLib = ctypes.windll.LoadLibrary("labjackud")
ec = staticLib.LJHash(ctypes.cast(hashStr, ctypes.POINTER(ctypes.c_char)),
size,
ctypes.cast(outBuff, ctypes.POINTER(ctypes.c_char)),
0)
if ec != 0: raise LabJackException(ec)
for i in range(16):
retBuff += outBuff[i]
return retBuff
def __listAllUE9Unix(connectionType):
"""Private listAll function for use on unix and mac machines to find UE9s.
"""
deviceList = {}
rcvDataBuff = []
if connectionType == LJ_ctUSB:
numDevices = staticLib.LJUSB_GetDevCount(LJ_dtUE9)
for i in xrange(numDevices):
try:
device = openLabJack(LJ_dtUE9, 1, firstFound = False, devNumber = i+1)
device.close()
deviceList[str(device.serialNumber)] = device.__dict__
except LabJackException:
pass
elif connectionType == LJ_ctETHERNET:
#Create a socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.settimeout(BROADCAST_SOCKET_TIMEOUT)
sndDataBuff = [0] * 6
sndDataBuff[0] = 0x22
sndDataBuff[1] = 0x78
sndDataBuff[3] = 0xa9
outBuff = ""
for item in sndDataBuff:
outBuff += chr(item)
s.sendto(outBuff, ("255.255.255.255", 52362))
try:
while True:
rcvDataBuff = s.recv(128)
try:
rcvDataBuff = [ord(val) for val in rcvDataBuff]
if verifyChecksum(rcvDataBuff):
#Parse the packet
macAddress = rcvDataBuff[28:34]
macAddress.reverse()
# The serial number is four bytes:
# 0x10 and the last three bytes of the MAC address
serialBytes = chr(0x10)
for j in macAddress[3:]:
serialBytes += chr(j)
serial = struct.unpack(">I", serialBytes)[0]
#Parse out the IP address
ipAddress = ""
for j in range(13, 9, -1):
ipAddress += str(int(rcvDataBuff[j]))
ipAddress += "."
ipAddress = ipAddress[0:-1]
#Local ID
localId = rcvDataBuff[8] & 0xff
deviceList[serial] = dict(devType = LJ_dtUE9, localId = localId, \
serialNumber = serial, ipAddress = ipAddress)
except Exception, e:
pass
except:
pass
return deviceList
def __listAllU3Unix():
"""Private listAll function for unix and mac machines. Works on the U3 only.
"""
deviceList = {}
numDevices = staticLib.LJUSB_GetDevCount(LJ_dtU3)
for i in xrange(numDevices):
try:
device = openLabJack(LJ_dtU3, 1, firstFound = False, devNumber = i+1)
device.close()
deviceList[str(device.serialNumber)] = device.__dict__
except LabJackException:
pass
return deviceList
def __listAllU6Unix():
""" List all for U6s """
deviceList = {}
numDevices = staticLib.LJUSB_GetDevCount(LJ_dtU6)
for i in xrange(numDevices):
try:
device = openLabJack(LJ_dtU6, 1, firstFound = False, devNumber = i+1)
device.close()
deviceList[str(device.serialNumber)] = device.__dict__
except LabJackException:
pass
return deviceList
def __listAllBridgesUnix():
""" List all for Bridges """
deviceList = {}
numDevices = staticLib.LJUSB_GetDevCount(0x501)
for i in xrange(numDevices):
try:
device = openLabJack(0x501, 1, firstFound = False, devNumber = i+1)
device.close()
deviceList[str(device.serialNumber)] = device.__dict__
except LabJackException:
pass
return deviceList
def setChecksum16(buffer):
total = 0;
for i in range(6, len(buffer)):
total += (buffer[i] & 0xff)
buffer[4] = (total & 0xff)
buffer[5] = ((total >> 8) & 0xff)
return buffer
def setChecksum8(buffer, numBytes):
total = 0
for i in range(1, numBytes):
total += (buffer[i] & 0xff)
buffer[0] = (total & 0xff) + ((total >> 8) & 0xff)
buffer[0] = (buffer[0] & 0xff) + ((buffer[0] >> 8) & 0xff)
return buffer
class LJSocketHandle(object):
"""
Class to replace a device handle with a socket to a LJSocket server.
"""
def __init__(self, ipAddress, port, devType, firstFound, pAddress):
try:
serverSocket = socket.socket()
serverSocket.connect((ipAddress, port))
serverSocket.settimeout(SOCKET_TIMEOUT)
f = serverSocket.makefile(bufsize = 0)
f.write("scan\r\n")
l = f.readline().strip()
try:
status, numLines = l.split(' ')
except ValueError:
raise Exception("Got invalid line from server: %s" % l)
if status.lower().startswith('ok'):
lines = []
marked = None
for i in range(int(numLines)):
l = f.readline().strip()
dev = parseline(l)
if devType == dev['prodId']:
lines.append(dev)
if not firstFound and (dev['localId'] == pAddress or dev['serial'] == pAddress):
marked = dev
f.close()
serverSocket.close()
#print "Result of scan:"
#print lines
if firstFound and len(lines) > 0:
marked = lines[0]
elif marked is not None:
pass
else:
raise Exception("LabJack not found.")
if marked['crPort'] != 'x':
self.crSocket = socket.socket()
self.crSocket.connect((ipAddress, marked['crPort']))
self.crSocket.settimeout(LJSOCKET_TIMEOUT)
else:
self.crSocket = None
if marked['modbusPort'] != 'x':
self.modbusSocket = socket.socket()
self.modbusSocket.connect((ipAddress, marked['modbusPort']))
self.modbusSocket.settimeout(LJSOCKET_TIMEOUT)
else:
self.modbusSocket = None
if marked['spontPort'] != 'x':
self.spontSocket = socket.socket()
self.spontSocket.connect((ipAddress, marked['spontPort']))
self.spontSocket.settimeout(LJSOCKET_TIMEOUT)
else:
self.spontSocket = None
else:
raise Exception("Got an error from LJSocket. It said '%s'" % l)
except Exception, e:
raise LabJackException(ec = LJE_LABJACK_NOT_FOUND, errorString = "Couldn't connect to a LabJack at %s:%s. The error was: %s" % (ipAddress, port, str(e)))
def close(self):
if self.crSocket is not None:
self.crSocket.close()
if self.modbusSocket is not None:
self.modbusSocket.close()
if self.spontSocket is not None:
self.spontSocket.close()
def parseline(line):
try:
prodId, crPort, modbusPort, spontPort, localId, serial = line.split(' ')
if not crPort.startswith('x'):
crPort = int(crPort)
if not modbusPort.startswith('x'):
modbusPort = int(modbusPort)
if not spontPort.startswith('x'):
spontPort = int(spontPort)
except ValueError:
raise Exception("")
return { 'prodId' : int(prodId), 'crPort' : crPort, 'modbusPort' : modbusPort, 'spontPort' : spontPort, 'localId' : int(localId), 'serial' : int(serial) }
#Class for handling UE9 TCP Connections
class UE9TCPHandle(object):
"""__UE9TCPHandle(ipAddress)
Creates two sockets for the streaming and non streaming port on the UE9.
Only works on default ports (Data 52360, Stream 52361).
"""
def __init__(self, ipAddress, timeout = SOCKET_TIMEOUT):
try:
self.data = socket.socket()
self.data.connect((ipAddress, 52360))
self.data.settimeout(timeout)
self.stream = socket.socket()
self.stream.connect((ipAddress, 52361))
self.stream.settimeout(timeout)
try:
self.modbus = socket.socket()
self.modbus.connect((ipAddress, 502))
self.modbus.settimeout(timeout)
except socket.error, e:
raise LabJackException("Couldn't connect to the Modbus port on the UE9. Please upgrade to UE9 Comm firmware to 1.43 or higher.")
except LabJackException, e:
raise e
except Exception, e:
print e
raise LabJackException("Couldn't open sockets to the UE9 at IP Address %s. Error was: %s" % (ipAddress, e))
def close(self):
try:
self.data.close()
self.stream.close()
self.modbus.close()
except Exception, e:
print "UE9 Handle close exception: ", e
pass
def toDouble(bytes):
"""
Name: toDouble(buffer)
Args: buffer, an array with 8 bytes
Desc: Converts the 8 byte array into a floating point number.
"""
right, left = struct.unpack("<Ii", struct.pack("B" * 8, *bytes[0:8]))
return float(left) + float(right)/(2**32)
def hexWithoutQuotes(l):
""" Return a string listing hex without all the single quotes.
>>> l = range(10)
>>> print hexWithoutQuotes(l)
[0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9]
"""
return str([hex (i) for i in l]).replace("'", "")
#device types
LJ_dtUE9 = 9
"""Device type for the UE9"""
LJ_dtU3 = 3
"""Device type for the U3"""
LJ_dtU6 = 6
"""Device type for the U6"""
# connection types:
LJ_ctUSB = 1 # UE9 + U3
"""Connection type for the UE9 and U3"""
LJ_ctETHERNET = 2 # UE9 only
"""Connection type for the UE9"""
LJ_ctUSB_RAW = 101 # UE9 + U3
"""Connection type for the UE9 and U3
Raw connection types are used to open a device but not communicate with it
should only be used if the normal connection types fail and for testing.
If a device is opened with the raw connection types, only LJ_ioRAW_OUT
and LJ_ioRAW_IN io types should be used
"""
LJ_ctETHERNET_RAW = 102 # UE9 only
"""Connection type for the UE9
Raw connection types are used to open a device but not communicate with it
should only be used if the normal connection types fail and for testing.
If a device is opened with the raw connection types, only LJ_ioRAW_OUT
and LJ_ioRAW_IN io types should be used
"""
LJ_ctLJSOCKET = 200
"""Connection type for USB LabJack connected to LJSocket server.
"""
# io types:
LJ_ioGET_AIN = 10 # UE9 + U3. This is single ended version.
"""IO type for the UE9 and U3
This is the single ended version
"""
LJ_ioGET_AIN_DIFF = 15 # U3 only. Put second channel in x1. If 32 is passed as x1, Vref will be added to the result.
"""IO type for the U3
Put second channel in x1. If 32 is passed as x1, Vref will be added to the result.
"""
LJ_ioPUT_AIN_RANGE = 2000 # UE9
"""IO type for the UE9"""
LJ_ioGET_AIN_RANGE = 2001 # UE9
"""IO type for the UE9"""
# sets or reads the analog or digital mode of the FIO and EIO pins. FIO is Channel 0-7, EIO 8-15
LJ_ioPUT_ANALOG_ENABLE_BIT = 2013 # U3
"""IO type for the U3
Sets or reads the analog or digital mode of the FIO and EIO pins. FIO is Channel 0-7, EIO 8-15
"""
LJ_ioGET_ANALOG_ENABLE_BIT = 2014 # U3
"""IO type for the U3
Sets or reads the analog or digital mode of the FIO and EIO pins. FIO is Channel 0-7, EIO 8-15
"""
# sets or reads the analog or digital mode of the FIO and EIO pins. Channel is starting
# bit #, x1 is number of bits to read. The pins are set by passing a bitmask as a double
# for the value. The first bit of the int that the double represents will be the setting
# for the pin number sent into the channel variable.
LJ_ioPUT_ANALOG_ENABLE_PORT = 2015 # U3
""" IO type for the U3
sets or reads the analog or digital mode of the FIO and EIO pins. Channel is starting
bit #, x1 is number of bits to read. The pins are set by passing a bitmask as a double
for the value. The first bit of the int that the double represents will be the setting
for the pin number sent into the channel variable.
"""
LJ_ioGET_ANALOG_ENABLE_PORT = 2016 # U3
""" IO type for the U3
sets or reads the analog or digital mode of the FIO and EIO pins. Channel is starting
bit #, x1 is number of bits to read. The pins are set by passing a bitmask as a double
for the value. The first bit of the int that the double represents will be the setting
for the pin number sent into the channel variable.
"""
LJ_ioPUT_DAC = 20 # UE9 + U3
"""IO type for the U3 and UE9"""
LJ_ioPUT_DAC_ENABLE = 2002 # UE9 + U3 (U3 on Channel 1 only)
"""IO type for the U3 and UE9
U3 on channel 1 only.
"""
LJ_ioGET_DAC_ENABLE = 2003 # UE9 + U3 (U3 on Channel 1 only)
"""IO type for the U3 and UE9
U3 on channel 1 only.
"""
LJ_ioGET_DIGITAL_BIT = 30 # UE9 + U3 # changes direction of bit to input as well
LJ_ioGET_DIGITAL_BIT_DIR = 31 # U3
LJ_ioGET_DIGITAL_BIT_STATE = 32 # does not change direction of bit, allowing readback of output
# channel is starting bit #, x1 is number of bits to read
LJ_ioGET_DIGITAL_PORT = 35 # UE9 + U3 # changes direction of bits to input as well
LJ_ioGET_DIGITAL_PORT_DIR = 36 # U3
LJ_ioGET_DIGITAL_PORT_STATE = 37 # U3 does not change direction of bits, allowing readback of output
# digital put commands will set the specified digital line(s) to output
LJ_ioPUT_DIGITAL_BIT = 40 # UE9 + U3
# channel is starting bit #, value is output value, x1 is bits to write
LJ_ioPUT_DIGITAL_PORT = 45 # UE9 + U3
# Used to create a pause between two events in a U3 low-level feedback
# command. For example, to create a 100 ms positive pulse on FIO0, add a
# request to set FIO0 high, add a request for a wait of 100000, add a
# request to set FIO0 low, then Go. Channel is ignored. Value is
# microseconds to wait and should range from 0 to 8388480. The actual
# resolution of the wait is 128 microseconds.
LJ_ioPUT_WAIT = 70 # U3
# counter. Input only.
LJ_ioGET_COUNTER = 50 # UE9 + U3
LJ_ioPUT_COUNTER_ENABLE = 2008 # UE9 + U3
LJ_ioGET_COUNTER_ENABLE = 2009 # UE9 + U3
# this will cause the designated counter to reset. If you want to reset the counter with
# every read, you have to use this command every time.
LJ_ioPUT_COUNTER_RESET = 2012 # UE9 + U3
# on UE9: timer only used for input. Output Timers don't use these. Only Channel used.
# on U3: Channel used (0 or 1).
LJ_ioGET_TIMER = 60 # UE9 + U3
LJ_ioPUT_TIMER_VALUE = 2006 # UE9 + U3. Value gets new value
LJ_ioPUT_TIMER_MODE = 2004 # UE9 + U3. On both Value gets new mode.
LJ_ioGET_TIMER_MODE = 2005 # UE9
# IOTypes for use with SHT sensor. For LJ_ioSHT_GET_READING, a channel of LJ_chSHT_TEMP (5000) will
# read temperature, and LJ_chSHT_RH (5001) will read humidity.
# The LJ_ioSHT_DATA_CHANNEL and LJ_ioSHT_SCK_CHANNEL iotypes use the passed channel
# to set the appropriate channel for the data and SCK lines for the SHT sensor.
# Default digital channels are FIO0 for the data channel and FIO1 for the clock channel.
LJ_ioSHT_GET_READING = 500 # UE9 + U3.
LJ_ioSHT_DATA_CHANNEL = 501 # UE9 + U3. Default is FIO0
LJ_ioSHT_CLOCK_CHANNEL = 502 # UE9 + U3. Default is FIO1
# Uses settings from LJ_chSPI special channels (set with LJ_ioPUT_CONFIG) to communcaite with
# something using an SPI interface. The value parameter is the number of bytes to transfer
# and x1 is the address of the buffer. The data from the buffer will be sent, then overwritten
# with the data read. The channel parameter is ignored.
LJ_ioSPI_COMMUNICATION = 503 # UE9
LJ_ioI2C_COMMUNICATION = 504 # UE9 + U3
LJ_ioASYNCH_COMMUNICATION = 505 # UE9 + U3
LJ_ioTDAC_COMMUNICATION = 506 # UE9 + U3
# Set's the U3 to it's original configuration. This means sending the following
# to the ConfigIO and TimerClockConfig low level functions
#
# ConfigIO
# Byte #
# 6 WriteMask 15 Write all parameters.
# 8 TimerCounterConfig 0 No timers/counters. Offset=0.
# 9 DAC1Enable 0 DAC1 disabled.
# 10 FIOAnalog 0 FIO all digital.
# 11 EIOAnalog 0 EIO all digital.
#
#
# TimerClockConfig
# Byte #
# 8 TimerClockConfig 130 Set clock to 24 MHz.
# 9 TimerClockDivisor 0 Divisor = 0.
#
LJ_ioPIN_CONFIGURATION_RESET = 2017 # U3
# the raw in/out are unusual, channel # corresponds to the particular comm port, which
# depends on the device. For example, on the UE9, 0 is main comm port, and 1 is the streaming comm.
# Make sure and pass a porter to a char buffer in x1, and the number of bytes desired in value. A call
# to GetResult will return the number of bytes actually read/written. The max you can send out in one call
# is 512 bytes to the UE9 and 16384 bytes to the U3.
LJ_ioRAW_OUT = 100 # UE9 + U3
LJ_ioRAW_IN = 101 # UE9 + U3
# sets the default power up settings based on the current settings of the device AS THIS DLL KNOWS. This last part
# basically means that you should set all parameters directly through this driver before calling this. This writes
# to flash which has a limited lifetime, so do not do this too often. Rated endurance is 20,000 writes.
LJ_ioSET_DEFAULTS = 103 # U3
# requests to create the list of channels to stream. Usually you will use the CLEAR_STREAM_CHANNELS request first, which
# will clear any existing channels, then use ADD_STREAM_CHANNEL multiple times to add your desired channels. Some devices will
# use value, x1 for other parameters such as gain. Note that you can do CLEAR, and then all your ADDs in a single Go() as long
# as you add the requests in order.
LJ_ioADD_STREAM_CHANNEL = 200
LJ_ioCLEAR_STREAM_CHANNELS = 201
LJ_ioSTART_STREAM = 202
LJ_ioSTOP_STREAM = 203
LJ_ioADD_STREAM_CHANNEL_DIFF = 206
# Get stream data has several options. If you just want to get a single channel's data (if streaming multiple channels), you
# can pass in the desired channel #, then the number of data points desired in Value, and a pointer to an array to put the
# data into as X1. This array needs to be an array of doubles. Therefore, the array needs to be 8 * number of
# requested data points in byte length. What is returned depends on the StreamWaitMode. If None, this function will only return
# data available at the time of the call. You therefore must call GetResult() for this function to retrieve the actually number
# of points retreived. If Pump or Sleep, it will return only when the appropriate number of points have been read or no
# new points arrive within 100ms. Since there is this timeout, you still need to use GetResult() to determine if the timeout
# occured. If AllOrNone, you again need to check GetResult.
# You can also retreive the entire scan by passing LJ_chALL_CHANNELS. In this case, the Value determines the number of SCANS
# returned, and therefore, the array must be 8 * number of scans requested * number of channels in each scan. Likewise
# GetResult() will return the number of scans, not the number of data points returned.
# Note: data is stored interleaved across all streaming channels. In other words, if you are streaming two channels, 0 and 1,
# and you request LJ_chALL_CHANNELS, you will get, Channel0, Channel1, Channel0, Channel1, etc. Once you have requested the
# data, any data returned is removed from the internal buffer, and the next request will give new data.
# Note: if reading the data channel by channel and not using LJ_chALL_CHANNELS, the data is not removed from the internal buffer
# until the data from the last channel in the scan is requested. This means that if you are streaming three channels, 0, 1 and 2,
# and you request data from channel 0, then channel 1, then channel 0 again, the request for channel 0 the second time will
# return the exact same amount of data. Also note, that the amount of data that will be returned for each channel request will be
# the same until you've read the last channel in the scan, at which point your next block may be a different size.
# Note: although more convenient, requesting individual channels is slightly slower then using LJ_chALL_CHANNELS. Since you
# are probably going to have to split the data out anyway, we have saved you the trouble with this option.
# Note: if you are only scanning one channel, the Channel parameter is ignored.
LJ_ioGET_STREAM_DATA = 204
# U3 only:
# Channel = 0 buzz for a count, Channel = 1 buzz continuous
# Value is the Period
# X1 is the toggle count when channel = 0
LJ_ioBUZZER = 300 # U3
# config iotypes:
LJ_ioPUT_CONFIG = 1000 # UE9 + U3
LJ_ioGET_CONFIG = 1001 # UE9 + U3
# channel numbers used for CONFIG types:
# UE9 + U3
LJ_chLOCALID = 0 # UE9 + U3
LJ_chHARDWARE_VERSION = 10 # UE9 + U3 (Read Only)
LJ_chSERIAL_NUMBER = 12 # UE9 + U3 (Read Only)
LJ_chFIRMWARE_VERSION = 11 # UE9 + U3 (Read Only)
LJ_chBOOTLOADER_VERSION = 15 # UE9 + U3 (Read Only)
# UE9 specific:
LJ_chCOMM_POWER_LEVEL = 1 #UE9
LJ_chIP_ADDRESS = 2 #UE9
LJ_chGATEWAY = 3 #UE9
LJ_chSUBNET = 4 #UE9
LJ_chPORTA = 5 #UE9
LJ_chPORTB = 6 #UE9
LJ_chDHCP = 7 #UE9
LJ_chPRODUCTID = 8 #UE9
LJ_chMACADDRESS = 9 #UE9
LJ_chCOMM_FIRMWARE_VERSION = 11
LJ_chCONTROL_POWER_LEVEL = 13 #UE9
LJ_chCONTROL_FIRMWARE_VERSION = 14 #UE9 (Read Only)
LJ_chCONTROL_BOOTLOADER_VERSION = 15 #UE9 (Read Only)
LJ_chCONTROL_RESET_SOURCE = 16 #UE9 (Read Only)
LJ_chUE9_PRO = 19 # UE9 (Read Only)
# U3 only:
# sets the state of the LED
LJ_chLED_STATE = 17 # U3 value = LED state
LJ_chSDA_SCL = 18 # U3 enable / disable SDA/SCL as digital I/O
# Used to access calibration and user data. The address of an array is passed in as x1.
# For the UE9, a 1024-element buffer of bytes is passed for user data and a 128-element
# buffer of doubles is passed for cal constants.
# For the U3, a 256-element buffer of bytes is passed for user data and a 12-element
# buffer of doubles is passed for cal constants.
# The layout of cal ants are defined in the users guide for each device.
# When the LJ_chCAL_CONSTANTS special channel is used with PUT_CONFIG, a
# special value (0x4C6C) must be passed in to the Value parameter. This makes it
# more difficult to accidently erase the cal constants. In all other cases the Value
# parameter is ignored.
LJ_chCAL_CONSTANTS = 400 # UE9 + U3
LJ_chUSER_MEM = 402 # UE9 + U3
# Used to write and read the USB descriptor strings. This is generally for OEMs
# who wish to change the strings.
# Pass the address of an array in x1. Value parameter is ignored.
# The array should be 128 elements of bytes. The first 64 bytes are for the
# iManufacturer string, and the 2nd 64 bytes are for the iProduct string.
# The first byte of each 64 byte block (bytes 0 and 64) contains the number
# of bytes in the string. The second byte (bytes 1 and 65) is the USB spec
# value for a string descriptor (0x03). Bytes 2-63 and 66-127 contain unicode
# encoded strings (up to 31 characters each).
LJ_chUSB_STRINGS = 404 # U3
# timer/counter related
LJ_chNUMBER_TIMERS_ENABLED = 1000 # UE9 + U3
LJ_chTIMER_CLOCK_BASE = 1001 # UE9 + U3
LJ_chTIMER_CLOCK_DIVISOR = 1002 # UE9 + U3
LJ_chTIMER_COUNTER_PIN_OFFSET = 1003 # U3
# AIn related
LJ_chAIN_RESOLUTION = 2000 # ue9 + u3
LJ_chAIN_SETTLING_TIME = 2001 # ue9 + u3
LJ_chAIN_BINARY = 2002 # ue9 + u3
# DAC related
LJ_chDAC_BINARY = 3000 # ue9 + u3
# SHT related
LJ_chSHT_TEMP = 5000 # ue9 + u3
LJ_chSHT_RH = 5001 # ue9 + u3
# SPI related
LJ_chSPI_AUTO_CS = 5100 # UE9
LJ_chSPI_DISABLE_DIR_CONFIG = 5101 # UE9
LJ_chSPI_MODE = 5102 # UE9
LJ_chSPI_CLOCK_FACTOR = 5103 # UE9
LJ_chSPI_MOSI_PINNUM = 5104 # UE9
LJ_chSPI_MISO_PINNUM = 5105 # UE9
LJ_chSPI_CLK_PINNUM = 5106 # UE9
LJ_chSPI_CS_PINNUM = 5107 # UE9
# I2C related :
# used with LJ_ioPUT_CONFIG
LJ_chI2C_ADDRESS_BYTE = 5108 # UE9 + U3
LJ_chI2C_SCL_PIN_NUM = 5109 # UE9 + U3
LJ_chI2C_SDA_PIN_NUM = 5110 # UE9 + U3
LJ_chI2C_OPTIONS = 5111 # UE9 + U3
LJ_chI2C_SPEED_ADJUST = 5112 # UE9 + U3
# used with LJ_ioI2C_COMMUNICATION :
LJ_chI2C_READ = 5113 # UE9 + U3
LJ_chI2C_WRITE = 5114 # UE9 + U3
LJ_chI2C_GET_ACKS = 5115 # UE9 + U3
LJ_chI2C_WRITE_READ = 5130 # UE9 + U3
# ASYNCH related :
# Used with LJ_ioASYNCH_COMMUNICATION
LJ_chASYNCH_RX = 5117 # UE9 + U3
LJ_chASYNCH_TX = 5118 # UE9 + U3
LJ_chASYNCH_FLUSH = 5128 # UE9 + U3
LJ_chASYNCH_ENABLE = 5129 # UE9 + U3
# Used with LJ_ioPUT_CONFIG and LJ_ioGET_CONFIG
LJ_chASYNCH_BAUDFACTOR = 5127 # UE9 + U3
# stream related. Note, Putting to any of these values will stop any running streams.
LJ_chSTREAM_SCAN_FREQUENCY = 4000
LJ_chSTREAM_BUFFER_SIZE = 4001
LJ_chSTREAM_CLOCK_OUTPUT = 4002
LJ_chSTREAM_EXTERNAL_TRIGGER = 4003
LJ_chSTREAM_WAIT_MODE = 4004
# readonly stream related
LJ_chSTREAM_BACKLOG_COMM = 4105
LJ_chSTREAM_BACKLOG_CONTROL = 4106
LJ_chSTREAM_BACKLOG_UD = 4107
LJ_chSTREAM_SAMPLES_PER_PACKET = 4108
# special channel #'s
LJ_chALL_CHANNELS = -1
LJ_INVALID_CONSTANT = -999
#Thermocouple Type constants.
LJ_ttB = 6001
"""Type B thermocouple constant"""
LJ_ttE = 6002
"""Type E thermocouple constant"""
LJ_ttJ = 6003
"""Type J thermocouple constant"""
LJ_ttK = 6004
"""Type K thermocouple constant"""
LJ_ttN = 6005
"""Type N thermocouple constant"""
LJ_ttR = 6006
"""Type R thermocouple constant"""
LJ_ttS = 6007
"""Type S thermocouple constant"""
LJ_ttT = 6008
"""Type T thermocouple constant"""
# other constants:
# ranges (not all are supported by all devices):
LJ_rgBIP20V = 1 # -20V to +20V
LJ_rgBIP10V = 2 # -10V to +10V
LJ_rgBIP5V = 3 # -5V to +5V
LJ_rgBIP4V = 4 # -4V to +4V
LJ_rgBIP2P5V = 5 # -2.5V to +2.5V
LJ_rgBIP2V = 6 # -2V to +2V
LJ_rgBIP1P25V = 7# -1.25V to +1.25V
LJ_rgBIP1V = 8 # -1V to +1V
LJ_rgBIPP625V = 9# -0.625V to +0.625V
LJ_rgUNI20V = 101 # 0V to +20V
LJ_rgUNI10V = 102 # 0V to +10V
LJ_rgUNI5V = 103 # 0V to +5V
LJ_rgUNI4V = 104 # 0V to +4V
LJ_rgUNI2P5V = 105 # 0V to +2.5V
LJ_rgUNI2V = 106 # 0V to +2V
LJ_rgUNI1P25V = 107# 0V to +1.25V
LJ_rgUNI1V = 108 # 0V to +1V
LJ_rgUNIP625V = 109# 0V to +0.625V
LJ_rgUNIP500V = 110 # 0V to +0.500V
LJ_rgUNIP3125V = 111 # 0V to +0.3125V
# timer modes (UE9 only):
LJ_tmPWM16 = 0 # 16 bit PWM
LJ_tmPWM8 = 1 # 8 bit PWM
LJ_tmRISINGEDGES32 = 2 # 32-bit rising to rising edge measurement
LJ_tmFALLINGEDGES32 = 3 # 32-bit falling to falling edge measurement
LJ_tmDUTYCYCLE = 4 # duty cycle measurement
LJ_tmFIRMCOUNTER = 5 # firmware based rising edge counter
LJ_tmFIRMCOUNTERDEBOUNCE = 6 # firmware counter with debounce
LJ_tmFREQOUT = 7 # frequency output
LJ_tmQUAD = 8 # Quadrature
LJ_tmTIMERSTOP = 9 # stops another timer after n pulses
LJ_tmSYSTIMERLOW = 10 # read lower 32-bits of system timer
LJ_tmSYSTIMERHIGH = 11 # read upper 32-bits of system timer
LJ_tmRISINGEDGES16 = 12 # 16-bit rising to rising edge measurement
LJ_tmFALLINGEDGES16 = 13 # 16-bit falling to falling edge measurement
# timer clocks:
LJ_tc750KHZ = 0 # UE9: 750 khz
LJ_tcSYS = 1 # UE9: system clock
LJ_tc2MHZ = 10 # U3: Hardware Version 1.20 or lower
LJ_tc6MHZ = 11 # U3: Hardware Version 1.20 or lower
LJ_tc24MHZ = 12 # U3: Hardware Version 1.20 or lower
LJ_tc500KHZ_DIV = 13# U3: Hardware Version 1.20 or lower
LJ_tc2MHZ_DIV = 14 # U3: Hardware Version 1.20 or lower
LJ_tc6MHZ_DIV = 15 # U3: Hardware Version 1.20 or lower
LJ_tc24MHZ_DIV = 16 # U3: Hardware Version 1.20 or lower
# stream wait modes
LJ_swNONE = 1 # no wait, return whatever is available
LJ_swALL_OR_NONE = 2 # no wait, but if all points requested aren't available, return none.
LJ_swPUMP = 11 # wait and pump the message pump. Prefered when called from primary thread (if you don't know
# if you are in the primary thread of your app then you probably are. Do not use in worker
# secondary threads (i.e. ones without a message pump).
LJ_swSLEEP = 12 # wait by sleeping (don't do this in the primary thread of your app, or it will temporarily
# hang) This is usually used in worker secondary threads.
# BETA CONSTANTS
# Please note that specific usage of these constants and their values might change
# SWDT related
LJ_chSWDT_RESET_COMM = 5200 # UE9 - Reset Comm on watchdog reset
LJ_chSWDT_RESET_CONTROL = 5201 # UE9 - Reset Control on watchdog trigger
LJ_chSWDT_UDPATE_DIO0 = 5202 # UE9 - Update DIO0 settings after reset
LJ_chSWDT_UPDATE_DIO1 = 5203 # UE9 - Update DIO1 settings after reset
LJ_chSWDT_DIO0 = 5204 # UE9 - DIO0 channel and state (value) to be set after reset
LJ_chSWDT_DIO1 = 5205 # UE9 - DIO1 channel and state (value) to be set after reset
LJ_chSWDT_UPDATE_DAC0 = 5206 # UE9 - Update DAC1 settings after reset
LJ_chSWDT_UPDATE_DAC1 = 5207 # UE9 - Update DAC1 settings after reset
LJ_chSWDT_DAC0 = 5208 # UE9 - voltage to set DAC0 at on watchdog reset
LJ_chSWDT_DAC1 = 5209 # UE9 - voltage to set DAC1 at on watchdog reset
LJ_chSWDT_DACS_ENABLE = 5210 # UE9 - Enable DACs on watchdog reset
LJ_chSWDT_ENABLE = 5211 # UE9 - used with LJ_ioSWDT_CONFIG to enable watchdog. Value paramter is number of seconds to trigger
LJ_chSWDT_DISABLE = 5212 # UE9 - used with LJ_ioSWDT_CONFIG to enable watchdog.
LJ_ioSWDT_CONFIG = 504 # UE9 - Use LJ_chSWDT_ENABLE or LJ_chSWDT_DISABLE
LJ_tc4MHZ = 20 # U3: Hardware Version 1.21 or higher
LJ_tc12MHZ = 21 # U3: Hardware Version 1.21 or higher
LJ_tc48MHZ = 22 # U3: Hardware Version 1.21 or higher
LJ_tc1000KHZ_DIV = 23# U3: Hardware Version 1.21 or higher
LJ_tc4MHZ_DIV = 24 # U3: Hardware Version 1.21 or higher
LJ_tc12MHZ_DIV = 25 # U3: Hardware Version 1.21 or higher
LJ_tc48MHZ_DIV = 26 # U3: Hardware Version 1.21 or higher
# END BETA CONSTANTS
# error codes: These will always be in the range of -1000 to 3999 for labView compatibility (+6000)
LJE_NOERROR = 0
LJE_INVALID_CHANNEL_NUMBER = 2 # occurs when a channel that doesn't exist is specified (i.e. DAC #2 on a UE9), or data from streaming is requested on a channel that isn't streaming
LJE_INVALID_RAW_INOUT_PARAMETER = 3
LJE_UNABLE_TO_START_STREAM = 4
LJE_UNABLE_TO_STOP_STREAM = 5
LJE_NOTHING_TO_STREAM = 6
LJE_UNABLE_TO_CONFIG_STREAM = 7
LJE_BUFFER_OVERRUN = 8 # occurs when stream buffer overruns (this is the driver buffer not the hardware buffer). Stream is stopped.
LJE_STREAM_NOT_RUNNING = 9
LJE_INVALID_PARAMETER = 10
LJE_INVALID_STREAM_FREQUENCY = 11
LJE_INVALID_AIN_RANGE = 12
LJE_STREAM_CHECKSUM_ERROR = 13 # occurs when a stream packet fails checksum. Stream is stopped
LJE_STREAM_COMMAND_ERROR = 14 # occurs when a stream packet has invalid command values. Stream is stopped.
LJE_STREAM_ORDER_ERROR = 15 # occurs when a stream packet is received out of order (typically one is missing). Stream is stopped.
LJE_AD_PIN_CONFIGURATION_ERROR = 16 # occurs when an analog or digital request was made on a pin that isn't configured for that type of request
LJE_REQUEST_NOT_PROCESSED = 17 # When a LJE_AD_PIN_CONFIGURATION_ERROR occurs, all other IO requests after the request that caused the error won't be processed. Those requests will return this error.
# U3 Specific Errors
LJE_SCRATCH_ERROR = 19
"""U3 error"""
LJE_DATA_BUFFER_OVERFLOW = 20
"""U3 error"""
LJE_ADC0_BUFFER_OVERFLOW = 21
"""U3 error"""
LJE_FUNCTION_INVALID = 22
"""U3 error"""
LJE_SWDT_TIME_INVALID = 23
"""U3 error"""
LJE_FLASH_ERROR = 24
"""U3 error"""
LJE_STREAM_IS_ACTIVE = 25
"""U3 error"""
LJE_STREAM_TABLE_INVALID = 26
"""U3 error"""
LJE_STREAM_CONFIG_INVALID = 27
"""U3 error"""
LJE_STREAM_BAD_TRIGGER_SOURCE = 28
"""U3 error"""
LJE_STREAM_INVALID_TRIGGER = 30
"""U3 error"""
LJE_STREAM_ADC0_BUFFER_OVERFLOW = 31
"""U3 error"""
LJE_STREAM_SAMPLE_NUM_INVALID = 33
"""U3 error"""
LJE_STREAM_BIPOLAR_GAIN_INVALID = 34
"""U3 error"""
LJE_STREAM_SCAN_RATE_INVALID = 35
"""U3 error"""
LJE_TIMER_INVALID_MODE = 36
"""U3 error"""
LJE_TIMER_QUADRATURE_AB_ERROR = 37
"""U3 error"""
LJE_TIMER_QUAD_PULSE_SEQUENCE = 38
"""U3 error"""
LJE_TIMER_BAD_CLOCK_SOURCE = 39
"""U3 error"""
LJE_TIMER_STREAM_ACTIVE = 40
"""U3 error"""
LJE_TIMER_PWMSTOP_MODULE_ERROR = 41
"""U3 error"""
LJE_TIMER_SEQUENCE_ERROR = 42
"""U3 error"""
LJE_TIMER_SHARING_ERROR = 43
"""U3 error"""
LJE_TIMER_LINE_SEQUENCE_ERROR = 44
"""U3 error"""
LJE_EXT_OSC_NOT_STABLE = 45
"""U3 error"""
LJE_INVALID_POWER_SETTING = 46
"""U3 error"""
LJE_PLL_NOT_LOCKED = 47
"""U3 error"""
LJE_INVALID_PIN = 48
"""U3 error"""
LJE_IOTYPE_SYNCH_ERROR = 49
"""U3 error"""
LJE_INVALID_OFFSET = 50
"""U3 error"""
LJE_FEEDBACK_IOTYPE_NOT_VALID = 51
"""U3 error
Has been described as mearly a flesh wound.
"""
LJE_SHT_CRC = 52
LJE_SHT_MEASREADY = 53
LJE_SHT_ACK = 54
LJE_SHT_SERIAL_RESET = 55
LJE_SHT_COMMUNICATION = 56
LJE_AIN_WHILE_STREAMING = 57
LJE_STREAM_TIMEOUT = 58
LJE_STREAM_CONTROL_BUFFER_OVERFLOW = 59
LJE_STREAM_SCAN_OVERLAP = 60
LJE_FIRMWARE_DOESNT_SUPPORT_IOTYPE = 61
LJE_FIRMWARE_DOESNT_SUPPORT_CHANNEL = 62
LJE_FIRMWARE_DOESNT_SUPPORT_VALUE = 63
LJE_MIN_GROUP_ERROR = 1000 # all errors above this number will stop all requests, below this number are request level errors.
LJE_UNKNOWN_ERROR = 1001 # occurs when an unknown error occurs that is caught, but still unknown.
LJE_INVALID_DEVICE_TYPE = 1002 # occurs when devicetype is not a valid device type
LJE_INVALID_HANDLE = 1003 # occurs when invalid handle used
LJE_DEVICE_NOT_OPEN = 1004 # occurs when Open() fails and AppendRead called despite.
LJE_NO_DATA_AVAILABLE = 1005 # this is cause when GetData() called without calling DoRead(), or when GetData() passed channel that wasn't read
LJE_NO_MORE_DATA_AVAILABLE = 1006
LJE_LABJACK_NOT_FOUND = 1007 # occurs when the labjack is not found at the given id or address.
LJE_COMM_FAILURE = 1008 # occurs when unable to send or receive the correct # of bytes
LJE_CHECKSUM_ERROR = 1009
LJE_DEVICE_ALREADY_OPEN = 1010
LJE_COMM_TIMEOUT = 1011
LJE_USB_DRIVER_NOT_FOUND = 1012
LJE_INVALID_CONNECTION_TYPE = 1013
LJE_INVALID_MODE = 1014
# warning are negative
LJE_DEVICE_NOT_CALIBRATED = -1 # defaults used instead
LJE_UNABLE_TO_READ_CALDATA = -2 # defaults used instead
# depreciated constants:
LJ_ioANALOG_INPUT = 10
"""Deprecated constant"""
LJ_ioANALOG_OUTPUT = 20 # UE9 + U3
"""Deprecated constant"""
LJ_ioDIGITAL_BIT_IN = 30 # UE9 + U3
"""Deprecated constant"""
LJ_ioDIGITAL_PORT_IN = 35 # UE9 + U3
"""Deprecated constant"""
LJ_ioDIGITAL_BIT_OUT = 40 # UE9 + U3
"""Deprecated constant"""
LJ_ioDIGITAL_PORT_OUT = 45 # UE9 + U3
"""Deprecated constant"""
LJ_ioCOUNTER = 50 # UE9 + U3
"""Deprecated constant"""
LJ_ioTIMER = 60 # UE9 + U3
"""Deprecated constant"""
LJ_ioPUT_COUNTER_MODE = 2010 # UE9
"""Deprecated constant"""
LJ_ioGET_COUNTER_MODE = 2011 # UE9
"""Deprecated constant"""
LJ_ioGET_TIMER_VALUE = 2007 # UE9
"""Deprecated constant"""
LJ_ioCYCLE_PORT = 102 # UE9
"""Deprecated constant"""
LJ_chTIMER_CLOCK_CONFIG = 1001 # UE9 + U3
"""Deprecated constant"""
LJ_ioPUT_CAL_CONSTANTS = 400
"""Deprecated constant"""
LJ_ioGET_CAL_CONSTANTS = 401
"""Deprecated constant"""
LJ_ioPUT_USER_MEM = 402
"""Deprecated constant"""
LJ_ioGET_USER_MEM = 403
"""Deprecated constant"""
LJ_ioPUT_USB_STRINGS = 404
"""Deprecated constant"""
LJ_ioGET_USB_STRINGS = 405
"""Deprecated constant"""
| 131,061 | 35.095291 | 272 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/src/Modbus.py | # File: Modbus.py
# Author: LabJack Corp.
# Created: 05.05.2008
# Last Modified: 12/3/2009
from __future__ import with_statement
from threading import Lock
from struct import pack, unpack #, unpack_from # unpack_from is new in 2.5
from datetime import datetime
AES_CHANNEL = 64000
IP_PART1_CHANNEL = 64008
IP_PART2_CHANNEL = 64009
PORT_CHANNEL = 64010
HEARTBEAT_CHANNEL = 64016
DEBUG_CHANNEL = 64017
DEVICE_TYPE_CHANNEL = 65000
SERIAL_NUMBER_CHANNEL = 65001
READ_PACKET = 3
WRITE_PACKET = 6
HEADER_LENGTH = 9
BYTES_PER_REGISTER = 2
GLOBAL_TRANSACTION_ID_LOCK = Lock()
MAX_TRANS_ID = 64760
def _calcBaseTransId():
t = datetime.now()
d = "%s%s%s%s" % (t.hour, t.minute, t.second, t.microsecond)
d = int(d) % MAX_TRANS_ID
return d
BASE_TRANS_ID = _calcBaseTransId()
CURRENT_TRANS_IDS = set()
def _buildHeaderBytes(length = 6, unitId = None):
with GLOBAL_TRANSACTION_ID_LOCK:
global BASE_TRANS_ID, CURRENT_TRANS_IDS
if unitId is None:
basicHeader = (BASE_TRANS_ID, 0, length, 0x00)
else:
basicHeader = (BASE_TRANS_ID, 0, length, unitId)
CURRENT_TRANS_IDS.add(BASE_TRANS_ID)
BASE_TRANS_ID = ( BASE_TRANS_ID + 1 ) % MAX_TRANS_ID
return pack('>HHHB', *basicHeader)
def _checkTransId(transId):
with GLOBAL_TRANSACTION_ID_LOCK:
global CURRENT_TRANS_IDS
if transId in CURRENT_TRANS_IDS:
CURRENT_TRANS_IDS.remove(transId)
else:
raise ModbusException("Got an unexpected transaction ID. Id = %s, Set = %s" % (transId, CURRENT_TRANS_IDS))
def readHoldingRegistersRequest(addr, numReg = None, unitId = None):
if numReg is None:
numReg = calcNumberOfRegisters(addr)
packet = _buildHeaderBytes(unitId = unitId) + pack('>BHH', 0x03, addr, numReg)
return packet
def readHoldingRegistersResponse(packet, payloadFormat=None):
# Example: Device type is 9
# [0, 0, 5, 255, 3, 2, 9]
# H H H c c c payload
# 0 1 2 3 4 5 6+
HEADER_LENGTH = 9
header = unpack('>HHHBBB', packet[:HEADER_LENGTH])
#print "header", [ c for c in header ]
#print "header", header
# Check that protocol ID is 0
if header[1] != 0:
raise ModbusException("Got an unexpected protocol ID: %s (expected 0). Please make sure that you have the latest firmware. UE9s need a Comm Firmware of 1.50 or greater.\n\nThe packet you received: %s" % (header[1], repr(packet)))
# Check for valid Trans ID
_checkTransId(header[0])
#Check for exception
if header[4] == 0x83:
raise ModbusException("Error reading register: A Modbus error %s was raised.\n\nThe packet you received: %s" % (header[5], repr(packet)))
#Check for proper command
if header[4] != 0x03:
raise ModbusException("Not a read holding registers packet.\n\nGot: %s" % repr(packet))
#Check for proper length
payloadLength = header[5]
if (payloadLength + HEADER_LENGTH) != len(packet):
#print "packet length is", len(packet)
#print "payload and header is", payloadLength + HEADER_LENGTH
raise ModbusException("Packet length not valid. Expected %s, Got %s\n\nThe packet you received: %s" % (payloadLength + HEADER_LENGTH, len(packet), repr(packet)))
if payloadFormat is None:
payloadFormat = '>' + 'H' * (payloadLength/2)
# When we write '>s', we mean a variable-length string.
# We just didn't know the length when we wrote it.
if payloadFormat == '>s':
payloadFormat = '>' + 's' * payloadLength
#print "Info: "
#print payloadFormat
#print type(packet)
#print [ ord(c) for c in packet ]
# Mike C.: unpack_from new in 2.5. Won't work on Joyent.
#payload = unpack_from(payloadFormat, packet, offset = HEADER_LENGTH)
payload = unpack(payloadFormat, packet[HEADER_LENGTH:])
if len(payload) == 1:
return payload[0]
else:
return list(payload)
def readInputRegistersRequest(addr, numReg = None):
if numReg is None:
numReg = calcNumberOfRegisters(addr)
packet = _buildHeaderBytes() + pack('>BHH', 0x04, addr, numReg)
#print "making readHoldingRegistersRequest packet"
#print [ ord(c) for c in packet ]
return packet
def readInputRegistersResponse(packet, payloadFormat=None):
# Example: Device type is 9
# [0, 0, 5, 255, 3, 2, 9]
# H H H c c c payload
# 0 1 2 3 4 5 6+
HEADER_LENGTH = 9
header = unpack('>HHHBBB', packet[:HEADER_LENGTH])
#print "header", [ c for c in header ]
#print "header", header
# Check for valid Trans ID
_checkTransId(header[0])
#Check for exception
if header[4] == 0x83:
raise ModbusException(header[5])
#Check for proper command
if header[4] != 0x04:
raise ModbusException("Not a read holding registers packet.")
#Check for proper length
payloadLength = header[5]
if (payloadLength + HEADER_LENGTH) != len(packet):
#print "packet length is", len(packet)
#print "payload and header is", payloadLength + HEADER_LENGTH
raise ModbusException("Packet length not valid.")
if payloadFormat is None:
payloadFormat = '>' + 'H' * (payloadLength/2)
# When we write '>s', we mean a variable-length string.
# We just didn't know the length when we wrote it.
if payloadFormat == '>s':
payloadFormat = '>' + 's' * payloadLength
#print payloadFormat
#print [ ord(c) for c in packet ]
# Mike C.: unpack_from new in 2.5. Won't work on Joyent.
#payload = unpack_from(payloadFormat, packet, offset = HEADER_LENGTH)
payload = unpack(payloadFormat, packet[HEADER_LENGTH:])
return payload
def writeRegisterRequest(addr, value, unitId = None):
if not isinstance(value, int):
raise TypeError("Value written must be an integer.")
packet = _buildHeaderBytes(unitId = unitId) + pack('>BHH', 0x06, addr, value)
return packet
def writeRegistersRequest(startAddr, values, unitId = None):
numReg = len(values)
for v in values:
if not isinstance(v, int):
raise TypeError("Value written must be an integer.")
if unitId is None:
unitId = 0xff
header = _buildHeaderBytes(length = 7+(numReg*2), unitId = unitId)
header += pack('>BHHB', *(16, startAddr, numReg, numReg*2) )
format = '>' + 'H' * numReg
packet = header + pack(format, *values)
return packet
def writeAesStingRegisterRequest(addr, a, b):
packet = TCP_HEADER + pack('>BHcc', 0x06, addr, a, b)
return packet
def writeRegisterRequestValue(data):
"""Return the value to be written in a writeRegisterRequest Packet."""
packet = unpack('>H', data[10:])
return packet[0]
class ModbusException(Exception):
def __init__(self, exceptCode):
self.exceptCode = exceptCode
def __str__(self):
return repr(self.exceptCode)
def calcNumberOfRegisters(addr, numReg = None):
return calcNumberOfRegistersAndFormat(addr, numReg)[0]
def calcFormat(addr, numReg = None):
return calcNumberOfRegistersAndFormat(addr, numReg)[1]
def calcNumberOfRegistersAndFormat(addr, numReg = None):
# TODO add special cases for channels above
if addr < 1000:
# Analog Inputs
minNumReg = 2
format = 'f'
elif addr >= 5000 and addr < 6000:
# DAC Values
minNumReg = 2
format = 'f'
elif addr >= 7000 and addr < 8000:
# Timers / Counters
minNumReg = 2
format = 'I'
elif addr in range(64008,64018) or addr == 65001:
# Serial Number
minNumReg = 2
format = 'I'
elif addr in range(10000,10010):
# VBatt/Temp/RH/Light/Pressure
minNumReg = 2
format = 'f'
elif addr in range(12000,13000):
# RXLQI/TXLQI/VBatt/Temp/Light/Motion/Sound/RH/Pressure
minNumReg = 2
format = 'f'
elif addr in range(50100, 50103):
# Check-in interval
minNumReg = 2
format = 'I'
elif addr in range(57002, 57010):
# TX/RX Bridge stuff
minNumReg = 2
format = 'I'
elif addr in range(57050, 57056):
# VUSB/VJack/VST
minNumReg = 2
format = 'f'
elif addr == 59990:
# Rapid mode
minNumReg = 1
format = 'H'
elif addr == 59200:
# NumberOfKnownDevices
minNumReg = 2
format = 'I'
else:
minNumReg = 1
format = 'H'
if numReg:
if (numReg%minNumReg) == 0:
return (numReg, '>' + ( format * (numReg/minNumReg) ))
else:
raise ModbusException("For address %s, the number of registers must be divisible by %s" % (addr, minNumReg))
else:
return ( minNumReg, '>'+format)
def getStartingAddress(packet):
"""Get the address of a modbus request"""
return ((ord(packet[8]) << 8) + ord(packet[9]))
def getRequestType(packet):
"""Get the request type of a modbus request."""
return ord(packet[7])
def getTransactionId(packet):
"""Pulls out the transaction id of the packet"""
if isinstance(packet, list):
return unpack(">H", pack("BB", *packet[:2]) )[0]
else:
return unpack(">H", packet[:2])[0]
def getProtocolId(packet):
"""Pulls out the transaction id of the packet"""
if isinstance(packet, list):
return unpack(">H", pack("BB", *packet[2:4]) )[0]
else:
return unpack(">H", packet[2:4])[0]
def parseIntoPackets(packet):
while True:
if isinstance(packet, list):
firstLength = packet[5]+6
else:
firstLength = ord(packet[5])+6
if len(packet) == firstLength:
yield packet
raise StopIteration
else:
yield packet[:firstLength]
packet = packet[firstLength:]
def parseSpontaneousDataPacket(packet):
if isinstance(packet, list):
localId = packet[6]
packet = pack("B"*len(packet), *packet)
else:
localId = ord(packet[6])
transId = unpack(">H", packet[0:2])[0]
report = unpack(">HBBfHH"+"f"*8, packet[9:53])
results = dict()
results['unitId'] = localId
results['transId'] = transId
results['Rxlqi'] = report[1]
results['Txlqi'] = report[2]
results['Battery'] = report[3]
results['Temperature'] = report[6]
results['Light'] = report[7]
results['Bump'] = report[4]
results['Sound'] = report[11]
return results
| 10,761 | 29.573864 | 237 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/src/mirrorGoHome.py | """
mirrorGoHome.py was written to send the 8711HV digital rotary servo
to the home position and turn off the laser box with the Labjack U3-HV
if need be.
author: Danica Marsden August 13, 2012
"""
import u3, time, sys
#u3.listAll(3)
# Open the LabJack
#d = u3.U3(debug = True)
d = u3.U3()
# Configure
d.configU3()
#print d.configU3()
#print d.configIO()
home = 0.467 # 0 degrees
# Set the timer clock to be 48 MHz/divisor with a divisor of 3
d.configTimerClock(TimerClockBase = 6, TimerClockDivisor = 3)
# Enable the timer, at FIO4
d.configIO(TimerCounterPinOffset = 4, NumberOfTimersEnabled = 1)
# Configure the timer for 16 bit PWM, with a duty cycle of a given %, where duty
# cycle is the amount of time "off"/down. This creates an overall PWM frequency
# of ~244.1Hz (4.1ms period) with (1 - dutyCycle)*4.1 ms "on"/high.
baseValue = 65536
dutyCycle = home
d.getFeedback( u3.Timer0Config(TimerMode = 0, Value = int(baseValue*dutyCycle)) )
d.getFeedback(u3.DAC16(Dac=0, Value = 0x0))
# Close the device
d.close
| 1,075 | 24.619048 | 81 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/src/u6.py | """
Name: u6.py
Desc: Defines the U6 class, which makes working with a U6 much easier. All of
the low-level functions for the U6 are implemented as functions of the U6
class. There are also a handful additional functions which improve upon
the interface provided by the low-level functions.
To learn about the low-level functions, please see Section 5.2 of the U6 User's Guide:
http://labjack.com/support/u6/users-guide/5.2
"""
from LabJackPython import *
import struct, ConfigParser
def openAllU6():
"""
A helpful function which will open all the connected U6s. Returns a
dictionary where the keys are the serialNumber, and the value is the device
object.
"""
returnDict = dict()
for i in range(deviceCount(6)):
d = U6(firstFound = False, devNumber = i+1)
returnDict[str(d.serialNumber)] = d
return returnDict
def dumpPacket(buffer):
"""
Name: dumpPacket(buffer)
Args: byte array
Desc: Returns hex value of all bytes in the buffer
"""
return repr([ hex(x) for x in buffer ])
def getBit(n, bit):
"""
Name: getBit(n, bit)
Args: n, the original integer you want the bit of
bit, the index of the bit you want
Desc: Returns the bit at position "bit" of integer "n"
>>> n = 5
>>> bit = 2
>>> getBit(n, bit)
1
>>> bit = 0
>>> getBit(n, bit)
1
"""
return int(bool((int(n) & (1 << bit)) >> bit))
def toBitList(inbyte):
"""
Name: toBitList(inbyte)
Args: a byte
Desc: Converts a byte into list for access to individual bits
>>> inbyte = 5
>>> toBitList(inbyte)
[1, 0, 1, 0, 0, 0, 0, 0]
"""
return [ getBit(inbyte, b) for b in range(8) ]
def dictAsString(d):
"""Helper function that returns a string representation of a dictionary"""
s = "{"
for key, val in sorted(d.items()):
s += "%s: %s, " % (key, val)
s = s.rstrip(", ") # Nuke the trailing comma
s += "}"
return s
class CalibrationInfo(object):
""" A class to hold the calibration info for a U6 """
def __init__(self):
# A flag to tell difference between nominal and actual values.
self.nominal = True
# Positive Channel calibration
self.ain10vSlope = 3.1580578 * (10 ** -4)
self.ain10vOffset = -10.5869565220
self.ain1vSlope = 3.1580578 * (10 ** -5)
self.ain1vOffset = -1.05869565220
self.ain100mvSlope = 3.1580578 * (10 ** -6)
self.ain100mvOffset = -0.105869565220
self.ain10mvSlope = 3.1580578 * (10 ** -7)
self.ain10mvOffset = -0.0105869565220
self.ainSlope = [self.ain10vSlope, self.ain1vSlope, self.ain100mvSlope, self.ain10mvSlope]
self.ainOffset = [ self.ain10vOffset, self.ain1vOffset, self.ain100mvOffset, self.ain10mvOffset ]
# Negative Channel calibration
self.ain10vNegSlope = -3.15805800 * (10 ** -4)
self.ain10vCenter = 33523.0
self.ain1vNegSlope = -3.15805800 * (10 ** -5)
self.ain1vCenter = 33523.0
self.ain100mvNegSlope = -3.15805800 * (10 ** -6)
self.ain100mvCenter = 33523.0
self.ain10mvNegSlope = -3.15805800 * (10 ** -7)
self.ain10mvCenter = 33523.0
self.ainNegSlope = [ self.ain10vNegSlope, self.ain1vNegSlope, self.ain100mvNegSlope, self.ain10mvNegSlope ]
self.ainCenter = [ self.ain10vCenter, self.ain1vCenter, self.ain100mvCenter, self.ain10mvCenter ]
# Miscellaneous
self.dac0Slope = 13200.0
self.dac0Offset = 0
self.dac1Slope = 13200.0
self.dac1Offset = 0
self.currentOutput0 = 0.0000100000
self.currentOutput1 = 0.0002000000
self.temperatureSlope = -92.379
self.temperatureOffset = 465.129
# Hi-Res ADC stuff
# Positive Channel calibration
self.proAin10vSlope = 3.1580578 * (10 ** -4)
self.proAin10vOffset = -10.5869565220
self.proAin1vSlope = 3.1580578 * (10 ** -5)
self.proAin1vOffset = -1.05869565220
self.proAin100mvSlope = 3.1580578 * (10 ** -6)
self.proAin100mvOffset = -0.105869565220
self.proAin10mvSlope = 3.1580578 * (10 ** -7)
self.proAin10mvOffset = -0.0105869565220
# Negative Channel calibration
self.proAin10vNegSlope = -3.15805800 * (10 ** -4)
self.proAin10vCenter = 33523.0
self.proAin1vNegSlope = -3.15805800 * (10 ** -5)
self.proAin1vCenter = 33523.0
self.proAin100mvNegSlope = -3.15805800 * (10 ** -6)
self.proAin100mvCenter = 33523.0
self.proAin10mvNegSlope = -3.15805800 * (10 ** -7)
self.proAin10mvCenter = 33523.0
def __str__(self):
return str(self.__dict__)
class U6(Device):
"""
U6 Class for all U6 specific low-level commands.
Example:
>>> import u6
>>> d = u6.U6()
>>> print d.configU6()
{'SerialNumber': 320032102, ... , 'FirmwareVersion': '1.26'}
"""
def __init__(self, debug = False, autoOpen = True, **kargs):
"""
Name: U6.__init__(self, debug = False, autoOpen = True, **kargs)
Args: debug, Do you want debug information?
autoOpen, If true, then the constructor will call open for you
**kargs, The arguments to be passed to open.
Desc: Your basic constructor.
"""
Device.__init__(self, None, devType = 6)
self.firmwareVersion = 0
self.bootloaderVersion = 0
self.hardwareVersion = 0
self.productId = 0
self.fioDirection = [None] * 8
self.fioState = [None] * 8
self.eioDirection = [None] * 8
self.eioState = [None] * 8
self.cioDirection = [None] * 8
self.cioState = [None] * 8
self.dac1Enable = 0
self.dac0 = 0
self.dac1 = 0
self.calInfo = CalibrationInfo()
self.productName = "U6"
self.debug = debug
if autoOpen:
self.open(**kargs)
def open(self, localId = None, firstFound = True, serial = None, devNumber = None, handleOnly = False, LJSocket = None):
"""
Name: U6.open(localId = None, firstFound = True, devNumber = None,
handleOnly = False, LJSocket = None)
Args: firstFound, If True, use the first found U6
serial, open a U6 with the given serial number
localId, open a U6 with the given local id.
devNumber, open a U6 with the given devNumber
handleOnly, if True, LabJackPython will only open a handle
LJSocket, set to "<ip>:<port>" to connect to LJSocket
Desc: Opens a U6 for reading and writing.
>>> myU6 = u6.U6(autoOpen = False)
>>> myU6.open()
"""
Device.open(self, 6, firstFound = firstFound, serial = serial, localId = localId, devNumber = devNumber, handleOnly = handleOnly, LJSocket = LJSocket )
def configU6(self, LocalID = None):
"""
Name: U6.configU6(LocalID = None)
Args: LocalID, if set, will write the new value to U6
Desc: Writes the Local ID, and reads some hardware information.
>>> myU6 = u6.U6()
>>> myU6.configU6()
{'BootloaderVersion': '6.15',
'FirmwareVersion': '0.88',
'HardwareVersion': '2.0',
'LocalID': 1,
'ProductID': 6,
'SerialNumber': 360005087,
'VersionInfo': 4}
"""
command = [ 0 ] * 26
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x0A
command[3] = 0x08
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
if LocalID != None:
command[6] = (1 << 3)
command[8] = LocalID
#command[7] = Reserved
#command[9-25] = Reserved
try:
result = self._writeRead(command, 38, [0xF8, 0x10, 0x08])
except LabJackException, e:
if e.errorCode is 4:
print "NOTE: ConfigU6 returned an error of 4. This probably means you are using U6 with a *really old* firmware. Please upgrade your U6's firmware as soon as possible."
result = self._writeRead(command, 38, [0xF8, 0x10, 0x08], checkBytes = False)
else:
raise e
self.firmwareVersion = "%s.%02d" % (result[10], result[9])
self.bootloaderVersion = "%s.%02d" % (result[12], result[11])
self.hardwareVersion = "%s.%02d" % (result[14], result[13])
self.serialNumber = struct.unpack("<I", struct.pack(">BBBB", *result[15:19]))[0]
self.productId = struct.unpack("<H", struct.pack(">BB", *result[19:21]))[0]
self.localId = result[21]
self.versionInfo = result[37]
self.deviceName = 'U6'
if self.versionInfo == 12:
self.deviceName = 'U6-Pro'
return { 'FirmwareVersion' : self.firmwareVersion, 'BootloaderVersion' : self.bootloaderVersion, 'HardwareVersion' : self.hardwareVersion, 'SerialNumber' : self.serialNumber, 'ProductID' : self.productId, 'LocalID' : self.localId, 'VersionInfo' : self.versionInfo, 'DeviceName' : self.deviceName }
def configIO(self, NumberTimersEnabled = None, EnableCounter1 = None, EnableCounter0 = None, TimerCounterPinOffset = None, EnableUART = None):
"""
Name: U6.configIO(NumberTimersEnabled = None, EnableCounter1 = None, EnableCounter0 = None, TimerCounterPinOffset = None)
Args: NumberTimersEnabled, Number of timers to enable
EnableCounter1, Set to True to enable counter 1, F to disable
EnableCounter0, Set to True to enable counter 0, F to disable
TimerCounterPinOffset, where should the timers/counters start
if all args are None, command just reads.
Desc: Writes and reads the current IO configuration.
>>> myU6 = u6.U6()
>>> myU6.configIO()
{'Counter0Enabled': False,
'Counter1Enabled': False,
'NumberTimersEnabled': 0,
'TimerCounterPinOffset': 0}
"""
command = [ 0 ] * 16
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x05
command[3] = 0x0B
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
if NumberTimersEnabled != None:
command[6] = 1
command[7] = NumberTimersEnabled
if EnableCounter0 != None:
command[6] = 1
if EnableCounter0:
command[8] = 1
if EnableCounter1 != None:
command[6] = 1
if EnableCounter1:
command[8] |= (1 << 1)
if TimerCounterPinOffset != None:
command[6] = 1
command[9] = TimerCounterPinOffset
if EnableUART is not None:
command[6] |= 1
command[6] |= (1 << 5)
result = self._writeRead(command, 16, [0xf8, 0x05, 0x0B])
return { 'NumberTimersEnabled' : result[8], 'Counter0Enabled' : bool(result[9] & 1), 'Counter1Enabled' : bool( (result[9] >> 1) & 1), 'TimerCounterPinOffset' : result[10] }
def configTimerClock(self, TimerClockBase = None, TimerClockDivisor = None):
"""
Name: U6.configTimerClock(TimerClockBase = None, TimerClockDivisor = None)
Args: TimerClockBase, which timer base to use
TimerClockDivisor, set the divisor
if all args are None, command just reads.
Also, if you cannot set the divisor without setting the base.
Desc: Writes and read the timer clock configuration.
>>> myU6 = u6.U6()
>>> myU6.configTimerClock()
{'TimerClockDivisor': 256, 'TimerClockBase': 2}
"""
command = [ 0 ] * 10
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x02
command[3] = 0x0A
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
#command[6] = Reserved
#command[7] = Reserved
if TimerClockBase != None:
command[8] = (1 << 7)
command[8] |= TimerClockBase & 7
if TimerClockDivisor != None:
command[9] = TimerClockDivisor
result = self._writeRead(command, 10, [0xF8, 0x2, 0x0A])
divisor = result[9]
if divisor == 0:
divisor = 256
return { 'TimerClockBase' : (result[8] & 7), 'TimerClockDivisor' : divisor }
def _buildBuffer(self, sendBuffer, readLen, commandlist):
for cmd in commandlist:
if isinstance(cmd, FeedbackCommand):
sendBuffer += cmd.cmdBytes
readLen += cmd.readLen
elif isinstance(cmd, list):
sendBuffer, readLen = self._buildBuffer(sendBuffer, readLen, cmd)
return (sendBuffer, readLen)
def _buildFeedbackResults(self, rcvBuffer, commandlist, results, i):
for cmd in commandlist:
if isinstance(cmd, FeedbackCommand):
results.append(cmd.handle(rcvBuffer[i:i+cmd.readLen]))
i += cmd.readLen
elif isinstance(cmd, list):
self._buildFeedbackResults(rcvBuffer, cmd, results, i)
return results
def getFeedback(self, *commandlist):
"""
Name: getFeedback(commandlist)
Args: the FeedbackCommands to run
Desc: Forms the commandlist into a packet, sends it to the U6, and reads the response.
>>> myU6 = U6()
>>> ledCommand = u6.LED(False)
>>> internalTempCommand = u6.AIN(30, 31, True)
>>> myU6.getFeedback(ledCommand, internalTempCommand)
[None, 23200]
OR if you like the list version better:
>>> myU6 = U6()
>>> ledCommand = u6.LED(False)
>>> internalTempCommand = u6.AIN(30, 31, True)
>>> commandList = [ ledCommand, internalTempCommand ]
>>> myU6.getFeedback(commandList)
[None, 23200]
"""
sendBuffer = [0] * 7
sendBuffer[1] = 0xF8
readLen = 9
sendBuffer, readLen = self._buildBuffer(sendBuffer, readLen, commandlist)
if len(sendBuffer) % 2:
sendBuffer += [0]
sendBuffer[2] = len(sendBuffer) / 2 - 3
if readLen % 2:
readLen += 1
if len(sendBuffer) > MAX_USB_PACKET_LENGTH:
raise LabJackException("ERROR: The feedback command you are attempting to send is bigger than 64 bytes ( %s bytes ). Break your commands up into separate calls to getFeedback()." % len(sendBuffer))
if readLen > MAX_USB_PACKET_LENGTH:
raise LabJackException("ERROR: The feedback command you are attempting to send would yield a response that is greater than 64 bytes ( %s bytes ). Break your commands up into separate calls to getFeedback()." % readLen)
rcvBuffer = self._writeRead(sendBuffer, readLen, [], checkBytes = False, stream = False, checksum = True)
# Check the response for errors
try:
self._checkCommandBytes(rcvBuffer, [0xF8])
if rcvBuffer[3] != 0x00:
raise LabJackException("Got incorrect command bytes")
except LowlevelErrorException, e:
if isinstance(commandlist[0], list):
culprit = commandlist[0][ (rcvBuffer[7] -1) ]
else:
culprit = commandlist[ (rcvBuffer[7] -1) ]
raise LowlevelErrorException("\nThis Command\n %s\nreturned an error:\n %s" % ( culprit, lowlevelErrorToString(rcvBuffer[6]) ) )
results = []
i = 9
return self._buildFeedbackResults(rcvBuffer, commandlist, results, i)
def readMem(self, BlockNum, ReadCal=False):
"""
Name: U6.readMem(BlockNum, ReadCal=False)
Args: BlockNum, which block to read
ReadCal, set to True to read the calibration data
Desc: Reads 1 block (32 bytes) from the non-volatile user or
calibration memory. Please read section 5.2.6 of the user's
guide before you do something you may regret.
>>> myU6 = U6()
>>> myU6.readMem(0)
[ < userdata stored in block 0 > ]
NOTE: Do not call this function while streaming.
"""
command = [ 0 ] * 8
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x01
command[3] = 0x2A
if ReadCal:
command[3] = 0x2D
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = 0x00
command[7] = BlockNum
result = self._writeRead(command, 40, [ 0xF8, 0x11, command[3] ])
return result[8:]
def readCal(self, BlockNum):
return self.readMem(BlockNum, ReadCal = True)
def writeMem(self, BlockNum, Data, WriteCal=False):
"""
Name: U6.writeMem(BlockNum, Data, WriteCal=False)
Args: BlockNum, which block to write
Data, a list of bytes to write
WriteCal, set to True to write calibration.
Desc: Writes 1 block (32 bytes) from the non-volatile user or
calibration memory. Please read section 5.2.7 of the user's
guide before you do something you may regret.
>>> myU6 = U6()
>>> myU6.writeMem(0, [ < userdata to be stored in block 0 > ])
NOTE: Do not call this function while streaming.
"""
if not isinstance(Data, list):
raise LabJackException("Data must be a list of bytes")
command = [ 0 ] * 40
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x11
command[3] = 0x28
if WriteCal:
command[3] = 0x2B
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = 0x00
command[7] = BlockNum
command[8:] = Data
self._writeRead(command, 8, [0xF8, 0x11, command[3]])
def writeCal(self, BlockNum, Data):
return self.writeMem(BlockNum, Data, WriteCal = True)
def eraseMem(self, EraseCal=False):
"""
Name: U6.eraseMem(EraseCal=False)
Args: EraseCal, set to True to erase the calibration memory.
Desc: The U6 uses flash memory that must be erased before writing.
Please read section 5.2.8 of the user's guide before you do
something you may regret.
>>> myU6 = U6()
>>> myU6.eraseMem()
NOTE: Do not call this function while streaming.
"""
if eraseCal:
command = [ 0 ] * 8
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x01
command[3] = 0x2C
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = 0x4C
command[7] = 0x6C
else:
command = [ 0 ] * 6
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x00
command[3] = 0x29
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
self._writeRead(command, 8, [0xF8, 0x01, command[3]])
def eraseCal(self):
return self.eraseMem(EraseCal=True)
def streamConfig(self, NumChannels = 1, ResolutionIndex = 0, SamplesPerPacket = 25, SettlingFactor = 0, InternalStreamClockFrequency = 0, DivideClockBy256 = False, ScanInterval = 1, ChannelNumbers = [0], ChannelOptions = [0], SampleFrequency = None):
"""
Name: U6.streamConfig(
NumChannels = 1, ResolutionIndex = 0,
SamplesPerPacket = 25, SettlingFactor = 0,
InternalStreamClockFrequency = 0, DivideClockBy256 = False,
ScanInterval = 1, ChannelNumbers = [0],
ChannelOptions = [0], SampleFrequency = None )
Args: NumChannels, the number of channels to stream
ResolutionIndex, the resolution of the samples
SettlingFactor, the settling factor to be used
ChannelNumbers, a list of channel numbers to stream
ChannelOptions, a list of channel options bytes
Set Either:
SampleFrequency, the frequency in Hz to sample
-- OR --
SamplesPerPacket, how many samples make one packet
InternalStreamClockFrequency, 0 = 4 MHz, 1 = 48 MHz
DivideClockBy256, True = divide the clock by 256
ScanInterval, clock/ScanInterval = frequency.
Desc: Configures streaming on the U6. On a decent machine, you can
expect to stream a range of 0.238 Hz to 15 Hz. Without the
conversion, you can get up to 55 Hz.
"""
if NumChannels != len(ChannelNumbers) or NumChannels != len(ChannelOptions):
raise LabJackException("NumChannels must match length of ChannelNumbers and ChannelOptions")
if len(ChannelNumbers) != len(ChannelOptions):
raise LabJackException("len(ChannelNumbers) doesn't match len(ChannelOptions)")
if SampleFrequency != None:
if SampleFrequency < 1000:
if SampleFrequency < 25:
SamplesPerPacket = SampleFrequency
DivideClockBy256 = True
ScanInterval = 15625/SampleFrequency
else:
DivideClockBy256 = False
ScanInterval = 4000000/SampleFrequency
# Force Scan Interval into correct range
ScanInterval = min( ScanInterval, 65535 )
ScanInterval = int( ScanInterval )
ScanInterval = max( ScanInterval, 1 )
# Same with Samples per packet
SamplesPerPacket = max( SamplesPerPacket, 1)
SamplesPerPacket = int( SamplesPerPacket )
SamplesPerPacket = min ( SamplesPerPacket, 25)
command = [ 0 ] * (14 + NumChannels*2)
#command[0] = Checksum8
command[1] = 0xF8
command[2] = NumChannels+4
command[3] = 0x11
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = NumChannels
command[7] = ResolutionIndex
command[8] = SamplesPerPacket
#command[9] = Reserved
command[10] = SettlingFactor
command[11] = (InternalStreamClockFrequency & 1) << 3
if DivideClockBy256:
command[11] |= 1 << 1
t = struct.pack("<H", ScanInterval)
command[12] = ord(t[0])
command[13] = ord(t[1])
for i in range(NumChannels):
command[14+(i*2)] = ChannelNumbers[i]
command[15+(i*2)] = ChannelOptions[i]
self._writeRead(command, 8, [0xF8, 0x01, 0x11])
# Set up the variables for future use.
self.streamSamplesPerPacket = SamplesPerPacket
self.streamChannelNumbers = ChannelNumbers
self.streamChannelOptions = ChannelOptions
self.streamConfiged = True
if InternalStreamClockFrequency == 1:
freq = float(48000000)
else:
freq = float(4000000)
if DivideClockBy256:
freq /= 256
freq = freq/ScanInterval
self.packetsPerRequest = max(1, int(freq/SamplesPerPacket))
self.packetsPerRequest = min(self.packetsPerRequest, 48)
def processStreamData(self, result, numBytes = None):
"""
Name: U6.processStreamData(result, numPackets = None)
Args: result, the string returned from streamData()
numBytes, the number of bytes per packet
Desc: Breaks stream data into individual channels and applies
calibrations.
>>> reading = d.streamData(convert = False)
>>> print proccessStreamData(reading['result'])
defaultDict(list, {'AIN0' : [3.123, 3.231, 3.232, ...]})
"""
if numBytes is None:
numBytes = 14 + (self.streamSamplesPerPacket * 2)
returnDict = collections.defaultdict(list)
j = self.streamPacketOffset
for packet in self.breakupPackets(result, numBytes):
for sample in self.samplesFromPacket(packet):
if j >= len(self.streamChannelNumbers):
j = 0
if self.streamChannelNumbers[j] in (193, 194):
value = struct.unpack('<BB', sample )
elif self.streamChannelNumbers[j] >= 200:
value = struct.unpack('<H', sample )[0]
else:
if (self.streamChannelOptions[j] >> 7) == 1:
# do signed
value = struct.unpack('<H', sample )[0]
else:
# do unsigned
value = struct.unpack('<H', sample )[0]
gainIndex = (self.streamChannelOptions[j] >> 4) & 0x3
value = self.binaryToCalibratedAnalogVoltage(gainIndex, value, is16Bits=True)
returnDict["AIN%s" % self.streamChannelNumbers[j]].append(value)
j += 1
self.streamPacketOffset = j
return returnDict
def watchdog(self, Write = False, ResetOnTimeout = False, SetDIOStateOnTimeout = False, TimeoutPeriod = 60, DIOState = 0, DIONumber = 0):
"""
Name: U6.watchdog(Write = False, ResetOnTimeout = False, SetDIOStateOnTimeout = False, TimeoutPeriod = 60, DIOState = 0, DIONumber = 0)
Args: Write, Set to True to write new values to the watchdog.
ResetOnTimeout, True means reset the device on timeout
SetDIOStateOnTimeout, True means set the sate of a DIO on timeout
TimeoutPeriod, Time, in seconds, to wait before timing out.
DIOState, 1 = High, 0 = Low
DIONumber, which DIO to set.
Desc: Controls a firmware based watchdog timer.
"""
command = [ 0 ] * 16
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x05
command[3] = 0x09
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
if Write:
command[6] = 1
if ResetOnTimeout:
command[7] = (1 << 5)
if SetDIOStateOnTimeout:
command[7] |= (1 << 4)
t = struct.pack("<H", TimeoutPeriod)
command[8] = ord(t[0])
command[9] = ord(t[1])
command[10] = ((DIOState & 1 ) << 7)
command[10] |= (DIONumber & 0xf)
result = self._writeRead(command, 16, [ 0xF8, 0x05, 0x09])
watchdogStatus = {}
if result[7] == 0:
watchdogStatus['WatchDogEnabled'] = False
watchdogStatus['ResetOnTimeout'] = False
watchdogStatus['SetDIOStateOnTimeout'] = False
else:
watchdogStatus['WatchDogEnabled'] = True
if (( result[7] >> 5 ) & 1):
watchdogStatus['ResetOnTimeout'] = True
else:
watchdogStatus['ResetOnTimeout'] = False
if (( result[7] >> 4 ) & 1):
watchdogStatus['SetDIOStateOnTimeout'] = True
else:
watchdogStatus['SetDIOStateOnTimeout'] = False
watchdogStatus['TimeoutPeriod'] = struct.unpack('<H', struct.pack("BB", *result[8:10]))
if (( result[10] >> 7 ) & 1):
watchdogStatus['DIOState'] = 1
else:
watchdogStatus['DIOState'] = 0
watchdogStatus['DIONumber'] = ( result[10] & 15 )
return watchdogStatus
SPIModes = { 'A' : 0, 'B' : 1, 'C' : 2, 'D' : 3 }
def spi(self, SPIBytes, AutoCS=True, DisableDirConfig = False, SPIMode = 'A', SPIClockFactor = 0, CSPINNum = 0, CLKPinNum = 1, MISOPinNum = 2, MOSIPinNum = 3):
"""
Name: U6.spi(SPIBytes, AutoCS=True, DisableDirConfig = False,
SPIMode = 'A', SPIClockFactor = 0, CSPINNum = 0,
CLKPinNum = 1, MISOPinNum = 2, MOSIPinNum = 3)
Args: SPIBytes, A list of bytes to send.
AutoCS, If True, the CS line is automatically driven low
during the SPI communication and brought back high
when done.
DisableDirConfig, If True, function does not set the direction
of the line.
SPIMode, 'A', 'B', 'C', or 'D'.
SPIClockFactor, Sets the frequency of the SPI clock.
CSPINNum, which pin is CS
CLKPinNum, which pin is CLK
MISOPinNum, which pin is MISO
MOSIPinNum, which pin is MOSI
Desc: Sends and receives serial data using SPI synchronous
communication. See Section 5.2.17 of the user's guide.
"""
if not isinstance(SPIBytes, list):
raise LabJackException("SPIBytes MUST be a list of bytes")
numSPIBytes = len(SPIBytes)
oddPacket = False
if numSPIBytes%2 != 0:
SPIBytes.append(0)
numSPIBytes = numSPIBytes + 1
oddPacket = True
command = [ 0 ] * (13 + numSPIBytes)
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 4 + (numSPIBytes/2)
command[3] = 0x3A
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
if AutoCS:
command[6] |= (1 << 7)
if DisableDirConfig:
command[6] |= (1 << 6)
command[6] |= ( self.SPIModes[SPIMode] & 3 )
command[7] = SPIClockFactor
#command[8] = Reserved
command[9] = CSPINNum
command[10] = CLKPinNum
command[11] = MISOPinNum
command[12] = MOSIPinNum
command[13] = numSPIBytes
if oddPacket:
command[13] = numSPIBytes - 1
command[14:] = SPIBytes
result = self._writeRead(command, 8+numSPIBytes, [ 0xF8, 1+(numSPIBytes/2), 0x3A ])
return { 'NumSPIBytesTransferred' : result[7], 'SPIBytes' : result[8:] }
def asynchConfig(self, Update = True, UARTEnable = True, DesiredBaud = None, BaudFactor = 63036):
"""
Name: U6.asynchConfig(Update = True, UARTEnable = True,
DesiredBaud = None, BaudFactor = 63036)
Args: Update, If True, new values are written.
UARTEnable, If True, UART will be enabled.
DesiredBaud, If set, will apply the formualt to
calculate BaudFactor.
BaudFactor, = 2^16 - 48000000/(2 * Desired Baud). Ignored
if DesiredBaud is set.
Desc: Configures the U6 UART for asynchronous communication. See
section 5.2.18 of the User's Guide.
"""
if UARTEnable:
self.configIO(EnableUART = True)
command = [ 0 ] * 10
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x02
command[3] = 0x14
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
#commmand[6] = 0x00
if Update:
command[7] = (1 << 7)
if UARTEnable:
command[7] |= (1 << 6)
if DesiredBaud != None:
BaudFactor = (2**16) - 48000000/(2 * DesiredBaud)
t = struct.pack("<H", BaudFactor)
command[8] = ord(t[0])
command[9] = ord(t[1])
results = self._writeRead(command, 10, [0xF8, 0x02, 0x14])
if command[8] != results[8] and command[9] != results[9]:
raise LabJackException("BaudFactor didn't stick.")
def asynchTX(self, AsynchBytes):
"""
Name: U6.asynchTX(AsynchBytes)
Args: AsynchBytes, List of bytes to send
Desc: Sends bytes to the U6 UART which will be sent asynchronously
on the transmit line. Section 5.2.19 of the User's Guide.
"""
numBytes = len(AsynchBytes)
oddPacket = False
if numBytes%2 != 0:
oddPacket = True
AsynchBytes.append(0)
numBytes = numBytes + 1
command = [ 0 ] * (8+numBytes)
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 1 + (numBytes/2)
command[3] = 0x15
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
#commmand[6] = 0x00
command[7] = numBytes
if oddPacket:
command[7] = numBytes-1
command[8:] = AsynchBytes
result = self._writeRead(command, 10, [ 0xF8, 0x02, 0x15])
return { 'NumAsynchBytesSent' : result[7], 'NumAsynchBytesInRXBuffer' : result[8] }
def asynchRX(self, Flush = False):
"""
Name: U6.asynchTX(AsynchBytes)
Args: Flush, If True, empties the entire 256-byte RX buffer.
Desc: Sends bytes to the U6 UART which will be sent asynchronously
on the transmit line. Section 5.2.20 of the User's Guide.
"""
command = [ 0, 0xF8, 0x01, 0x16, 0, 0, 0, int(Flush)]
result = self._writeRead(command, 40, [ 0xF8, 0x11, 0x16 ])
return { 'NumAsynchBytesInRXBuffer' : result[7], 'AsynchBytes' : result[8:] }
def i2c(self, Address, I2CBytes, EnableClockStretching = False, NoStopWhenRestarting = False, ResetAtStart = False, SpeedAdjust = 0, SDAPinNum = 0, SCLPinNum = 1, NumI2CBytesToReceive = 0, AddressByte = None):
"""
Name: U6.i2c(Address, I2CBytes, EnableClockStretching = False, NoStopWhenRestarting = False, ResetAtStart = False, SpeedAdjust = 0, SDAPinNum = 0, SCLPinNum = 1, NumI2CBytesToReceive = 0, AddressByte = None)
Args: Address, the address (Not shifted over)
I2CBytes, a list of bytes to send
EnableClockStretching, True enables clock stretching
NoStopWhenRestarting, True means no stop sent when restarting
ResetAtStart, if True, an I2C bus reset will be done
before communicating.
SpeedAdjust, Allows the communication frequency to be reduced.
SDAPinNum, Which pin will be data
SCLPinNum, Which pin is clock
NumI2CBytesToReceive, Number of I2C bytes to expect back.
AddressByte, The address as you would put it in the lowlevel
packet. Overrides Address. Optional.
Desc: Sends and receives serial data using I2C synchronous
communication. Section 5.2.21 of the User's Guide.
"""
numBytes = len(I2CBytes)
oddPacket = False
if numBytes%2 != 0:
oddPacket = True
I2CBytes.append(0)
numBytes = numBytes+1
command = [ 0 ] * (14+numBytes)
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 4 + (numBytes/2)
command[3] = 0x3B
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
if EnableClockStretching:
command[6] |= (1 << 3)
if NoStopWhenRestarting:
command[6] |= (1 << 2)
if ResetAtStart:
command[6] |= (1 << 1)
command[7] = SpeedAdjust
command[8] = SDAPinNum
command[9] = SCLPinNum
if AddressByte != None:
command[10] = AddressByte
else:
command[10] = Address << 1
#command[11] = Reserved
command[12] = numBytes
if oddPacket:
command[12] = numBytes-1
command[13] = NumI2CBytesToReceive
command[14:] = I2CBytes
oddResponse = False
if NumI2CBytesToReceive%2 != 0:
NumI2CBytesToReceive = NumI2CBytesToReceive+1
oddResponse = True
result = self._writeRead(command, (12+NumI2CBytesToReceive), [0xF8, (3+(NumI2CBytesToReceive/2)), 0x3B])
if NumI2CBytesToReceive != 0:
return { 'AckArray' : result[8:12], 'I2CBytes' : result[12:] }
else:
return { 'AckArray' : result[8:12] }
def sht1x(self, DataPinNum = 0, ClockPinNum = 1, SHTOptions = 0xc0):
"""
Name: U6.sht1x(DataPinNum = 0, ClockPinNum = 1, SHTOptions = 0xc0)
Args: DataPinNum, Which pin is the Data line
ClockPinNum, Which line is the Clock line
SHTOptions (and proof people read documentation):
bit 7 = Read Temperature
bit 6 = Read Realtive Humidity
bit 2 = Heater. 1 = on, 0 = off
bit 1 = Reserved at 0
bit 0 = Resolution. 1 = 8 bit RH, 12 bit T; 0 = 12 RH, 14 bit T
Desc: Reads temperature and humidity from a Sensirion SHT1X sensor.
Section 5.2.22 of the User's Guide.
"""
command = [ 0 ] * 10
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x02
command[3] = 0x39
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = DataPinNum
command[7] = ClockPinNum
#command[8] = Reserved
command[9] = SHTOptions
result = self._writeRead(command, 16, [ 0xF8, 0x05, 0x39])
val = (result[11]*256) + result[10]
temp = -39.60 + 0.01*val
val = (result[14]*256) + result[13]
humid = -4 + 0.0405*val + -.0000028*(val*val)
humid = (temp - 25)*(0.01 + 0.00008*val) + humid
return { 'StatusReg' : result[8], 'StatusCRC' : result[9], 'Temperature' : temp, 'TemperatureCRC' : result[12], 'Humidity' : humid, 'HumidityCRC' : result[15] }
# --------------------------- Old U6 code -------------------------------
def _readCalDataBlock(self, n):
"""
Internal routine to read the specified calibration block (0-2)
"""
sendBuffer = [0] * 8
sendBuffer[1] = 0xF8 # command byte
sendBuffer[2] = 0x01 # number of data words
sendBuffer[3] = 0x2D # extended command number
sendBuffer[6] = 0x00
sendBuffer[7] = n # Blocknum = 0
self.write(sendBuffer)
buff = self.read(40)
return buff[8:]
def getCalibrationData(self):
"""
Name: getCalibrationData(self)
Args: None
Desc: Gets the slopes and offsets for AIN and DACs,
as well as other calibration data
>>> myU6 = U6()
>>> myU6.getCalibrationData()
>>> myU6.calInfo
<ainDiffOffset: -2.46886488446,...>
"""
if self.debug is True:
print "Calibration data retrieval"
self.calInfo.nominal = False
#reading block 0 from memory
rcvBuffer = self._readCalDataBlock(0)
# Positive Channel calibration
self.calInfo.ain10vSlope = toDouble(rcvBuffer[:8])
self.calInfo.ain10vOffset = toDouble(rcvBuffer[8:16])
self.calInfo.ain1vSlope = toDouble(rcvBuffer[16:24])
self.calInfo.ain1vOffset = toDouble(rcvBuffer[24:])
#reading block 1 from memory
rcvBuffer = self._readCalDataBlock(1)
self.calInfo.ain100mvSlope = toDouble(rcvBuffer[:8])
self.calInfo.ain100mvOffset = toDouble(rcvBuffer[8:16])
self.calInfo.ain10mvSlope = toDouble(rcvBuffer[16:24])
self.calInfo.ain10mvOffset = toDouble(rcvBuffer[24:])
self.calInfo.ainSlope = [self.calInfo.ain10vSlope, self.calInfo.ain1vSlope, self.calInfo.ain100mvSlope, self.calInfo.ain10mvSlope]
self.calInfo.ainOffset = [ self.calInfo.ain10vOffset, self.calInfo.ain1vOffset, self.calInfo.ain100mvOffset, self.calInfo.ain10mvOffset ]
#reading block 2 from memory
rcvBuffer = self._readCalDataBlock(2)
# Negative Channel calibration
self.calInfo.ain10vNegSlope = toDouble(rcvBuffer[:8])
self.calInfo.ain10vCenter = toDouble(rcvBuffer[8:16])
self.calInfo.ain1vNegSlope = toDouble(rcvBuffer[16:24])
self.calInfo.ain1vCenter = toDouble(rcvBuffer[24:])
#reading block 3 from memory
rcvBuffer = self._readCalDataBlock(3)
self.calInfo.ain100mvNegSlope = toDouble(rcvBuffer[:8])
self.calInfo.ain100mvCenter = toDouble(rcvBuffer[8:16])
self.calInfo.ain10mvNegSlope = toDouble(rcvBuffer[16:24])
self.calInfo.ain10mvCenter = toDouble(rcvBuffer[24:])
self.calInfo.ainNegSlope = [ self.calInfo.ain10vNegSlope, self.calInfo.ain1vNegSlope, self.calInfo.ain100mvNegSlope, self.calInfo.ain10mvNegSlope ]
self.calInfo.ainCenter = [ self.calInfo.ain10vCenter, self.calInfo.ain1vCenter, self.calInfo.ain100mvCenter, self.calInfo.ain10mvCenter ]
#reading block 4 from memory
rcvBuffer = self._readCalDataBlock(4)
# Miscellaneous
self.calInfo.dac0Slope = toDouble(rcvBuffer[:8])
self.calInfo.dac0Offset = toDouble(rcvBuffer[8:16])
self.calInfo.dac1Slope = toDouble(rcvBuffer[16:24])
self.calInfo.dac1Offset = toDouble(rcvBuffer[24:])
#reading block 5 from memory
rcvBuffer = self._readCalDataBlock(5)
self.calInfo.currentOutput0 = toDouble(rcvBuffer[:8])
self.calInfo.currentOutput1 = toDouble(rcvBuffer[8:16])
self.calInfo.temperatureSlope = toDouble(rcvBuffer[16:24])
self.calInfo.temperatureOffset = toDouble(rcvBuffer[24:])
if self.productName == "U6-Pro":
# Hi-Res ADC stuff
#reading block 6 from memory
rcvBuffer = self._readCalDataBlock(6)
# Positive Channel calibration
self.calInfo.proAin10vSlope = toDouble(rcvBuffer[:8])
self.calInfo.proAin10vOffset = toDouble(rcvBuffer[8:16])
self.calInfo.proAin1vSlope = toDouble(rcvBuffer[16:24])
self.calInfo.proAin1vOffset = toDouble(rcvBuffer[24:])
#reading block 7 from memory
rcvBuffer = self._readCalDataBlock(7)
self.calInfo.proAin100mvSlope = toDouble(rcvBuffer[:8])
self.calInfo.proAin100mvOffset = toDouble(rcvBuffer[8:16])
self.calInfo.proAin10mvSlope = toDouble(rcvBuffer[16:24])
self.calInfo.proAin10mvOffset = toDouble(rcvBuffer[24:])
self.calInfo.proAinSlope = [self.calInfo.proAin10vSlope, self.calInfo.proAin1vSlope, self.calInfo.proAin100mvSlope, self.calInfo.proAin10mvSlope]
self.calInfo.proAinOffset = [ self.calInfo.proAin10vOffset, self.calInfo.proAin1vOffset, self.calInfo.proAin100mvOffset, self.calInfo.proAin10mvOffset ]
#reading block 8 from memory
rcvBuffer = self._readCalDataBlock(8)
# Negative Channel calibration
self.calInfo.proAin10vNegSlope = toDouble(rcvBuffer[:8])
self.calInfo.proAin10vCenter = toDouble(rcvBuffer[8:16])
self.calInfo.proAin1vNegSlope = toDouble(rcvBuffer[16:24])
self.calInfo.proAin1vCenter = toDouble(rcvBuffer[24:])
#reading block 9 from memory
rcvBuffer = self._readCalDataBlock(9)
self.calInfo.proAin100mvNegSlope = toDouble(rcvBuffer[:8])
self.calInfo.proAin100mvCenter = toDouble(rcvBuffer[8:16])
self.calInfo.proAin10mvNegSlope = toDouble(rcvBuffer[16:24])
self.calInfo.proAin10mvCenter = toDouble(rcvBuffer[24:])
self.calInfo.proAinNegSlope = [ self.calInfo.proAin10vNegSlope, self.calInfo.proAin1vNegSlope, self.calInfo.proAin100mvNegSlope, self.calInfo.proAin10mvNegSlope ]
self.calInfo.proAinCenter = [ self.calInfo.proAin10vCenter, self.calInfo.proAin1vCenter, self.calInfo.proAin100mvCenter, self.calInfo.proAin10mvCenter ]
def binaryToCalibratedAnalogVoltage(self, gainIndex, bytesVoltage, is16Bits=False):
"""
Name: binaryToCalibratedAnalogVoltage(gainIndex, bytesVoltage, is16Bits = False)
Args: gainIndex, which gain did you use?
bytesVoltage, bytes returned from the U6
is16bits, set to True if bytesVolotage is 16 bits (not 24)
Desc: Converts binary voltage to an analog value.
"""
if not is16Bits:
bits = float(bytesVoltage)/256
else:
bits = float(bytesVoltage)
center = self.calInfo.ainCenter[gainIndex]
negSlope = self.calInfo.ainNegSlope[gainIndex]
posSlope = self.calInfo.ainSlope[gainIndex]
if self.productName == "U6-Pro":
center = self.calInfo.proAinCenter[gainIndex]
negSlope = self.calInfo.proAinNegSlope[gainIndex]
posSlope = self.calInfo.proAinSlope[gainIndex]
if bits < center:
return (center - bits) * negSlope
else:
return (bits - center) * posSlope
def binaryToCalibratedAnalogTemperature(self, bytesTemperature):
voltage = self.binaryToCalibratedAnalogVoltage(0, bytesTemperature)
return self.calInfo.temperatureSlope * float(voltage) + self.calInfo.temperatureOffset
def softReset(self):
"""
Name: softReset
Args: none
Desc: Send a soft reset.
>>> myU6 = U6()
>>> myU6.softReset()
"""
command = [ 0x00, 0x99, 0x01, 0x00 ]
command = setChecksum8(command, 4)
self.write(command, False, False)
results = self.read(4)
if results[3] != 0:
raise LowlevelErrorException(results[3], "The softReset command returned an error:\n %s" % lowlevelErrorToString(results[3]))
def hardReset(self):
"""
Name: hardReset
Args: none
Desc: Send a hard reset.
>>> myU6 = U6()
>>> myU6.hardReset()
"""
command = [ 0x00, 0x99, 0x02, 0x00 ]
command = setChecksum8(command, 4)
self.write(command, False, False)
results = self.read(4)
if results[3] != 0:
raise LowlevelErrorException(results[3], "The softHard command returned an error:\n %s" % lowlevelErrorToString(results[3]))
self.close()
def setLED(self, state):
"""
Name: setLED(self, state)
Args: state: 1 = On, 0 = Off
Desc: Sets the state of the LED. (5.2.5.4 of user's guide)
>>> myU6 = U6()
>>> myU6.setLED(0)
... (LED turns off) ...
"""
self.getFeedback(LED(state))
def getTemperature(self):
"""
Name: getTemperature
Args: none
Desc: Reads the U6's internal temperature sensor in Kelvin.
See Section 2.6.4 of the U6 User's Guide.
>>> myU6.getTemperature()
299.87723471224308
"""
if self.calInfo.nominal:
# Read the actual calibration constants if we haven't already.
self.getCalibrationData()
result = self.getFeedback(AIN24AR(14))
return self.binaryToCalibratedAnalogTemperature(result[0]['AIN'])
def getAIN(self, positiveChannel, resolutionIndex = 0, gainIndex = 0, settlingFactor = 0, differential = False):
"""
Name: getAIN
Args: positiveChannel, resolutionIndex = 0, gainIndex = 0, settlingFactor = 0, differential = False
Desc: Reads an AIN and applies the calibration constants to it.
>>> myU6.getAIN(14)
299.87723471224308
"""
result = self.getFeedback(AIN24AR(positiveChannel, resolutionIndex, gainIndex, settlingFactor, differential))
return self.binaryToCalibratedAnalogVoltage(result[0]['GainIndex'], result[0]['AIN'])
def readDefaultsConfig(self):
"""
Name: U6.readDefaultsConfig( )
Args: None
Desc: Reads the power-up defaults stored in flash.
"""
results = dict()
defaults = self.readDefaults(0)
results['FIODirection'] = defaults[4]
results['FIOState'] = defaults[5]
results['EIODirection'] = defaults[8]
results['EIOState'] = defaults[9]
results['CIODirection'] = defaults[12]
results['CIOState'] = defaults[13]
results['ConfigWriteMask'] = defaults[16]
results['NumOfTimersEnable'] = defaults[17]
results['CounterMask'] = defaults[18]
results['PinOffset'] = defaults[19]
defaults = self.readDefaults(1)
results['ClockSource'] = defaults[0]
results['Divisor'] = defaults[1]
results['TMR0Mode'] = defaults[16]
results['TMR0ValueL'] = defaults[17]
results['TMR0ValueH'] = defaults[18]
results['TMR1Mode'] = defaults[20]
results['TMR1ValueL'] = defaults[21]
results['TMR1ValueH'] = defaults[22]
results['TMR2Mode'] = defaults[24]
results['TMR2ValueL'] = defaults[25]
results['TMR2ValueH'] = defaults[26]
results['TMR3Mode'] = defaults[28]
results['TMR3ValueL'] = defaults[29]
results['TMR3ValueH'] = defaults[30]
defaults = self.readDefaults(2)
results['DAC0'] = struct.unpack( ">H", struct.pack("BB", *defaults[16:18]) )[0]
results['DAC1'] = struct.unpack( ">H", struct.pack("BB", *defaults[20:22]) )[0]
defaults = self.readDefaults(3)
for i in range(14):
results["AIN%sGainRes" % i] = defaults[i]
results["AIN%sOptions" % i] = defaults[i+16]
return results
def exportConfig(self):
"""
Name: U6.exportConfig( )
Args: None
Desc: Takes a configuration and puts it into a ConfigParser object.
"""
# Make a new configuration file
parser = ConfigParser.SafeConfigParser()
# Change optionxform so that options preserve their case.
parser.optionxform = str
# Local Id and name
section = "Identifiers"
parser.add_section(section)
parser.set(section, "Local ID", str(self.localId))
parser.set(section, "Name", str(self.getName()))
parser.set(section, "Device Type", str(self.devType))
# FIO Direction / State
section = "FIOs"
parser.add_section(section)
dirs, states = self.getFeedback( PortDirRead(), PortStateRead() )
for key, value in dirs.items():
parser.set(section, "%s Directions" % key, str(value))
for key, value in states.items():
parser.set(section, "%s States" % key, str(value))
# DACs
section = "DACs"
parser.add_section(section)
dac0 = self.readRegister(5000)
dac0 = max(dac0, 0)
dac0 = min(dac0, 5)
parser.set(section, "DAC0", "%0.2f" % dac0)
dac1 = self.readRegister(5002)
dac1 = max(dac1, 0)
dac1 = min(dac1, 5)
parser.set(section, "DAC1", "%0.2f" % dac1)
# Timer Clock Configuration
section = "Timer Clock Speed Configuration"
parser.add_section(section)
timerclockconfig = self.configTimerClock()
for key, value in timerclockconfig.items():
parser.set(section, key, str(value))
# Timers / Counters
section = "Timers And Counters"
parser.add_section(section)
ioconfig = self.configIO()
for key, value in ioconfig.items():
parser.set(section, key, str(value))
for i in range(ioconfig['NumberTimersEnabled']):
mode, value = self.readRegister(7100 + (2 * i), numReg = 2, format = ">HH")
parser.set(section, "Timer%s Mode" % i, str(mode))
parser.set(section, "Timer%s Value" % i, str(value))
return parser
def loadConfig(self, configParserObj):
"""
Name: U6.loadConfig( configParserObj )
Args: configParserObj, A Config Parser object to load in
Desc: Takes a configuration and updates the U6 to match it.
"""
parser = configParserObj
# Set Identifiers:
section = "Identifiers"
if parser.has_section(section):
if parser.has_option(section, "device type"):
if parser.getint(section, "device type") != self.devType:
raise Exception("Not a U6 Config file.")
if parser.has_option(section, "local id"):
self.configU6( LocalID = parser.getint(section, "local id"))
if parser.has_option(section, "name"):
self.setName( parser.get(section, "name") )
# Set FIOs:
section = "FIOs"
if parser.has_section(section):
fiodirs = 0
eiodirs = 0
ciodirs = 0
fiostates = 0
eiostates = 0
ciostates = 0
if parser.has_option(section, "fios directions"):
fiodirs = parser.getint(section, "fios directions")
if parser.has_option(section, "eios directions"):
eiodirs = parser.getint(section, "eios directions")
if parser.has_option(section, "cios directions"):
ciodirs = parser.getint(section, "cios directions")
if parser.has_option(section, "fios states"):
fiostates = parser.getint(section, "fios states")
if parser.has_option(section, "eios states"):
eiostates = parser.getint(section, "eios states")
if parser.has_option(section, "cios states"):
ciostates = parser.getint(section, "cios states")
self.getFeedback( PortStateWrite([fiostates, eiostates, ciostates]), PortDirWrite([fiodirs, eiodirs, ciodirs]) )
# Set DACs:
section = "DACs"
if parser.has_section(section):
if parser.has_option(section, "dac0"):
self.writeRegister(5000, parser.getfloat(section, "dac0"))
if parser.has_option(section, "dac1"):
self.writeRegister(5002, parser.getfloat(section, "dac1"))
# Set Timer Clock Configuration
section = "Timer Clock Speed Configuration"
if parser.has_section(section):
if parser.has_option(section, "timerclockbase") and parser.has_option(section, "timerclockdivisor"):
self.configTimerClock(TimerClockBase = parser.getint(section, "timerclockbase"), TimerClockDivisor = parser.getint(section, "timerclockdivisor"))
# Set Timers / Counters
section = "Timers And Counters"
if parser.has_section(section):
nte = None
c0e = None
c1e = None
cpo = None
if parser.has_option(section, "NumberTimersEnabled"):
nte = parser.getint(section, "NumberTimersEnabled")
if parser.has_option(section, "TimerCounterPinOffset"):
cpo = parser.getint(section, "TimerCounterPinOffset")
if parser.has_option(section, "Counter0Enabled"):
c0e = parser.getboolean(section, "Counter0Enabled")
if parser.has_option(section, "Counter1Enabled"):
c1e = parser.getboolean(section, "Counter1Enabled")
self.configIO(NumberTimersEnabled = nte, EnableCounter1 = c1e, EnableCounter0 = c0e, TimerCounterPinOffset = cpo)
mode = None
value = None
for i in range(4):
if parser.has_option(section, "timer%i mode" % i):
mode = parser.getint(section, "timer%i mode" % i)
if parser.has_option(section, "timer%i value" % i):
value = parser.getint(section, "timer%i value" % i)
self.getFeedback( TimerConfig(i, mode, value) )
class FeedbackCommand(object):
'''
The base FeedbackCommand class
Used to make Feedback easy. Make a list of these
and call getFeedback.
'''
readLen = 0
def handle(self, input):
return None
validChannels = range(144)
class AIN(FeedbackCommand):
'''
Analog Input Feedback command
AIN(PositiveChannel)
PositiveChannel : the positive channel to use
NOTE: This function kept for compatibility. Please use
the new AIN24 and AIN24AR.
returns 16-bit unsigned int sample
>>> d.getFeedback( u6.AIN( PositiveChannel ) )
[ 19238 ]
'''
def __init__(self, PositiveChannel):
if PositiveChannel not in validChannels:
raise LabJackException("Invalid Positive Channel specified")
self.positiveChannel = PositiveChannel
self.cmdBytes = [ 0x01, PositiveChannel, 0 ]
readLen = 2
def __repr__(self):
return "<u6.AIN( PositiveChannel = %s )>" % self.positiveChannel
def handle(self, input):
result = (input[1] << 8) + input[0]
return result
class AIN24(FeedbackCommand):
'''
Analog Input 24-bit Feedback command
ainCommand = AIN24(PositiveChannel, ResolutionIndex = 0, GainIndex = 0, SettlingFactor = 0, Differential = False)
See section 5.2.5.2 of the user's guide.
NOTE: If you use a gain index of 15 (autorange), you should be using
the AIN24AR command instead.
positiveChannel : The positive channel to use
resolutionIndex : 0=default, 1-8 for high-speed ADC,
9-12 for high-res ADC on U6-Pro.
gainIndex : 0=x1, 1=x10, 2=x100, 3=x1000, 15=autorange
settlingFactor : 0=5us, 1=10us, 2=100us, 3=1ms, 4=10ms
differential : If this bit is set, a differential reading is done where
the negative channel is positiveChannel+1
returns 24-bit unsigned int sample
>>> d.getFeedback( u6.AIN24(PositiveChannel, ResolutionIndex = 0,
GainIndex = 0, SettlingFactor = 0,
Differential = False ) )
[ 193847 ]
'''
def __init__(self, PositiveChannel, ResolutionIndex = 0, GainIndex = 0, SettlingFactor = 0, Differential = False):
if PositiveChannel not in validChannels:
raise LabJackException("Invalid Positive Channel specified")
self.positiveChannel = PositiveChannel
self.resolutionIndex = ResolutionIndex
self.gainIndex = GainIndex
self.settlingFactor = SettlingFactor
self.differential = Differential
byte2 = ( ResolutionIndex & 0xf )
byte2 = ( ( GainIndex & 0xf ) << 4 ) + byte2
byte3 = (int(Differential) << 7) + SettlingFactor
self.cmdBytes = [ 0x02, PositiveChannel, byte2, byte3 ]
def __repr__(self):
return "<u6.AIN24( PositiveChannel = %s, ResolutionIndex = %s, GainIndex = %s, SettlingFactor = %s, Differential = %s )>" % (self.positiveChannel, self.resolutionIndex, self.gainIndex, self.settlingFactor, self.differential)
readLen = 3
def handle(self, input):
#Put it all into an integer.
result = (input[2] << 16 ) + (input[1] << 8 ) + input[0]
return result
class AIN24AR(FeedbackCommand):
'''
Autorange Analog Input 24-bit Feedback command
ainARCommand = AIN24AR(0, ResolutionIndex = 0, GainIndex = 0, SettlingFactor = 0, Differential = False)
See section 5.2.5.3 of the user's guide
PositiveChannel : The positive channel to use
ResolutionIndex : 0=default, 1-8 for high-speed ADC,
9-13 for high-res ADC on U6-Pro.
GainIndex : 0=x1, 1=x10, 2=x100, 3=x1000, 15=autorange
SettlingFactor : 0=5us, 1=10us, 2=100us, 3=1ms, 4=10ms
Differential : If this bit is set, a differential reading is done where
the negative channel is positiveChannel+1
returns a dictionary:
{
'AIN' : < 24-bit binary reading >,
'ResolutionIndex' : < actual resolution setting used for the reading >,
'GainIndex' : < actual gain used for the reading >,
'Status' : < reserved for future use >
}
>>> d.getFeedback( u6.AIN24AR( PositiveChannel, ResolutionIndex = 0,
GainIndex = 0, SettlingFactor = 0,
Differential = False ) )
{ 'AIN' : 193847, 'ResolutionIndex' : 0, 'GainIndex' : 0, 'Status' : 0 }
'''
def __init__(self, PositiveChannel, ResolutionIndex = 0, GainIndex = 0, SettlingFactor = 0, Differential = False):
if PositiveChannel not in validChannels:
raise LabJackException("Invalid Positive Channel specified")
self.positiveChannel = PositiveChannel
self.resolutionIndex = ResolutionIndex
self.gainIndex = GainIndex
self.settlingFactor = SettlingFactor
self.differential = Differential
byte2 = ( ResolutionIndex & 0xf )
byte2 = ( ( GainIndex & 0xf ) << 4 ) + byte2
byte3 = (int(Differential) << 7) + SettlingFactor
self.cmdBytes = [ 0x03, PositiveChannel, byte2, byte3 ]
def __repr__(self):
return "<u6.AIN24AR( PositiveChannel = %s, ResolutionIndex = %s, GainIndex = %s, SettlingFactor = %s, Differential = %s )>" % (self.positiveChannel, self.resolutionIndex, self.gainIndex, self.settlingFactor, self.differential)
readLen = 5
def handle(self, input):
#Put it all into an integer.
result = (input[2] << 16 ) + (input[1] << 8 ) + input[0]
resolutionIndex = input[3] & 0xf
gainIndex = ( input[3] >> 4 ) & 0xf
status = input[4]
return { 'AIN' : result, 'ResolutionIndex' : resolutionIndex, 'GainIndex' : gainIndex, 'Status' : status }
class WaitShort(FeedbackCommand):
'''
WaitShort Feedback command
specify the number of 128us time increments to wait
>>> d.getFeedback( u6.WaitShort( Time ) )
[ None ]
'''
def __init__(self, Time):
self.time = Time % 256
self.cmdBytes = [ 5, Time % 256 ]
def __repr__(self):
return "<u6.WaitShort( Time = %s )>" % self.time
class WaitLong(FeedbackCommand):
'''
WaitLong Feedback command
specify the number of 32ms time increments to wait
>>> d.getFeedback( u6.WaitLog( Time ) )
[ None ]
'''
def __init__(self, Time):
self.time = Time
self.cmdBytes = [ 6, Time % 256 ]
def __repr__(self):
return "<u6.WaitLog( Time = %s )>" % self.time
class LED(FeedbackCommand):
'''
LED Toggle
specify whether the LED should be on or off by truth value
1 or True = On, 0 or False = Off
>>> d.getFeedback( u6.LED( State ) )
[ None ]
'''
def __init__(self, State):
self.state = State
self.cmdBytes = [ 9, int(bool(State)) ]
def __repr__(self):
return "<u6.LED( State = %s )>" % self.state
class BitStateRead(FeedbackCommand):
'''
BitStateRead Feedback command
read the state of a single bit of digital I/O. Only digital
lines return valid readings.
IONumber: 0-7=FIO, 8-15=EIO, 16-19=CIO
return 0 or 1
>>> d.getFeedback( u6.BitStateRead( IONumber ) )
[ 1 ]
'''
def __init__(self, IONumber):
self.ioNumber = IONumber
self.cmdBytes = [ 10, IONumber % 20 ]
def __repr__(self):
return "<u6.BitStateRead( IONumber = %s )>" % self.ioNumber
readLen = 1
def handle(self, input):
return int(bool(input[0]))
class BitStateWrite(FeedbackCommand):
'''
BitStateWrite Feedback command
write a single bit of digital I/O. The direction of the
specified line is forced to output.
IONumber: 0-7=FIO, 8-15=EIO, 16-19=CIO
State: 0 or 1
>>> d.getFeedback( u6.BitStateWrite( IONumber, State ) )
[ None ]
'''
def __init__(self, IONumber, State):
self.ioNumber = IONumber
self.state = State
self.cmdBytes = [ 11, (IONumber % 20) + (int(bool(State)) << 7) ]
def __repr__(self):
return "<u6.BitStateWrite( IONumber = %s, State = %s )>" % self.ioNumber
class BitDirRead(FeedbackCommand):
'''
Read the digital direction of one I/O
IONumber: 0-7=FIO, 8-15=EIO, 16-19=CIO
returns 1 = Output, 0 = Input
>>> d.getFeedback( u6.BitDirRead( IONumber ) )
[ 1 ]
'''
def __init__(self, IONumber):
self.ioNumber = IONumber
self.cmdBytes = [ 12, IONumber % 20 ]
def __repr__(self):
return "<u6.BitDirRead( IONumber = %s )>" % self.ioNumber
readLen = 1
def handle(self, input):
return int(bool(input[0]))
class BitDirWrite(FeedbackCommand):
'''
BitDirWrite Feedback command
Set the digital direction of one I/O
IONumber: 0-7=FIO, 8-15=EIO, 16-19=CIO
Direction: 1 = Output, 0 = Input
>>> d.getFeedback( u6.BitDirWrite( IONumber, Direction ) )
[ None ]
'''
def __init__(self, IONumber, Direction):
self.ioNumber = IONumber
self.direction = Direction
self.cmdBytes = [ 13, (IONumber % 20) + (int(bool(Direction)) << 7) ]
def __repr__(self):
return "<u6.BitDirWrite( IONumber = %s, Direction = %s )>" % (self.ioNumber, self.direction)
class PortStateRead(FeedbackCommand):
"""
PortStateRead Feedback command
Reads the state of all digital I/O.
>>> d.getFeedback( u6.PortStateRead() )
[ { 'FIO' : 10, 'EIO' : 0, 'CIO' : 0 } ]
"""
def __init__(self):
self.cmdBytes = [ 26 ]
def __repr__(self):
return "<u6.PortStateRead()>"
readLen = 3
def handle(self, input):
return {'FIO' : input[0], 'EIO' : input[1], 'CIO' : input[2] }
class PortStateWrite(FeedbackCommand):
"""
PortStateWrite Feedback command
State: A list of 3 bytes representing FIO, EIO, CIO
WriteMask: A list of 3 bytes, representing which to update.
The Default is all ones.
>>> d.getFeedback( u6.PortStateWrite( State,
WriteMask = [ 0xff, 0xff, 0xff] ) )
[ None ]
"""
def __init__(self, State, WriteMask = [ 0xff, 0xff, 0xff]):
self.state = State
self.writeMask = WriteMask
self.cmdBytes = [ 27 ] + WriteMask + State
def __repr__(self):
return "<u6.PortStateWrite( State = %s, WriteMask = %s )>" % (self.state, self.writeMask)
class PortDirRead(FeedbackCommand):
"""
PortDirRead Feedback command
Reads the direction of all digital I/O.
>>> d.getFeedback( u6.PortDirRead() )
[ { 'FIO' : 10, 'EIO' : 0, 'CIO' : 0 } ]
"""
def __init__(self):
self.cmdBytes = [ 28 ]
def __repr__(self):
return "<u6.PortDirRead()>"
readLen = 3
def handle(self, input):
return {'FIO' : input[0], 'EIO' : input[1], 'CIO' : input[2] }
class PortDirWrite(FeedbackCommand):
"""
PortDirWrite Feedback command
Direction: A list of 3 bytes representing FIO, EIO, CIO
WriteMask: A list of 3 bytes, representing which to update. Default is all ones.
>>> d.getFeedback( u6.PortDirWrite( Direction,
WriteMask = [ 0xff, 0xff, 0xff] ) )
[ None ]
"""
def __init__(self, Direction, WriteMask = [ 0xff, 0xff, 0xff]):
self.direction = Direction
self.writeMask = WriteMask
self.cmdBytes = [ 29 ] + WriteMask + Direction
def __repr__(self):
return "<u6.PortDirWrite( Direction = %s, WriteMask = %s )>" % (self.direction, self.writeMask)
class DAC8(FeedbackCommand):
'''
8-bit DAC Feedback command
Controls a single analog output
Dac: 0 or 1
Value: 0-255
>>> d.getFeedback( u6.DAC8( Dac, Value ) )
[ None ]
'''
def __init__(self, Dac, Value):
self.dac = Dac
self.value = Value % 256
self.cmdBytes = [ 34 + (Dac % 2), Value % 256 ]
def __repr__(self):
return "<u6.DAC8( Dac = %s, Value = %s )>" % (self.dac, self.value)
class DAC0_8(DAC8):
"""
8-bit DAC Feedback command for DAC0
Controls DAC0 in 8-bit mode.
Value: 0-255
>>> d.getFeedback( u6.DAC0_8( Value ) )
[ None ]
"""
def __init__(self, Value):
DAC8.__init__(self, 0, Value)
def __repr__(self):
return "<u6.DAC0_8( Value = %s )>" % self.value
class DAC1_8(DAC8):
"""
8-bit DAC Feedback command for DAC1
Controls DAC1 in 8-bit mode.
Value: 0-255
>>> d.getFeedback( u6.DAC1_8( Value ) )
[ None ]
"""
def __init__(self, Value):
DAC8.__init__(self, 1, Value)
def __repr__(self):
return "<u6.DAC1_8( Value = %s )>" % self.value
class DAC16(FeedbackCommand):
'''
16-bit DAC Feedback command
Controls a single analog output
Dac: 0 or 1
Value: 0-65535
>>> d.getFeedback( u6.DAC16( Dac, Value ) )
[ None ]
'''
def __init__(self, Dac, Value):
self.dac = Dac
self.value = Value
self.cmdBytes = [ 38 + (Dac % 2), Value % 256, Value >> 8 ]
def __repr__(self):
return "<u6.DAC8( Dac = %s, Value = %s )>" % (self.dac, self.value)
class DAC0_16(DAC16):
"""
16-bit DAC Feedback command for DAC0
Controls DAC0 in 16-bit mode.
Value: 0-65535
>>> d.getFeedback( u6.DAC0_16( Value ) )
[ None ]
"""
def __init__(self, Value):
DAC16.__init__(self, 0, Value)
def __repr__(self):
return "<u6.DAC0_16( Value = %s )>" % self.value
class DAC1_16(DAC16):
"""
16-bit DAC Feedback command for DAC1
Controls DAC1 in 16-bit mode.
Value: 0-65535
>>> d.getFeedback( u6.DAC1_16( Value ) )
[ None ]
"""
def __init__(self, Value):
DAC16.__init__(self, 1, Value)
def __repr__(self):
return "<u6.DAC1_16( Value = %s )>" % self.value
class Timer(FeedbackCommand):
"""
For reading the value of the Timer. It provides the ability to update/reset
a given timer, and read the timer value.
( Section 5.2.5.17 of the User's Guide)
timer: Either 0 or 1 for counter0 or counter1
UpdateReset: Set True if you want to update the value
Value: Only updated if the UpdateReset bit is 1. The meaning of this
parameter varies with the timer mode.
Mode: Set to the timer mode to handle any special processing. See classes
QuadratureInputTimer and TimerStopInput1.
Returns an unsigned integer of the timer value, unless Mode has been
specified and there are special return values. See Section 2.9.1 for
expected return values.
>>> d.getFeedback( u6.Timer( timer, UpdateReset = False, Value = 0 \
... , Mode = None ) )
[ 12314 ]
"""
def __init__(self, timer, UpdateReset = False, Value=0, Mode = None):
if timer != 0 and timer != 1:
raise LabJackException("Timer should be either 0 or 1.")
if UpdateReset and Value == None:
raise LabJackException("UpdateReset set but no value.")
self.timer = timer
self.updateReset = UpdateReset
self.value = Value
self.mode = Mode
self.cmdBytes = [ (42 + (2*timer)), UpdateReset, Value % 256, Value >> 8 ]
readLen = 4
def __repr__(self):
return "<u6.Timer( timer = %s, UpdateReset = %s, Value = %s, Mode = %s )>" % (self.timer, self.updateReset, self.value, self.mode)
def handle(self, input):
inStr = struct.pack('B' * len(input), *input)
if self.mode == 8:
return struct.unpack('<i', inStr )[0]
elif self.mode == 9:
maxCount, current = struct.unpack('<HH', inStr )
return current, maxCount
else:
return struct.unpack('<I', inStr )[0]
class Timer0(Timer):
"""
For reading the value of the Timer0. It provides the ability to
update/reset Timer0, and read the timer value.
( Section 5.2.5.17 of the User's Guide)
UpdateReset: Set True if you want to update the value
Value: Only updated if the UpdateReset bit is 1. The meaning of this
parameter varies with the timer mode.
Mode: Set to the timer mode to handle any special processing. See classes
QuadratureInputTimer and TimerStopInput1.
>>> d.getFeedback( u6.Timer0( UpdateReset = False, Value = 0, \
... Mode = None ) )
[ 12314 ]
"""
def __init__(self, UpdateReset = False, Value = 0, Mode = None):
Timer.__init__(self, 0, UpdateReset, Value, Mode)
def __repr__(self):
return "<u6.Timer0( UpdateReset = %s, Value = %s, Mode = %s )>" % (self.updateReset, self.value, self.mode)
class Timer1(Timer):
"""
For reading the value of the Timer1. It provides the ability to
update/reset Timer1, and read the timer value.
( Section 5.2.5.17 of the User's Guide)
UpdateReset: Set True if you want to update the value
Value: Only updated if the UpdateReset bit is 1. The meaning of this
parameter varies with the timer mode.
Mode: Set to the timer mode to handle any special processing. See classes
QuadratureInputTimer and TimerStopInput1.
>>> d.getFeedback( u6.Timer1( UpdateReset = False, Value = 0, \
... Mode = None ) )
[ 12314 ]
"""
def __init__(self, UpdateReset = False, Value = 0, Mode = None):
Timer.__init__(self, 1, UpdateReset, Value, Mode)
def __repr__(self):
return "<u6.Timer1( UpdateReset = %s, Value = %s, Mode = %s )>" % (self.updateReset, self.value, self.mode)
class QuadratureInputTimer(Timer):
"""
For reading Quadrature input timers. They are special because their values
are signed.
( Section 2.9.1.8 of the User's Guide)
Args:
UpdateReset: Set True if you want to reset the counter.
Value: Set to 0, and UpdateReset to True to reset the counter.
Returns a signed integer.
>>> # Setup the two timers to be quadrature
>>> d.getFeedback( u6.Timer0Config( 8 ), u6.Timer1Config( 8 ) )
[None, None]
>>> # Read the value
>>> d.getFeedback( u6.QuadratureInputTimer() )
[-21]
"""
def __init__(self, UpdateReset = False, Value = 0):
Timer.__init__(self, 0, UpdateReset, Value, Mode = 8)
def __repr__(self):
return "<u6.QuadratureInputTimer( UpdateReset = %s, Value = %s )>" % (self.updateReset, self.value)
class TimerStopInput1(Timer1):
"""
For reading a stop input timer. They are special because the value returns
the current edge count and the stop value.
( Section 2.9.1.9 of the User's Guide)
Args:
UpdateReset: Set True if you want to update the value.
Value: The stop value. Only updated if the UpdateReset bit is 1.
Returns a tuple where the first value is current edge count, and the second
value is the stop value.
>>> # Setup the timer to be Stop Input
>>> d.getFeedback( u6.Timer0Config( 9, Value = 30 ) )
[None]
>>> # Read the timer
>>> d.getFeedback( u6.TimerStopInput1() )
[(0, 30)]
"""
def __init__(self, UpdateReset = False, Value = 0):
Timer.__init__(self, 1, UpdateReset, Value, Mode = 9)
def __repr__(self):
return "<u6.TimerStopInput1( UpdateReset = %s, Value = %s )>" % (self.updateReset, self.value)
class TimerConfig(FeedbackCommand):
"""
This IOType configures a particular timer.
timer = # of the timer to configure
TimerMode = See Section 2.9 for more information about the available modes.
Value = The meaning of this parameter varies with the timer mode.
>>> d.getFeedback( u6.TimerConfig( timer, TimerMode, Value = 0 ) )
[ None ]
"""
def __init__(self, timer, TimerMode, Value=0):
'''Creates command bytes for configureing a Timer'''
#Conditions come from pages 33-34 of user's guide
if timer not in range(4):
raise LabJackException("Timer should be either 0-3.")
if TimerMode > 14 or TimerMode < 0:
raise LabJackException("Invalid Timer Mode.")
self.timer = timer
self.timerMode = TimerMode
self.value = Value
self.cmdBytes = [43 + (timer * 2), TimerMode, Value % 256, Value >> 8]
def __repr__(self):
return "<u6.TimerConfig( timer = %s, TimerMode = %s, Value = %s )>" % (self.timer, self.timerMode, self.value)
class Timer0Config(TimerConfig):
"""
This IOType configures Timer0.
TimerMode = See Section 2.9 for more information about the available modes.
Value = The meaning of this parameter varies with the timer mode.
>>> d.getFeedback( u6.Timer0Config( TimerMode, Value = 0 ) )
[ None ]
"""
def __init__(self, TimerMode, Value = 0):
TimerConfig.__init__(self, 0, TimerMode, Value)
def __repr__(self):
return "<u6.Timer0Config( TimerMode = %s, Value = %s )>" % (self.timerMode, self.value)
class Timer1Config(TimerConfig):
"""
This IOType configures Timer1.
TimerMode = See Section 2.9 for more information about the available modes.
Value = The meaning of this parameter varies with the timer mode.
>>> d.getFeedback( u6.Timer1Config( TimerMode, Value = 0 ) )
[ None ]
"""
def __init__(self, TimerMode, Value = 0):
TimerConfig.__init__(self, 1, TimerMode, Value)
def __repr__(self):
return "<u6.Timer1Config( TimerMode = %s, Value = %s )>" % (self.timerMode, self.value)
class Counter(FeedbackCommand):
'''
Counter Feedback command
Reads a hardware counter, optionally resetting it
counter: 0 or 1
Reset: True ( or 1 ) = Reset, False ( or 0 ) = Don't Reset
Returns the current count from the counter if enabled. If reset,
this is the value before the reset.
>>> d.getFeedback( u6.Counter( counter, Reset = False ) )
[ 2183 ]
'''
def __init__(self, counter, Reset):
self.counter = counter
self.reset = Reset
self.cmdBytes = [ 54 + (counter % 2), int(bool(Reset))]
def __repr__(self):
return "<u6.Counter( counter = %s, Reset = %s )>" % (self.counter, self.reset)
readLen = 4
def handle(self, input):
inStr = ''.join([chr(x) for x in input])
return struct.unpack('<I', inStr )[0]
class Counter0(Counter):
'''
Counter0 Feedback command
Reads hardware counter0, optionally resetting it
Reset: True ( or 1 ) = Reset, False ( or 0 ) = Don't Reset
Returns the current count from the counter if enabled. If reset,
this is the value before the reset.
>>> d.getFeedback( u6.Counter0( Reset = False ) )
[ 2183 ]
'''
def __init__(self, Reset = False):
Counter.__init__(self, 0, Reset)
def __repr__(self):
return "<u6.Counter0( Reset = %s )>" % self.reset
class Counter1(Counter):
'''
Counter1 Feedback command
Reads hardware counter1, optionally resetting it
Reset: True ( or 1 ) = Reset, False ( or 0 ) = Don't Reset
Returns the current count from the counter if enabled. If reset,
this is the value before the reset.
>>> d.getFeedback( u6.Counter1( Reset = False ) )
[ 2183 ]
'''
def __init__(self, Reset = False):
Counter.__init__(self, 1, Reset)
def __repr__(self):
return "<u6.Counter1( Reset = %s )>" % self.reset
class DSP(FeedbackCommand):
'''
DSP Feedback command
Acquires 1000 samples from the specified AIN at 50us intervals and performs
the specified analysis on the acquired data.
AcquireNewData: True, acquire new data; False, operate on existing data
DSPAnalysis: 1, True RMS; 2, DC Offset; 3, Peak To Peak; 4, Period (ms)
PLine: Positive Channel
Gain: The gain you would like to use
Resolution: The resolution index to use
SettlingFactor: The SettlingFactor to use
Differential: True, do differential readings; False, single-ended readings
See section 5.2.5.20 of the U3 User's Guide
(http://labjack.com/support/u6/users-guide/5.2.5.20)
>>> d.getFeedback( u6.DSP( PLine, Resolution = 0, Gain = 0,
SettlingFactor = 0, Differential = False,
DSPAnalysis = 1, AcquireNewData = True) )
[ 2183 ]
'''
def __init__(self, PLine, Resolution = 0, Gain = 0, SettlingFactor = 0, Differential = False, DSPAnalysis = 1, AcquireNewData = True):
self.pline = PLine
self.resolution = Resolution
self.gain = Gain
self.settlingFactor = SettlingFactor
self.differential = Differential
self.dspAnalysis = DSPAnalysis
self.acquireNewData = AcquireNewData
byte1 = DSPAnalysis + ( int(AcquireNewData) << 7 )
byte4 = ( Gain << 4 ) + Resolution
byte5 = ( int(Differential) << 7 ) + SettlingFactor
self.cmdBytes = [ 62, byte1, PLine, 0, byte4, byte5, 0, 0 ]
def __repr__(self):
return "<u6.DSP( PLine = %s, Resolution = %s, Gain = %s, SettlingFactor = %s, Differential = %s, DSPAnalysis = %s, AcquireNewData = %s )>" % (self.pline, self.resolution, self.gain, self.settlingFactor, self.differential, self.dspAnalysis, self.acquireNewData)
readLen = 4
def handle(self, input):
inStr = ''.join([chr(x) for x in input])
return struct.unpack('<I', inStr )[0]
| 83,591 | 35.344348 | 305 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/src/u3_examples.py | """
u3_examples.py was written to test comands for the Labjack U3-HV.
author: Danica Marsden August 6, 2012
"""
import u3, time
# Open the LabJack
d = u3.U3(debug = True)
# Configure
d.configU3()
print d.configU3()
print d.configIO()
#
# Control the status LED:
#
d.getFeedback(u3.LED(0))
d.getFeedback(u3.LED(1))
#
# Example with DAC0 hotwired to AIN0:
#
DAC0_REGISTER = 5000
# Set DAC0 to 1.5 V
d.writeRegister(DAC0_REGISTER, 1.5)
# Read value
AIN0_REGISTER = 0
d.readRegister(AIN0_REGISTER)
# Set DAC0 to 0.5 V
d.writeRegister(DAC0_REGISTER, .5)
d.readRegister(AIN0_REGISTER)
#
# Set DAC output levels another way:
#
d.getFeedback(u3.DAC16(Dac=0, Value = 0x7fff)) # ~2.5V = 1/2 of 0xffff
d.getFeedback(u3.DAC16(Dac=1, Value = 0xffff)) # ~4.95V
d.getFeedback(u3.DAC16(Dac=0, Value = 0x0))
d.getFeedback(u3.DAC16(Dac=1, Value = 0x0))
#
# Blink the U3's status LED until the AIN0 input exceeds a limit value.
# Any voltage source with a range between 0 and 5VDC will work as AIN0
# input. Touching a jumper wire between AIN0 and any VS terminal will
# also work.
#
LEDoff = u3.LED(0)
LEDon = u3.LED(1)
AINcmd = u3.AIN(0, 31, False, False)
toggle = 0
while True:
# blink the LED while looping
if toggle == 0:
d.getFeedback(LEDon)
toggle = 1
else:
d.getFeedback(LEDoff)
toggle = 0
# getFeedback returns a list with a single element
inval = d.getFeedback(AINcmd)[0]
print inval
if inval > 40000:
break
time.sleep(1)
d.getFeedback(LEDon)
print "Done."
#
# FIO4 ( a digital output) rapidly toggled on and off:
# (It’s fast, you’ll need an oscilloscope if you want to see this activity)
#
biton = u3.BitStateWrite(4,1)
bitoff = u3.BitStateWrite(4,0)
d.getFeedback(bitoff, biton, bitoff, biton, bitoff)
# Close the device
d.close
##############################
#a list of the FeedbackCommand derived class commands in the u3.py module:
# AIN(PositiveChannel, NegativeChannel=31, LongSettling=False, QuickSample=False)
# WaitShort(Time)
# WaitLong(Time) (python's sleep() method is better!)
# LED(State)
# BitStateRead(IONumber)
# BitStateWrite(IONumber, State)
# BitDirRead(IONumber)
# BitDirWrite(IONumber, Direction)
# PortStateRead()
# PortStateWrite(State, WriteMask=[0xff, 0xff, 0xff])
# PortDirRead()
# PortDirWrite(Direction, WriteMask=[0xff, 0xff, 0xff])
# DAC8(Dac, Value)
# DAC0_8(Value)
# DAC1_8(Value)
# DAC16(Dac, Value)
# DAC0_16(Value)
# DAC1_16(Value)
# Timer(timer, UpdateReset=False, Value=0, Mode=None)
# Timer0(UpdateReset=False, Value=0, Mode=None)
# Timer1(UpdateReset=False, Value=0, Mode=None)
# QuadratureInputTimer(UpdateReset=False, Value=0)
# TimerStopInput1(UpdateReset=False, Value=0)
# TimerConfig(timer, TimerMode, Value=0)
# Timer0Config(TimerMode, Value=0)
# Timer1Config(TimerMode, Value=0)
# Counter(counter, Reset=False)
# Counter0(Reset=False)
# Counter1(Reset=False)
# class U3 functions:
# asynchConfig()
# asynchRX()
# asynchTX()
# binaryToCalibratedAnalogVoltage()
# configAnalog()
# configDigital()
# configIO()
# configTimerClock()
# configU3()
# eraseCal()
# eraseMem()
# exportConfig()
# getAIN()
# getCalibrationData()
# getFIOState()
# getFeedback()
# i2c()
# loadConfig()
# open()
# processStreamData()
# readCal()
# readDefaultsConfig()
# readMem()
# reset()
# setFIOState()
# sht1x()
# spi()
# streamConfig()
# toggleLED()
# voltageToDACBits()
# watchdog()
# writeCal()
# writeMem()
# class Device:
# breakupPackets()
# close()
# getName()
# open()
# ping()
# read()
# readCurrent()
# readDefaults()
# readRegister()
# reset()
# samplesFromPacket()
# setDIOState()
# setDefaults()
# setName()
# setToFactoryDefaults()
# streamData()
# streamStart()
# streamStop()
# write()
# writeRegister()
| 3,806 | 18.523077 | 81 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/src/u3.py | """
Name: u3.py
Desc: Defines the U3 class, which makes working with a U3 much easier. All of
the low-level functions for the U3 are implemented as functions of the U3
class. There are also a handful additional functions which improve upon
the interface provided by the low-level functions.
To learn about the low-level functions, please see Section 5.2 of the U3 User's Guide:
http://labjack.com/support/u3/users-guide/5.2
Section Number Mapping:
1 = Object Functions
2 = User's Guide Functions
3 = Convenience Functions
4 = Private Helper Functions
"""
from LabJackPython import *
import struct, ConfigParser
FIO0, FIO1, FIO2, FIO3, FIO4, FIO5, FIO6, FIO7, \
EIO0, EIO1, EIO2, EIO3, EIO4, EIO5, EIO6, EIO7, \
CIO0, CIO1, CIO2, CIO3 = range(20)
def openAllU3():
"""
A helpful function which will open all the connected U3s. Returns a
dictionary where the keys are the serialNumber, and the value is the device
object.
"""
returnDict = dict()
for i in range(deviceCount(3)):
d = U3(firstFound = False, devNumber = i+1)
returnDict[str(d.serialNumber)] = d
return returnDict
class U3(Device):
"""
U3 Class for all U3 specific low-level commands.
Example:
>>> import u3
>>> d = u3.U3()
>>> print d.configU3()
{'SerialNumber': 320032102, ... , 'FirmwareVersion': '1.26'}
"""
def __init__(self, debug = False, autoOpen = True, **kargs):
"""
Name: U3.__init__(debug = False, autoOpen = True, **openArgs)
Args: debug, enables debug output
autoOpen, if true, the class will try to open a U3 using openArgs
**openArgs, the arguments to pass to the open call. See U3.open()
Desc: Instantiates a new U3 object. If autoOpen == True, then it will
also open a U3.
Examples:
Simplest:
>>> import u3
>>> d = u3.U3()
For debug output:
>>> import u3
>>> d = u3.U3(debug = True)
To open a U3 with Local ID = 2:
>>> import u3
>>> d = u3.U3(localId = 2)
"""
Device.__init__(self, None, devType = 3)
self.debug = debug
self.calData = None
self.ledState = True
if autoOpen:
self.open(**kargs)
__init__.section = 1
def open(self, firstFound = True, serial = None, localId = None, devNumber = None, handleOnly = False, LJSocket = None):
"""
Name: U3.open(firstFound = True, localId = None, devNumber = None,
handleOnly = False, LJSocket = None)
Args: firstFound, If True, use the first found U3
serial, open a U3 with the given serial number
localId, open a U3 with the given local id.
devNumber, open a U3 with the given devNumber
handleOnly, if True, LabJackPython will only open a handle
LJSocket, set to "<ip>:<port>" to connect to LJSocket
Desc: Use to open a U3. If handleOnly is false, it will call configU3
and save the resulting information to the object. This allows the
use of d.serialNumber, d.firmwareVersion, etc.
Examples:
Simplest:
>>> import u3
>>> d = u3.U3(autoOpen = False)
>>> d.open()
Handle-only, with a serial number = 320095789:
>>> import u3
>>> d = u3.U3(autoOpen = False)
>>> d.open(handleOnly = True, serial = 320095789)
Using LJSocket:
>>> import u3
>>> d = u3.U3(autoOpen = False)
>>> d.open(LJSocket = "localhost:6000")
"""
Device.open(self, 3, firstFound = firstFound, serial = serial, localId = localId, devNumber = devNumber, handleOnly = handleOnly, LJSocket = LJSocket )
open.section = 1
def configU3(self, LocalID = None, TimerCounterConfig = None, FIOAnalog = None, FIODirection = None, FIOState = None, EIOAnalog = None, EIODirection = None, EIOState = None, CIODirection = None, CIOState = None, DAC1Enable = None, DAC0 = None, DAC1 = None, TimerClockConfig = None, TimerClockDivisor = None, CompatibilityOptions = None ):
"""
Name: U3.configU3(LocalID = None, TimerCounterConfig = None, FIOAnalog = None, FIODirection = None, FIOState = None, EIOAnalog = None, EIODirection = None, EIOState = None, CIODirection = None, CIOState = None, DAC1Enable = None, DAC0 = None, DAC1 = None, TimerClockConfig = None, TimerClockDivisor = None, CompatibilityOptions = None)
Args: See section 5.2.2 of the users guide.
Desc: Sends the low-level configU3 command. Also saves relevant
information to the U3 object for later use.
Example:
Simplest:
>>> import u3
>>> d = u3.U3()
>>> print d.configU3()
{
'LocalID': 1,
'SerialNumber': 320035782,
'DeviceName': 'U3-LV',
'FIODirection': 0,
'FirmwareVersion': '1.24',
... ,
'ProductID': 3
}
Configure all FIOs and EI0s to analog on boot:
>>> import u3
>>> d = u3.U3()
>>> print d.configU3( FIOAnalog = 255, EIOAnalog = 255)
{
'FIOAnalog': 255,
'EIOAnalog': 255,
... ,
'ProductID': 3
}
"""
writeMask = 0
if FIOAnalog is not None or FIODirection is not None or FIOState is not None or EIOAnalog is not None or EIODirection is not None or EIOState is not None or CIODirection is not None or CIOState is not None:
writeMask |= 2
if DAC1Enable is not None or DAC0 is not None or DAC1 is not None:
writeMask |= 4
if LocalID is not None:
writeMask |= 8
command = [ 0 ] * 26
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x0A
command[3] = 0x08
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = writeMask
#command[7] = WriteMask1
if LocalID is not None:
command[8] = LocalID
if TimerCounterConfig is not None:
command[9] = TimerCounterConfig
if FIOAnalog is not None:
command[10] = FIOAnalog
if FIODirection is not None:
command[11] = FIODirection
if FIOState is not None:
command[12] = FIOState
if EIOAnalog is not None:
command[13] = EIOAnalog
if EIODirection is not None:
command[14] = EIODirection
if EIOState is not None:
command[15] = EIOState
if CIODirection is not None:
command[16] = CIODirection
if CIOState is not None:
command[17] = CIOState
if DAC1Enable is not None:
command[18] = DAC1Enable
if DAC0 is not None:
command[19] = DAC0
if DAC1 is not None:
command[20] = DAC1
if TimerClockConfig is not None:
command[21] = TimerClockConfig
if TimerClockDivisor is not None:
command[22] = TimerClockDivisor
if CompatibilityOptions is not None:
command[23] = CompatibilityOptions
result = self._writeRead(command, 38, [0xF8, 0x10, 0x08])
# Error-free, time to parse the response
self.firmwareVersion = "%d.%02d" % (result[10], result[9])
self.bootloaderVersion = "%d.%02d" % (result[12], result[11])
self.hardwareVersion = "%d.%02d" % (result[14], result[13])
self.serialNumber = struct.unpack("<I", struct.pack(">BBBB", *result[15:19]))[0]
self.productId = struct.unpack("<H", struct.pack(">BB", *result[19:21]))[0]
self.localId = result[21]
self.timerCounterMask = result[22]
self.fioAnalog = result[23]
self.fioDirection = result[24]
self.fioState = result[25]
self.eioAnalog = result[26]
self.eioDirection = result[27]
self.eioState = result[28]
self.cioDirection = result[29]
self.cioState = result[30]
self.dac1Enable = result[31]
self.dac0 = result[32]
self.dac1 = result[33]
self.timerClockConfig = result[34]
self.timerClockDivisor = result[35]
if result[35] == 0:
self.timerClockDivisor = 256
self.compatibilityOptions = result[36]
self.versionInfo = result[37]
self.deviceName = 'U3'
if self.versionInfo == 1:
self.deviceName += 'B'
elif self.versionInfo == 2:
self.deviceName += '-LV'
elif self.versionInfo == 18:
self.deviceName += '-HV'
return { 'FirmwareVersion' : self.firmwareVersion, 'BootloaderVersion' : self.bootloaderVersion, 'HardwareVersion' : self.hardwareVersion, 'SerialNumber' : self.serialNumber, 'ProductID' : self.productId, 'LocalID' : self.localId, 'TimerCounterMask' : self.timerCounterMask, 'FIOAnalog' : self.fioAnalog, 'FIODirection' : self.fioDirection, 'FIOState' : self.fioState, 'EIOAnalog' : self.eioAnalog, 'EIODirection' : self.eioDirection, 'EIOState' : self.eioState, 'CIODirection' : self.cioDirection, 'CIOState' : self.cioState, 'DAC1Enable' : self.dac1Enable, 'DAC0' : self.dac0, 'DAC1' : self.dac1, 'TimerClockConfig' : self.timerClockConfig, 'TimerClockDivisor' : self.timerClockDivisor, 'CompatibilityOptions' : self.compatibilityOptions, 'VersionInfo' : self.versionInfo, 'DeviceName' : self.deviceName }
configU3.section = 2
def configIO(self, TimerCounterPinOffset = None, EnableCounter1 = None, EnableCounter0 = None, NumberOfTimersEnabled = None, FIOAnalog = None, EIOAnalog = None, EnableUART = None):
"""
Name: U3.configIO(TimerCounterPinOffset = 4, EnableCounter1 = None, EnableCounter0 = None, NumberOfTimersEnabled = None, FIOAnalog = None, EIOAnalog = None, EnableUART = None)
Args: See section 5.2.3 of the user's guide.
Desc: The configIO command.
Examples:
Simplest:
>>> import u3
>>> d = u3.U3()
>>> print d.configIO()
{
'NumberOfTimersEnabled': 0,
'TimerCounterPinOffset': 4,
'DAC1Enable': 0,
'FIOAnalog': 239,
'EIOAnalog': 0,
'TimerCounterConfig': 64,
'EnableCounter1': False,
'EnableCounter0': False
}
Set all FIOs and EIOs to digital (until power cycle):
>>> import u3
>>> d = u3.U3()
>>> print d.configIO(FIOAnalog = 0, EIOAnalog = 0)
{
'NumberOfTimersEnabled': 0,
'TimerCounterPinOffset': 4,
'DAC1Enable': 0,
'FIOAnalog': 0,
'EIOAnalog': 0,
'TimerCounterConfig': 64,
'EnableCounter1': False,
'EnableCounter0': False
}
"""
writeMask = 0
if EIOAnalog is not None:
writeMask |= 1
writeMask |= 8
if FIOAnalog is not None:
writeMask |= 1
writeMask |= 4
if EnableUART is not None:
writeMask |= 1
writeMask |= (1 << 5)
if TimerCounterPinOffset is not None or EnableCounter1 is not None or EnableCounter0 is not None or NumberOfTimersEnabled is not None :
writeMask |= 1
command = [ 0 ] * 12
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x03
command[3] = 0x0B
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = writeMask
#command[7] = Reserved
command[8] = 0
if EnableUART is not None:
command[9] = int(EnableUART) << 2
if TimerCounterPinOffset is None:
command[8] |= ( 4 & 15 ) << 4
else:
command[8] |= ( TimerCounterPinOffset & 15 ) << 4
if EnableCounter1 is not None:
command[8] |= 1 << 3
if EnableCounter0 is not None:
command[8] |= 1 << 2
if NumberOfTimersEnabled is not None:
command[8] |= ( NumberOfTimersEnabled & 3 )
if FIOAnalog is not None:
command[10] = FIOAnalog
if EIOAnalog is not None:
command[11] = EIOAnalog
result = self._writeRead(command, 12, [0xF8, 0x03, 0x0B])
self.timerCounterConfig = result[8]
self.numberTimersEnabled = self.timerCounterConfig & 3
self.counter0Enabled = bool( (self.timerCounterConfig >> 2) & 1 )
self.counter1Enabled = bool( (self.timerCounterConfig >> 3) & 1 )
self.timerCounterPinOffset = ( self.timerCounterConfig >> 4 )
self.dac1Enable = result[9]
self.fioAnalog = result[10]
self.eioAnalog = result[11]
return { 'TimerCounterConfig' : self.timerCounterConfig, 'DAC1Enable' : self.dac1Enable, 'FIOAnalog' : self.fioAnalog, 'EIOAnalog' : self.eioAnalog, 'NumberOfTimersEnabled' : self.numberTimersEnabled, 'EnableCounter0' : self.counter0Enabled, 'EnableCounter1' : self.counter1Enabled, 'TimerCounterPinOffset' : self.timerCounterPinOffset }
configIO.section = 2
def configTimerClock(self, TimerClockBase = None, TimerClockDivisor = None):
"""
Name: U3.configTimerClock(TimerClockBase = None, TimerClockDivisor = None)
Args: TimeClockBase, the base for the timer clock.
TimerClockDivisor, the divisor for the clock.
Desc: Writes and reads the time clock configuration. See section 5.2.4
of the user's guide.
Note: TimerClockBase and TimerClockDivisor must be set at the same time.
"""
command = [ 0 ] * 10
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x02
command[3] = 0x0A
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
#command[6] = Reserved
#command[7] = Reserved
if TimerClockBase is not None:
command[8] = ( 1 << 7 ) + ( TimerClockBase & 7 )
if TimerClockDivisor is not None:
command[9] = TimerClockDivisor
elif TimerClockDivisor is not None:
raise LabJackException("You can't set just the divisor, must set both.")
result = self._writeRead(command, 10, [0xf8, 0x02, 0x0A])
self.timerClockBase = ( result[8] & 7 )
self.timerClockDivisor = result[9]
return { 'TimerClockBase' : self.timerClockBase, 'TimerClockDivisor' : self.timerClockDivisor }
configTimerClock.section = 2
def toggleLED(self):
"""
Name: U3.toggleLED()
Args: None
Desc: Toggles the state LED on and off.
Example:
>>> import u3
>>> d = u3.U3()
>>> d.toggleLED()
"""
self.getFeedback( LED( not self.ledState ) )
self.ledState = not self.ledState
toggleLED.section = 3
def setFIOState(self, fioNum, state = 1):
"""
Name: U3.setFIOState(fioNum, state = 1)
Args: fioNum, which FIO to change
state, 1 = High, 0 = Low
Desc: A convenience function to set the state of an FIO. Will also
set the direction to output.
Example:
>>> import u3
>>> d = u3.U3()
>>> d.setFIOState(4, state = 1)
"""
self.getFeedback(BitDirWrite(fioNum, 1), BitStateWrite(fioNum, state))
setFIOState.section = 3
def getFIOState(self, fioNum):
"""
Name: U3.getFIOState(fioNum)
Args: fioNum, which FIO to read
Desc: A convenience function to read the state of an FIO.
Example:
>>> import u3
>>> d = u3.U3()
>>> print d.getFIOState(4)
1
"""
return self.getFeedback(BitStateRead(fioNum))[0]
getFIOState.section = 3
def getTemperature(self):
"""
Name: U3.getTemperature()
Args: None
Desc: Reads the internal temperature sensor on the U3. Returns the
temperature in Kelvin.
"""
# Get the calibration data first, otherwise the conversion is way off (10 degC on my U3)
if self.calData is None:
self.getCalibrationData()
bits, = self.getFeedback( AIN(30, 31) )
return self.binaryToCalibratedAnalogTemperature(bits)
def getAIN(self, posChannel, negChannel = 31, longSettle=False, quickSample=False):
"""
Name: U3.getAIN(posChannel, negChannel = 31, longSettle=False,
quickSample=False)
Args: posChannel, the positive channel to read from.
negChannel, the negitive channel to read from.
longSettle, set to True for longSettle
quickSample, set to True for quickSample
Desc: A convenience function to read an AIN.
Example:
>>> import u3
>>> d = u3.U3()
>>> print d.getAIN( 0 )
0.0501680038869
"""
isSpecial = False
if negChannel == 32:
isSpecial = True
negChannel = 30
bits = self.getFeedback(AIN(posChannel, negChannel, longSettle, quickSample))[0]
singleEnded = True
if negChannel != 31:
singleEnded = False
lvChannel = True
try:
if self.deviceName.endswith("-HV") and posChannel < 4:
lvChannel = False
except AttributeError:
pass
if isSpecial:
negChannel = 32
return self.binaryToCalibratedAnalogVoltage(bits, isLowVoltage = lvChannel, isSingleEnded = singleEnded, isSpecialSetting = isSpecial, channelNumber = posChannel)
getAIN.section = 3
def configAnalog(self, *args):
"""
Convenience method to configIO() that adds the given input numbers
in the range FIO0-EIO7 (0-15) to the analog team. That is, it adds
the given bit positions to those already set in the FIOAnalog
and EIOAnalog bitfields.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.configIO()
Sent: [0x47, 0xf8, 0x3, 0xb, 0x40, 0x0, 0x0, 0x0, 0x40, 0x0, 0x0, 0x0]
Result: [0x56, 0xf8, 0x3, 0xb, 0x4f, 0x0, 0x0, 0x0, 0x40, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 0, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 64, 'EnableCounter1': False, 'EnableCounter0': False}
>>> d.configAnalog(u3.FIO4, u3.FIO5)
Sent: [0x47, 0xf8, 0x3, 0xb, 0x40, 0x0, 0x0, 0x0, 0x40, 0x0, 0x0, 0x0]
Result: [0x56, 0xf8, 0x3, 0xb, 0x4f, 0x0, 0x0, 0x0, 0x40, 0x0, 0xf, 0x0]
Sent: [0x93, 0xf8, 0x3, 0xb, 0x8c, 0x0, 0xd, 0x0, 0x40, 0x0, 0x3f, 0x0]
Result: [0x86, 0xf8, 0x3, 0xb, 0x7f, 0x0, 0x0, 0x0, 0x40, 0x0, 0x3f, 0x0]
{'NumberOfTimersEnabled': 0, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 63, 'EIOAnalog': 0, 'TimerCounterConfig': 64, 'EnableCounter1': False, 'EnableCounter0': False}
"""
configIODict = self.configIO()
# Without args, return the same as configIO()
if len(args) == 0:
return configIODict
FIOAnalog, EIOAnalog = configIODict['FIOAnalog'], configIODict['EIOAnalog']
#
for i in args:
if i > EIO7:
pass # Invalid. Must be in the range FIO0-EIO7.
elif i < EIO0:
FIOAnalog |= 2**i
else:
EIOAnalog |= 2**(i-EIO0) # Start the EIO counting at 0, not 8
return self.configIO(FIOAnalog = FIOAnalog, EIOAnalog = EIOAnalog)
def configDigital(self, *args):
"""
The converse of configAnalog(). The convenience method to configIO,
adds the given input numbers in the range FIO0-EIO7 (0-15) to the
digital team. That is, it removes the given bit positions from those
already set in the FIOAnalog and EIOAnalog bitfields.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.configIO()
Sent: [0x47, 0xf8, 0x3, 0xb, 0x40, 0x0, 0x0, 0x0, 0x40, 0x0, 0x0, 0x0]
Result: [0x56, 0xf8, 0x3, 0xb, 0x4f, 0x0, 0x0, 0x0, 0x40, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 0, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 64, 'EnableCounter1': False, 'EnableCounter0': False}
>>> d.configAnalog(u3.FIO4, u3.FIO5, u3.EIO0)
Sent: [0x47, 0xf8, 0x3, 0xb, 0x40, 0x0, 0x0, 0x0, 0x40, 0x0, 0x0, 0x0]
Result: [0x56, 0xf8, 0x3, 0xb, 0x4f, 0x0, 0x0, 0x0, 0x40, 0x0, 0xf, 0x0]
Sent: [0x94, 0xf8, 0x3, 0xb, 0x8d, 0x0, 0xd, 0x0, 0x40, 0x0, 0x3f, 0x1]
Result: [0x87, 0xf8, 0x3, 0xb, 0x80, 0x0, 0x0, 0x0, 0x40, 0x0, 0x3f, 0x1]
{'NumberOfTimersEnabled': 0, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 63, 'EIOAnalog': 1, 'TimerCounterConfig': 64, 'EnableCounter1': False, 'EnableCounter0': False}
>>> d.configDigital(u3.FIO4, u3.FIO5, u3.EIO0)
Sent: [0x47, 0xf8, 0x3, 0xb, 0x40, 0x0, 0x0, 0x0, 0x40, 0x0, 0x0, 0x0]
Result: [0x87, 0xf8, 0x3, 0xb, 0x80, 0x0, 0x0, 0x0, 0x40, 0x0, 0x3f, 0x1]
Sent: [0x63, 0xf8, 0x3, 0xb, 0x5c, 0x0, 0xd, 0x0, 0x40, 0x0, 0xf, 0x0]
Result: [0x56, 0xf8, 0x3, 0xb, 0x4f, 0x0, 0x0, 0x0, 0x40, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 0, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 64, 'EnableCounter1': False, 'EnableCounter0': False}
"""
configIODict = self.configIO()
# Without args, return the same as configIO()
if len(args) == 0:
return configIODict
FIOAnalog, EIOAnalog = configIODict['FIOAnalog'], configIODict['EIOAnalog']
#
for i in args:
if i > EIO7:
pass # Invalid. Must be in the range FIO0-EIO7.
elif i < EIO0:
if FIOAnalog & 2**i: # If it is set
FIOAnalog ^= 2**i # Remove it
else:
if EIOAnalog & 2**(i-EIO0): # Start the EIO counting at 0, not 8
EIOAnalog ^= 2**(i-EIO0)
return self.configIO(FIOAnalog = FIOAnalog, EIOAnalog = EIOAnalog)
def _buildBuffer(self, sendBuffer, readLen, commandlist):
"""
Builds up the buffer to be written for getFeedback
"""
for cmd in commandlist:
if isinstance(cmd, FeedbackCommand):
sendBuffer += cmd.cmdBytes
readLen += cmd.readLen
elif isinstance(cmd, list):
sendBuffer, readLen = self._buildBuffer(sendBuffer, readLen, cmd)
return (sendBuffer, readLen)
_buildBuffer.section = 4
def _buildFeedbackResults(self, rcvBuffer, commandlist, results, i):
"""
Builds the result list from the results of getFeedback
"""
for cmd in commandlist:
if isinstance(cmd, FeedbackCommand):
results.append(cmd.handle(rcvBuffer[i:i+cmd.readLen]))
i += cmd.readLen
elif isinstance(cmd, list):
self._buildFeedbackResults(rcvBuffer, cmd, results, i)
return results
_buildFeedbackResults.section = 4
def getFeedback(self, *commandlist):
"""
Name: U3.getFeedback(commandlist)
Args: the FeedbackCommands to run
Desc: Forms the commandlist into a packet, sends it to the U3, and reads the response.
Examples:
>>> myU3 = u3.U3()
>>> ledCommand = u3.LED(False)
>>> ain0Command = u3.AIN(0, 31, True)
>>> myU3.getFeedback(ledCommand, ain0Command)
[None, 9376]
OR if you like the list version better:
>>> myU3 = U3()
>>> ledCommand = u3.LED(False)
>>> ain0Command = u3.AIN(30, 31, True)
>>> commandList = [ ledCommand, ain0Command ]
>>> myU3.getFeedback(commandList)
[None, 9376]
"""
sendBuffer = [0] * 7
sendBuffer[1] = 0xF8
readLen = 9
sendBuffer, readLen = self._buildBuffer(sendBuffer, readLen, commandlist)
if len(sendBuffer) % 2:
sendBuffer += [0]
sendBuffer[2] = len(sendBuffer) / 2 - 3
if readLen % 2:
readLen += 1
if len(sendBuffer) > MAX_USB_PACKET_LENGTH:
raise LabJackException("ERROR: The feedback command you are attempting to send is bigger than 64 bytes ( %s bytes ). Break your commands up into separate calls to getFeedback()." % len(sendBuffer))
if readLen > MAX_USB_PACKET_LENGTH:
raise LabJackException("ERROR: The feedback command you are attempting to send would yield a response that is greater than 64 bytes ( %s bytes ). Break your commands up into separate calls to getFeedback()." % readLen)
rcvBuffer = self._writeRead(sendBuffer, readLen, [], checkBytes = False, stream = False, checksum = True)
# Check the response for errors
try:
self._checkCommandBytes(rcvBuffer, [0xF8])
if rcvBuffer[3] != 0x00:
raise LabJackException("Got incorrect command bytes")
except LowlevelErrorException, e:
if isinstance(commandlist[0], list):
culprit = commandlist[0][ (rcvBuffer[7] -1) ]
else:
culprit = commandlist[ (rcvBuffer[7] -1) ]
raise LowlevelErrorException("\nThis Command\n %s\nreturned an error:\n %s" % (culprit , lowlevelErrorToString(rcvBuffer[6])))
results = []
i = 9
return self._buildFeedbackResults(rcvBuffer, commandlist, results, i)
getFeedback.section = 2
def readMem(self, blockNum, readCal=False):
"""
Name: U3.readMem(blockNum, readCal=False)
Args: blockNum, which block to read from
readCal, set to True to read from calibration instead.
Desc: Reads 1 block (32 bytes) from the non-volatile user or
calibration memory. Please read section 5.2.6 of the user's guide
before you do something you may regret.
NOTE: Do not call this function while streaming.
"""
command = [ 0 ] * 8
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x01
command[3] = 0x2A
if readCal:
command[3] = 0x2D
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = 0x00
command[7] = blockNum
result = self._writeRead(command, 40, [0xF8, 0x11, command[3]])
return result[8:]
readMem.section = 2
def readCal(self, blockNum):
"""
Name: U3.readCal(blockNum)
Args: blockNum, which block to read
Desc: See the description of readMem and section 5.2.6 of the user's
guide.
Note: Do not call this function while streaming.
"""
return self.readMem(blockNum, readCal = True)
readCal.section = 2
def writeMem(self, blockNum, data, writeCal=False):
"""
Name: U3.writeMem(blockNum, data, writeCal=False)
Args: blockNum, which block to write
data, a list of bytes to write.
writeCal, set to True to write to calibration instead
Desc: Writes 1 block (32 bytes) from the non-volatile user or
calibration memory. Please read section 5.2.7 of the user's guide
before you do something you may regret. Memory must be erased
before writing.
Note: Do not call this function while streaming.
"""
if not isinstance(data, list):
raise LabJackException("Data must be a list of bytes")
command = [ 0 ] * 40
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x11
command[3] = 0x28
if writeCal:
command[3] = 0x2B
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = 0x00
command[7] = blockNum
command[8:] = data
self._writeRead(command, 8, [0xF8, 0x01, command[3]])
writeMem.section = 2
def writeCal(self, blockNum):
"""
Name: U3.writeCal(blockNum, data)
Args: blockNum, which block to write
data, a list of bytes
Desc: See the description of writeMem and section 5.2.7 of the user's
guide.
Note: Do not call this function while streaming.
"""
return self.writeMem(blockNum, data, writeCal = True)
writeCal.section = 2
def eraseMem(self, eraseCal=False):
"""
Name: U3.eraseMem(eraseCal=False)
Args: eraseCal, set to True to erase the calibration memory instead
Desc: The U3 uses flash memory that must be erased before writing.
Please read section 5.2.8 of the user's guide before you do
something you may regret.
Note: Do not call this function while streaming.
"""
if eraseCal:
command = [ 0 ] * 8
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x01
command[3] = 0x2C
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = 0x4C
command[7] = 0x6C
else:
command = [ 0 ] * 6
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x00
command[3] = 0x29
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
self._writeRead(command, 8, [0xF8, 0x01, command[3]])
eraseMem.section = 2
def eraseCal(self):
"""
Name: U3.eraseCal()
Args: None
Desc: See the description of writeMem and section 5.2.8 of the user's
guide.
Note: Do not call this function while streaming.
"""
return self.eraseMem(eraseCal = True)
eraseCal.section = 2
def reset(self, hardReset = False):
"""
Name: U3.reset(hardReset = False)
Args: hardReset, set to True for a hard reset.
Desc: Causes a soft or hard reset. A soft reset consists of
re-initializing most variables without re-enumeration. A hard
reset is a reboot of the processor and does cause re-enumeration.
See section 5.2.9 of the User's guide.
"""
command = [ 0 ] * 4
#command[0] = Checksum8
command[1] = 0x99
command[2] = 1
if hardReset:
command[2] = 2
command[3] = 0x00
command = setChecksum8(command, 4)
self._writeRead(command, 4, [], False, False, False)
reset.section = 2
def streamConfig(self, NumChannels = 1, SamplesPerPacket = 25, InternalStreamClockFrequency = 0, DivideClockBy256 = False, Resolution = 3, ScanInterval = 1, PChannels = [30], NChannels = [31], SampleFrequency = None):
"""
Name: U3.streamConfig(NumChannels = 1, SamplesPerPacket = 25,
InternalStreamClockFrequency = 0,
DivideClockBy256 = False, Resolution = 3,
ScanInterval = 1, PChannels = [30],
NChannels = [31], SampleFrequency = None)
Args: NumChannels, the number of channels to stream
Resolution, the resolution of the samples (0 - 3)
PChannels, a list of channel numbers to stream
NChannels, a list of channel options bytes
Set Either:
SampleFrequency, the frequency in Hz to sample
-- OR --
SamplesPerPacket, how many samples make one packet
InternalStreamClockFrequency, 0 = 4 MHz, 1 = 48 MHz
DivideClockBy256, True = divide the clock by 256
ScanInterval, clock/ScanInterval = frequency.
Desc: Stream mode operates on a table of channels that are scanned
at the specified scan rate. Before starting a stream, you need
to call this function to configure the table and scan clock.
Note: Requires U3 hardware version 1.21 or greater.
"""
if len(PChannels) != NumChannels:
raise LabJackException("Length of PChannels didn't match NumChannels")
if len(NChannels) != NumChannels:
raise LabJackException("Length of NChannels didn't match NumChannels")
if len(PChannels) != len(NChannels):
raise LabJackException("Length of PChannels didn't match the length of NChannels")
if SampleFrequency != None:
if SampleFrequency < 1000:
if SampleFrequency < 25:
SamplesPerPacket = SampleFrequency
DivideClockBy256 = True
ScanInterval = 15625/SampleFrequency
else:
DivideClockBy256 = False
ScanInterval = 4000000/SampleFrequency
# Force Scan Interval into correct range
ScanInterval = min( ScanInterval, 65535 )
ScanInterval = int( ScanInterval )
ScanInterval = max( ScanInterval, 1 )
# Same with Samples per packet
SamplesPerPacket = max( SamplesPerPacket, 1)
SamplesPerPacket = int( SamplesPerPacket )
SamplesPerPacket = min ( SamplesPerPacket, 25)
command = [ 0 ] * ( 12 + (NumChannels * 2) )
#command[0] = Checksum8
command[1] = 0xF8
command[2] = NumChannels+3
command[3] = 0x11
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = NumChannels
command[7] = SamplesPerPacket
#command[8] = Reserved
command[9] |= ( InternalStreamClockFrequency & 0x01 ) << 3
if DivideClockBy256:
command[9] |= 1 << 2
command[9] |= ( Resolution & 3 )
t = struct.pack("<H", ScanInterval)
command[10] = ord(t[0])
command[11] = ord(t[1])
for i in range(NumChannels):
command[12+(i*2)] = PChannels[i]
command[13+(i*2)] = NChannels[i]
self._writeRead(command, 8, [0xF8, 0x01, 0x11])
self.streamSamplesPerPacket = SamplesPerPacket
self.streamChannelNumbers = PChannels
self.streamNegChannels = NChannels
self.streamConfiged = True
if InternalStreamClockFrequency == 1:
freq = float(48000000)
else:
freq = float(4000000)
if DivideClockBy256:
freq /= 256
freq = freq/ScanInterval
self.packetsPerRequest = max(1, int(freq/SamplesPerPacket))
self.packetsPerRequest = min(self.packetsPerRequest, 48)
streamConfig.section = 2
def processStreamData(self, result, numBytes = None):
"""
Name: U3.processStreamData(result, numBytes = None)
Args: result, the string returned from streamData()
numBytes, the number of bytes per packet.
Desc: Breaks stream data into individual channels and applies
calibrations.
>>> reading = d.streamData(convert = False)
>>> print proccessStreamData(reading['result'])
defaultDict(list, {'AIN0' : [3.123, 3.231, 3.232, ...]})
"""
if numBytes is None:
numBytes = 14 + (self.streamSamplesPerPacket * 2)
returnDict = collections.defaultdict(list)
for packet in self.breakupPackets(result, numBytes):
for sample in self.samplesFromPacket(packet):
if self.streamPacketOffset >= len(self.streamChannelNumbers):
self.streamPacketOffset = 0
if self.streamChannelNumbers[self.streamPacketOffset] in (193, 194):
value = struct.unpack('<BB', sample )
elif self.streamChannelNumbers[self.streamPacketOffset] >= 200:
value = struct.unpack('<H', sample )[0]
else:
if self.streamNegChannels[self.streamPacketOffset] != 31:
# do signed
value = struct.unpack('<H', sample )[0]
singleEnded = False
else:
# do unsigned
value = struct.unpack('<H', sample )[0]
singleEnded = True
lvChannel = True
if self.deviceName.lower().endswith('hv') and self.streamChannelNumbers[self.streamPacketOffset] < 4:
lvChannel = False
value = self.binaryToCalibratedAnalogVoltage(value, isLowVoltage = lvChannel, isSingleEnded = singleEnded, channelNumber = self.streamChannelNumbers[self.streamPacketOffset])
returnDict["AIN%s" % self.streamChannelNumbers[self.streamPacketOffset]].append(value)
self.streamPacketOffset += 1
return returnDict
processStreamData.section = 3
def watchdog(self, ResetOnTimeout = False, SetDIOStateOnTimeout = False, TimeoutPeriod = 60, DIOState = 0, DIONumber = 0, onlyRead=False):
"""
Name: U3.watchdog(ResetOnTimeout = False, SetDIOStateOnTimeout = False,
TimeoutPeriod = 60, DIOState = 0, DIONumber = 0,
onlyRead = False)
Args: Check out section 5.2.14 of the user's guide.
Set onlyRead to True to perform only a read
Desc: This function will write the configuration of the watchdog,
unless onlyRead is set to True.
Returns a dictionary:
{
'WatchDogEnabled' : True if the watchdog is enabled, otherwise False
'ResetOnTimeout' : If True, the device will reset on timeout.
'SetDIOStateOnTimeout' : If True, the state of a DIO will be set
'TimeoutPeriod' : Timeout Period in seconds
'DIOState' : The state the DIO will be set to on timeout
'DIONumber' : Which DIO will be set on timeout
}
NOTE: Requires U3 hardware version 1.21 or greater.
"""
command = [ 0 ] * 16
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x05
command[3] = 0x09
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
if not onlyRead:
command[6] = 1
if ResetOnTimeout:
command[7] |= 1 << 5
if SetDIOStateOnTimeout:
command[7] |= 1 << 4
t = struct.pack("<H", TimeoutPeriod)
command[8] = ord(t[0])
command[9] = ord(t[1])
command[10] = (( DIOState & 1 ) << 7) + ( DIONumber & 15)
result = self._writeRead(command, 16, [0xF8, 0x05, 0x09])
watchdogStatus = {}
if result[7] == 0 or result[7] == 255:
watchdogStatus['WatchDogEnabled'] = False
watchdogStatus['ResetOnTimeout'] = False
watchdogStatus['SetDIOStateOnTimeout'] = False
else:
watchdogStatus['WatchDogEnabled'] = True
if (( result[7] >> 5 ) & 1):
watchdogStatus['ResetOnTimeout'] = True
else:
watchdogStatus['ResetOnTimeout'] = False
if (( result[7] >> 4 ) & 1):
watchdogStatus['SetDIOStateOnTimeout'] = True
else:
watchdogStatus['SetDIOStateOnTimeout'] = False
watchdogStatus['TimeoutPeriod'] = struct.unpack('<H', struct.pack("BB", *result[8:10]))
if (( result[10] >> 7 ) & 1):
watchdogStatus['DIOState'] = 1
else:
watchdogStatus['DIOState'] = 0
watchdogStatus['DIONumber'] = ( result[10] & 15 )
return watchdogStatus
watchdog.section = 2
SPIModes = { 'A' : 0, 'B' : 1, 'C' : 2, 'D' : 3 }
def spi(self, SPIBytes, AutoCS=True, DisableDirConfig = False, SPIMode = 'A', SPIClockFactor = 0, CSPINNum = 4, CLKPinNum = 5, MISOPinNum = 6, MOSIPinNum = 7):
"""
Name: U3.spi(SPIBytes, AutoCS=True, DisableDirConfig = False,
SPIMode = 'A', SPIClockFactor = 0, CSPINNum = 4,
CLKPinNum = 5, MISOPinNum = 6, MOSIPinNum = 7)
Args: SPIBytes, a list of bytes to be transferred.
See Section 5.2.15 of the user's guide.
Desc: Sends and receives serial data using SPI synchronous
communication.
NOTE: Requires U3 hardware version 1.21 or greater.
"""
if not isinstance(SPIBytes, list):
raise LabJackException("SPIBytes MUST be a list of bytes")
numSPIBytes = len(SPIBytes)
oddPacket = False
if numSPIBytes%2 != 0:
SPIBytes.append(0)
numSPIBytes = numSPIBytes + 1
oddPacket = True
command = [ 0 ] * (13 + numSPIBytes)
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 4 + (numSPIBytes/2)
command[3] = 0x3A
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
if AutoCS:
command[6] |= (1 << 7)
if DisableDirConfig:
command[6] |= (1 << 6)
command[6] |= ( self.SPIModes[SPIMode] & 3 )
command[7] = SPIClockFactor
#command[8] = Reserved
command[9] = CSPINNum
command[10] = CLKPinNum
command[11] = MISOPinNum
command[12] = MOSIPinNum
command[13] = numSPIBytes
if oddPacket:
command[13] = numSPIBytes - 1
command[14:] = SPIBytes
result = self._writeRead(command, 8+numSPIBytes, [ 0xF8, 1+(numSPIBytes/2), 0x3A ])
return result[8:]
spi.section = 2
def asynchConfig(self, Update = True, UARTEnable = True, DesiredBaud = 9600, olderHardware = False, configurePins = True ):
"""
Name: U3.asynchConfig(Update = True, UARTEnable = True,
DesiredBaud = 9600, olderHardware = False,
configurePins = True)
Args: See section 5.2.16 of the User's Guide.
olderHardware, If using hardware 1.21, please set olderHardware
to True and read the timer configuration first.
configurePins, Will call the configIO to set up pins for you.
Desc: Configures the U3 UART for asynchronous communication.
returns a dictionary:
{
'Update' : True means new parameters were written
'UARTEnable' : True means the UART is enabled
'BaudFactor' : The baud factor being used
}
Note: Requires U3 hardware version 1.21+.
"""
if configurePins:
self.configIO(EnableUART=True)
command = [ 0 ] * 10
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x02
command[3] = 0x14
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
#command[6] = 0x00
if Update:
command[7] |= ( 1 << 7 )
if UARTEnable:
command[7] |= ( 1 << 6 )
#command[8] = Reserved
if olderHardware:
command[9] = (2**8) - self.timerClockBase/DesiredBaud
else:
BaudFactor = (2**16) - 48000000/(2 * DesiredBaud)
t = struct.pack("<H", BaudFactor)
command[8] = ord(t[0])
command[9] = ord(t[1])
if olderHardware:
result = self._writeRead(command, 10, [0xF8, 0x02, 0x14])
else:
result = self._writeRead(command, 10, [0xF8, 0x02, 0x14])
returnDict = {}
if ( ( result[7] >> 7 ) & 1 ):
returnDict['Update'] = True
else:
returnDict['Update'] = False
if ( ( result[7] >> 6 ) & 1):
returnDict['UARTEnable'] = True
else:
returnDict['UARTEnable'] = False
if olderHardware:
returnDict['BaudFactor'] = result[9]
else:
returnDict['BaudFactor'] = struct.unpack("<H", struct.pack("BB", *result[8:]))[0]
return returnDict
asynchConfig.section = 2
def asynchTX(self, AsynchBytes):
"""
Name: U3.asynchTX(AsynchBytes)
Args: AsynchBytes, must be a list of bytes to transfer.
Desc: Sends bytes to the U3 UART which will be sent asynchronously on
the transmit line. See section 5.2.17 of the user's guide.
returns a dictionary:
{
'NumAsynchBytesSent' : Number of Asynch Bytes Sent
'NumAsynchBytesInRXBuffer' : How many bytes are currently in the
RX buffer.
}
Note: Requres U3 hardware version 1.21 or greater.
"""
if not isinstance(AsynchBytes, list):
raise LabJackException("AsynchBytes must be a list")
numBytes = len(AsynchBytes)
oddPacket = False
if numBytes%2 != 0:
AsynchBytes.append(0)
numBytes = numBytes+1
oddPacket = True
command = [ 0 ] * ( 8 + numBytes)
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 1 + ( numBytes/2 )
command[3] = 0x15
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
#command[6] = 0x00
command[7] = numBytes
if oddPacket:
command[7] = numBytes - 1
command[8:] = AsynchBytes
result = self._writeRead(command, 10, [0xF8, 0x02, 0x15])
return { 'NumAsynchBytesSent' : result[7], 'NumAsynchBytesInRXBuffer' : result[8] }
asynchTX.section = 2
def asynchRX(self, Flush = False):
"""
Name: U3.asynchRX(Flush = False)
Args: Flush, Set to True to flush
Desc: Reads the oldest 32 bytes from the U3 UART RX buffer
(received on receive terminal). The buffer holds 256 bytes. See
section 5.2.18 of the User's Guide.
returns a dictonary:
{
'AsynchBytes' : List of received bytes
'NumAsynchBytesInRXBuffer' : Number of AsynchBytes are in the RX
Buffer.
}
Note: Requres U3 hardware version 1.21 or greater.
"""
command = [ 0 ] * 8
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x01
command[3] = 0x16
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
#command[6] = 0x00
if Flush:
command[7] = 1
result = self._writeRead(command, 40, [0xF8, 0x11, 0x16])
return { 'AsynchBytes' : result[8:], 'NumAsynchBytesInRXBuffer' : result[7] }
asynchRX.section = 2
def i2c(self, Address, I2CBytes, EnableClockStretching = False, NoStopWhenRestarting = False, ResetAtStart = False, SpeedAdjust = 0, SDAPinNum = 6, SCLPinNum = 7, NumI2CBytesToReceive = 0, AddressByte = None):
"""
Name: U3.i2c(Address, I2CBytes, ResetAtStart = False,
EnableClockStretching = False, SpeedAdjust = 0,
SDAPinNum = 6, SCLPinNum = 7, NumI2CBytesToReceive = 0,
AddressByte = None)
Args: Address, the address (not shifted over)
I2CBytes, must be a list of bytes to send.
See section 5.2.19 of the user's guide.
AddressByte, use this if you don't want a shift applied.
This address will be put it in the low-level
packet directly and overrides Address. Optional.
Desc: Sends and receives serial data using I2C synchronous
communication.
Note: Requires hardware version 1.21 or greater.
"""
if not isinstance(I2CBytes, list):
raise LabJackException("I2CBytes must be a list")
numBytes = len(I2CBytes)
oddPacket = False
if numBytes%2 != 0:
I2CBytes.append(0)
numBytes = numBytes + 1
oddPacket = True
command = [ 0 ] * (14 + numBytes)
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 4 + (numBytes/2)
command[3] = 0x3B
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
if ResetAtStart:
command[6] |= (1 << 1)
if NoStopWhenRestarting:
command[6] |= (1 << 2)
if EnableClockStretching:
command[6] |= (1 << 3)
command[7] = SpeedAdjust
command[8] = SDAPinNum
command[9] = SCLPinNum
if AddressByte != None:
command[10] = AddressByte
else:
command[10] = Address << 1
command[12] = numBytes
if oddPacket:
command[12] = numBytes-1
command[13] = NumI2CBytesToReceive
command[14:] = I2CBytes
oddResponse = False
if NumI2CBytesToReceive%2 != 0:
NumI2CBytesToReceive = NumI2CBytesToReceive+1
oddResponse = True
result = self._writeRead(command, 12+NumI2CBytesToReceive, [0xF8, (3+(NumI2CBytesToReceive/2)), 0x3B])
if len(result) > 12:
if oddResponse:
return { 'AckArray' : result[8:12], 'I2CBytes' : result[12:-1] }
else:
return { 'AckArray' : result[8:12], 'I2CBytes' : result[12:] }
else:
return { 'AckArray' : result[8:], 'I2CBytes' : [] }
i2c.section = 2
def sht1x(self, DataPinNum = 4, ClockPinNum = 5, SHTOptions = 0xc0):
"""
Name: U3.sht1x(DataPinNum = 4, ClockPinNum = 5, SHTOptions = 0xc0)
Args: See section 5.2.20 of the user's guide.
SHTOptions, see below.
Desc: Reads temperature and humidity from a Sensirion SHT1X sensor
(which is used by the EI-1050).
Returns a dictonary:
{
'StatusReg' : SHT1X status register
'StatusRegCRC' : SHT1X status register CRC value
'Temperature' : The temperature in C
'TemperatureCRC' : The CRC value for the temperature
'Humidity' : The humidity
'HumidityCRC' : The CRC value for the humidity
}
Note: Requires hardware version 1.21 or greater.
SHTOptions (and proof people read documentation):
bit 7 = Read Temperature
bit 6 = Read Realtive Humidity
bit 2 = Heater. 1 = on, 0 = off
bit 1 = Reserved at 0
bit 0 = Resolution. 1 = 8 bit RH, 12 bit T; 0 = 12 RH, 14 bit T
"""
command = [ 0 ] * 10
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x02
command[3] = 0x39
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = DataPinNum
command[7] = ClockPinNum
#command[8] = Reserved
command[9] = SHTOptions
result = self._writeRead(command, 16, [0xF8, 0x05, 0x39])
val = (result[11]*256) + result[10]
temp = -39.60 + 0.01*val
val = (result[14]*256) + result[13]
humid = -4 + 0.0405*val + -.0000028*(val*val)
humid = (temp - 25)*(0.01 + 0.00008*val) + humid
return { 'StatusReg' : result[8], 'StatusRegCRC' : result[9], 'Temperature' : temp, 'TemperatureCRC' : result[12] , 'Humidity' : humid, 'HumidityCRC' : result[15] }
sht1x.section = 2
def binaryToCalibratedAnalogVoltage(self, bits, isLowVoltage = True, isSingleEnded = True, isSpecialSetting = False, channelNumber = 0):
"""
Name: U3.binaryToCalibratedAnalogVoltage(bits, isLowVoltage = True,
isSingleEnded = True,
isSpecialSetting = False,
channelNumber = 0)
Args: bits, the binary value of the reading.
isLowVoltage, True if the reading came from a low-voltage channel
isSingleEnded, True if the reading is not differential
isSpecialSetting, True if the reading came from special range
channelNumber, used to apply the correct calibration for HV
Desc: Converts the bits returned from AIN functions into a calibrated
voltage.
Example:
>>> import u3
>>> d = u3.U3()
>>> bits = d.getFeedback( u3.AIN(0, 31))[0]
>>> print bits
1248
>>> print d.binaryToCalibratedAnalogVoltage(bits)
0.046464288000000006
"""
hasCal = self.calData is not None
if isLowVoltage:
if isSingleEnded and not isSpecialSetting:
if hasCal:
return ( bits * self.calData['lvSESlope'] ) + self.calData['lvSEOffset']
else:
return ( bits * 0.000037231 ) + 0
elif isSpecialSetting:
if hasCal:
return ( bits * self.calData['lvDiffSlope'] ) + self.calData['lvDiffOffset'] + self.calData['vRefAtCAl']
else:
return (bits * 0.000074463)
else:
if hasCal:
return ( bits * self.calData['lvDiffSlope'] ) + self.calData['lvDiffOffset']
else:
return (bits * 0.000074463) - 2.44
else:
if isSingleEnded and not isSpecialSetting:
if hasCal:
return ( bits * self.calData['hvAIN%sSlope' % channelNumber] ) + self.calData['hvAIN%sOffset' % channelNumber]
else:
return ( bits * 0.000314 ) + -10.3
elif isSpecialSetting:
if hasCal:
hvSlope = self.calData['hvAIN%sSlope' % channelNumber]
hvOffset = self.calData['hvAIN%sOffset' % channelNumber]
diffR = ( bits * self.calData['lvDiffSlope'] ) + self.calData['lvDiffOffset'] + self.calData['vRefAtCAl']
reading = diffR * hvSlope / self.calData['lvSESlope'] + hvOffset
return reading
else:
return (bits * 0.000074463) * (0.000314 / 0.000037231) + -10.3
else:
raise Exception, "Can't do differential on high voltage channels"
binaryToCalibratedAnalogVoltage.section = 3
def binaryToCalibratedAnalogTemperature(self, bytesTemperature):
hasCal = self.calData is not None
if hasCal:
return self.calData['tempSlope'] * float(bytesTemperature)
else:
return float(bytesTemperature) * 0.013021
def voltageToDACBits(self, volts, dacNumber = 0, is16Bits = False):
"""
Name: U3.voltageToDACBits(volts, dacNumber = 0, is16Bits = False)
Args: volts, the voltage you would like to set the DAC to.
dacNumber, 0 or 1, helps apply the correct calibration
is16Bits, True if you are going to use the 16-bit DAC command
Desc: Takes a voltage, and turns it into the bits needed for the DAC
Feedback commands.
"""
if self.calData is not None:
if is16Bits:
bits = ( volts * self.calData['dac%sSlope' % dacNumber] * 256) + self.calData['dac%sOffset' % dacNumber] * 256
else:
bits = ( volts * self.calData['dac%sSlope' % dacNumber] ) + self.calData['dac%sOffset' % dacNumber]
else:
bits = ( volts / 4.95 ) * 256
return int(bits)
voltageToDACBits.section = 3
def getCalibrationData(self):
"""
Name: U3.getCalibrationData()
Args: None
Desc: Reads in the U3's calibrations, so they can be applied to
readings. Section 2.6.2 of the User's Guide is helpful. Sets up
an internal calData dict for any future calls that need
calibration.
"""
self.calData = dict()
calData = self.readCal(0)
self.calData['lvSESlope'] = toDouble(calData[0:8])
self.calData['lvSEOffset'] = toDouble(calData[8:16])
self.calData['lvDiffSlope'] = toDouble(calData[16:24])
self.calData['lvDiffOffset'] = toDouble(calData[24:32])
calData = self.readCal(1)
self.calData['dac0Slope'] = toDouble(calData[0:8])
self.calData['dac0Offset'] = toDouble(calData[8:16])
self.calData['dac1Slope'] = toDouble(calData[16:24])
self.calData['dac1Offset'] = toDouble(calData[24:32])
calData = self.readCal(2)
self.calData['tempSlope'] = toDouble(calData[0:8])
self.calData['vRefAtCAl'] = toDouble(calData[8:16])
self.calData['vRef1.5AtCal'] = toDouble(calData[16:24])
self.calData['vRegAtCal'] = toDouble(calData[24:32])
try:
#these blocks do not exist on hardware revisions < 1.30
calData = self.readCal(3)
self.calData['hvAIN0Slope'] = toDouble(calData[0:8])
self.calData['hvAIN1Slope'] = toDouble(calData[8:16])
self.calData['hvAIN2Slope'] = toDouble(calData[16:24])
self.calData['hvAIN3Slope'] = toDouble(calData[24:32])
calData = self.readCal(4)
self.calData['hvAIN0Offset'] = toDouble(calData[0:8])
self.calData['hvAIN1Offset'] = toDouble(calData[8:16])
self.calData['hvAIN2Offset'] = toDouble(calData[16:24])
self.calData['hvAIN3Offset'] = toDouble(calData[24:32])
except LowlevelErrorException, ex:
if ex.errorCode != 26:
#not an invalid block error, so do not disregard
raise ex
return self.calData
getCalibrationData.section = 3
def readDefaultsConfig(self):
"""
Name: U3.readDefaultsConfig( )
Args: None
Desc: Reads the power-up defaults stored in flash.
"""
results = dict()
defaults = self.readDefaults(0)
results['FIODirection'] = defaults[4]
results['FIOState'] = defaults[5]
results['FIOAnalog'] = defaults[6]
results['EIODirection'] = defaults[8]
results['EIOState'] = defaults[9]
results['EIOAnalog'] = defaults[10]
results['CIODirection'] = defaults[12]
results['CIOState'] = defaults[13]
results['NumOfTimersEnable'] = defaults[17]
results['CounterMask'] = defaults[18]
results['PinOffset'] = defaults[19]
results['Options'] = defaults[20]
defaults = self.readDefaults(1)
results['ClockSource'] = defaults[0]
results['Divisor'] = defaults[1]
results['TMR0Mode'] = defaults[16]
results['TMR0ValueL'] = defaults[17]
results['TMR0ValueH'] = defaults[18]
results['TMR1Mode'] = defaults[20]
results['TMR1ValueL'] = defaults[21]
results['TMR1ValueH'] = defaults[22]
defaults = self.readDefaults(2)
results['DAC0'] = struct.unpack( ">H", struct.pack("BB", *defaults[16:18]) )[0]
results['DAC1'] = struct.unpack( ">H", struct.pack("BB", *defaults[20:22]) )[0]
defaults = self.readDefaults(3)
for i in range(16):
results["AIN%sNegChannel" % i] = defaults[i]
return results
readDefaultsConfig.section = 3
def exportConfig(self):
"""
Name: U3.exportConfig( )
Args: None
Desc: Takes the current configuration and puts it into a ConfigParser
object. Useful for saving the setup of your U3.
"""
# Make a new configuration file
parser = ConfigParser.SafeConfigParser()
# Change optionxform so that options preserve their case.
parser.optionxform = str
# Local Id and name
self.configU3()
section = "Identifiers"
parser.add_section(section)
parser.set(section, "Local ID", str(self.localId))
parser.set(section, "Name", str(self.getName()))
parser.set(section, "Device Type", str(self.devType))
# FIO Direction / State
section = "FIOs"
parser.add_section(section)
dirs, states = self.getFeedback( PortDirRead(), PortStateRead() )
parser.set(section, "FIOs Analog", str( self.readRegister(50590) ))
parser.set(section, "EIOs Analog", str( self.readRegister(50591) ))
for key, value in dirs.items():
parser.set(section, "%s Directions" % key, str(value))
for key, value in states.items():
parser.set(section, "%s States" % key, str(value))
# DACs
section = "DACs"
parser.add_section(section)
dac0 = self.readRegister(5000)
dac0 = max(dac0, 0)
dac0 = min(dac0, 5)
parser.set(section, "DAC0", "%0.2f" % dac0)
dac1 = self.readRegister(5002)
dac1 = max(dac1, 0)
dac1 = min(dac1, 5)
parser.set(section, "DAC1", "%0.2f" % dac1)
# Timer Clock Configuration
section = "Timer Clock Speed Configuration"
parser.add_section(section)
timerclockconfig = self.configTimerClock()
for key, value in timerclockconfig.items():
parser.set(section, key, str(value))
# Timers / Counters
section = "Timers And Counters"
parser.add_section(section)
timerCounterConfig = self.configIO()
nte = timerCounterConfig['NumberOfTimersEnabled']
ec0 = timerCounterConfig['EnableCounter0']
ec1 = timerCounterConfig['EnableCounter1']
cpo = timerCounterConfig['TimerCounterPinOffset']
parser.set(section, "NumberTimersEnabled", str(nte) )
parser.set(section, "Counter0Enabled", str(ec0) )
parser.set(section, "Counter1Enabled", str(ec1) )
parser.set(section, "TimerCounterPinOffset", str(cpo) )
for i in range(nte):
mode, value = self.readRegister(7100 + (2*i), numReg = 2, format = ">HH")
parser.set(section, "Timer%i Mode" % i, str(mode))
parser.set(section, "Timer%i Value" % i, str(value))
return parser
exportConfig.section = 3
def loadConfig(self, configParserObj):
"""
Name: U3.loadConfig( configParserObj )
Args: configParserObj, A Config Parser object to load in
Desc: Takes a configuration and updates the U3 to match it.
"""
parser = configParserObj
# Set Identifiers:
section = "Identifiers"
if parser.has_section(section):
if parser.has_option(section, "device type"):
if parser.getint(section, "device type") != self.devType:
raise Exception("Not a U3 Config file.")
if parser.has_option(section, "local id"):
self.configU3( LocalID = parser.getint(section, "local id"))
if parser.has_option(section, "name"):
self.setName( parser.get(section, "name") )
# Set FIOs:
section = "FIOs"
if parser.has_section(section):
fioanalog = 0
eioanalog = 0
fiodirs = 0
eiodirs = 0
ciodirs = 0
fiostates = 0
eiostates = 0
ciostates = 0
if parser.has_option(section, "fios analog"):
fioanalog = parser.getint(section, "fios analog")
if parser.has_option(section, "eios analog"):
eioanalog = parser.getint(section, "eios analog")
if parser.has_option(section, "fios directions"):
fiodirs = parser.getint(section, "fios directions")
if parser.has_option(section, "eios directions"):
eiodirs = parser.getint(section, "eios directions")
if parser.has_option(section, "cios directions"):
ciodirs = parser.getint(section, "cios directions")
if parser.has_option(section, "fios states"):
fiostates = parser.getint(section, "fios states")
if parser.has_option(section, "eios states"):
eiostates = parser.getint(section, "eios states")
if parser.has_option(section, "cios states"):
ciostates = parser.getint(section, "cios states")
self.configIO(FIOAnalog = fioanalog, EIOAnalog = eioanalog)
self.getFeedback( PortStateWrite([fiostates, eiostates, ciostates]), PortDirWrite([fiodirs, eiodirs, ciodirs]) )
# Set DACs:
section = "DACs"
if parser.has_section(section):
if parser.has_option(section, "dac0"):
self.writeRegister(5000, parser.getfloat(section, "dac0"))
if parser.has_option(section, "dac1"):
self.writeRegister(5002, parser.getfloat(section, "dac1"))
# Set Timer Clock Configuration
section = "Timer Clock Speed Configuration"
if parser.has_section(section):
if parser.has_option(section, "timerclockbase") and parser.has_option(section, "timerclockdivisor"):
self.configTimerClock(TimerClockBase = parser.getint(section, "timerclockbase"), TimerClockDivisor = parser.getint(section, "timerclockdivisor"))
# Set Timers / Counters
section = "Timers And Counters"
if parser.has_section(section):
nte = None
c0e = None
c1e = None
cpo = None
if parser.has_option(section, "NumberTimersEnabled"):
nte = parser.getint(section, "NumberTimersEnabled")
if parser.has_option(section, "TimerCounterPinOffset"):
cpo = parser.getint(section, "TimerCounterPinOffset")
if parser.has_option(section, "Counter0Enabled"):
c0e = parser.getboolean(section, "Counter0Enabled")
if parser.has_option(section, "Counter1Enabled"):
c1e = parser.getboolean(section, "Counter1Enabled")
self.configIO(NumberOfTimersEnabled = nte, EnableCounter1 = c1e, EnableCounter0 = c0e, TimerCounterPinOffset = cpo)
mode = None
value = None
if parser.has_option(section, "timer0 mode"):
mode = parser.getint(section, "timer0 mode")
if parser.has_option(section, "timer0 value"):
value = parser.getint(section, "timer0 value")
self.getFeedback( Timer0Config(mode, value) )
if parser.has_option(section, "timer1 mode"):
mode = parser.getint(section, "timer1 mode")
if parser.has_option(section, "timer1 value"):
value = parser.getint(section, "timer1 value")
self.getFeedback( Timer1Config(mode, value) )
loadConfig.section = 3
class FeedbackCommand(object):
"""
The FeedbackCommand class is the base for all the Feedback commands.
"""
readLen = 0
def handle(self, input):
return None
class AIN(FeedbackCommand):
'''
Analog Input Feedback command
specify the positive and negative channels to use
(0-16, 30 and 31 are possible)
also specify whether to turn on longSettle or quick Sample
returns 16-bit signed int sample
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.AIN(PositiveChannel = 0, NegativeChannel=31, LongSettling=False, QuickSample=False))
Sent: [0x1b, 0xf8, 0x2, 0x0, 0x20, 0x0, 0x0, 0x1, 0x0, 0x1f]
Response: [0xab, 0xf8, 0x3, 0x0, 0xaf, 0x0, 0x0, 0x0, 0x0, 0x20, 0x8f, 0x0]
[36640]
'''
def __init__(self, PositiveChannel, NegativeChannel=31,
LongSettling=False, QuickSample=False):
self.positiveChannel = PositiveChannel
self.negativeChannel = NegativeChannel
self.longSettling = LongSettling
self.quickSample = QuickSample
validChannels = range(16) + [30, 31]
if PositiveChannel not in validChannels:
raise Exception("Invalid Positive Channel specified")
if NegativeChannel not in validChannels:
raise Exception("Invalid Negative Channel specified")
b = PositiveChannel
b |= (int(bool(LongSettling)) << 6)
b |= (int(bool(QuickSample)) << 7)
self.cmdBytes = [ 0x01, b, NegativeChannel ]
readLen = 2
def __repr__(self):
return "<u3.AIN( PositiveChannel = %s, NegativeChannel = %s, LongSettling = %s, QuickSample = %s )>" % ( self.positiveChannel, self.negativeChannel, self.longSettling, self.quickSample )
def handle(self, input):
result = (input[1] << 8) + input[0]
return result
class WaitShort(FeedbackCommand):
'''
WaitShort Feedback command
specify the number of 128us time increments to wait
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.WaitShort(Time = 9))
Sent: [0x9, 0xf8, 0x2, 0x0, 0xe, 0x0, 0x0, 0x5, 0x9, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
'''
def __init__(self, Time):
self.time = Time % 256
self.cmdBytes = [ 5, Time % 256 ]
def __repr__(self):
return "<u3.WaitShort( Time = %s )>" % self.time
class WaitLong(FeedbackCommand):
'''
WaitLong Feedback command
specify the number of 32ms time increments to wait
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.WaitLong(Time = 70))
Sent: [0x47, 0xf8, 0x2, 0x0, 0x4c, 0x0, 0x0, 0x6, 0x46, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
'''
def __init__(self, Time):
self.time = Time % 256
self.cmdBytes = [ 6, Time % 256 ]
def __repr__(self):
return "<u3.WaitLong( Time = %s )>" % self.time
class LED(FeedbackCommand):
'''
LED Toggle
specify whether the LED should be on or off by truth value
1 or True = On, 0 or False = Off
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.LED(State = False))
Sent: [0x4, 0xf8, 0x2, 0x0, 0x9, 0x0, 0x0, 0x9, 0x0, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
>>> d.getFeedback(u3.LED(State = True))
Sent: [0x5, 0xf8, 0x2, 0x0, 0xa, 0x0, 0x0, 0x9, 0x1, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
'''
def __init__(self, State):
self.state = State
self.cmdBytes = [ 9, int(bool(State)) ]
def __repr__(self):
return "<u3.LED( State = %s )>" % self.state
class BitStateRead(FeedbackCommand):
'''
BitStateRead Feedback command
read the state of a single bit of digital I/O. Only digital
lines return valid readings.
IONumber: 0-7=FIO, 8-15=EIO, 16-19=CIO
return 0 or 1
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.BitStateRead(IONumber = 5))
Sent: [0xa, 0xf8, 0x2, 0x0, 0xf, 0x0, 0x0, 0xa, 0x5, 0x0]
Response: [0xfb, 0xf8, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1]
[1]
'''
def __init__(self, IONumber):
self.ioNumber = IONumber
self.cmdBytes = [ 10, IONumber % 20 ]
readLen = 1
def __repr__(self):
return "<u3.BitStateRead( IONumber = %s )>" % self.ioNumber
def handle(self, input):
return int(bool(input[0]))
class BitStateWrite(FeedbackCommand):
'''
BitStateWrite Feedback command
write a single bit of digital I/O. The direction of the
specified line is forced to output.
IONumber: 0-7=FIO, 8-15=EIO, 16-19=CIO
State: 0 or 1
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.BitStateWrite(IONumber = 5, State = 0))
Sent: [0xb, 0xf8, 0x2, 0x0, 0x10, 0x0, 0x0, 0xb, 0x5, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
'''
def __init__(self, IONumber, State):
self.ioNumber = IONumber
self.state = State
self.cmdBytes = [ 11, (IONumber % 20) + (int(bool(State)) << 7) ]
def __repr__(self):
return "<u3.BitStateWrite( IONumber = %s, State = %s )>" % (self.ioNumber, self.state)
class BitDirRead(FeedbackCommand):
'''
Read the digital direction of one I/O
IONumber: 0-7=FIO, 8-15=EIO, 16-19=CIO
returns 1 = Output, 0 = Input
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.BitDirRead(IONumber = 5))
Sent: [0xc, 0xf8, 0x2, 0x0, 0x11, 0x0, 0x0, 0xc, 0x5, 0x0]
Response: [0xfb, 0xf8, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1]
[1]
'''
def __init__(self, IONumber):
self.ioNumber = IONumber
self.cmdBytes = [ 12, IONumber % 20 ]
readLen = 1
def __repr__(self):
return "<u3.BitDirRead( IONumber = %s )>" % self.ioNumber
def handle(self, input):
return int(bool(input[0]))
class BitDirWrite(FeedbackCommand):
'''
BitDirWrite Feedback command
Set the digital direction of one I/O
IONumber: 0-7=FIO, 8-15=EIO, 16-19=CIO
Direction: 1 = Output, 0 = Input
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.BitDirWrite(IONumber = 5, Direction = 0))
Sent: [0xd, 0xf8, 0x2, 0x0, 0x12, 0x0, 0x0, 0xd, 0x5, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
'''
def __init__(self, IONumber, Direction):
self.ioNumber = IONumber
self.direction = Direction
self.cmdBytes = [ 13, (IONumber % 20) + (int(bool(Direction)) << 7) ]
def __repr__(self):
return "<u3.BitDirWrite( IONumber = %s, Direction = %s )>" % (self.ioNumber, self.direction)
class PortStateRead(FeedbackCommand):
"""
PortStateRead Feedback command
Reads the state of all digital I/O.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.PortStateRead())
Sent: [0x14, 0xf8, 0x1, 0x0, 0x1a, 0x0, 0x0, 0x1a]
Response: [0xeb, 0xf8, 0x3, 0x0, 0xee, 0x1, 0x0, 0x0, 0x0, 0xe0, 0xff, 0xf]
[{'CIO': 15, 'FIO': 224, 'EIO': 255}]
"""
def __init__(self):
self.cmdBytes = [ 26 ]
readLen = 3
def handle(self, input):
return {'FIO' : input[0], 'EIO' : input[1], 'CIO' : input[2] }
def __repr__(self):
return "<u3.PortStateRead()>"
class PortStateWrite(FeedbackCommand):
"""
PortStateWrite Feedback command
State: A list of 3 bytes representing FIO, EIO, CIO
WriteMask: A list of 3 bytes, representing which to update.
The Default is all ones.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.PortStateWrite(State = [0xab, 0xcd, 0xef], WriteMask = [0xff, 0xff, 0xff]))
Sent: [0x81, 0xf8, 0x4, 0x0, 0x7f, 0x5, 0x0, 0x1b, 0xff, 0xff, 0xff, 0xab, 0xcd, 0xef]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
"""
def __init__(self, State, WriteMask = [0xff, 0xff, 0xff]):
self.state = State
self.writeMask = WriteMask
self.cmdBytes = [ 27 ] + WriteMask + State
def __repr__(self):
return "<u3.PortStateWrite( State = %s, WriteMask = %s )>" % (self.state, self.writeMask)
class PortDirRead(FeedbackCommand):
"""
PortDirRead Feedback command
Reads the direction of all digital I/O.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.PortDirRead())
Sent: [0x16, 0xf8, 0x1, 0x0, 0x1c, 0x0, 0x0, 0x1c]
Response: [0xfb, 0xf8, 0x3, 0x0, 0xfe, 0x1, 0x0, 0x0, 0x0, 0xf0, 0xff, 0xf]
[{'CIO': 15, 'FIO': 240, 'EIO': 255}]
"""
def __init__(self):
self.cmdBytes = [ 28 ]
readLen = 3
def __repr__(self):
return "<u3.PortDirRead()>"
def handle(self, input):
return {'FIO' : input[0], 'EIO' : input[1], 'CIO' : input[2] }
class PortDirWrite(FeedbackCommand):
"""
PortDirWrite Feedback command
Direction: A list of 3 bytes representing FIO, EIO, CIO
WriteMask: A list of 3 bytes, representing which to update. Default is all ones.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.PortDirWrite(Direction = [0xaa, 0xcc, 0xff], WriteMask = [0xff, 0xff, 0xff]))
Sent: [0x91, 0xf8, 0x4, 0x0, 0x8f, 0x5, 0x0, 0x1d, 0xff, 0xff, 0xff, 0xaa, 0xcc, 0xff]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
"""
def __init__(self, Direction, WriteMask = [ 0xff, 0xff, 0xff]):
self.direction = Direction
self.writeMask = WriteMask
self.cmdBytes = [ 29 ] + WriteMask + Direction
def __repr__(self):
return "<u3.PortDirWrite( Direction = %s, WriteMask = %s )>" % (self.direction, self.writeMask)
class DAC8(FeedbackCommand):
'''
8-bit DAC Feedback command
Controls a single analog output
Dac: 0 or 1
Value: 0-255
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.DAC8(Dac = 0, Value = 0x55))
Sent: [0x72, 0xf8, 0x2, 0x0, 0x77, 0x0, 0x0, 0x22, 0x55, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
'''
def __init__(self, Dac, Value):
self.dac = Dac
self.value = Value % 256
self.cmdBytes = [ 34 + (Dac % 2), Value % 256 ]
def __repr__(self):
return "<u3.DAC8( Dac = %s, Value = %s )>" % (self.dac, self.value)
class DAC0_8(DAC8):
"""
8-bit DAC Feedback command for DAC0
Controls DAC0 in 8-bit mode.
Value: 0-255
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.DAC0_8(Value = 0x33))
Sent: [0x50, 0xf8, 0x2, 0x0, 0x55, 0x0, 0x0, 0x22, 0x33, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
"""
def __init__(self, Value):
DAC8.__init__(self, 0, Value)
def __repr__(self):
return "<u3.DAC0_8( Value = %s )>" % self.value
class DAC1_8(DAC8):
"""
8-bit DAC Feedback command for DAC1
Controls DAC1 in 8-bit mode.
Value: 0-255
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.DAC1_8(Value = 0x22))
Sent: [0x40, 0xf8, 0x2, 0x0, 0x45, 0x0, 0x0, 0x23, 0x22, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
"""
def __init__(self, Value):
DAC8.__init__(self, 1, Value)
def __repr__(self):
return "<u3.DAC1_8( Value = %s )>" % self.value
class DAC16(FeedbackCommand):
'''
16-bit DAC Feedback command
Controls a single analog output
Dac: 0 or 1
Value: 0-65535
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.DAC16(Dac = 0, Value = 0x5566))
Sent: [0xdc, 0xf8, 0x2, 0x0, 0xe1, 0x0, 0x0, 0x26, 0x66, 0x55]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
'''
def __init__(self, Dac, Value):
self.dac = Dac
self.value = Value
self.cmdBytes = [ 38 + (Dac % 2), Value % 256, Value >> 8 ]
def __repr__(self):
return "<u3.DAC16( Dac = %s, Value = %s )>" % (self.dac, self.value)
class DAC0_16(DAC16):
"""
16-bit DAC Feedback command for DAC0
Controls DAC0 in 16-bit mode.
Value: 0-65535
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.DAC0_16(Value = 0x1122))
Sent: [0x54, 0xf8, 0x2, 0x0, 0x59, 0x0, 0x0, 0x26, 0x22, 0x11]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
"""
def __init__(self, Value):
DAC16.__init__(self, 0, Value)
def __repr__(self):
return "<u3.DAC0_16( Value = %s )>" % self.value
class DAC1_16(DAC16):
"""
16-bit DAC Feedback command for DAC1
Controls DAC1 in 16-bit mode.
Value: 0-65535
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.DAC1_16(Value = 0x2233))
Sent: [0x77, 0xf8, 0x2, 0x0, 0x7c, 0x0, 0x0, 0x27, 0x33, 0x22]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
"""
def __init__(self, Value):
DAC16.__init__(self, 1, Value)
def __repr__(self):
return "<u3.DAC1_16( Value = %s )>" % self.value
class Timer(FeedbackCommand):
"""
For reading the value of the Timer. It provides the ability to update/reset
a given timer, and read the timer value.
(Section 5.2.5.14 of the User's Guide)
timer: Either 0 or 1 for timer 0 or timer 1
UpdateReset: Set True if you want to update the value
Value: Only updated if the UpdateReset bit is 1. The meaning of this
parameter varies with the timer mode.
Mode: Set to the timer mode to handle any special processing. See classes
QuadratureInputTimer and TimerStopInput1.
Returns an unsigned integer of the timer value, unless Mode has been
specified and there are special return values. See Section 2.9.1 for
expected return values.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.configIO(NumberOfTimersEnabled = 1)
Sent: [0x49, 0xf8, 0x3, 0xb, 0x42, 0x0, 0x1, 0x0, 0x41, 0x0, 0x0, 0x0]
Response: [0x57, 0xf8, 0x3, 0xb, 0x50, 0x0, 0x0, 0x0, 0x41, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 1, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 65, 'EnableCounter1': False, 'EnableCounter0': False}
>>> d.getFeedback(u3.Timer(timer = 0, UpdateReset = False, Value = 0, Mode = None))
Sent: [0x26, 0xf8, 0x3, 0x0, 0x2a, 0x0, 0x0, 0x2a, 0x0, 0x0, 0x0, 0x0]
Response: [0xfc, 0xf8, 0x4, 0x0, 0xfe, 0x1, 0x0, 0x0, 0x0, 0x63, 0xdd, 0x4c, 0x72, 0x0]
[1917640035]
"""
def __init__(self, timer, UpdateReset = False, Value=0, Mode = None):
self.timer = timer
self.updateReset = UpdateReset
self.value = Value
self.mode = Mode
if timer != 0 and timer != 1:
raise LabJackException("Timer should be either 0 or 1.")
if UpdateReset and Value == None:
raise LabJackException("UpdateReset set but no value.")
self.cmdBytes = [ (42 + (2*timer)), UpdateReset, Value % 256, Value >> 8 ]
readLen = 4
def __repr__(self):
return "<u3.Timer( timer = %s, UpdateReset = %s, Value = %s, Mode = %s )>" % (self.timer, self.updateReset, self.value, self.mode)
def handle(self, input):
inStr = struct.pack('B' * len(input), *input)
if self.mode == 8:
return struct.unpack('<i', inStr )[0]
elif self.mode == 9:
maxCount, current = struct.unpack('<HH', inStr )
return current, maxCount
else:
return struct.unpack('<I', inStr )[0]
class Timer0(Timer):
"""
For reading the value of the Timer0. It provides the ability to
update/reset Timer0, and read the timer value.
(Section 5.2.5.14 of the User's Guide)
UpdateReset: Set True if you want to update the value
Value: Only updated if the UpdateReset bit is 1. The meaning of this
parameter varies with the timer mode.
Mode: Set to the timer mode to handle any special processing. See classes
QuadratureInputTimer and TimerStopInput1.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.configIO(NumberOfTimersEnabled = 1)
Sent: [0x49, 0xf8, 0x3, 0xb, 0x42, 0x0, 0x1, 0x0, 0x41, 0x0, 0x0, 0x0]
Response: [0x57, 0xf8, 0x3, 0xb, 0x50, 0x0, 0x0, 0x0, 0x41, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 1, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 65, 'EnableCounter1': False, 'EnableCounter0': False}
>>> d.getFeedback(u3.Timer0(UpdateReset = False, Value = 0, Mode = None))
Sent: [0x26, 0xf8, 0x3, 0x0, 0x2a, 0x0, 0x0, 0x2a, 0x0, 0x0, 0x0, 0x0]
Response: [0x51, 0xf8, 0x4, 0x0, 0x52, 0x2, 0x0, 0x0, 0x0, 0xf6, 0x90, 0x46, 0x86, 0x0]
[2252771574]
"""
def __init__(self, UpdateReset = False, Value = 0, Mode = None):
Timer.__init__(self, 0, UpdateReset, Value, Mode)
def __repr__(self):
return "<u3.Timer0( UpdateReset = %s, Value = %s, Mode = %s )>" % (self.updateReset, self.value, self.mode)
class Timer1(Timer):
"""
For reading the value of the Timer1. It provides the ability to
update/reset Timer1, and read the timer value.
(Section 5.2.5.14 of the User's Guide)
UpdateReset: Set True if you want to update the value
Value: Only updated if the UpdateReset bit is 1. The meaning of this
parameter varies with the timer mode.
Mode: Set to the timer mode to handle any special processing. See classes
QuadratureInputTimer and TimerStopInput1.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.configIO(NumberOfTimersEnabled = 2)
Sent: [0x4a, 0xf8, 0x3, 0xb, 0x43, 0x0, 0x1, 0x0, 0x42, 0x0, 0x0, 0x0]
Response: [0x58, 0xf8, 0x3, 0xb, 0x51, 0x0, 0x0, 0x0, 0x42, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 2, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 66, 'EnableCounter1': False, 'EnableCounter0': False}
>>> d.getFeedback(u3.Timer1(UpdateReset = False, Value = 0, Mode = None))
Sent: [0x28, 0xf8, 0x3, 0x0, 0x2c, 0x0, 0x0, 0x2c, 0x0, 0x0, 0x0, 0x0]
Response: [0x8d, 0xf8, 0x4, 0x0, 0x8e, 0x2, 0x0, 0x0, 0x0, 0xf3, 0x31, 0xd0, 0x9a, 0x0]
[2597335539]
"""
def __init__(self, UpdateReset = False, Value = 0, Mode = None):
Timer.__init__(self, 1, UpdateReset, Value, Mode)
def __repr__(self):
return "<u3.Timer1( UpdateReset = %s, Value = %s, Mode = %s )>" % (self.updateReset, self.value, self.mode)
class QuadratureInputTimer(Timer):
"""
For reading Quadrature input timers. They are special because their values
are signed.
(Section 2.9.1.8 of the User's Guide)
Args:
UpdateReset: Set True if you want to reset the counter.
Value: Set to 0, and UpdateReset to True to reset the counter.
Returns a signed integer.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.configIO(NumberOfTimersEnabled = 2)
Sent: [0x4a, 0xf8, 0x3, 0xb, 0x43, 0x0, 0x1, 0x0, 0x42, 0x0, 0x0, 0x0]
Response: [0x58, 0xf8, 0x3, 0xb, 0x51, 0x0, 0x0, 0x0, 0x42, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 2, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 66, 'EnableCounter1': False, 'EnableCounter0': False}
>>> # Setup the two timers to be quadrature
>>> d.getFeedback(u3.Timer0Config(8), u3.Timer1Config(8))
Sent: [0x66, 0xf8, 0x5, 0x0, 0x68, 0x0, 0x0, 0x2b, 0x8, 0x0, 0x0, 0x2d, 0x8, 0x0, 0x0, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None, None]
>>> # Read the value
[0]
>>> d.getFeedback(u3.QuadratureInputTimer())
Sent: [0x26, 0xf8, 0x3, 0x0, 0x2a, 0x0, 0x0, 0x2a, 0x0, 0x0, 0x0, 0x0]
Response: [0xf5, 0xf8, 0x4, 0x0, 0xf5, 0x3, 0x0, 0x0, 0x0, 0xf8, 0xff, 0xff, 0xff, 0x0]
[-8]
>>> d.getFeedback(u3.QuadratureInputTimer())
Sent: [0x26, 0xf8, 0x3, 0x0, 0x2a, 0x0, 0x0, 0x2a, 0x0, 0x0, 0x0, 0x0]
Response: [0x9, 0xf8, 0x4, 0x0, 0xc, 0x0, 0x0, 0x0, 0x0, 0xc, 0x0, 0x0, 0x0, 0x0]
[12]
"""
def __init__(self, UpdateReset = False, Value = 0):
Timer.__init__(self, 0, UpdateReset, Value, Mode = 8)
def __repr__(self):
return "<u3.QuadratureInputTimer( UpdateReset = %s, Value = %s )>" % (self.updateReset, self.value)
class TimerStopInput1(Timer1):
"""
For reading a stop input timer. They are special because the value returns
the current edge count and the stop value.
(Section 2.9.1.9 of the User's Guide)
Args:
UpdateReset: Set True if you want to update the value.
Value: The stop value. Only updated if the UpdateReset bit is 1.
Returns a tuple where the first value is current edge count, and the second
value is the stop value.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.configIO(NumberOfTimersEnabled = 2)
Sent: [0x4a, 0xf8, 0x3, 0xb, 0x43, 0x0, 0x1, 0x0, 0x42, 0x0, 0x0, 0x0]
Response: [0x58, 0xf8, 0x3, 0xb, 0x51, 0x0, 0x0, 0x0, 0x42, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 2, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 66, 'EnableCounter1': False, 'EnableCounter0': False}
>>> # Setup the timer to be Stop Input
>>> d.getFeedback(u3.Timer1Config(9, Value = 30))
Sent: [0x50, 0xf8, 0x3, 0x0, 0x54, 0x0, 0x0, 0x2d, 0x9, 0x1e, 0x0, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
>>> d.getFeedback(u3.TimerStopInput1())
Sent: [0x28, 0xf8, 0x3, 0x0, 0x2c, 0x0, 0x0, 0x2c, 0x0, 0x0, 0x0, 0x0]
Response: [0x1b, 0xf8, 0x4, 0x0, 0x1e, 0x0, 0x0, 0x0, 0x0, 0x1e, 0x0, 0x0, 0x0, 0x0]
[(0, 0)]
"""
def __init__(self, UpdateReset = False, Value = 0):
Timer.__init__(self, 1, UpdateReset, Value, Mode = 9)
def __repr__(self):
return "<u3.TimerStopInput1( UpdateReset = %s, Value = %s )>" % (self.updateReset, self.value)
class TimerConfig(FeedbackCommand):
"""
This IOType configures a particular timer.
timer = # of the timer to configure
TimerMode = See Section 2.9 for more information about the available modes.
Value = The meaning of this parameter varies with the timer mode.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.configIO(NumberOfTimersEnabled = 1)
Sent: [0x49, 0xf8, 0x3, 0xb, 0x42, 0x0, 0x1, 0x0, 0x41, 0x0, 0x0, 0x0]
Response: [0x57, 0xf8, 0x3, 0xb, 0x50, 0x0, 0x0, 0x0, 0x41, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 1, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 65, 'EnableCounter1': False, 'EnableCounter0': False}
>>> d.getFeedback(u3.TimerConfig(timer = 0, TimerMode = 0, Value = 0))
Sent: [0x27, 0xf8, 0x3, 0x0, 0x2b, 0x0, 0x0, 0x2b, 0x0, 0x0, 0x0, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
>>> d.getFeedback(u3.TimerConfig(timer = 0, TimerMode = 0, Value = 65535))
Sent: [0x27, 0xf8, 0x3, 0x0, 0x29, 0x2, 0x0, 0x2b, 0x0, 0xff, 0xff, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
"""
def __init__(self, timer, TimerMode, Value=0):
'''Creates command bytes for configureing a Timer'''
#Conditions come from pages 33-34 of user's guide
if timer != 0 and timer != 1:
raise LabJackException("Timer should be either 0 or 1.")
if TimerMode > 14 or TimerMode < 0:
raise LabJackException("Invalid Timer Mode.")
self.timer = timer
self.timerMode = TimerMode
self.value = Value
self.cmdBytes = [43 + (timer * 2), TimerMode, Value % 256, Value >> 8]
def __repr__(self):
return "<u3.TimerConfig( timer = %s, TimerMode = %s, Value = %s )>" % (self.timer, self.timerMode, self.value)
class Timer0Config(TimerConfig):
"""
This IOType configures Timer0.
TimerMode = See Section 2.9 for more information about the available modes.
Value = The meaning of this parameter varies with the timer mode.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.configIO(NumberOfTimersEnabled = 1)
Sent: [0x49, 0xf8, 0x3, 0xb, 0x42, 0x0, 0x1, 0x0, 0x41, 0x0, 0x0, 0x0]
Response: [0x57, 0xf8, 0x3, 0xb, 0x50, 0x0, 0x0, 0x0, 0x41, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 1, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 65, 'EnableCounter1': False, 'EnableCounter0': False}
>>> d.getFeedback(u3.Timer0Config(TimerMode = 1, Value = 0))
Sent: [0x28, 0xf8, 0x3, 0x0, 0x2c, 0x0, 0x0, 0x2b, 0x1, 0x0, 0x0, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
>>> d.getFeedback(u3.Timer0Config(TimerMode = 1, Value = 65535))
Sent: [0x28, 0xf8, 0x3, 0x0, 0x2a, 0x2, 0x0, 0x2b, 0x1, 0xff, 0xff, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
"""
def __init__(self, TimerMode, Value = 0):
TimerConfig.__init__(self, 0, TimerMode, Value)
def __repr__(self):
return "<u3.Timer0Config( TimerMode = %s, Value = %s )>" % (self.timerMode, self.value)
class Timer1Config(TimerConfig):
"""
This IOType configures Timer1.
TimerMode = See Section 2.9 for more information about the available modes.
Value = The meaning of this parameter varies with the timer mode.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.configIO(NumberOfTimersEnabled = 2)
Sent: [0x4a, 0xf8, 0x3, 0xb, 0x43, 0x0, 0x1, 0x0, 0x42, 0x0, 0x0, 0x0]
Response: [0x58, 0xf8, 0x3, 0xb, 0x51, 0x0, 0x0, 0x0, 0x42, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 2, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 66, 'EnableCounter1': False, 'EnableCounter0': False}
>>> d.getFeedback(u3.Timer1Config(TimerMode = 6, Value = 1))
Sent: [0x30, 0xf8, 0x3, 0x0, 0x34, 0x0, 0x0, 0x2d, 0x6, 0x1, 0x0, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
"""
def __init__(self, TimerMode, Value = 0):
TimerConfig.__init__(self, 1, TimerMode, Value)
def __repr__(self):
return "<u3.Timer1Config( TimerMode = %s, Value = %s )>" % (self.timerMode, self.value)
class Counter(FeedbackCommand):
'''
Counter Feedback command
Reads a hardware counter, optionally resetting it
counter: 0 or 1
Reset: True ( or 1 ) = Reset, False ( or 0 ) = Don't Reset
Returns the current count from the counter if enabled. If reset,
this is the value before the reset.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.configIO(EnableCounter0 = True, FIOAnalog = 15)
Sent: [0x5f, 0xf8, 0x3, 0xb, 0x58, 0x0, 0x5, 0x0, 0x44, 0x0, 0xf, 0x0]
Response: [0x5a, 0xf8, 0x3, 0xb, 0x53, 0x0, 0x0, 0x0, 0x44, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 0, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 68, 'EnableCounter1': False, 'EnableCounter0': True}
>>> d.getFeedback(u3.Counter(counter = 0, Reset = False))
Sent: [0x31, 0xf8, 0x2, 0x0, 0x36, 0x0, 0x0, 0x36, 0x0, 0x0]
Response: [0xfc, 0xf8, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[0]
>>> # Tap a ground wire to counter 0
>>> d.getFeedback(u3.Counter(counter = 0, Reset = False))
Sent: [0x31, 0xf8, 0x2, 0x0, 0x36, 0x0, 0x0, 0x36, 0x0, 0x0]
Response: [0xe9, 0xf8, 0x4, 0x0, 0xec, 0x0, 0x0, 0x0, 0x0, 0xe8, 0x4, 0x0, 0x0, 0x0]
[1256]
'''
def __init__(self, counter, Reset = False):
self.counter = counter
self.reset = Reset
self.cmdBytes = [ 54 + (counter % 2), int(bool(Reset))]
readLen = 4
def __repr__(self):
return "<u3.Counter( counter = %s, Reset = %s )>" % (self.counter, self.reset)
def handle(self, input):
inStr = ''.join([chr(x) for x in input])
return struct.unpack('<I', inStr )[0]
class Counter0(Counter):
'''
Counter0 Feedback command
Reads hardware counter0, optionally resetting it
Reset: True ( or 1 ) = Reset, False ( or 0 ) = Don't Reset
Returns the current count from the counter if enabled. If reset,
this is the value before the reset.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.configIO(EnableCounter0 = True, FIOAnalog = 15)
Sent: [0x5f, 0xf8, 0x3, 0xb, 0x58, 0x0, 0x5, 0x0, 0x44, 0x0, 0xf, 0x0]
Response: [0x5a, 0xf8, 0x3, 0xb, 0x53, 0x0, 0x0, 0x0, 0x44, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 0, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 68, 'EnableCounter1': False, 'EnableCounter0': True}
>>> d.getFeedback(u3.Counter0( Reset = False ) )
Sent: [0x31, 0xf8, 0x2, 0x0, 0x36, 0x0, 0x0, 0x36, 0x0, 0x0]
Response: [0xfc, 0xf8, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[0]
>>> # Tap a ground wire to counter 0
>>> d.getFeedback(u3.Counter0(Reset = False))
Sent: [0x31, 0xf8, 0x2, 0x0, 0x36, 0x0, 0x0, 0x36, 0x0, 0x0]
Response: [0xe, 0xf8, 0x4, 0x0, 0x11, 0x0, 0x0, 0x0, 0x0, 0x11, 0x0, 0x0, 0x0, 0x0]
[17]
>>> # Tap a ground wire to counter 0
>>> d.getFeedback(u3.Counter0(Reset = False))
Sent: [0x31, 0xf8, 0x2, 0x0, 0x36, 0x0, 0x0, 0x36, 0x0, 0x0]
Response: [0x19, 0xf8, 0x4, 0x0, 0x1c, 0x0, 0x0, 0x0, 0x0, 0xb, 0x11, 0x0, 0x0, 0x0]
[4363]
'''
def __init__(self, Reset = False):
Counter.__init__(self, 0, Reset)
def __repr__(self):
return "<u3.Counter0( Reset = %s )>" % self.reset
class Counter1(Counter):
'''
Counter1 Feedback command
Reads hardware counter1, optionally resetting it
Reset: True ( or 1 ) = Reset, False ( or 0 ) = Don't Reset
Returns the current count from the counter if enabled. If reset,
this is the value before the reset.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.configIO(EnableCounter1 = True, FIOAnalog = 15)
Sent: [0x63, 0xf8, 0x3, 0xb, 0x5c, 0x0, 0x5, 0x0, 0x48, 0x0, 0xf, 0x0]
Response: [0x5e, 0xf8, 0x3, 0xb, 0x57, 0x0, 0x0, 0x0, 0x48, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 0, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 72, 'EnableCounter1': True, 'EnableCounter0': False}
>>> d.getFeedback(u3.Counter1(Reset = False))
Sent: [0x32, 0xf8, 0x2, 0x0, 0x37, 0x0, 0x0, 0x37, 0x0, 0x0]
Response: [0xfc, 0xf8, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[0]
>>> # Tap a ground wire to counter 1
>>> d.getFeedback(u3.Counter1(Reset = False))
Sent: [0x32, 0xf8, 0x2, 0x0, 0x37, 0x0, 0x0, 0x37, 0x0, 0x0]
Response: [0xfd, 0xf8, 0x4, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0]
[1]
>>> # Tap a ground wire to counter 1
>>> d.getFeedback(u3.Counter1(Reset = False))
Sent: [0x32, 0xf8, 0x2, 0x0, 0x37, 0x0, 0x0, 0x37, 0x0, 0x0]
Response: [0xb4, 0xf8, 0x4, 0x0, 0xb7, 0x0, 0x0, 0x0, 0x0, 0x6b, 0x2b, 0x21, 0x0, 0x0]
[2173803]
'''
def __init__(self, Reset = False):
Counter.__init__(self, 1, Reset)
def __repr__(self):
return "<u3.Counter0( Reset = %s )>" % self.reset
| 102,511 | 36.522694 | 815 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/Examples/u3allio.py | # Based on u3allio.c
import u3
from datetime import datetime
import sys
numChannels = int(sys.argv[1])
quickSample = 1
longSettling = 0
latestAinValues = [0] * numChannels
numIterations = 1000
d = u3.U3()
try:
#Configure the IOs before the test starts
FIOEIOAnalog = ( 2 ** numChannels ) - 1;
fios = FIOEIOAnalog & (0xFF)
eios = FIOEIOAnalog/256
d.configIO( FIOAnalog = fios, EIOAnalog = eios )
d.getFeedback(u3.PortDirWrite(Direction = [0, 0, 0], WriteMask = [0, 0, 15]))
feedbackArguments = []
feedbackArguments.append(u3.DAC0_8(Value = 125))
feedbackArguments.append(u3.PortStateRead())
#Check if the U3 is an HV
if d.configU3()['VersionInfo']&18 == 18:
isHV = True
else:
isHV = False
for i in range(numChannels):
feedbackArguments.append( u3.AIN(i, 31, QuickSample = quickSample, LongSettling = longSettling ) )
#print feedbackArguments
start = datetime.now()
# Call Feedback 1000 times
i = 0
while i < numIterations:
results = d.getFeedback( feedbackArguments )
#print results
for j in range(numChannels):
#Figure out if the channel is low or high voltage to use the correct calibration
if isHV == True and j < 4:
lowVoltage = False
else:
lowVoltage = True
latestAinValues[j] = d.binaryToCalibratedAnalogVoltage(results[ 2 + j ], isLowVoltage = lowVoltage, isSingleEnded = True)
i += 1
end = datetime.now()
delta = end - start
print "Time difference: ", delta
dm = delta / numIterations
print "Time per iteration: ", dm
print "Time per iteration in millis: ", dm.microseconds / 1000.0
print "Latest readings: ", latestAinValues
finally:
d.close()
| 1,847 | 25.4 | 133 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/Examples/streamTest.py | import u3, u6
from time import sleep
from datetime import datetime
import struct
# MAX_REQUESTS is the number of packets to be read.
# At high frequencies ( >5 kHz), the number of samples will be MAX_REQUESTS times 48 (packets per request) times 25 (samples per packet)
MAX_REQUESTS = 75
################################################################################
## U3
## Uncomment these lines to stream from a U3
################################################################################
#d = u3.U3()
#
## to learn the if the U3 is an HV
#d.configU3()
#
## Set the FIO0 to Analog
#d.configIO(FIOAnalog = 1)
#
#print "configuring U3 stream"
#d.streamConfig( NumChannels = 1, PChannels = [ 0 ], NChannels = [ 31 ], Resolution = 3, SampleFrequency = 10000 )
################################################################################
## U6
## Uncomment these lines to stream from a U6
################################################################################
#d = u6.U6()
#
## For applying the proper calibration to readings.
#d.getCalibrationData()
#
#print "configuring U6 stream"
#
#d.streamConfig( NumChannels = 1, ChannelNumbers = [ 0 ], ChannelOptions = [ 0 ], SettlingFactor = 1, ResolutionIndex = 1, SampleFrequency = 10000 )
try:
start = datetime.now()
print "start stream", start
d.streamStart()
missed = 0
start = datetime.now()
dataCount = 0
byteCount = 0
for r in d.streamData():
if r is not None:
# Our stop condition
if dataCount > MAX_REQUESTS:
break
if r['errors'] != 0:
print "Error: %s ; " % r['errors'], datetime.now()
if r['numPackets'] != d.packetsPerRequest:
print "----- UNDERFLOW : %s : " % r['numPackets'], datetime.now()
if r['missed'] != 0:
missed += r['missed']
print "+++ Missed ", r['missed']
# Comment out this print and do something with r
print "Average of", len(r['AIN0']), "reading(s):", sum(r['AIN0'])/len(r['AIN0'])
dataCount += 1
else:
# Got no data back from our read.
# This only happens if your stream isn't faster than the
# the USB read timeout, ~1 sec.
print "No data", datetime.now()
finally:
print "stream stopped."
stop = datetime.now()
d.streamStop()
d.close()
total = dataCount * d.packetsPerRequest * d.streamSamplesPerPacket
print "%s requests with %s packets per request with %s samples per packet = %s samples total." % ( dataCount, d.packetsPerRequest, d.streamSamplesPerPacket, total )
print "%s samples were lost due to errors." % missed
total -= missed
print "Adjusted number of samples = %s" % total
runTime = (stop-start).seconds + float((stop-start).microseconds)/1000000
print "The experiment took %s seconds." % runTime
print "%s samples / %s seconds = %s Hz" % ( total, runTime, float(total)/runTime )
| 3,077 | 31.744681 | 168 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/Examples/ktypeExample.py | import u6, ue9
from time import sleep
# Coefficients
# -200 C to 0 C
# -5.891 mV to 0 mV
# 0.0E0
# 2.5173462E1
# -1.1662878E0
# -1.0833638E0
# -8.977354E-1
# -3.7342377E-1
# -8.6632643E-2
# -1.0450598E-2
# -5.1920577E-4
voltsToTemp1 = (0.0E0,
2.5173462E1,
-1.1662878E0,
-1.0833638E0,
-8.977354E-1,
-3.7342377E-1,
-8.6632643E-2,
-1.0450598E-2,
-5.1920577E-4)
# 0 C to 500 C
# 0 mV to 20.644 mV
# 0.0E0
# 2.508355E1
# 7.860106E-2
# -2.503131E-1
# 8.31527E-2
# -1.228034E-2
# 9.804036E-4
# -4.41303E-5
# 1.057734E-6
# -1.052755E-8
voltsToTemp2 = (0.0E0,
2.508355E1,
7.860106E-2,
-2.503131E-1,
8.31527E-2,
-1.228034E-2,
9.804036E-4,
-4.41303E-5,
1.057734E-6,
-1.052755E-8)
# 500 C to 1372 C
# 20.644 mV to 54.886 mV
# -1.318058E2
# 4.830222E1
# -1.646031E0
# 5.464731E-2
# -9.650715E-4
# 8.802193E-6
# -3.11081E-8
voltsToTemp3 = (-1.318058E2,
4.830222E1,
-1.646031E0,
5.464731E-2,
-9.650715E-4,
8.802193E-6,
-3.11081E-8)
def voltsToTempConstants(mVolts):
if mVolts < -5.891 or mVolts > 54.886:
raise Exception("Invalid range")
if mVolts < 0:
return voltsToTemp1
elif mVolts < 20.644:
return voltsToTemp2
else:
return voltsToTemp3
# -270 C to 0 C
# 0E0
# 0.39450128E-1
# 0.236223736E-4
# -0.328589068E-6
# -0.499048288E-8
# -0.675090592E-10
# -0.574103274E-12
# -0.310888729E-14
# -0.104516094E-16
# -0.198892669E-19
# -0.163226975E-22
tempToVolts1 = (0.0E0,
0.39450128E-1,
0.236223736E-4,
-0.328589068E-6,
-0.499048288E-8,
-0.675090592E-10,
-0.574103274E-12,
-0.310888729E-14,
-0.104516094E-16,
-0.198892669E-19,
-0.163226975E-22)
# 0 C to 1372 C
# -0.176004137E-1
# 0.38921205E-1
# 0.1855877E-4
# -0.994575929E-7
# 0.318409457E-9
# -0.560728449E-12
# 0.560750591E-15
# -0.3202072E-18
# 0.971511472E-22
# -0.121047213E-25
#
# 0.1185976E0
# -0.1183432E-3
# 0.1269686E3
class ExtendedList(list):
pass
tempToVolts2 = ExtendedList()
tempToVolts2.append(-0.176004137E-1)
tempToVolts2.append(0.38921205E-1)
tempToVolts2.append(0.1855877E-4)
tempToVolts2.append(-0.994575929E-7)
tempToVolts2.append(0.318409457E-9)
tempToVolts2.append(-0.560728449E-12)
tempToVolts2.append(0.560750591E-15)
tempToVolts2.append(-0.3202072E-18)
tempToVolts2.append(0.971511472E-22)
tempToVolts2.append(-0.121047213E-25)
tempToVolts2.extended = (0.1185976E0, -0.1183432E-3, 0.1269686E3)
def tempToVoltsConstants(tempC):
if tempC < -270 or tempC > 1372:
raise Exception("Invalid range")
if tempC < 0:
return tempToVolts1
else:
return tempToVolts2
def evaluatePolynomial(coeffs, x):
sum = 0
y = 1
for a in coeffs:
sum += y * a
y *= x
return sum
def tempCToMVolts(tempC):
coeffs = tempToVoltsConstants(tempC)
if hasattr(coeffs, "extended"):
a0, a1, a2 = coeffs.extended
import math
extendedCalc = a0 * math.exp(a1 * (tempC - a2) * (tempC - a2))
return evaluatePolynomial(coeffs, tempC) + extendedCalc
else:
return evaluatePolynomial(coeffs, tempC)
def mVoltsToTempC(mVolts):
coeffs = voltsToTempConstants(mVolts)
return evaluatePolynomial(coeffs, mVolts)
if __name__ == '__main__':
d = u6.U6()
for i in range(10):
# The cold junction temperature
# Important: Must be in Celsius
CJTEMPinC = d.getTemperature() + 2.5 - 273.15
# The thermocouple's analog voltage
# Important: Must be in millivolts
TCmVolts = d.getAIN(0, resolutionIndex = 8, gainIndex = 3) * 1000
print "Cold Junction Temp:", CJTEMPinC
print "Voltage (in milivolts):", TCmVolts
totalMVolts = TCmVolts + tempCToMVolts(CJTEMPinC)
print "Temperature:", mVoltsToTempC(totalMVolts)
sleep(1) | 4,394 | 22.88587 | 73 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/Examples/u3Noise.py | """
" Name: u3Noise.py
" Desc: ( See below )
"""
DESC = """
This program will attempt to measure the noise of a provided signal on the U3. This is good if there is ever a question of noise from the labjack or from a signal.
The experiment is performed by taking 128 readings in quick succession. The results are then operated on the get the following values:
Peak-To-Peak Noise: The difference between the minimum and the maximum of the 128 values. Since all readings should be the same, any variation is noise.
Noise Free Resolution (bits): This represents how many bits are noise free.
Noise Free Resolution (mV): The smallest value that can be represented noise free.
Connect your signal and run this program. After, connect something with an obviously low noise signal ( like a battery ) and runt the program. If you don't have a low-noise signal, you can always jumper two FIO's to Ground and measure the noise as a differential.
You'll find that by comparing the two results, the labjack is rarely the reason for noisy readings.
On with the test:
"""
import u3
import math
def calcNoiseAndResolution(d, positiveChannel = 0, negitiveChannel = 31):
readings = []
cmd = u3.AIN(positiveChannel, negitiveChannel, QuickSample = False, LongSettling = False)
for i in xrange(128):
readings.append( float(d.getFeedback(cmd)[0])/16 )
#print readings
# Peak-To-Peak Noise
p2pn = max(readings) - min(readings)
# Noise-free resolution in bits
if p2pn > 0:
nfrbits = 12 - math.log(p2pn, 2)
else:
nfrbits = 12
# Noise-free resolution in milivolts
if d.deviceName.endswith("HV") and positiveChannel < 4:
vRange = 20.6
else:
if negitiveChannel != 31:
vRange = 4.88
else:
vRange = 2.44
nfrres = ( vRange / (2**nfrbits) ) * (10 ** 3)
return p2pn, nfrbits, nfrres
print DESC
pos = raw_input("Positive Channel (0-31) [0]: ")
try:
pos = int(pos)
except:
pos = 0
neg = raw_input("Negitive Channel (0-31) [31]: ")
try:
neg = int(neg)
except:
neg = 31
d = u3.U3()
results = calcNoiseAndResolution(d, pos, neg)
print "Peak-To-Peak Noise =", results[0]
print "Noise Free Resolution (bits) =", results[1]
print "Noise Free Resolution (mV) =", results[2]
d.close() | 2,341 | 28.275 | 263 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/Examples/u6Noise.py | """
Name: noise.py
Intended Device: U6
Desc: An example program that will calculate the values that can be found in
Appendix B of the U6 User's Guide.
"""
import u6 # Import the u6 class
import math # Need math for square root and log.
from datetime import datetime
# The size of the various ranges
ranges = [20, 2, 0.2, 0.02]
# A nice string representation of each range
strRanges = ["+/- 10", "+/- 1", "+/- 0.1", "+/- 0.01"]
# Numerical versions of range that the LabJack expects
vRanges = range(4)
def calcNoiseAndResolution(d, resolutionIndex, voltageRange):
"""
Takes 128 readings and calculates noise and resolution
"""
# Make a list to hold our readings
readings = []
# The feedback command to send to the device
cmd = u6.AIN24AR(15, ResolutionIndex = resolutionIndex, GainIndex = voltageRange, SettlingFactor = 4)
start = datetime.now()
# Collect 128 samples
for i in xrange(128):
readings.append(d.getFeedback(cmd)[0]['AIN'])
finish = datetime.now()
print "%s per sample" % ( (finish-start) / 128)
# The Peak-To-Peak Noise is difference between the max and the min.
p2pn = max(readings) - min(readings)
# Noise-Free resolution in bits follows the formula:
nfrbits = 24 - math.log(p2pn, 2)
# Noise-Free Resolution (uV) =
# <range> / 2 ^ < Noise-Free resolution (bits) >
nfrres = ( ranges[voltageRange] / (2**nfrbits) ) * (10 ** 6)
# Get the RMS Noise by calculating the standard deviation.
mean = sum(readings) / len(readings)
rms = 0
for r in readings:
rms += (r - mean) ** 2
rms = float(rms)/len(readings)
rms = math.sqrt(rms)
# Effective Resolution is uses a similar formulas as Noise-Free.
erbits = 24 - math.log(rms, 2)
erres = ( ranges[voltageRange] / (2**erbits) ) * (10 ** 6)
return [ p2pn, nfrbits, nfrres, rms, erbits, erres ]
d = u6.U6()
# If you have a U6-Pro, this will run though all the Resolution Indexs
if d.deviceName.endswith("Pro"):
rIndexes = range(1, 13)
else:
rIndexes = range(1, 9)
for i in rIndexes:
for r in vRanges:
rs = calcNoiseAndResolution(d,i,r)
print "Resolution Index = %s, Range = %s:\n\tPeak-To-Peak Noise = %s, Noise-Free Resolution (bits) = %.1f, Noise-Free Resolution (uV) = %.1f\n\tRMS Noise = %i, Effective Resolution (bits) = %.1f, Effective Resolution (uV) = %.1f\n" % (i, strRanges[r], rs[0], rs[1], rs[2], rs[3], rs[4], rs[5] )
| 2,548 | 30.8625 | 302 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/Examples/dca10.py | """
A class to make working with the DCA-10 easier. More info on the DCA-10 here:
http://labjack.com/support/dca-10/datasheet
"""
import LabJackPython, u3, u6, ue9
U3_WIRING_DESCRIPTION = """
Connection on DCA-10 -> Connection on LabJack
IN1 -> FIO5
IN2 -> FIO4
EN -> FIO6
GND -> GND
CS -> AIN0/FIO0
"""
U6_AND_UE9_WIRING_DESCRIPTION = """
Connection on DCA-10 -> Connection on LabJack
IN1 -> FIO1
IN2 -> FIO0
EN -> FIO2
GND -> GND
CS -> AIN0
"""
U6_AND_UE9_WITH_ENCODER_WIRING_DESCRIPTION = """
Connection on DCA-10 -> Connection on LabJack
IN1 -> EIO1
IN2 -> FIO2
EN -> EIO0
GND -> GND
CS -> AIN0
Encoder1 -> FIO0
Encoder2 -> FIO2
Power -> VS
GND -> GND
"""
class DCA10Exception(Exception): pass
class NoDevicesConnectedException(DCA10Exception): pass
class InvalidConfigurationException(DCA10Exception): pass
class DCA10(object):
"""
The DCA10 Class provides a nice interface for working with the DCA-10 motor
controller and a LabJack. For an example of how to use this class see
dca10Example.py.
"""
def __init__(self, devType = None, encoderAttached = False):
"""
Name: DAC10.__init__(devType = None, encoderAttached = False)
Args: devType, set to 3 to force use of U3, 6 for U6, 9 for UE9.
encoderAttached, set to True if your motor has a quadrature
encoder output and you want to use it. Note: This requires the
use of the EIOs so a CB15 is required. Also, the U3 only has two
timers and is therefore incapable of doing both the PWM to the
DCA and Quadrature.
Desc: Makes a new instance of the DCA10 class.
Examples:
To open the first found device, without an encoder:
>>> import dca10
>>> d = dca10.DCA10()
To open the first found U6, without an encoder:
>>> import dca10
>>> d = dca10.DCA10(devType = 6)
To open the first found UE9, with an encoder:
>>> import dca10
>>> d = dca10.DCA10(devType = 6, encoderAttached = True)
"""
self.device = None
self.encoderAttached = encoderAttached
self.directionLine = None
self.enableLine = None
self.currentLine = None
self.enableState = 1
self.directionState = 1
if devType is None:
if len(LabJackPython.listAll(3)) != 0:
self.device = u3.U3()
elif len(LabJackPython.listAll(6)) != 0:
self.device = u6.U6()
elif len(LabJackPython.listAll(9)) != 0:
self.device = ue9.UE9()
else:
raise NoDevicesConnectedException("Couldn't find any connected devices. Please connect a LabJack and try again.")
elif devType == 3:
self.device = u3.U3()
elif devType == 6:
self.device = u6.U6()
elif devType == 9:
self.device = ue9.UE9()
else:
raise InvalidConfigurationException("Invalid device type submitted. Got %s expected 3, 6, or 9." % devType)
if self.device.devType == 3 and self.encoderAttached:
raise InvalidConfigurationException("The U3 does not have enough timers to support an encoder.")
if self.device.devType == 3:
self.directionLine = 5
self.enableLine = 6
self.currentLine = 0
else:
if self.encoderAttached:
self.directionLine = 9
self.enableLine = 8
else:
self.directionLine = 1
self.enableLine = 2
self.currentLine = 0
# Make sure all the pins are digital, and enable a timer.
if self.device.devType == 3:
self.device.writeRegister(50590, 1)
if self.device.devType == 9:
self.device.writeRegister(7000, 1)
else:
self.device.writeRegister(7000, 2)
self.device.writeRegister(7002, 1)
# Set the Timer for PWM and Duty Cycle of 0%
if self.encoderAttached:
self.device.writeRegister(50501, 3)
self.device.writeRegister(7100, [8, 0, 8, 0, 0, 65535])
else:
self.device.writeRegister(50500, 0)
self.device.writeRegister(50501, 1)
self.device.writeRegister(7100, [0, 65535])
# Set the direction and enable lines to output.
# Don't have to do this because modbus will take care of direction.
#self.device.writeRegister(6100 + self.enableLine, 1)
#self.device.writeRegister(6100 + self.directionLine, 1)
# Set the direction and enable lines high.
self.device.writeRegister(6000 + self.enableLine, 1)
self.device.writeRegister(6000 + self.directionLine, 1)
def startMotor(self, dutyCycle = 1):
"""
Name: DCA10.startMotor(dutyCycle = 1)
Args: dutyCycle, a value between 0-1 representing the duty cycle of the
PWM output. ( Controls how fast the motor spins ).
Desc: Starts the motor at the specified duty cycle.
By default, will start the motor with a 100% duty cycle.
Example:
>>> import dca10
>>> d = dca10.DCA10()
>>> d.startMotor(dutyCycle = 0.5)
"""
if dutyCycle < 0 or dutyCycle > 1:
raise InvalidConfigurationException("Duty cycle must be between 0 and 1. Got %s." % dutyCycle)
value = int(65535 - (65535 * dutyCycle))
if self.encoderAttached:
self.device.writeRegister(7104, [0, value])
else:
self.device.writeRegister(7100, [0, value])
if not self.enableState:
self.device.writeRegister(6000 + self.enableLine, 1)
def stopMotor(self):
"""
Name: DCA10.stopMotor()
Args: None
Desc: Sets the enable line low, stopping the motor.
Example:
>>> import dca10
>>> d = dca10.DCA10()
>>> d.startMotor(dutyCycle = 0.5)
>>> d.stopMotor()
"""
self.device.writeRegister(6000 + self.enableLine, 0)
self.enableState = 0
def toggleDirection(self):
"""
Name: DCA10.toggleDirection()
Args: None
Desc: Toggles the direction line, which causes the motor to change
directions.
Example:
>>> import dca10
>>> d = dca10.DCA10()
>>> d.startMotor(dutyCycle = 0.5)
>>> d.toggleDirection()
"""
self.directionState = not self.directionState
self.device.writeRegister(6000 + self.directionLine, self.directionState)
def readCurrent(self):
"""
Name: DCA10.readCurrent()
Args: None
Desc: Takes a sample off the CS line and applies the offset from the
DCA-10 datasheet. Returns a floating point value representing
Amps.
Example:
>>> import dca10
>>> d = dca10.DCA10()
>>> d.startMotor(dutyCycle = 0.5)
>>> print d.readCurrent()
0.018158430290222165
"""
return (self.device.readRegister(0 + self.currentLine) * 3.7596 )
def readEncoder(self):
"""
Name: DCA10.readEncoder()
Args: None
Desc: Reads the current value of the quadrature encoder. Raises a
DCA10Exception if the encoder is not attached.
Example:
>>> import dca10
>>> d = dca10.DCA10(encoderAttached = True)
>>> d.startMotor(dutyCycle = 0.5)
>>> print d.readEncoder()
3925
"""
if self.encoderAttached:
return self.device.readRegister(7200)
else:
raise DCA10Exception("You cannot read the Quadrature Encoder when it is not connected.")
def wiringDescription(self):
"""
Name: DCA10.wiringDescription()
Args: None
Desc: Returns a string that describes how the DCA-10 should be wired to
the LabJack.
Example:
>>> import dca10
>>> d = dca10.DCA10(devType = 6)
>>> print d.wiringDescription()
Connection on DCA-10 -> Connection on LabJack
IN1 -> FIO1
IN2 -> FIO0
EN -> FIO2
GND -> GND
CS -> AIN0
"""
if self.device.devType == 3:
return U3_WIRING_DESCRIPTION
elif self.encoderAttached:
return U6_AND_UE9_WITH_ENCODER_WIRING_DESCRIPTION
else:
return U6_AND_UE9_WIRING_DESCRIPTION | 9,008 | 30.833922 | 129 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/Examples/u3SampleAndLogToCloudDot.py | #!/usr/bin/env python
# u3SampleAndLogToCloudDot.py
#
# This program demonstrates how to sample data from a USB LabJack and
# log it to CloudDot using CloudDot's REST API.
#
# Requirements:
#
# 1. A U3 (You can modify the code to use another LabJack.)
# 2. A UNIX-compatible computer (Replace the signal.SIGALRM usage with sleep() on another platform)
# 3. The httplib2 Python module. Install it via
# $ sudo easy_install httplib2
# or download it from
# http://code.google.com/p/httplib2/
# 4. A CloudDot account. Start with the walkthrough and tutorial if you don't have one yet:
# http://labjack.com/support/clouddot/users-guide/1
# 5. Details from your CloudDot account:
# a. Username
# b. API Key (on your Account page)
# c. A channel nickname from a virtual channel (make a virtual channel on your Channels page)
#
# For information on the CloudDot REST API, visit:
# http://labjack.com/support/clouddot/rest-api
# Replace these three fields
CLOUDDOT_USERNAME = ""
CLOUDDOT_API_KEY = "01234567890123456789"
CLOUDDOT_CHANNEL = "Temperature"
SAMPLE_INTERVAL = 30 # Sample and post to CloudDot after this time in seconds
MODBUS_REGISTER = 0 # Read from this register to get the data. See http://labjack.com/support/modbus
import u3
import signal
from datetime import datetime
from httplib2 import Http
from urllib import urlencode
def sampleAndPost(*args):
print "----- Gathering sample at", datetime.now()
reading = d.readRegister(MODBUS_REGISTER)
print "===== Read", reading
data = dict(value = reading)
# Here is the call that posts to CloudDot
resp, content = h.request(writeUrl, "POST", urlencode(data))
print "+++++ Post to CloudDot at", datetime.now(), "Response status:", resp["status"]
if resp["status"].startswith('2') == False:
raise Exception("Post failed; check your CloudDot username, API key, and channel. Response status was: %s" % (resp["status"],))
print
d = u3.U3()
writeUrl = "http://cloudapi.labjack.com/%s/channels/%s/write.json" % (CLOUDDOT_USERNAME, CLOUDDOT_CHANNEL)
h = Http()
h.add_credentials(CLOUDDOT_USERNAME, CLOUDDOT_API_KEY)
# Call it once at first because we're impatient
sampleAndPost()
# Set it up to call every SAMPLE_INTERVAL
signal.signal(signal.SIGALRM, sampleAndPost)
signal.setitimer(signal.ITIMER_REAL, SAMPLE_INTERVAL, SAMPLE_INTERVAL)
while True:
signal.pause()
| 2,410 | 34.985075 | 135 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/Examples/u6allio.py | # Based on u6allio.c
import u6
from datetime import datetime
import sys
numChannels = int(sys.argv[1])
resolutionIndex = 1
gainIndex = 0
settlingFactor = 0
differential = False
latestAinValues = [0] * numChannels
numIterations = 1000
d = u6.U6()
d.getCalibrationData()
try:
#Configure the IOs before the test starts
FIOEIOAnalog = ( 2 ** numChannels ) - 1;
fios = FIOEIOAnalog & (0xFF)
eios = FIOEIOAnalog/256
d.getFeedback(u6.PortDirWrite(Direction = [0, 0, 0], WriteMask = [0, 0, 15]))
feedbackArguments = []
feedbackArguments.append(u6.DAC0_8(Value = 125))
feedbackArguments.append(u6.PortStateRead())
for i in range(numChannels):
feedbackArguments.append( u6.AIN24(i, resolutionIndex, gainIndex, settlingFactor, differential) )
start = datetime.now()
# Call Feedback 1000 times
i = 0
while i < numIterations:
results = d.getFeedback( feedbackArguments )
for j in range(numChannels):
latestAinValues[j] = d.binaryToCalibratedAnalogVoltage(gainIndex, results[ 2 + j ])
i += 1
end = datetime.now()
delta = end - start
print "Time difference: ", delta
dm = delta / numIterations
print "Time per iteration: ", dm
print "Time per iteration in millis: ", dm.microseconds / 1000.0
print "Latest readings: ", latestAinValues
finally:
d.close() | 1,429 | 23.237288 | 105 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/Examples/workingWithModbus.py | """
" An example program to show you how easy it is to work with Modbus on a
" LabJack.
"
" Be sure to check out the Modbus map (http://labjack.com/support/modbus) for a
" full list of registers.
"""
import u3, u6, ue9
import random
if __name__ == '__main__':
print "This program shows how to work with modbus and your device. Registers are taken directly from the Modbus map (http://labjack.com/support/modbus).\n"
print "Opening device...",
d = u3.U3() # Opens first found U3 over USB
#d = u6.U6() # Opens first found U6 over USB
#d = ue9.UE9() # Opens first found UE9 over USB
# Opens a UE9 at IP Address 192.168.1.129
#d = ue9.UE9( ethernet = True, ipAddress = "192.168.1.129")
print "Done\n"
isU3 = False
if isinstance(d, u3.U3):
isU3 = True
if isU3:
print "Setting FIO0-3 to analog, and the rest to digital...",
d.writeRegister(50590, 15)
print "Done\n"
# Reading Analog Inputs.
print "Analog Inputs:"
for i in range(4):
register = 0 + i*2 # Starting register 0, 2 registers at a time
print "AIN%s (register %s): %s" % (i, register, d.readRegister(register))
# Reading Digital I/O
print "\nDigital I/O:"
for i in range(4):
dirRegister = 6100 + i # Starting register 6100, 1 register at a time
stateRegister = 6000 + i # Starting register 6000, 1 register at a time
fio = i
if isU3:
fio = i+4
dirRegister = 6100 + 4 + i
stateRegister = 6000 + 4 + i
print "FIO%s (register %s) Direction: %s" % (fio, dirRegister, d.readRegister(dirRegister))
state = d.readRegister(stateRegister)
print "FIO%s (register %s) State: %s" % (fio, stateRegister, state)
if state == 0:
state = 1
wordState = "high"
else:
state = 0
wordState = "low"
print "Setting FIO%s to output %s (register %s = %s )..." % (fio, wordState, stateRegister, state),
d.writeRegister(stateRegister, state)
print "Done"
print "FIO%s (register %s) Direction: %s" % (fio, dirRegister, d.readRegister(dirRegister))
print "FIO%s (register %s) State: %s\n" % (fio, stateRegister, d.readRegister(stateRegister))
# Seed the random number generator. Has nothing to do with modbus
random.seed()
# Reading and writing to a DAC
print "\nReading and writing to DACs:"
for i in range(2):
dacRegister = 5000 + i*2 # Starting register 5000, 2 registers at a time
print "DAC%s (register %s) reads %s Volts." % (i, dacRegister, d.readRegister(dacRegister))
voltage = float("%s.%s" % (random.randint(0,4), random.randint(0,9)) )
print "Setting DAC%s to %s Volts..." % (i, voltage),
d.writeRegister(dacRegister, voltage)
print "Done"
print "DAC%s (register %s) reads %s Volts.\n" % (i, dacRegister, d.readRegister(dacRegister)) | 3,053 | 36.703704 | 159 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/Examples/outputSinDAC.py | # An example script to show how to output a sine wave using a DAC.
# Because we have to do it all in software, there are limitations on how fast
# we can update the DAC. Update intervals faster than 5 ms may give weird
# results because of the large percentage of missed updates.
#
# Note: This example uses signal.setitimer() and signal.alarm(), and therefore
# requires Python 2.6 on Unix to run. See:
# http://docs.python.org/library/signal.html#signal.setitimer
# http://docs.python.org/library/signal.html#signal.alarm
#
# When changing the update interval and frequency, consider how your values
# effect the waveform. A slow update interval coupled with a fast frequency
# can result in strange behavior. Try to keep the period (1/frequency) much
# greater than update interval.
# Constants. Change these to change the results:
# Controls how fast the DAC will be updated, in seconds.
UPDATE_INTERVAL = 0.005
# The frequency of the sine wave, in Hz
FREQUENCY = 10
# Imports:
import u3, u6, ue9 # For working with the U3
import signal # For timing
import math # For sin function
from datetime import datetime # For printing times
if __name__ == '__main__':
print "This program will attempt to generate a sine wave with a frequency of %s Hz, updating once every %s seconds." % (FREQUENCY, UPDATE_INTERVAL)
print "Opening LabJack...",
# Open up our LabJack
d = u3.U3()
#d = u6.U6()
#d = ue9.UE9()
print "Done"
# Make a class to keep track of variables and the like
class DacSetter(object):
def __init__(self, frequency, updateInterval):
self.count = 0
self.dac = 0
self.setDacCount = 0
self.go = True
# Points between peaks (pbp)
pbp = (float(1)/frequency)/updateInterval
# Figure out how many degrees per update we need to go.
self.step = float(360)/pbp
# Stupid sin function only takes radians... but I think in degrees.
self.degToRad = ( (2*math.pi) / 360 )
def setDac(self):
# calculate the value to put in the sin
value = (self.setDacCount * self.step) * self.degToRad
# Writes the dac.
self.dac = d.writeRegister(5000, 2.5+2*math.sin(value))
# Count measures how many successful updates occurred.
self.count += 1
# Lower the go flag
self.go = False
def handleSetDac(self, signum, frame):
# This function gets called every UPDATE_INTERVAL seconds.
# Raise the go flag.
self.go = True
# setDacCount measures how many times the timer went off.
self.setDacCount += 1
# Create our DacSetter
dacs = DacSetter(FREQUENCY, UPDATE_INTERVAL)
# Set up the signals
signal.signal(signal.SIGALRM, dacs.handleSetDac)
signal.setitimer(signal.ITIMER_REAL, UPDATE_INTERVAL, UPDATE_INTERVAL)
# Run for ~10 seconds. Expect about 2 extra seconds of overhead.
signalcount = int(10/UPDATE_INTERVAL)
# Print the current time, just to let you know something is happening.
print "Start:", datetime.now()
for i in xrange(signalcount):
# Wait for signal to be received
signal.pause()
# If the dacs flag is set, set the dac.
if dacs.go:
dacs.setDac()
# Print the stop time, in case you wanted to know.
print "Stop:", datetime.now()
# Done with the timer, let's turn it off.
signal.setitimer(signal.ITIMER_REAL, 0)
# Print short summary of the difference between how may updates were
# expected and how many occurred.
print "# of Updates = %s, # of signals = %s" % (dacs.count, dacs.setDacCount)
print "The closer the number of updates is to the number of signals, the better your waveform will be."
| 4,045 | 34.80531 | 151 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/Examples/dca10Example.py | """
An example showing how to work with a DCA-10 Motor Controller. More info on the DCA-10 here:
http://labjack.com/support/dca-10/datasheet
See the dca10.py for more information on the DCA10 class.
"""
import dca10
from time import sleep
from time import time
r = raw_input("Do you have an encoder to connect to the LabJack? [y/N] ")
ea = False
if r.lower().strip().startswith('y'):
ea = True
print "Opening device, and configuring it for the DCA-10...",
d = dca10.DCA10(encoderAttached = ea)
print "Done\n"
print "Before we begin, please insure that the DCA-10 is wired to the LabJack as follows:"
print d.wiringDescription()
r = raw_input("Press enter key when ready.")
print "Starting motor at 50%...",
d.startMotor(0.50)
print "Done"
sleep(3)
print "Changing motor direction...",
d.toggleDirection()
print "Done"
sleep(3)
print "Reading current usage...",
usage = d.readCurrent()
print "Done"
print "The current drawn by the DCA-10 is %0.4f Amps" % usage
sleep(3)
print "Increasing motor speed to 100%...",
d.startMotor(1)
print "Done"
sleep(3)
if ea:
print "Measuring RPM...",
a = int(time())
s = d.readEncoder()
sleep(2)
f = d.readEncoder()
b = int(time())
cps = float(f-s)/float(b-a)
cpm = cps * 60
print "Done"
print "Motor spinning at %s CPM (%s Counts Per Second)." % (cpm, cps)
print "Decreasing motor speed to 50%...",
d.startMotor(0.50)
print "Done"
sleep(3)
print "Measuring RPM...",
a = int(time())
s = d.readEncoder()
sleep(2)
f = d.readEncoder()
b = int(time())
cps = float(f-s)/float(b-a)
cpm = cps * 60
print "Done"
print "Motor spinning at %s CPM (%s Counts Per Second)." % (cpm, cps)
sleep(3)
print "Stopping Motor...",
d.stopMotor()
print "Done"
| 1,833 | 18.72043 | 92 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/Examples/PWM-looping.py | """ Runs through the whole range of PWM Duty Cycles
For the complete modbus map, visit the Modbus support page:
http://labjack.com/support/Modbus
Note: Low-level commands that are commented out work only for U6/U3. UE9 is a
little more complicated.
"""
import u3, u6, ue9
from time import sleep
# Open the LabJack. Comment out all but one of these:
d = ue9.UE9()
#d = u3.U3()
#d = u6.U6()
if d.devType == 9:
# Set the timer clock to be the system clock with a given divisor
d.writeRegister(7000, 1)
d.writeRegister(7002, 15)
else:
# Set the timer clock to be 4 MHz with a given divisor
#d.configTimerClock( TimerClockBase = 4, TimerClockDivisor = 15)
d.writeRegister(7000, 4)
d.writeRegister(7002, 15)
# Enable the timer
#d.configIO( NumberTimersEnabled = 1 )
d.writeRegister(50501, 1)
# Configure the timer for PWM, starting with a duty cycle of 0.0015%.
baseValue = 65535
#d.getFeedback( u6.Timer0Config(TimerMode = 0, Value = baseValue) )
d.writeRegister(7100, [0, baseValue])
# Loop, updating the duty cycle every time.
for i in range(65):
currentValue = baseValue - (i * 1000)
dutyCycle = ( float(65536 - currentValue) / 65535 ) * 100
print "Duty Cycle = %s%%" % dutyCycle
#d.getFeedback( u6.Timer0( Value = currentValue, UpdateReset = True ) )
d.writeRegister(7200, currentValue)
sleep(0.3)
print "Duty Cycle = 100%"
#d.getFeedback( u6.Timer0( Value = 0, UpdateReset = True ) )
d.writeRegister(7200, 0)
# Close the device.
d.close | 1,507 | 29.77551 | 77 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/Examples/streamTest-threading.py | """
This example uses Python's built-in threading module to reach faster streaming
speeds than streamTest.py.
On a Ubuntu 9.10 machine with a AMD Athlon(tm) 64 X2 Dual Core Processor 5200+,
we got speeds up to 50kHz.
On a Mac OS 10.6 machine with a 2.53 GHz Intel Core 2 Duo Processor, we got
speeds up to 50kHz.
On a Mac OS 10.5 machine with a 1.42 GHz G4 Processor, we saw max speeds of
about 40kHz.
"""
import u3, u6, LabJackPython
from time import sleep
from datetime import datetime
import struct
import threading
import Queue
import ctypes, copy, sys
# MAX_REQUESTS is the number of packets to be read.
# At high frequencies ( >5 kHz), the number of samples will be MAX_REQUESTS times 48 (packets per request) times 25 (samples per packet)
MAX_REQUESTS = 2500
d = None
################################################################################
## U3
## Uncomment these lines to stream from a U3
################################################################################
#d = u3.U3()
#
## to learn the if the U3 is an HV
#d.configU3()
#
## Set the FIO0 to Analog
#d.configIO(FIOAnalog = 1)
#
#print "configuring U3 stream"
#d.streamConfig( NumChannels = 1, PChannels = [ 0 ], NChannels = [ 31 ], Resolution = 3, SampleFrequency = 50000 )
################################################################################
## U6
## Uncomment these lines to stream from a U6
################################################################################
#d = u6.U6()
#
## For applying the proper calibration to readings.
#d.getCalibrationData()
#
#print "configuring U6 stream"
#d.streamConfig( NumChannels = 1, ChannelNumbers = [ 0 ], ChannelOptions = [ 0 ], SettlingFactor = 1, ResolutionIndex = 1, SampleFrequency = 50000 )
if d is None:
print "Configure a device first.\nPlease open streamTest-threading.py in a text editor and uncomment the lines for your device, starting at about line 16.\n\nExiting..."
sys.exit(0)
class StreamDataReader(object):
def __init__(self, device):
self.device = device
self.data = Queue.Queue()
self.dataCount = 0
self.missed = 0
self.running = False
def readStreamData(self):
self.running = True
start = datetime.now()
self.device.streamStart()
while self.running:
# Calling with convert = False, because we are going to convert in
# the main thread.
returnDict = self.device.streamData(convert = False).next()
self.data.put_nowait(copy.deepcopy(returnDict))
self.dataCount += 1
if self.dataCount > MAX_REQUESTS:
self.running = False
print "stream stopped."
self.device.streamStop()
stop = datetime.now()
total = self.dataCount * self.device.packetsPerRequest * self.device.streamSamplesPerPacket
print "%s requests with %s packets per request with %s samples per packet = %s samples total." % ( self.dataCount, d.packetsPerRequest, d.streamSamplesPerPacket, total )
print "%s samples were lost due to errors." % self.missed
total -= self.missed
print "Adjusted number of samples = %s" % total
runTime = (stop-start).seconds + float((stop-start).microseconds)/1000000
print "The experiment took %s seconds." % runTime
print "%s samples / %s seconds = %s Hz" % ( total, runTime, float(total)/runTime )
sdr = StreamDataReader(d)
sdrThread = threading.Thread(target = sdr.readStreamData)
# Start the stream and begin loading the result into a Queue
sdrThread.start()
errors = 0
missed = 0
while True:
try:
# Check if the thread is still running
if not sdr.running:
break
# Pull results out of the Queue in a blocking manner.
result = sdr.data.get(True, 1)
# If there were errors, print that.
if result['errors'] != 0:
errors += result['errors']
missed += result['missed']
print "+++++ Total Errors: %s, Total Missed: %s" % (errors, missed)
# Convert the raw bytes (result['result']) to voltage data.
r = d.processStreamData(result['result'])
# Do some processing on the data to show off.
print "Average of", len(r['AIN0']), "reading(s):", sum(r['AIN0'])/len(r['AIN0'])
except Queue.Empty:
print "Queue is empty. Stopping..."
sdr.running = False
break
except KeyboardInterrupt:
sdr.running = False
except Exception, e:
print type(e), e
sdr.running = False
break
| 4,718 | 32.707143 | 177 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/Examples/EI1050/ei1050.py | """
Name: EI1050
Desc: A few simple classes to handle communication with the EI1050 probe
"""
import threading
import time
import sys
import u3
import u6
import ue9
class EI1050:
"""
EI1050 class to simplify communication with an EI1050 probe
"""
U3 = 3
U6 = 6
UE9 = 9
U3_STRING = "U3"
U6_STRING = "U6"
UE9_STRING = "UE9"
U3_DEFAULT_DATA_PIN_NUM = 4
U3_DEFAULT_CLOCK_PIN_NUM = 5
U3_DEFAULT_ENABLE_PIN_NUM = 7
U6_DEFAULT_DATA_PIN_NUM = 0
U6_DEFAULT_CLOCK_PIN_NUM = 1
U6_DEFAULT_ENABLE_PIN_NUM = 3
UE9_DEFAULT_DATA_PIN_NUM = 0
UE9_DEFAULT_CLOCK_PIN_NUM = 1
UE9_DEFAULT_ENABLE_PIN_NUM = 3
FIO_PIN_STATE = 0
def __init__(self, device, autoUpdate=True, enablePinNum=-1, dataPinNum = -1, clockPinNum = -1, shtOptions = 0xc0):
self.device = device
self.autoUpdate = autoUpdate
self.dataPinNum = dataPinNum
self.clockPinNum = clockPinNum
self.shtOptions = shtOptions
self.enablePinNum = enablePinNum
self.curState = { 'StatusReg' : None, 'StatusCRC' : None, 'Temperature' : None, 'TemperatureCRC' : None, 'Humidity' : None, 'HumidityCRC' : None }
# Determine device type
if self.device.__class__.__name__ == EI1050.U3_STRING: self.deviceType = EI1050.U3
elif self.device.__class__.__name__ == EI1050.U6_STRING: self.deviceType = EI1050.U6
elif self.device.__class__.__name__ == EI1050.UE9_STRING: self.deviceType = EI1050.UE9
else:
raise TypeError('Invalid device passed. Can not get default values.')
# If not specified otherwise, use class default for the data pin number
if self.enablePinNum == -1:
if self.deviceType == EI1050.U3: self.enablePinNum = EI1050.U3_DEFAULT_ENABLE_PIN_NUM
elif self.deviceType == EI1050.U6: self.enablePinNum = EI1050.U6_DEFAULT_ENABLE_PIN_NUM
elif self.deviceType == EI1050.UE9: self.enablePinNum = EI1050.UE9_DEFAULT_ENABLE_PIN_NUM
else:
raise TypeError('Invalid device passed. Can not get default values.')
# If not specified otherwise, use class default for the data pin number
if self.dataPinNum == -1:
if self.deviceType == EI1050.U3: self.dataPinNum = EI1050.U3_DEFAULT_DATA_PIN_NUM
elif self.deviceType == EI1050.U6: self.dataPinNum = EI1050.U6_DEFAULT_DATA_PIN_NUM
elif self.deviceType == EI1050.UE9: self.dataPinNum = EI1050.UE9_DEFAULT_DATA_PIN_NUM
else:
raise TypeError('Invalid device passed. Can not get default values.')
# If not specified otherwise, use class default for the clock pin number
if self.clockPinNum == -1:
if self.deviceType == EI1050.U3: self.clockPinNum = EI1050.U3_DEFAULT_CLOCK_PIN_NUM
elif self.deviceType == EI1050.U6: self.clockPinNum = EI1050.U6_DEFAULT_CLOCK_PIN_NUM
elif self.deviceType == EI1050.UE9: self.clockPinNum = EI1050.UE9_DEFAULT_CLOCK_PIN_NUM
else:
raise TypeError('Invalid device passed. Can not get default values.')
# Set U3 pins
if self.deviceType == EI1050.U3:
self.device.configIO(FIOAnalog = EI1050.FIO_PIN_STATE)
# Set to write out
if self.deviceType == EI1050.U3: self.device.getFeedback(u3.BitDirWrite(self.enablePinNum,1))
elif self.deviceType == EI1050.U6: self.device.getFeedback(u6.BitDirWrite(self.enablePinNum,1))
def enableAutoUpdate(self):
"""
Name: EI1050.enableAutoUpdate()
Desc: Turns on automatic updating of readings
"""
self.autoUpdate = True
def disableAutoUpdate(self):
"""
Name: EI1050.disableAutoUpdate()
Desc: Truns off automatic updating of readings
"""
self.autoUpdate = False
def getStatus(self):
"""
Name: EI1050.getStatus()
Desc: A read of the SHT1x status register
"""
if self.autoUpdate: self.update()
return self.curState['StatusReg']
def getStatusCRC(self):
"""
Name: EI1050.getStatusCRC()
Desc: Get cyclic reduancy check for status
"""
if self.autoUpdate: self.update()
return self.curState['StatusCRC']
def getTemperature(self):
"""
Name: EI1050.getTemperature()
Desc: Get a temperature reading from the EI1050 probe
"""
if self.autoUpdate: self.update()
return self.curState['Temperature']
def getTemperatureCRC(self):
"""
Name: EI1050.getStatusCRC()
Desc: Get cyclic redundancy check for temperature reading
"""
if self.autoUpdate: self.update()
return self.curState['TemperatureCRC']
def getHumidity(self):
"""
Name: EI1050.getHumidity()
Desc: Get a humidity reading from the EI1050 probe
"""
if self.autoUpdate: self.update()
return self.curState['Humidity']
def getHumidityCRC(self):
"""
Name: EI1050.getHumidityCRC()
Desc: Get cyclic redundancy check for humidity reading
"""
if self.autoUpdate: self.update()
return self.curState['HumidityCRC']
def getReading(self):
"""
Name: EI1050.getReading()
Desc: Get a reading and create a Reading object with the information
"""
if self.autoUpdate: self.update()
if self.curState.has_key('StatusCRC'): return Reading(self.curState['StatusReg'], self.curState['StatusCRC'], self.curState['Temperature'], self.curState['TemperatureCRC'], self.curState['Humidity'], self.curState['HumidityCRC'])
else: return Reading(self.curState['StatusReg'], 0, self.curState['Temperature'], self.curState['TemperatureCRC'], self.curState['Humidity'], self.curState['HumidityCRC'])
def update(self):
"""
Name: EI1050.update()
Desc: Gets a fresh set of readings from this probe
"""
self.writeBitState(self.enablePinNum,1) # Enable the probe
self.curState = self.device.sht1x(self.dataPinNum, self.clockPinNum, self.shtOptions)
self.writeBitState(self.enablePinNum,0) # Disable the probe
def writeBitState(self, pinNum, state):
"""
Name: EI1050.writeBitState(pinNum, state)
Desc: Device independent way to write bit state
"""
if self.deviceType == EI1050.U3: self.device.getFeedback(u3.BitStateWrite(pinNum,state))
elif self.deviceType == EI1050.U6: self.device.getFeedback(u6.BitStateWrite(pinNum,state))
elif self.deviceType == EI1050.UE9: self.device.singleIO(1, pinNum, Dir=1, State=state)
class Reading:
"""
A class that represents a reading taken from an EI1050 probe
"""
def __init__(self, status, statusCRC, temperature, temperatureCRC, humidity, humidityCRC):
self.__status = status
self.__statusCRC = statusCRC
self.__temperature = temperature
self.__temperatureCRC = temperatureCRC
self.__humidity = humidity
self.__humidityCRC = humidityCRC
def getStatus(self):
"""
Name: Reading.getStatus()
Desc: Returns that status of the EI1050 probe at the time of this reading
"""
return self.__status
def getStatusCRC(self):
"""
Name: Reading.getStatusCRC()
Desc: Get the cyclic reduancy check for status at the time of this reading
"""
return self.__statusCRC
def getTemperature(self):
"""
Name: Reading.getTemperature()
Desc: Get the temperature reported by the EI1050 probe at the time of this reading
"""
return self.__temperature
def getTemperatureCRC(self):
"""
Name: Reading.getStatusCRC()
Desc: Get cyclic redundancy check for the temperature reading
"""
return self.__temperatureCRC
def getHumidity(self):
"""
Name: Reading.getHumidity()
Desc: Get the humidity reported by the EI1050 probe at the time of this reading
"""
return self.__humidity
def getHumidityCRC(self):
"""
Name: Reading.getHumidityCRC()
Desc: Get cyclic redundancy check for humidity reading
"""
return self.__humidityCRC
class EI1050Reader(threading.Thread):
"""
A simple threading class to read EI1050 values
"""
def __init__(self, device, targetQueue, readingDelay=1, autoUpdate=True, enablePinNum=-1, dataPinNum = -1, clockPinNum = -1, shtOptions = 0xc0):
try:
self.readingDelay = readingDelay # How long to wait between reads (in sec)
self.targetQueue = targetQueue # The queue in which readings will be placed
self.probe = EI1050(device, autoUpdate, enablePinNum, dataPinNum, clockPinNum, shtOptions)
self.running = False
self.exception = None
threading.Thread.__init__(self, group=None)
except:
self.exception = sys.exc_info()
def stop(self):
"""
Stops this thread's activity. Note: this may not be immediate
"""
self.running = False
def run(self):
self.running = True
while self.running:
try:
self.targetQueue.put(self.probe.getReading())
time.sleep(self.readingDelay)
except:
self.exception = sys.exc_info()
self.stop()
break
| 9,598 | 36.350195 | 237 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/Examples/EI1050/ei1050SampleApp.py | """
Name: ei1050SampleApp
Desc: A simple GUI application to demonstrate the usage of the ei1050 and
LabJack Python modules. For an example of using the Labjack Python module directly
look at the source code of ei1050.py
"""
import sys
from Queue import Queue
from Tkinter import *
import tkMessageBox
try:
import LabJackPython
from u3 import *
from u6 import *
from ue9 import *
from ei1050 import *
except:
tkMessageBox.showerror("Driver error", "The driver could not be imported.\nIf you are on windows, please install the UD driver from www.labjack.com")
class MainWindow:
"""
The main window of the application
"""
FONT_SIZE = 10
FIO_PIN_STATE = 0 # for u3
FONT = "Arial"
def __init__(self):
# Basic setup
self.window = Tk()
self.window.title("EI1050 Sample Application")
self.readingsFrame = Frame(height=500, width=2000, bd=1, relief=SUNKEN)
self.readingsFrame.pack(side=LEFT)
self.buttonsFrame = Frame(height=500, width=500, bd=1, relief=SUNKEN)
self.buttonsFrame.pack(side=RIGHT)
# Readings frame
Label(self.readingsFrame, text="Device Serial Number:", font=(MainWindow.FONT, MainWindow.FONT_SIZE)).grid(row=0, column=0, sticky=W, padx=1, pady=1)
Label(self.readingsFrame, text="Temperature:", font=(MainWindow.FONT, MainWindow.FONT_SIZE)).grid(row=1, column=0, sticky=W, padx=1, pady=1)
Label(self.readingsFrame, text="Humidity:", font=(MainWindow.FONT, MainWindow.FONT_SIZE)).grid(row=2, column=0, sticky=W, padx=1, pady=1)
Label(self.readingsFrame, text="Probe Status:", font=(MainWindow.FONT, MainWindow.FONT_SIZE)).grid(row=3, column=0,sticky=W, padx=1, pady=1)
Label(self.readingsFrame, text="(c) 2009 Labjack Corp. ", font=(MainWindow.FONT, MainWindow.FONT_SIZE)).grid(row=4, column=0, columnspan=2, sticky=W, padx=1, pady=1)
self.serialDisplay = Label(self.readingsFrame, text="", font=(MainWindow.FONT, MainWindow.FONT_SIZE))
self.serialDisplay.grid(row=0, column=1, sticky=W, padx=1, pady=1)
self.tempDisplay = Label(self.readingsFrame, text="", font=(MainWindow.FONT, MainWindow.FONT_SIZE))
self.tempDisplay.grid(row=1, column=1, sticky=W, padx=1, pady=1)
self.humidDisplay = Label(self.readingsFrame, text="", font=(MainWindow.FONT, MainWindow.FONT_SIZE))
self.humidDisplay.grid(row=2, column=1, sticky=W, padx=1, pady=1)
self.statusDisplay = Label(self.readingsFrame, text="", font=(MainWindow.FONT, MainWindow.FONT_SIZE))
self.statusDisplay.grid(row=3, column=1, sticky=W, padx=1, pady=1)
# Buttons frame
self.startButton = Button(self.buttonsFrame, text="Start", command=self.start, font=(MainWindow.FONT, MainWindow.FONT_SIZE))
self.startButton.grid(row=0, column=0)
Label(self.readingsFrame, text="", font=(MainWindow.FONT, MainWindow.FONT_SIZE)).grid(row=2, column=0)
self.instructionsButton = Button(self.buttonsFrame, text="Instructions", command=self.showInstructions, font=(MainWindow.FONT, MainWindow.FONT_SIZE))
self.instructionsButton.grid(row=2, column=0)
#self.deviceSelection = StringVar(self.window)
#self.deviceSelection.set("U3")
#OptionMenu(self.buttonsFrame, self.deviceSelection, "U3", "U6", "UE9").grid(row=2, column=0)
# Ensure the exsistance of a thread, queue, and device variable
self.targetQueue = Queue()
self.thread = None
self.device = None
# Determine if we are reading data
self.reading = False
# Start mainloop
self.window.protocol("WM_DELETE_WINDOW", self.close)
self.window.mainloop()
def start(self):
"""
Name:MainWindow.start()
Desc:Starts reading values from EI1050 probe
"""
try:
# Get device selection
#if self.deviceSelection.get() == "U3": self.device = U3()
#elif self.deviceSelection.get() == "U6": self.device = U6()
#else: self.device = UE9()
if len(LabJackPython.listAll(3)) > 0: self.device = U3()
elif len(LabJackPython.listAll(6)) > 0: self.device = U6()
else: self.device = UE9()
self.serialDisplay.config(text=self.device.serialNumber)
#if self.deviceSelection.get() == "U6" or self.deviceSelection.get() == "U3": self.device.setToFactoryDefaults()
#if len(LabJackPython.listAll(3)) > 0:
# print MainWindow.FIO_PIN_STATE
# self.device.configU3(FIOAnalog = MainWindow.FIO_PIN_STATE)
# Create and start the thread
self.thread = EI1050Reader(self.device, self.targetQueue)
# Start scheduleing
self.window.after(1000,self.updateLabels)
self.thread.start()
# Change button
self.startButton.config(text="Stop", command=self.stop)
except:
showErrorWindow(sys.exc_info()[0], sys.exc_info()[1])
def stop(self):
"""
Name:MainWindow.stop()
Desc: Stops reading values from EI1050 probe
"""
self.thread.stop()
self.thread.join()
self.device.close()
self.startButton.config(text="Start", command=self.start)
def updateLabels(self):
"""
Name:MainWindow.updateLabels()
Desc: Gets the latest reading from the readings queue and display it
"""
# Check for errors
if self.thread.exception != None:
showErrorWindow(self.thread.exception[0], self.thread.exception[1])
else:
# Change out the display
latestReading = None
while not self.targetQueue.empty():
latestReading = self.targetQueue.get()
if latestReading != None:
self.tempDisplay.config(text = str(latestReading.getTemperature()) + " deg C")
self.humidDisplay.config(text = str(latestReading.getHumidity()) + " %")
self.statusDisplay.config(text = str(latestReading.getStatus()))
self.window.after(1000,self.updateLabels)
def showInstructions(self):
tkMessageBox.showinfo("Instructions", '''U3 SHT configured with pins as follows:
Green(Data) -- FIO4
White(Clock) -- FIO5
Black(GND) -- GND
Red(Power) -- FIO7
Brown(Enable) -- FIO7
U6/UE9 SHT configured with pins as follows:
Green(Data) -- FIO0
White(Clock) -- FIO1
Black(GND) -- GND
Red(Power) -- FIO3
Brown(Enable) -- FIO3''')
def close(self):
try:
if self.thread != None:
self.thread.stop()
self.thread.join()
if self.device != None:
self.device.close()
except: print "error terminating app"
finally:
self.window.destroy()
def showErrorWindow(title, info):
"""
Name:showErrorWindow()
Desc:Shows an error popup for last exception encountered
"""
tkMessageBox.showerror(title, str(info) + "\n\nPlease check your wiring. If you need help, click instructions.")
MainWindow()
| 7,336 | 40.925714 | 197 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/Examples/LJTickDAC/LJTickDAC.py | """
Name: LJTickDAC
Desc: A simple GUI application to demonstrate the usage of the I2C and
LabJack Python modules to set the value of DACA and DACB in a LJ-TickDAC
"""
import time
import sys
from threading import Thread
from Tkinter import *
import tkMessageBox
# Attempt to load the labjack driver
try:
import LabJackPython
from u3 import *
from u6 import *
from ue9 import *
except:
tkMessageBox.showerror("Driver error", "The driver could not be imported.\nIf you are on windows, please install the UD driver from www.labjack.com")
sys.exit()
def toDouble(buffer):
"""
Name: toDouble(buffer)
Args: buffer, an array with 8 bytes
Desc: Converts the 8 byte array into a floating point number.
"""
if type(buffer) == type(''):
bufferStr = buffer[:8]
else:
bufferStr = ''.join(chr(x) for x in buffer[:8])
dec, wh = struct.unpack('<Ii', bufferStr)
return float(wh) + float(dec)/2**32
class LJTickDAC(Tk):
"""
Name: LJTickDAC
Desc: A simple GUI application to demonstrate the usage of the I2C and
LabJack Python modules to set the value of DACA and DACB in a LJ-TickDAC
"""
U3 = 3
U6 = 6
UE9 = 9
AUTO = 0
FONT_SIZE = 10
FONT = "Arial"
AIN_PIN_DEFAULT = -1 # AIN must be configured
DAC_PIN_DEFAULT = 0
U3_DAC_PIN_OFFSET = 4
EEPROM_ADDRESS = 0x50
DAC_ADDRESS = 0x12
def __init__(self):
# Create the window
Tk.__init__(self)
self.title("LJTickDAC")
# Create and place labels
Label(self, text="Serial Num:", font=(LJTickDAC.FONT, LJTickDAC.FONT_SIZE)).grid(row=0, column=0, sticky=W)
self.serialDisplay = Label(self, font=(LJTickDAC.FONT, LJTickDAC.FONT_SIZE), text="please wait...",)
self.serialDisplay.grid(row=0, column=1, sticky=W)
Label(self, text="DAC A:", font=(LJTickDAC.FONT, LJTickDAC.FONT_SIZE)).grid(row=1, column=0, sticky=W)
Label(self, text="DAC B:", font=(LJTickDAC.FONT, LJTickDAC.FONT_SIZE)).grid(row=2, column=0, sticky=W)
self.ainALabel = Label(self, text="AIN:", font=(LJTickDAC.FONT, LJTickDAC.FONT_SIZE))
self.ainALabel.grid(row=3, column=0, sticky=W)
self.ainDisplay = Label(self, text="not configured", font=(LJTickDAC.FONT, LJTickDAC.FONT_SIZE))
self.ainDisplay.grid(row=3, column=1, sticky=W)
# Create and place entry boxes
self.dacAEntry = Entry(self, font=(LJTickDAC.FONT, LJTickDAC.FONT_SIZE))
self.dacAEntry.grid(row=1, column=1, sticky=E+W)
self.dacBEntry = Entry(self, font=(LJTickDAC.FONT, LJTickDAC.FONT_SIZE))
self.dacBEntry.grid(row=2, column=1, sticky=E+W)
# Create and place buttons
Button(self, text="Setup", command=self.showSetup, font=(LJTickDAC.FONT, LJTickDAC.FONT_SIZE)).grid(row=4, column=0, sticky=W)
Button(self, text="Apply Changes", font=(LJTickDAC.FONT, LJTickDAC.FONT_SIZE), comman=self.updateDevice).grid(row=4, column=1, sticky=E+W)
Label(self, text="(c) 2009 Labjack Corp. ", font=(LJTickDAC.FONT, LJTickDAC.FONT_SIZE)).grid(row=5, column=0, columnspan=2, sticky=W, padx=1, pady=1)
# Set defaults
self.ainPin = LJTickDAC.AIN_PIN_DEFAULT
self.dacPin = LJTickDAC.DAC_PIN_DEFAULT
# Create a variable for the ain read thread
self.ainReadThread = None
# load the devices
self.loadFirstDevice()
# Organize cleanup
self.protocol("WM_DELETE_WINDOW", self.cleanUp)
# Show settings window
self.searchForDevices()
settingsWindow = SettingsWindow(self, self.deviceType, self.dacPin, self.ainPin, self.u3Available, self.u6Available, self.ue9Available)
try: settingsWindow.attributes('-topmost', True)
except: pass
def updateDevice(self):
"""
Name: updateDevice()
Desc: Changes DACA and DACB to the amounts specified by the user
"""
# Determine pin numbers
if self.deviceType == self.U3:
sclPin = self.dacPin + LJTickDAC.U3_DAC_PIN_OFFSET
sdaPin = sclPin + 1
else:
sclPin = self.dacPin
sdaPin = sclPin + 1
# Get voltage for DACA
try:voltageA = float(self.dacAEntry.get())
except:
self.showErrorWindow("Invalid entry", "Please enter a numerical value for DAC A")
return
# Get voltage DACB
try:voltageB = float(self.dacBEntry.get())
except:
self.showErrorWindow("Invalid entry", "Please enter a numerical value for DAC B")
return
# Make requests
try:
self.device.i2c(LJTickDAC.DAC_ADDRESS, [48, int(((voltageA*self.aSlope)+self.aOffset)/256), int(((voltageA*self.aSlope)+self.aOffset)%256)], SDAPinNum = sdaPin, SCLPinNum = sclPin)
self.device.i2c(LJTickDAC.DAC_ADDRESS, [49, int(((voltageB*self.bSlope)+self.bOffset)/256), int(((voltageB*self.bSlope)+self.bOffset)%256)], SDAPinNum = sdaPin, SCLPinNum = sclPin)
except:
self.showErrorWindow("I2C Error", "Whoops! Something went wrong when setting the LJTickDAC. Is the device detached?\n\nPython error:" + str(sys.exc_info()[1]))
self.showSetup()
def searchForDevices(self):
"""
Name: searchForDevices()
Desc: Determines which devices are available
"""
self.u3Available = len(LabJackPython.listAll(LJTickDAC.U3)) > 0
self.u6Available = len(LabJackPython.listAll(LJTickDAC.U6)) > 0
self.ue9Available = len(LabJackPython.listAll(LJTickDAC.UE9)) > 0
def loadFirstDevice(self):
"""
Name: loadFirstDevice()
Desc: Determines which devices are available and loads the first one found
"""
try:
self.searchForDevices()
# Determine which device to use
if self.u3Available: self.deviceType = LJTickDAC.U3
elif self.u6Available: self.deviceType = LJTickDAC.U6
elif self.ue9Available: self.deviceType = LJTickDAC.UE9
else:
self.showErrorWindow("Fatal Error", "No LabJacks were found to be connected to your computer.\nPlease check your wiring and try again.")
sys.exit()
self.loadDevice(self.deviceType)
except:
self.showErrorWindow("Fatal Error - First Load", "Python error:" + str(sys.exc_info()[1]))
sys.exit()
def loadDevice(self, deviceType):
"""
Name: loadDevice(deviceType)
Desc: loads the first device of device type
"""
self.deviceType = deviceType
# Determine which device to use
if self.deviceType == LJTickDAC.U3: self.device = U3()
elif self.deviceType == LJTickDAC.U6: self.device = U6()
else: self.device = UE9()
# Display serial number
self.serialDisplay.config(text=self.device.serialNumber)
# Configure pins if U3
if self.deviceType == LJTickDAC.U3:
self.device.configIO(FIOAnalog=15, TimerCounterPinOffset=8) # Configures FIO0-2 as analog
# Get the calibration constants
self.getCalConstants()
def showSetup(self):
"""
Name: showSetup()
Desc: Display the settings window
"""
self.searchForDevices()
SettingsWindow(self, self.deviceType, self.dacPin, self.ainPin, self.u3Available, self.u6Available, self.ue9Available)
def showErrorWindow(self, title, info):
"""
Name:showErrorWindow(title, info)
Desc:Shows an error popup for last exception encountered
"""
tkMessageBox.showerror(title, str(info))
def updateSettings(self, deviceType, ainPin, dacPin):
"""
Name: updateSettings(deviceType, ainPin, dacPin)
Desc: updates the configuration of the application
"""
try:
if self.ainReadThread != None: self.ainReadThread.stop()
self.device.close()
self.ainPin = ainPin
self.dacPin = dacPin
self.loadDevice(deviceType)
if ainPin != -1: # AIN is configured
self.ainReadThread = AINReadThread(self.ainDisplay, self.device, self.deviceType, self.ainPin)
self.ainReadThread.start()
else:
self.ainDisplay.config(text="disabled")
except:
self.showErrorWindow("Update Settings Error", "Python error:" + str(sys.exc_info()[1]))
sys.exit()
def cleanUp(self):
"""
Name: cleanUp()
Desc: Closes devices, terminates threads, and closes windows
"""
if self.ainReadThread != None: self.ainReadThread.stop()
if self.device != None: self.device.close()
self.destroy()
def getCalConstants(self):
"""
Name: getCalConstants()
Desc: Loads or reloads the calibration constants for the LJTic-DAC
See datasheet for more info
"""
# Determine pin numbers
if self.deviceType == LJTickDAC.U3:
sclPin = self.dacPin + LJTickDAC.U3_DAC_PIN_OFFSET
sdaPin = sclPin + 1
else:
sclPin = self.dacPin
sdaPin = sclPin + 1
# Make request
data = self.device.i2c(LJTickDAC.EEPROM_ADDRESS, [64], NumI2CBytesToReceive=36, SDAPinNum = sdaPin, SCLPinNum = sclPin)
response = data['I2CBytes']
self.aSlope = toDouble(response[0:8])
self.aOffset = toDouble(response[8:16])
self.bSlope = toDouble(response[16:24])
self.bOffset = toDouble(response[24:32])
if 255 in response: self.showErrorWindow("Pins", "The calibration constants seem a little off. Please go into settings and make sure the pin numbers are correct and that the LJTickDAC is properly attached.")
class SettingsWindow(Toplevel):
"""
Name: SettingsWindow
Desc: A dialog window that allows the user to set the pins and device
used by the application.
"""
FONT_SIZE = 12
FONT = "Arial"
def __init__(self, parent, currentDevice, currentDACPin, currentAINPin, u3Available, u6Available, ue9Available):
# Create window
Toplevel.__init__(self, parent)
self.title("Setup")
self.parent = parent
# Create and place labels
Label(self, text="Device:", font=(LJTickDAC.FONT, LJTickDAC.FONT_SIZE)).grid(row=0, column=0, sticky=W)
Label(self, text="DAC Pins:", font=(LJTickDAC.FONT, LJTickDAC.FONT_SIZE)).grid(row=1, column=0, sticky=W)
Label(self, text="AIN Pins:", font=(LJTickDAC.FONT, LJTickDAC.FONT_SIZE)).grid(row=2, column=0, sticky=W)
Label(self, text="Notice: Settings only take effect after clicking apply. AIN pins are provided for testing.").grid(row=4, column=0, columnspan=2)
# Create and place radio buttons for the device
self.deviceVar = IntVar()
self.deviceVar.set(currentDevice)
deviceFrame = Frame(self)
u3Radio = Radiobutton(deviceFrame, text="U3", variable=self.deviceVar, value=LJTickDAC.U3, font=(SettingsWindow.FONT, SettingsWindow.FONT_SIZE), command=self.adjustText)
u3Radio.grid(row=0, column=0)
if not u3Available: u3Radio.config(state=DISABLED)
u6Radio = Radiobutton(deviceFrame, text="U6", variable=self.deviceVar, value=LJTickDAC.U6, font=(SettingsWindow.FONT, SettingsWindow.FONT_SIZE), command=self.adjustText)
u6Radio.grid(row=0, column=1)
if not u6Available: u6Radio.config(state=DISABLED)
ue9Radio = Radiobutton(deviceFrame, text="UE9", variable=self.deviceVar, value=LJTickDAC.UE9, font=(SettingsWindow.FONT, SettingsWindow.FONT_SIZE), command=self.adjustText)
ue9Radio.grid(row=0, column=2)
if not ue9Available: ue9Radio.config(state=DISABLED)
deviceFrame.grid(row=0, column=1, sticky=E+W)
# Create and place radio buttons for the dac pins
self.dacPin = IntVar()
self.dacPin.set(currentDACPin)
dacPinFrame = Frame(self)
self.dacOptARadio = Radiobutton(dacPinFrame, text="FIO 0/1", variable=self.dacPin, value=0, font=(SettingsWindow.FONT, SettingsWindow.FONT_SIZE))
self.dacOptARadio.grid(row=0, column=0)
self.dacOptBRadio = Radiobutton(dacPinFrame, text="FIO 2/3", variable=self.dacPin, value=2, font=(SettingsWindow.FONT, SettingsWindow.FONT_SIZE))
self.dacOptBRadio.grid(row=0, column=1)
dacPinFrame.grid(row=1, column=1, sticky=E+W)
# Create and place the radio buttons for the ain pins
self.ainPin = IntVar()
self.ainPin.set(currentAINPin)
ainPinFrame = Frame(self)
Radiobutton(ainPinFrame, text="None", variable=self.ainPin, value=-1, font=(SettingsWindow.FONT, SettingsWindow.FONT_SIZE)).grid(row=0, column=0)
self.ainOptARadio = Radiobutton(ainPinFrame, text="AIN 0", variable=self.ainPin, value=0, font=(SettingsWindow.FONT, SettingsWindow.FONT_SIZE))
self.ainOptARadio.grid(row=0, column=1)
self.ainOptBRadio = Radiobutton(ainPinFrame, text="AIN 2", variable=self.ainPin, value=2, font=(SettingsWindow.FONT, SettingsWindow.FONT_SIZE))
self.ainOptBRadio.grid(row=0, column=2)
ainPinFrame.grid(row=2, column=1, sticky=E+W)
# Create and place apply and cancel buttons
buttonsFrame = Frame(self)
Button(buttonsFrame, text="Apply", command=self.applyChanges, font=(SettingsWindow.FONT, SettingsWindow.FONT_SIZE)).grid(row=0, column=0)
#Button(buttonsFrame, text="Cancel", font=(SettingsWindow.FONT, SettingsWindow.FONT_SIZE)).grid(row=0, column=1)
buttonsFrame.grid(row=3, column=0, columnspan=2, sticky=E+W)
# Adjust text for device and prepare for future adjustments
self.adjustText()
def adjustText(self):
"""
Name: adjustText()
Desc: Adjusts the text of the radio buttons depending on the device type selected
"""
deviceType = self.deviceVar.get()
if deviceType == LJTickDAC.U3:
self.dacOptARadio.config(text="FIO 4/5")
self.dacOptBRadio.config(text="FIO 6/7")
self.ainOptARadio.config(text="AIN/FIO 0")
self.ainOptBRadio.config(text="AIN/FIO 2")
else:
self.dacOptARadio.config(text="FIO 0/1")
self.dacOptBRadio.config(text="FIO 2/3")
self.ainOptARadio.config(text="AIN 0")
self.ainOptBRadio.config(text="AIN 2")
def applyChanges(self):
"""
Name: applyChanges()
Desc: applys the changes to the application and closes the window
"""
self.parent.updateSettings(self.deviceVar.get(), self.ainPin.get(), self.dacPin.get())
self.destroy()
class AINReadThread(Thread):
"""
Name: AINReadThread
Desc: A thread that reads from a given analog input every secound and updates a GUI
"""
def __init__(self, displayLabel, device, deviceType, pinNum):
Thread.__init__(self)
self.displayLabel = displayLabel
self.device = device
self.pinNum = pinNum
self.deviceType = deviceType
def stop(self):
"""
Name: stop()
Desc: Stops this thread
"""
self.running = False
def run(self):
"""
Name: run()
Desc: Starts this thread
"""
try:
self.running = True
while self.running:
if self.deviceType == LJTickDAC.UE9:
# See section 2.7.2 until better calibartion is applied
voltage = self.device.feedback(AINMask=5)['AIN'+str(self.pinNum)]/65536.0*5
elif self.deviceType == LJTickDAC.U3:
voltage = self.device.getAIN(self.pinNum)
else: voltage = self.device.getAIN(self.pinNum)
self.displayLabel.config(text=str(voltage))
time.sleep(1)
except:
self.displayLabel.config(text="AIN read error. Device detached?\nClick \"Setup\" to start again...")
# Create application
LJTickDAC().mainloop()
| 16,296 | 40.894602 | 215 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/build/lib/ue9.py | """
Name: ue9.py
Desc: Defines the UE9 class, which makes working with a UE9 much easier. All of
the low-level functions for the UE9 are implemented as functions of the
UE9 class. There are also a handful additional functions which improve
upon the interface provided by the low-level functions.
To learn about the low-level functions, please see Section 5.2 of the UE9 User's Guide:
http://labjack.com/support/ue9/users-guide/5.2
"""
from LabJackPython import *
import struct, socket, select, ConfigParser
def openAllUE9():
"""
A helpful function which will open all the connected UE9s. Returns a
dictionary where the keys are the serialNumber, and the value is the device
object.
"""
returnDict = dict()
for i in range(deviceCount(9)):
d = UE9(firstFound = False, devNumber = i+1)
returnDict[str(d.serialNumber)] = d
return returnDict
def parseIpAddress(bytes):
return "%s.%s.%s.%s" % (bytes[3], bytes[2], bytes[1], bytes[0] )
def unpackInt(bytes):
return struct.unpack("<I", struct.pack("BBBB", *bytes))[0]
def unpackShort(bytes):
return struct.unpack("<H", struct.pack("BB", *bytes))[0]
DEFAULT_CAL_CONSTANTS = { "AINSlopes" : { '0' : 0.000077503, '1' : 0.000038736, '2' : 0.000019353, '3' : 0.0000096764, '8' : 0.00015629 }, "AINOffsets" : { '0' : -0.012000, '1' : -0.012000, '2' : -0.012000, '3' : -0.012000, '8' : -5.1760 }, "TempSlope" : 0.012968 }
class UE9(Device):
"""
UE9 Class for all UE9 specific low-level commands.
Example:
>>> import ue9
>>> d = ue9.UE9()
>>> print d.commConfig()
{'CommFWVersion': '1.47', ..., 'IPAddress': '192.168.1.114'}
"""
def __init__(self, debug = False, autoOpen = True, **kargs):
"""
Name: UE9.__init__(self)
Args: debug, True for debug information
Desc: Your basic constructor.
>>> myUe9 = ue9.UE9()
"""
Device.__init__(self, None, devType = 9)
self.debug = debug
self.calData = None
self.controlFWVersion = self.commFWVersion = None
if autoOpen:
self.open(**kargs)
def open(self, firstFound = True, serial = None, ipAddress = None, localId = None, devNumber = None, ethernet=False, handleOnly = False, LJSocket = None):
"""
Name: UE9.open(firstFound = True, ipAddress = None, localId = None, devNumber = None, ethernet=False)
Args: firstFound, Open the first found UE9
serial, open a UE9 with the given serial number.
ipAddress, Specify the IP Address of the UE9 you want to open
localId, Specify the localId of the UE9 you want to open
devNumber, Specify the USB dev number of the UE9
ethernet, set to true to connect over ethernet.
handleOnly, if True, LabJackPython will only open a handle
LJSocket, set to "<ip>:<port>" to connect to LJSocket
Desc: Opens the UE9.
>>> myUe9 = ue9.UE9(autoOpen = False)
>>> myUe9.open()
"""
Device.open(self, 9, Ethernet = ethernet, firstFound = firstFound, serial = serial, localId = localId, devNumber = devNumber, ipAddress = ipAddress, handleOnly = handleOnly, LJSocket = LJSocket)
def commConfig(self, LocalID = None, IPAddress = None, Gateway = None, Subnet = None, PortA = None, PortB = None, DHCPEnabled = None):
"""
Name: UE9.commConfig(LocalID = None, IPAddress = None, Gateway = None,
Subnet = None, PortA = None, PortB = None, DHCPEnabled = None)
Args: LocalID, Set the LocalID
IPAddress, Set the IPAdress
Gateway, Set the Gateway
Subnet, Set the Subnet
PortA, Set Port A
PortB, Set Port B
DHCPEnabled, True = Enabled, False = Disabled
Desc: Writes and reads various configuration settings associated
with the Comm processor. Section 5.2.1 of the User's Guide.
>>> myUe9 = ue9.UE9()
>>> myUe9.commConfig()
{'CommFWVersion': '1.47',
'DHCPEnabled': False,
'Gateway': '192.168.1.1',
'HWVersion': '1.10',
'IPAddress': '192.168.1.114',
'LocalID': 1,
'MACAddress': 'XX:XX:XX:XX:XX:XX',
'PortA': 52360,
'PortB': 52361,
'PowerLevel': 0,
'ProductID': 9,
'SerialNumber': 27121XXXX,
'Subnet': '255.255.255.0'}
"""
command = [ 0 ] * 38
#command[0] = Checksum8
command[1] = 0x78
command[2] = 0x10
command[3] = 0x01
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
#command[6] = Writemask. Set it along the way.
#command[7] = Reserved
if LocalID != None:
command[6] |= 1
command[8] = LocalID
if IPAddress != None:
command[6] |= (1 << 2)
ipbytes = IPAddress.split('.')
ipbytes = [ int(x) for x in ipbytes ]
ipbytes.reverse()
command[10:14] = ipbytes
if Gateway != None:
command[6] |= (1 << 3)
gwbytes = Gateway.split('.')
gwbytes = [ int(x) for x in gwbytes ]
gwbytes.reverse()
command[14:18] = gwbytes
if Subnet != None:
command[6] |= (1 << 4)
snbytes = Subnet.split('.')
snbytes = [ int(x) for x in snbytes ]
snbytes.reverse()
command[18:21] = snbytes
if PortA != None:
command[6] |= (1 << 5)
t = struct.pack("<H", PortA)
command[22] = ord(t[0])
command[23] = ord(t[1])
if PortB != None:
command[6] |= (1 << 5)
t = struct.pack("<H", PortB)
command[24] = ord(t[0])
command[25] = ord(t[1])
if DHCPEnabled != None:
command[6] |= (1 << 6)
if DHCPEnabled:
command[26] = 1
result = self._writeRead(command, 38, [], checkBytes = False)
if result[0] == 0xB8 and result[1] == 0xB8:
raise LabJackException("Device detected a bad checksum.")
elif result[1:4] != [ 0x78, 0x10, 0x01 ]:
raise LabJackException("Got incorrect command bytes.")
elif not verifyChecksum(result):
raise LabJackException("Checksum was incorrect.")
self.localId = result[8]
self.powerLevel = result[9]
self.ipAddress = parseIpAddress(result[10:14])
self.gateway = parseIpAddress(result[14:18])
self.subnet = parseIpAddress(result[18:22])
self.portA = struct.unpack("<H", struct.pack("BB", *result[22:24]))[0]
self.portB = struct.unpack("<H", struct.pack("BB", *result[24:26]))[0]
self.DHCPEnabled = bool(result[26])
self.productId = result[27]
macBytes = result[28:34]
self.macAddress = "%02X:%02X:%02X:%02X:%02X:%02X" % (result[33], result[32], result[31], result[30], result[29], result[28])
self.serialNumber = struct.unpack("<I", struct.pack("BBBB", result[28], result[29], result[30], 0x10))[0]
self.hwVersion = "%s.%02d" % (result[35], result[34])
self.commFWVersion = "%s.%02d" % (result[37], result[36])
self.firmwareVersion = [self.controlFWVersion, self.commFWVersion]
return { 'LocalID' : self.localId, 'PowerLevel' : self.powerLevel, 'IPAddress' : self.ipAddress, 'Gateway' : self.gateway, 'Subnet' : self.subnet, 'PortA' : self.portA, 'PortB' : self.portB, 'DHCPEnabled' : self.DHCPEnabled, 'ProductID' : self.productId, 'MACAddress' : self.macAddress, 'HWVersion' : self.hwVersion, 'CommFWVersion' : self.commFWVersion, 'SerialNumber' : self.serialNumber}
def flushBuffer(self):
"""
Name: UE9.flushBuffer()
Args: None
Desc: Resets the pointers to the stream buffer to make it empty.
>>> myUe9 = ue9.UE9()
>>> myUe9.flushBuffer()
"""
command = [ 0x08, 0x08 ]
self._writeRead(command, 2, [], False)
def discoveryUDP(self):
"""
Name: UE9.discoveryUDP()
Args: None
Desc: Sends a UDP Broadcast packet and returns a dictionary of the
result. The dictionary contains all the things that are in the
commConfig dictionary.
>>> myUe9 = ue9.UE9()
>>> myUe9.discoveryUDP()
{'192.168.1.114': {'CommFWVersion': '1.47', ... },
'192.168.1.209': {'CommFWVersion': '1.47', ... }}
"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
host = '255.255.255.255'
port = 52362
addr = (host,port)
sndBuffer = [0] * 6
sndBuffer[0] = 0x22
sndBuffer[1] = 0x78
sndBuffer[2] = 0x00
sndBuffer[3] = 0xA9
sndBuffer[4] = 0x00
sndBuffer[5] = 0x00
packFormat = "B" * len(sndBuffer)
tempString = struct.pack(packFormat, *sndBuffer)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.sendto(tempString, addr)
inputs = [s]
ue9s = {}
listen = True
while listen:
#We will wait 2 seconds for a response from a Ue9
rs,ws,es = select.select(inputs, [], [], 1)
listen = False
for r in rs:
if r is s:
data,addr = s.recvfrom(38)
ue9s[addr[0]] = data
listen = True
s.close()
for ip, data in ue9s.items():
data = list(struct.unpack("B"*38, data))
ue9 = { 'LocalID' : data[8], 'PowerLevel' : data[9] , 'IPAddress' : parseIpAddress(data[10:14]), 'Gateway' : parseIpAddress(data[14:18]), 'Subnet' : parseIpAddress(data[18:23]), 'PortA' : struct.unpack("<H", struct.pack("BB", *data[22:24]))[0], 'PortB' : struct.unpack("<H", struct.pack("BB", *data[24:26]))[0], 'DHCPEnabled' : bool(data[26]), 'ProductID' : data[27], 'MACAddress' : "%02X:%02X:%02X:%02X:%02X:%02X" % (data[33], data[32], data[31], data[30], data[29], data[28]), 'SerialNumber' : struct.unpack("<I", struct.pack("BBBB", data[28], data[29], data[30], 0x10))[0], 'HWVersion' : "%s.%02d" % (data[35], data[34]), 'CommFWVersion' : "%s.%02d" % (data[37], data[36])}
ue9s[ip] = ue9
return ue9s
def controlConfig(self, PowerLevel = None, FIODir = None, FIOState = None, EIODir = None, EIOState = None, CIODirection = None, CIOState = None, MIODirection = None, MIOState = None, DoNotLoadDigitalIODefaults = None, DAC0Enable = None, DAC0 = None, DAC1Enable = None, DAC1 = None):
"""
Name: UE9.controlConfig(PowerLevel = None, FIODir = None,
FIOState = None, EIODir = None,
EIOState = None, CIODirection = None, CIOState = None,
MIODirection = None, MIOState = None,
DoNotLoadDigitalIODefaults = None, DAC0Enable = None,
DAC0 = None, DAC1Enable = None, DAC1 = None)
Args: PowerLevel, 0 = Fixed High, 48 MHz, 1 = Fixed low, 6 MHz
FIODir, Direction of FIOs
FIOState, State of FIOs
EIODir, Direction of EIOs
EIOState, State of EIOs
CIODirection, Direction of CIOs (max of 4)
CIOState, State of CIOs (max of 4)
MIODirection, Direction of MIOs (max of 3)
MIOState, Direction of MIOs (max of 3)
DoNotLoadDigitalIODefaults, Set True, to not load the defaults
DAC0Enable, True = DAC0 Enabled, False = DAC0 Disabled
DAC0, The default value for DAC0
DAC1Enable, True = DAC1 Enabled, False = DAC1 Disabled
DAC1, The default value for DAC1
Desc: Configures various parameters associated with the Control
processor. Affects only the power-up values, not current
state. See section 5.3.2 of the User's Guide.
>>> myUe9 = ue9.UE9()
>>> myUe9.controlConfig()
{'CIODirection': 0,
'CIOState': 0,
'ControlBLVersion': '1.12',
'ControlFWVersion': '1.97',
'DAC0': 0,
'DAC0 Enabled': False,
'DAC1': 0,
'DAC1 Enabled': False,
'EIODir': 0,
'EIOState': 0,
'FIODir': 0,
'FIOState': 0,
'HiRes Flag': False,
'MIODirection': 0,
'MIOState': 0,
'PowerLevel': 0,
'ResetSource': 119}
"""
command = [ 0 ] * 18
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x06
command[3] = 0x08
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
#command[6] = Writemask. Set it along the way.
if PowerLevel != None:
command[6] |= 1
command[7] = PowerLevel
if FIODir != None:
command[6] |= (1 << 1)
command[8] = FIODir
if FIOState != None:
command[6] |= (1 << 1)
command[9] = FIOState
if EIODir != None:
command[6] |= (1 << 1)
command[10] = EIODir
if EIOState != None:
command[6] |= (1 << 1)
command[11] = EIOState
if CIODirection != None:
command[6] |= (1 << 1)
command[12] = ( CIODirection & 0xf) << 4
if CIOState != None:
command[6] |= (1 << 1)
command[12] |= ( CIOState & 0xf )
if DoNotLoadDigitalIODefaults != None:
command[6] |= (1 << 1)
if DoNotLoadDigitalIODefaults:
command[13] |= (1 << 7)
if MIODirection != None:
command[6] |= (1 << 1)
command[13] |= ( MIODirection & 7 ) << 4
if MIOState != None:
command[6] |= (1 << 1)
command[13] |= ( MIOState & 7 )
if DAC0Enable != None:
command[6] |= (1 << 2)
if DAC0Enable:
command[15] = (1 << 7)
if DAC0 != None:
command[6] |= (1 << 2)
command[14] = DAC0 & 0xff
command[15] |= (DAC0 >> 8 ) & 0xf
if DAC1Enable != None:
command[6] |= (1 << 2)
if DAC1Enable:
command[17] = (1 << 7)
if DAC1 != None:
command[6] |= (1 << 2)
command[16] = DAC1 & 0xff
command[17] |= (DAC1 >> 8 ) & 0xf
result = self._writeRead(command, 24, [ 0xF8, 0x09, 0x08 ])
self.powerLevel = result[7]
self.controlFWVersion = "%s.%02d" % (result[10], result[9])
self.firmwareVersion = [self.controlFWVersion, self.commFWVersion]
self.controlBLVersion = "%s.%02d" % (result[12], result[11])
self.hiRes = bool(result[13] & 1)
self.deviceName = 'UE9'
if self.hiRes:
self.deviceName = 'UE9-Pro'
return { 'PowerLevel' : self.powerLevel, 'ResetSource' : result[8], 'ControlFWVersion' : self.controlFWVersion, 'ControlBLVersion' : self.controlBLVersion, 'HiRes Flag' : self.hiRes, 'FIODir' : result[14], 'FIOState' : result[15], 'EIODir' : result[16], 'EIOState' : result[17], 'CIODirection' : (result[18] >> 4) & 0xf, 'CIOState' : result[18] & 0xf, 'MIODirection' : (result[19] >> 4) & 7, 'MIOState' : result[19] & 7, 'DAC0 Enabled' : bool(result[21] >> 7 & 1), 'DAC0' : (result[21] & 0xf) + result[20], 'DAC1 Enabled' : bool(result[23] >> 7 & 1), 'DAC1' : (result[23] & 0xf) + result[22], 'DeviceName' : self.deviceName }
def feedback(self, FIOMask = 0, FIODir = 0, FIOState = 0, EIOMask = 0, EIODir = 0, EIOState = 0, CIOMask = 0, CIODirection = 0, CIOState = 0, MIOMask = 0, MIODirection = 0, MIOState = 0, DAC0Update = False, DAC0Enabled = False, DAC0 = 0, DAC1Update = False, DAC1Enabled = False, DAC1 = 0, AINMask = 0, AIN14ChannelNumber = 0, AIN15ChannelNumber = 0, Resolution = 0, SettlingTime = 0, AIN1_0_BipGain = 0, AIN3_2_BipGain = 0, AIN5_4_BipGain = 0, AIN7_6_BipGain = 0, AIN9_8_BipGain = 0, AIN11_10_BipGain = 0, AIN13_12_BipGain = 0, AIN15_14_BipGain = 0):
"""
Name: UE9.feedback(FIOMask = 0, FIODir = 0, FIOState = 0,
EIOMask = 0, EIODir = 0, EIOState = 0, CIOMask = 0,
CIODirection = 0, CIOState = 0, MIOMask = 0, MIODirection = 0,
MIOState = 0, DAC0Update = False, DAC0Enabled = None,
DAC0 = None, DAC1Update = False, DAC1Enabled = None, DAC1 = None,
AINMask = 0, AIN14ChannelNumber = 0, AIN15ChannelNumber = 0,
Resolution = 0, SettlingTime = 0, AIN1_0_BipGain = 0,
AIN3_2_BipGain = 0, AIN5_4_BipGain = 0, AIN7_6_BipGain = 0,
AIN9_8_BipGain = 0, AIN11_10_BipGain = 0, AIN13_12_BipGain = 0,
AIN15_14_BipGain = 0)
Args: See section 5.3.3 of the User's Guide
Desc: A very useful function that writes/reads almost every I/O on the
LabJack UE9. See section 5.3.3 of the User's Guide.
>>> myUe9 = ue9.UE9()
>>> myUe9.feedback()
{'AIN0': 0, ...
'TimerB': 0,
'TimerC': 0}
"""
command = [ 0 ] * 34
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x0E
command[3] = 0x00
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = FIOMask
command[7] = FIODir
command[8] = FIOState
command[9] = EIOMask
command[10] = EIODir
command[11] = EIOState
command[12] = CIOMask
command[13] = (CIODirection & 0xf) << 4
command[13] |= (CIOState & 0xf)
command[14] = MIOMask
command[15] = (MIODirection & 7) << 4
command[15] |= (MIOState & 7 )
if DAC0Update:
if DAC0Enabled:
command[17] = 1 << 7
command[17] |= 1 << 6
command[16] = DAC0 & 0xff
command[17] |= (DAC0 >> 8) & 0xf
if DAC0Update:
if DAC0Enabled:
command[19] = 1 << 7
command[19] |= 1 << 6
command[18] = DAC0 & 0xff
command[19] |= (DAC0 >> 8) & 0xf
command[20] = AINMask & 0xff
command[21] = (AINMask >> 8) & 0xff
command[22] = AIN14ChannelNumber
command[23] = AIN15ChannelNumber
command[24] = Resolution
command[25] = SettlingTime
command[26] = AIN1_0_BipGain
command[27] = AIN3_2_BipGain
command[28] = AIN5_4_BipGain
command[29] = AIN7_6_BipGain
command[30] = AIN9_8_BipGain
command[31] = AIN11_10_BipGain
command[32] = AIN13_12_BipGain
command[33] = AIN15_14_BipGain
result = self._writeRead(command, 64, [ 0xF8, 0x1D, 0x00], checkBytes = False)
returnDict = { 'FIODir' : result[6], 'FIOState' : result[7], 'EIODir' : result[8], 'EIOState' : result[9], 'CIODir' : (result[10] >> 4) & 0xf, 'CIOState' : result[10] & 0xf, 'MIODir' : (result[11] >> 4) & 7, 'MIOState' : result[11] & 7, 'Counter0' : unpackInt(result[44:48]), 'Counter1' : unpackInt(result[48:52]), 'TimerA' : unpackInt(result[52:56]), 'TimerB' : unpackInt(result[56:60]), 'TimerC' : unpackInt(result[60:]) }
"""
'AIN0' : b2c(unpackShort(result[12:14])), 'AIN1' : unpackShort(result[14:16]), 'AIN2' : unpackShort(result[16:18]), 'AIN3' : unpackShort(result[18:20]), 'AIN4' : unpackShort(result[20:22]), 'AIN5' : unpackShort(result[22:24]), 'AIN6' : unpackShort(result[24:26]), 'AIN7' : unpackShort(result[26:28]), 'AIN8' : unpackShort(result[28:30]), 'AIN9' : unpackShort(result[30:32]), 'AIN10' : unpackShort(result[32:34]), 'AIN11' : unpackShort(result[34:36]), 'AIN12' : unpackShort(result[36:38]), 'AIN13' : unpackShort(result[38:40]), 'AIN14' : unpackShort(result[40:42]), 'AIN15' : unpackShort(result[42:44]),
"""
b2c = self.binaryToCalibratedAnalogVoltage
g = 0
for i in range(16):
bits = unpackShort(result[(12+(2*i)):(14+(2*i))])
if i%2 == 0:
gain = command[26 + g] & 0xf
else:
gain = (command[26 + g] >> 4) & 0xf
g += 1
returnDict["AIN%s" % i] = b2c(bits, gain)
return returnDict
digitalPorts = [ 'FIO', 'EIO', 'CIO', 'MIO' ]
def singleIO(self, IOType, Channel, Dir = None, BipGain = None, State = None, Resolution = None, DAC = 0, SettlingTime = 0):
"""
Name: UE9.singleIO(IOType, Channel, Dir = None, BipGain = None, State = None, Resolution = None, DAC = 0, SettlingTime = 0)
Args: See section 5.3.4 of the User's Guide
Desc: An alternative to Feedback, is this function which writes or
reads a single output or input. See section 5.3.4 of the User's
Guide.
>>> myUe9 = ue9.UE9()
>>> myUe9.singleIO(1, 0, Dir = 1, State = 0)
{'FIO0 Direction': 1, 'FIO0 State': 0}
"""
command = [ 0 ] * 8
#command[0] = Checksum8
command[1] = 0xA3
command[2] = IOType
command[3] = Channel
if IOType == 0:
#Digital Bit Read
pass
elif IOType == 1:
#Digital Bit Write
if Dir == None or State == None:
raise LabJackException("Need to specify a direction and state")
command[4] = Dir
command[5] = State
elif IOType == 2:
#Digital Port Read
pass
elif IOType == 3:
#Digital Port Write
if Dir == None or State == None:
raise LabJackException("Need to specify a direction and state")
command[4] = Dir
command[5] = State
elif IOType == 4:
#Analog In
if BipGain == None or Resolution == None or SettlingTime == None:
raise LabJackException("Need to specify a BipGain, Resolution, and SettlingTime")
command[4] = BipGain
command[5] = Resolution
command[6] = SettlingTime
elif IOType == 5:
#Analog Out
if DAC == None:
raise LabJackException("Need to specify a DAC Value")
command[4] = DAC & 0xff
command[5] = (DAC >> 8) & 0xf
result = self._writeRead(command, 8, [ 0xA3 ], checkBytes = False)
if result[2] == 0:
#Digital Bit Read
return { "FIO%s State" % result[3] : result[5], "FIO%s Direction" % result[3] : result[4] }
elif result[2] == 1:
#Digital Bit Write
return { "FIO%s State" % result[3] : result[5], "FIO%s Direction" % result[3] : result[4] }
elif result[2] == 2:
#Digital Port Read
return { "%s Direction" % self.digitalPorts[result[3]] : result[4], "%s State" % self.digitalPorts[result[3]] : result [5] }
elif result[2] == 3:
#Digital Port Write
return { "%s Direction" % self.digitalPorts[result[3]] : result[4], "%s State" % self.digitalPorts[result[3]] : result [5] }
elif result[2] == 4:
#Analog In
ain = float((result[6] << 16) + (result[5] << 8) + result[4]) / 256
return { "AIN%s" % result[3] : ain }
elif result[2] == 5:
#Analog Out
dac = (result[6] << 16) + (result[5] << 8) + result[4]
return { "DAC%s" % result[3] : dac }
def timerCounter(self, TimerClockDivisor=0, UpdateConfig=False, NumTimersEnabled=0, Counter0Enabled=False, Counter1Enabled=False, TimerClockBase=LJ_tcSYS, ResetTimer0=False, ResetTimer1=False, ResetTimer2=False, ResetTimer3=False, ResetTimer4=False, ResetTimer5=False, ResetCounter0=False, ResetCounter1=False, Timer0Mode=None, Timer0Value=None, Timer1Mode=None, Timer1Value=None, Timer2Mode=None, Timer2Value=None, Timer3Mode=None, Timer3Value=None, Timer4Mode=None, Timer4Value=None, Timer5Mode=None, Timer5Value=None):
"""
Name: UE9.timerCounter(TimerClockDivisor=0, UpdateConfig=False,
NumTimersEnabled=0, Counter0Enabled=False,
Counter1Enabled=True, TimerClockBase=LJ_tcSYS,
ResetTimer0=False, ResetTimer1=False,
ResetTimer2=False, ResetTimer3=False,
ResetTimer4=False, ResetTimer5=False,
ResetCounter0=False, ResetCounter1=False,
Timer0Mode=None, Timer0Value=None,
Timer1Mode=None, Timer1Value=None,
Timer2Mode=None, Timer2Value=None,
Timer3Mode=None, Timer3Value=None,
Timer4Mode=None, Timer4Value=None,
Timer5Mode=None, Timer5Value=None)
Args: TimerClockDivisor, The timer clock is divided by this value, or
divided by 256 if this value is 0. The
UpdateConfig bit must be set to change this
parameter.
UpdateConfig, If true, counters and timers are re-configured by
this call. If false, the timer/counter configuration
will remain the same.
NumTimersEnabled, The number of timers enabled
TimerClockBase, The determines the timer base clock which is used
by all output mode timers. The choices are a fixed
750 kHz clock source, or the system clock. The UE9
is by default in high power mode which means the
system clock is fixed at 48 MHz. The UpdateConfig
bit must be set to change this parameter.
ResetTimer#, Resets the specified timer
ResetCounter#, Resets the specified counter
Timer#Mode, These values are only updated if the UpdateConfig
parameter is True. See section 5.3.5 in the User's
Guide for values to pass to configure a timer.
Timer#Value, Only updates if UpdateReset is True. The meaning of
this parameter varies with the timer mode. See
Section 2.10 for further information.
Desc: Enables, configures, and reads the counters and timers. See
section 5.3.5 of the User's Guide for more information.
>>> dev = UE9()
>>> dev.timerCounter()
{'Counter0Enabled': False, 'Timer5Enabled': False, 'Timer0Enabled': False, 'Timer1': 0, 'Timer4': 0, 'Timer3Enabled': False, 'Timer4Enabled': False, 'Timer5': 0, 'Counter1Enabled': False, 'Timer3': 0, 'Timer2': 0, 'Timer1Enabled': False, 'Timer0': 0, 'Timer2Enabled': False}
"""
command = [ 0 ] * 30
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x0C
command[3] = 0x18
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = TimerClockDivisor
# Create EnableMask
if UpdateConfig:
command[7] = 128 | NumTimersEnabled
if Counter0Enabled: command[7] = command[7] | 8
if Counter1Enabled: command[7] = command[7] | 16
else: UpdateConfig = 0
# Configure clock base
command[8] = TimerClockBase
# Configure UpdateReset
if ResetTimer0: command[9] = 1
if ResetTimer1: command[9] = command[9] | 2
if ResetTimer2: command[9] = command[9] | 4
if ResetTimer3: command[9] = command[9] | 8
if ResetTimer4: command[9] = command[9] | 16
if ResetTimer5: command[9] = command[9] | 32
if ResetCounter0: command[9] = command[9] | 64
if ResetCounter1: command[9] = command[9] | 128
# Configure timers and counters if we are updating the configuration
if UpdateConfig:
if NumTimersEnabled >= 1:
if Timer0Mode == None: raise LabJackException("Need to specify a mode for Timer0")
if Timer0Value == None: raise LabJackException("Need to specify a value for Timer0")
command[10] = Timer0Mode
command[11] = Timer0Value & 0xff
command[12] = (Timer0Value >> 8) & 0xff
if NumTimersEnabled >= 2:
if Timer1Mode == None: raise LabJackException("Need to specify a mode for Timer1")
if Timer1Value == None: raise LabJackException("Need to specify a value for Timer1")
command[13] = Timer1Mode
command[14] = Timer1Value & 0xff
command[15] = (Timer1Value >> 8) & 0xff
if NumTimersEnabled >= 3:
if Timer2Mode == None: raise LabJackException("Need to specify a mode for Timer2")
if Timer2Value == None: raise LabJackException("Need to specify a value for Timer2")
command[16] = Timer2Mode
command[17] = Timer2Value & 0xff
command[18] = (Timer2Value >> 8) & 0xff
if NumTimersEnabled >= 4:
if Timer3Mode == None: raise LabJackException("Need to specify a mode for Timer3")
if Timer3Value == None: raise LabJackException("Need to specify a value for Timer3")
command[19] = Timer3Mode
command[20] = Timer3Value & 0xff
command[21] = (Timer3Value >> 8) & 0xff
if NumTimersEnabled >= 5:
if Timer4Mode == None: raise LabJackException("Need to specify a mode for Timer4")
if Timer4Value == None: raise LabJackException("Need to specify a value for Timer4")
command[22] = Timer4Mode
command[23] = Timer4Value & 0xff
command[24] = (Timer4Value >> 8) & 0xff
if NumTimersEnabled == 6:
if Timer5Mode == None: raise LabJackException("Need to specify a mode for Timer5")
if Timer5Value == None: raise LabJackException("Need to specify a value for Timer5")
command[25] = Timer5Mode
command[26] = Timer5Value & 0xff
command[27] = (Timer5Value >> 8) & 0xff
if NumTimersEnabled > 7: raise LabJackException("Only a maximum of 5 timers can be enabled")
command[28] = 0#command[28] = Counter0Mode
command[29] = 0#command[29] = Counter1Mode
result = self._writeRead(command, 40, [ 0xF8, 0x11, 0x18 ])
# Parse the results
returnValue = {}
for i in range(0,6):
returnValue["Timer" + str(i) + "Enabled"] = result[7] >> i & 1 == 1
for i in range(0,2):
returnValue["Counter" + str(i) + "Enabled"] = result[7] >> i + 6 & 1 == 1
for i in range(0, 6):
returnValue["Timer" + str(i)] = unpackInt(result[8+i*4:12+i*4])
for i in range(0,2):
counterValue = [0]
counterValue.extend(result[32+i*4:35+i*4])
returnValue["Counter" + str(i)] = unpackInt(counterValue)
return returnValue
def readMem(self, BlockNum):
"""
Name: UE9.readMem(BlockNum)
Args: BlockNum, which block to read
ReadCal, set to True to read the calibration data
Desc: Reads 1 block (128 bytes) from the non-volatile user or
calibration memory. Please read section 5.3.10 of the user's
guide before you do something you may regret.
>>> myUE9 = UE9()
>>> myUE9.readMem(0)
[ < userdata stored in block 0 > ]
NOTE: Do not call this function while streaming.
"""
command = [ 0 ] * 8
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x01
command[3] = 0x2A
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = 0x00
command[7] = BlockNum
result = self._writeRead(command, 136, [ 0xF8, 0x41, 0x2A ])
return result[8:]
def writeMem(self, BlockNum, Data):
"""
Name: UE9.writeMem(BlockNum, Data, WriteCal=False)
Args: BlockNum, which block to write
Data, a list of bytes to write
Desc: Writes 1 block (128 bytes) from the non-volatile user or
calibration memory. Please read section 5.3.11 of the user's
guide before you do something you may regret.
>>> myUE9 = UE9()
>>> myUE9.writeMem(0, [ < userdata to be stored in block 0 > ])
NOTE: Do not call this function while streaming.
"""
if not isinstance(Data, list):
raise LabJackException("Data must be a list of bytes")
command = [ 0 ] * 136
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x41
command[3] = 0x28
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = 0x00
command[7] = BlockNum
command[8:] = Data
self._writeRead(command, 8, [0xF8, 0x01, command[3]])
def eraseMem(self, EraseCal=False):
"""
Name: UE9.eraseMem(EraseCal=False)
Args: EraseCal, set to True to erase the calibration memory.
Desc: The UE9 uses flash memory that must be erased before writing.
Please read section 5.2.12 of the user's guide before you do
something you may regret.
>>> myUE9 = UE9()
>>> myUE9.eraseMem()
NOTE: Do not call this function while streaming.
"""
command = [ 0 ] * 8
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x01
command[3] = 0x29
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
if EraseCal:
command[6] = 0x4C
command[7] = 0x4A
else:
command[6] = 0x00
command[7] = 0x00
self._writeRead(command, 8, [0xF8, 0x01, command[3]])
def watchdogConfig(self, ResetCommonTimeout = False, ResetControlonTimeout = False, UpdateDigitalIOB = False, UpdateDigitalIOA = False, UpdateDAC1onTimeout = False, UpdateDAC0onTimeout = False, TimeoutPeriod = 60, DIOConfigA = 0, DIOConfigB = 0, DAC0Enabled = False, DAC0 = 0, DAC1Enabled = False, DAC1 = 0):
command = [ 0 ] * 16
command[1] = 0xF8
command[2] = 0x05
command[3] = 0x09
if ResetCommonTimeout:
command[7] |= (1 << 6)
if ResetControlonTimeout:
command[7] |= (1 << 5)
if UpdateDigitalIOB:
command[7] |= (1 << 4)
if UpdateDigitalIOA:
command[7] |= (1 << 3)
if UpdateDAC1onTimeout:
command[7] |= (1 << 1)
if UpdateDAC0onTimeout:
command[7] |= (1 << 0)
t = struct.pack("<H", TimeoutPeriod)
command[8] = ord(t[0])
command[9] = ord(t[1])
command[10] = DIOConfigA
command[11] = DIOConfigB
command[12] = DAC0 & 0xff
command[13] = (int(DAC0Enabled) << 7) + (DAC0 & 0xf)
command[14] = DAC1 & 0xff
command[15] = (int(DAC1Enabled) << 7) + (DAC1 & 0xf)
result = self._writeRead(command, 8, [0xF8, 0x01, 0x09])
return { 'UpdateDAC0onTimeout' : bool(result[7]& 1), 'UpdateDAC1onTimeout' : bool((result[7] >> 1) & 1), 'UpdateDigitalIOBonTimeout' : bool((result[7] >> 3) & 1), 'UpdateDigitalIOBonTimeout' : bool((result[7] >> 4) & 1), 'ResetControlOnTimeout' : bool((result[7] >> 5) & 1), 'ResetCommOnTimeout' : bool((result[7] >> 6) & 1) }
def watchdogRead(self):
"""
Name: UE9.watchdogRead()
Args: None
Desc: Reads the current watchdog settings.
"""
command = [ 0 ] * 6
command[1] = 0xF8
command[2] = 0x00
command[3] = 0x09
command = setChecksum8(command, 6)
result = self._writeRead(command, 16, [0xF8, 0x05, 0x09], checksum = False)
return { 'UpdateDAC0onTimeout' : bool(result[7]& 1), 'UpdateDAC1onTimeout' : bool((result[7] >> 1) & 1), 'UpdateDigitalIOBonTimeout' : bool((result[7] >> 3) & 1), 'UpdateDigitalIOBonTimeout' : bool((result[7] >> 4) & 1), 'ResetControlOnTimeout' : bool((result[7] >> 5) & 1), 'ResetCommOnTimeout' : bool((result[7] >> 6) & 1), 'TimeoutPeriod' : struct.unpack('<H', struct.pack("BB", *result[8:10]))[0], 'DIOConfigA' : result[10], 'DIOConfigB' : result[11], 'DAC0' : struct.unpack('<H', struct.pack("BB", *result[8:10]))[0], 'DAC1' : struct.unpack('<H', struct.pack("BB", *result[8:10]))[0] }
SPIModes = { 'A' : 0, 'B' : 1, 'C' : 2, 'D' : 3 }
def spi(self, SPIBytes, AutoCS=True, DisableDirConfig = False, SPIMode = 'A', SPIClockFactor = 0, CSPINNum = 1, CLKPinNum = 0, MISOPinNum = 3, MOSIPinNum = 2):
"""
Name: UE9.spi(SPIBytes, AutoCS=True, DisableDirConfig = False,
SPIMode = 'A', SPIClockFactor = 0, CSPINNum = 1,
CLKPinNum = 0, MISOPinNum = 3, MOSIPinNum = 2)
Args: SPIBytes, a list of bytes to be transferred.
See Section 5.3.16 of the user's guide.
Desc: Sends and receives serial data using SPI synchronous
communication.
"""
print SPIBytes
if not isinstance(SPIBytes, list):
raise LabJackException("SPIBytes MUST be a list of bytes")
numSPIBytes = len(SPIBytes)
oddPacket = False
if numSPIBytes%2 != 0:
SPIBytes.append(0)
numSPIBytes = numSPIBytes + 1
oddPacket = True
command = [ 0 ] * (13 + numSPIBytes)
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 4 + (numSPIBytes/2)
command[3] = 0x3A
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
if AutoCS:
command[6] |= (1 << 7)
if DisableDirConfig:
command[6] |= (1 << 6)
command[6] |= ( self.SPIModes[SPIMode] & 3 )
command[7] = SPIClockFactor
#command[8] = Reserved
command[9] = CSPINNum
command[10] = CLKPinNum
command[11] = MISOPinNum
command[12] = MOSIPinNum
command[13] = numSPIBytes
if oddPacket:
command[13] = numSPIBytes - 1
command[14:] = SPIBytes
result = self._writeRead(command, 8+numSPIBytes, [ 0xF8, 1+(numSPIBytes/2), 0x3A ])
return result[8:]
def asynchConfig(self, Update = True, UARTEnable = True, DesiredBaud = 9600):
"""
Name: UE9.asynchConfig(Update = True, UARTEnable = True,
DesiredBaud = 9600)
Args: See section 5.3.17 of the User's Guide.
Desc: Configures the U3 UART for asynchronous communication.
returns a dictionary:
{
'Update' : True means new parameters were written
'UARTEnable' : True means the UART is enabled
'BaudFactor' : The baud factor being used
}
"""
command = [ 0 ] * 10
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x02
command[3] = 0x14
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
#command[6] = 0x00
if Update:
command[7] |= ( 1 << 7 )
if UARTEnable:
command[7] |= ( 1 << 6 )
BaudFactor = (2**16) - 48000000/(2 * DesiredBaud)
t = struct.pack("<H", BaudFactor)
command[8] = ord(t[0])
command[9] = ord(t[1])
result = self._writeRead(command, 10, [0xF8, 0x02, 0x14])
returnDict = {}
if ( ( result[7] >> 7 ) & 1 ):
returnDict['Update'] = True
else:
returnDict['Update'] = False
if ( ( result[7] >> 6 ) & 1):
returnDict['UARTEnable'] = True
else:
returnDict['UARTEnable'] = False
returnDict['BaudFactor'] = struct.unpack("<H", struct.pack("BB", *result[8:]))[0]
return returnDict
def asynchTX(self, AsynchBytes):
"""
Name: UE9.asynchTX(AsynchBytes)
Args: AsynchBytes, must be a list of bytes to transfer.
Desc: Sends bytes to the U3 UART which will be sent asynchronously on
the transmit line. See section 5.3.18 of the user's guide.
returns a dictionary:
{
'NumAsynchBytesSent' : Number of Asynch Bytes Sent
'NumAsynchBytesInRXBuffer' : How many bytes are currently in the
RX buffer.
}
"""
if not isinstance(AsynchBytes, list):
raise LabJackException("AsynchBytes must be a list")
numBytes = len(AsynchBytes)
oddPacket = False
if numBytes%2 != 0:
AsynchBytes.append(0)
numBytes = numBytes+1
oddPacket = True
command = [ 0 ] * ( 8 + numBytes)
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 1 + ( numBytes/2 )
command[3] = 0x15
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
#command[6] = 0x00
command[7] = numBytes
if oddPacket:
command[7] = numBytes - 1
command[8:] = AsynchBytes
result = self._writeRead(command, 10, [0xF8, 0x02, 0x15])
return { 'NumAsynchBytesSent' : result[7], 'NumAsynchBytesInRXBuffer' : result[8] }
def asynchRX(self, Flush = False):
"""
Name: UE9.asynchRX(Flush = False)
Args: Flush, Set to True to flush
Desc: Reads the oldest 32 bytes from the U3 UART RX buffer
(received on receive terminal). The buffer holds 256 bytes. See
section 5.3.19 of the User's Guide.
returns a dictonary:
{
'AsynchBytes' : List of received bytes
'NumAsynchBytesInRXBuffer' : Number of AsynchBytes are in the RX
Buffer.
}
"""
command = [ 0 ] * 8
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x01
command[3] = 0x16
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
#command[6] = 0x00
if Flush:
command[7] = 1
result = self._writeRead(command, 40, [0xF8, 0x11, 0x16])
return { 'AsynchBytes' : result[8:], 'NumAsynchBytesInRXBuffer' : result[7] }
def i2c(self, Address, I2CBytes, EnableClockStretching = False, NoStopWhenRestarting = False, ResetAtStart = False, SpeedAdjust = 0, SDAPinNum = 1, SCLPinNum = 0, NumI2CBytesToReceive = 0, AddressByte = None):
"""
Name: UE9.i2c(Address, I2CBytes, ResetAtStart = False, EnableClockStretching = False, SpeedAdjust = 0, SDAPinNum = 0, SCLPinNum = 1, NumI2CBytesToReceive = 0, AddressByte = None)
Args: Address, the address (not shifted over)
I2CBytes, must be a list of bytes to send.
See section 5.3.20 of the user's guide.
AddressByte, The address as you would put it in the lowlevel
packet. Overrides Address. Optional
Desc: Sends and receives serial data using I2C synchronous
communication.
"""
if not isinstance(I2CBytes, list):
raise LabJackException("I2CBytes must be a list")
numBytes = len(I2CBytes)
oddPacket = False
if numBytes%2 != 0:
I2CBytes.append(0)
numBytes = numBytes + 1
oddPacket = True
command = [ 0 ] * (14 + numBytes)
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 4 + (numBytes/2)
command[3] = 0x3B
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
if ResetAtStart:
command[6] |= (1 << 1)
if NoStopWhenRestarting:
command[6] |= (1 << 2)
if EnableClockStretching:
command[6] |= (1 << 3)
command[7] = SpeedAdjust
command[8] = SDAPinNum
command[9] = SCLPinNum
if AddressByte != None:
command[10] = AddressByte
else:
command[10] = Address << 1
command[12] = numBytes
if oddPacket:
command[12] = numBytes-1
command[13] = NumI2CBytesToReceive
command[14:] = I2CBytes
oddResponse = False
if NumI2CBytesToReceive%2 != 0:
NumI2CBytesToReceive = NumI2CBytesToReceive+1
oddResponse = True
result = self._writeRead(command, 12+NumI2CBytesToReceive, [0xF8, (3+(NumI2CBytesToReceive/2)), 0x3B])
if len(result) > 12:
if oddResponse:
return { 'AckArray' : result[8:12], 'I2CBytes' : result[12:-1] }
else:
return { 'AckArray' : result[8:12], 'I2CBytes' : result[12:] }
else:
return { 'AckArray' : result[8:], 'I2CBytes' : [] }
def sht1x(self, DataPinNum = 0, ClockPinNum = 1, SHTOptions = 0xc0):
"""
Name: UE9.sht1x(DataPinNum = 0, ClockPinNum = 1, SHTOptions = 0xc0)
Args: DataPinNum, Which pin is the Data line
ClockPinNum, Which line is the Clock line
SHTOptions (and proof people read documentation):
bit 7 = Read Temperature
bit 6 = Read Realtive Humidity
bit 2 = Heater. 1 = on, 0 = off
bit 1 = Reserved at 0
bit 0 = Resolution. 1 = 8 bit RH, 12 bit T; 0 = 12 RH, 14 bit T
Desc: Reads temperature and humidity from a Sensirion SHT1X sensor.
Section 5.3.21 of the User's Guide.
"""
command = [ 0 ] * 10
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x02
command[3] = 0x39
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = DataPinNum
command[7] = ClockPinNum
#command[8] = Reserved
command[9] = SHTOptions
result = self._writeRead(command, 16, [ 0xF8, 0x05, 0x39])
val = (result[11]*256) + result[10]
temp = -39.60 + 0.01*val
val = (result[14]*256) + result[13]
humid = -4 + 0.0405*val + -.0000028*(val*val)
humid = (temp - 25)*(0.01 + 0.00008*val) + humid
return { 'StatusReg' : result[8], 'StatusCRC' : result[9], 'Temperature' : temp, 'TemperatureCRC' : result[12], 'Humidity' : humid, 'HumidityCRC' : result[15] }
def getAIN(self, channel, BipGain = 0x00, Resolution = 12, SettlingTime = 0):
"""
Name: UE9.getAIN(channel, BipGain = 0x00, Resolution = 12,
SettlingTime = 0)
"""
bits = self.singleIO(4, channel, BipGain = BipGain, Resolution = Resolution, SettlingTime = SettlingTime )
return self.binaryToCalibratedAnalogVoltage(bits["AIN%s"%channel], BipGain)
def getTemperature(self):
"""
Name: UE9.getTemperature()
"""
if self.calData is None:
self.getCalibrationData()
bits = self.singleIO(4, 133, BipGain = 0x00, Resolution = 12, SettlingTime = 0 )
return self.binaryToCalibratedAnalogTemperature(bits["AIN133"])
def binaryToCalibratedAnalogVoltage(self, bits, gain):
""" Name: UE9.binaryToCalibratedAnalogVoltage( bits, gain )
Args: bits, the binary value to be converted
gain, the gain used. Please use the values from 5.3.3 of the
UE9's user's guide.
Desc: Converts the binary value returned from Feedback and SingleIO
to a calibrated, analog voltage.
>>> print d.singleIO(4, 1, BipGain = 0x01, Resolution = 12 )
{'AIN1': 65520.0}
>>> print d.binaryToCalibratedAnalogVoltage(65520.0, 0x01)
2.52598272
"""
if self.calData is not None:
slope = self.calData['AINSlopes'][str(gain)]
offset = self.calData['AINOffsets'][str(gain)]
else:
slope = DEFAULT_CAL_CONSTANTS['AINSlopes'][str(gain)]
offset = DEFAULT_CAL_CONSTANTS['AINOffsets'][str(gain)]
return (bits * slope) + offset
def binaryToCalibratedAnalogTemperature(self, bits):
if self.calData is not None:
return bits * self.calData['TempSlope']
else:
return bits * DEFAULT_CAL_CONSTANTS['TempSlope']
def getCalibrationData(self):
""" Name: UE9.getCalibrationData()
Args: None
Desc: Reads the calibration constants off the UE9, and stores them
for use with binaryToCalibratedAnalogVoltage.
Note: Please note that this function calls controlConfig to check
if the device is a UE9 or not. It also makes calls to
readMem, so please don't call this while streaming.
"""
# Insure that we know if we are dealing with a Pro or not.
self.controlConfig()
results = dict()
ainslopes = { '0' : None, '1' : None, '2' : None, '3' : None, '8' : None }
ainoffsets = { '0' : None, '1' : None, '2' : None, '3' : None, '8' : None }
dacslopes = { '0' : None, '1' : None }
dacoffsets = { '0' : None, '1' : None }
tempslope = None
memBlock = self.readMem(0)
ainslopes['0'] = toDouble(memBlock[:8])
ainoffsets['0'] = toDouble(memBlock[8:16])
ainslopes['1'] = toDouble(memBlock[16:24])
ainoffsets['1'] = toDouble(memBlock[24:32])
ainslopes['2'] = toDouble(memBlock[32:40])
ainoffsets['2'] = toDouble(memBlock[40:48])
ainslopes['3'] = toDouble(memBlock[48:56])
ainoffsets['3'] = toDouble(memBlock[56:])
memBlock = self.readMem(1)
ainslopes['8'] = toDouble(memBlock[:8])
ainoffsets['8'] = toDouble(memBlock[8:16])
# Read DAC and Temperature slopes
memBlock = self.readMem(2)
dacslopes['0'] = toDouble(memBlock[:8])
dacoffsets['0'] = toDouble(memBlock[8:16])
dacslopes['1'] = toDouble(memBlock[16:24])
dacoffsets['1'] = toDouble(memBlock[24:32])
tempslope = toDouble(memBlock[32:40])
if self.deviceName.endswith("Pro"):
memBlock = self.readMem(3)
ainslopes['0'] = toDouble(memBlock[:8])
ainoffsets['0'] = toDouble(memBlock[8:16])
memBlock = self.readMem(4)
ainslopes['8'] = toDouble(memBlock[:8])
ainoffsets['8'] = toDouble(memBlock[8:16])
self.calData = { "AINSlopes" : ainslopes, "AINOffsets" : ainoffsets, 'TempSlope' : tempslope, "DACSlopes" : dacslopes, "DACOffsets" : dacoffsets }
return self.calData
def readDefaultsConfig(self):
"""
Name: UE9.readDefaultsConfig( )
Args: None
Desc: Reads the power-up defaults stored in flash.
"""
results = dict()
defaults = self.readDefaults(0)
results['FIODirection'] = defaults[4]
results['FIOState'] = defaults[5]
results['EIODirection'] = defaults[6]
results['EIOState'] = defaults[7]
results['CIODirection'] = defaults[8]
results['CIOState'] = defaults[9]
results['MIODirection'] = defaults[10]
results['MIOState'] = defaults[11]
results['ConfigWriteMask'] = defaults[16]
results['NumOfTimersEnable'] = defaults[17]
results['CounterMask'] = defaults[18]
results['PinOffset'] = defaults[19]
defaults = self.readDefaults(1)
results['ClockSource'] = defaults[0]
results['Divisor'] = defaults[1]
results['TMR0Mode'] = defaults[16]
results['TMR0ValueL'] = defaults[17]
results['TMR0ValueH'] = defaults[18]
results['TMR1Mode'] = defaults[20]
results['TMR1ValueL'] = defaults[21]
results['TMR1ValueH'] = defaults[22]
results['TMR2Mode'] = defaults[24]
results['TMR2ValueL'] = defaults[25]
results['TMR2ValueH'] = defaults[26]
results['TMR3Mode'] = defaults[28]
results['TMR3ValueL'] = defaults[29]
results['TMR3ValueH'] = defaults[30]
defaults = self.readDefaults(2)
results['TMR4Mode'] = defaults[0]
results['TMR4ValueL'] = defaults[1]
results['TMR4ValueH'] = defaults[2]
results['TMR5Mode'] = defaults[4]
results['TMR5ValueL'] = defaults[5]
results['TMR5ValueH'] = defaults[6]
results['DAC0'] = struct.unpack( ">H", struct.pack("BB", *defaults[16:18]) )[0]
results['DAC1'] = struct.unpack( ">H", struct.pack("BB", *defaults[20:22]) )[0]
defaults = self.readDefaults(3)
for i in range(14):
results["AIN%sRes" % i] = defaults[i]
results["AIN%sBPGain" % i] = defaults[i+16]
defaults = self.readDefaults(4)
for i in range(14):
results["AIN%sSettling" % i] = defaults[i]
return results
def exportConfig(self):
"""
Name: UE9.exportConfig( )
Args: None
Desc: Takes the current configuration and puts it into a ConfigParser
object. Useful for saving the setup of your UE9.
"""
# Make a new configuration file
parser = ConfigParser.SafeConfigParser()
# Change optionxform so that options preserve their case.
parser.optionxform = str
# Local Id and name
self.commConfig()
self.controlConfig()
section = "Identifiers"
parser.add_section(section)
parser.set(section, "Local ID", str(self.localId))
parser.set(section, "Name", str(self.getName()))
parser.set(section, "Device Type", str(self.devType))
parser.set(section, "MAC Address", str(self.macAddress))
# Comm Config settings
section = "Communication"
parser.add_section(section)
parser.set(section, "DHCPEnabled", str(self.DHCPEnabled))
parser.set(section, "IP Address", str(self.ipAddress))
parser.set(section, "Subnet", str(self.subnet))
parser.set(section, "Gateway", str(self.gateway))
parser.set(section, "PortA", str(self.portA))
parser.set(section, "PortB", str(self.portB))
# FIO Direction / State
section = "FIOs"
parser.add_section(section)
parser.set(section, "FIO Directions", str( self.readRegister(6750) ))
parser.set(section, "FIO States", str( self.readRegister(6700) ))
parser.set(section, "EIO Directions", str( self.readRegister(6751) ))
parser.set(section, "EIO States", str( self.readRegister(6701) ))
parser.set(section, "CIO Directions", str( self.readRegister(6752) ))
parser.set(section, "CIO States", str( self.readRegister(6702) ))
#parser.set(section, "MIOs Directions", str( self.readRegister(50591) ))
#parser.set(section, "MIOs States", str( self.readRegister(50591) ))
# DACs
section = "DACs"
parser.add_section(section)
dac0 = self.readRegister(5000)
dac0 = max(dac0, 0)
dac0 = min(dac0, 5)
parser.set(section, "DAC0", "%0.2f" % dac0)
dac1 = self.readRegister(5002)
dac1 = max(dac1, 0)
dac1 = min(dac1, 5)
parser.set(section, "DAC1", "%0.2f" % dac1)
# Timer Clock Configuration
section = "Timer Clock Speed Configuration"
parser.add_section(section)
parser.set(section, "TimerClockBase", str(self.readRegister(7000)))
parser.set(section, "TimerClockDivisor", str(self.readRegister(7002)))
# Timers / Counters
section = "Timers And Counters"
parser.add_section(section)
nte = self.readRegister(50501)
cm = self.readRegister(50502)
ec0 = bool( cm & 1 )
ec1 = bool( (cm >> 1) & 1 )
parser.set(section, "NumberTimersEnabled", str(nte) )
parser.set(section, "Counter0Enabled", str(ec0) )
parser.set(section, "Counter1Enabled", str(ec1) )
for i in range(nte):
mode, value = self.readRegister(7100 + (i*2), numReg = 2, format = ">HH")
parser.set(section, "Timer%s Mode" % i, str(mode))
parser.set(section, "Timer%s Value" % i, str(value))
return parser
def loadConfig(self, configParserObj):
"""
Name: UE9.loadConfig( configParserObj )
Args: configParserObj, A Config Parser object to load in
Desc: Takes a configuration and updates the UE9 to match it.
"""
parser = configParserObj
# Set Identifiers:
section = "Identifiers"
if parser.has_section(section):
if parser.has_option(section, "device type"):
if parser.getint(section, "device type") != self.devType:
raise Exception("Not a UE9 Config file.")
if parser.has_option(section, "local id"):
self.commConfig( LocalID = parser.getint(section, "local id"))
if parser.has_option(section, "name"):
self.setName( parser.get(section, "name") )
# Comm Config settings
section = "Communication"
if parser.has_section(section):
DHCPEnabled = None
ipAddress = None
subnet = None
gateway = None
portA = None
portB = None
if parser.has_option(section, "DHCPEnabled"):
DHCPEnabled = parser.getboolean(section, "DHCPEnabled")
if parser.has_option(section, "ipAddress"):
ipAddress = parser.get(section, "ipAddress")
if parser.has_option(section, "subnet"):
subnet = parser.get(section, "subnet")
if parser.has_option(section, "gateway"):
gateway = parser.get(section, "gateway")
if parser.has_option(section, "portA"):
portA = parser.getint(section, "portA")
if parser.has_option(section, "portB"):
portB = parser.getint(section, "portB")
self.commConfig( DHCPEnabled = DHCPEnabled, IPAddress = ipAddress, Subnet = subnet, Gateway = gateway, PortA = portA, PortB = portB )
# Set FIOs:
section = "FIOs"
if parser.has_section(section):
fiodirs = 0
eiodirs = 0
ciodirs = 0
fiostates = 0
eiostates = 0
ciostates = 0
if parser.has_option(section, "fios directions"):
fiodirs = parser.getint(section, "fios directions")
if parser.has_option(section, "eios directions"):
eiodirs = parser.getint(section, "eios directions")
if parser.has_option(section, "cios directions"):
ciodirs = parser.getint(section, "cios directions")
if parser.has_option(section, "fios states"):
fiostates = parser.getint(section, "fios states")
if parser.has_option(section, "eios states"):
eiostates = parser.getint(section, "eios states")
if parser.has_option(section, "cios states"):
ciostates = parser.getint(section, "cios states")
bitmask = 0xff00
# FIO State/Dir
self.writeRegister(6700, bitmask + fiostates )
self.writeRegister(6750, bitmask + fiodirs )
# EIO State/Dir
self.writeRegister(6701, bitmask + eiostates )
self.writeRegister(6751, bitmask + eiodirs )
# CIO State/Dir
self.writeRegister(6702, bitmask + ciostates )
self.writeRegister(6752, bitmask + ciodirs )
# Set DACs:
section = "DACs"
if parser.has_section(section):
if parser.has_option(section, "dac0"):
self.writeRegister(5000, parser.getfloat(section, "dac0"))
if parser.has_option(section, "dac1"):
self.writeRegister(5002, parser.getfloat(section, "dac1"))
# Set Timer Clock Configuration
section = "Timer Clock Speed Configuration"
if parser.has_section(section):
if parser.has_option(section, "timerclockbase"):
self.writeRegister(7000, parser.getint(section, "timerclockbase"))
if parser.has_option(section, "timerclockdivisor"):
self.writeRegister(7002, parser.getint(section, "timerclockbase"))
# Set Timers / Counters
section = "Timers And Counters"
if parser.has_section(section):
nte = 0
if parser.has_option(section, "NumberTimersEnabled"):
nte = parser.getint(section, "NumberTimersEnabled")
self.writeRegister(50501, nte)
if parser.has_option(section, "Counter0Enabled"):
cm = (self.readRegister(50502) & 2) # 0b10
c0e = parser.getboolean(section, "Counter0Enabled")
self.writeRegister(50502, cm + int(c0e))
if parser.has_option(section, "Counter1Enabled"):
cm = (self.readRegister(50502) & 1) # 0b01
c1e = parser.getboolean(section, "Counter1Enabled")
self.writeRegister(50502, (int(c1e) << 1) + 1)
mode = None
value = None
for i in range(nte):
if parser.has_option(section, "timer%s mode"):
mode = parser.getint(section, "timer%s mode")
if parser.has_option(section, "timer%s value"):
value = parser.getint(section, "timer%s mode")
self.writeRegister(7100 + (i*2), [mode, value])
| 64,151 | 40.361702 | 688 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/build/lib/skymote.py | """
Name: bridge.py
Desc: Provides a Bridge and Mote class for working with SkyMote bridges and
motes.
"""
from LabJackPython import *
if os.name == "nt":
if skymoteLib is None:
raise ImportError("Couldn't load liblabjackusb.dll. Please install, and try again.")
def serialToDotHex(serial):
bytes = struct.unpack("BBBBBBBB", struct.pack(">Q", serial))
line = ""
for i in range(7):
line += "%02x:" % bytes[i]
line += "%02x" % bytes[7]
return line
def dotHexToSerial(dothex):
bytes = [ int(i, 16) for i in dothex.split(":") ]
serial = 0
for i, byte in enumerate(bytes):
serial += byte << (8 * (7-i))
return serial
class Bridge(Device):
"""
Bridge class for working with wireless bridges
>>> import bridge
>>> d = bridge.Bridge()
"""
# ------------------ Object Functions ------------------
# These functions are part of object interaction in python
def __init__(self, handle = None, autoOpen = True, **kargs):
Device.__init__(self, None, devType = 0x501)
self.handle = handle
if 'localId' in kargs:
self.localId = kargs['localId']
else:
self.localId = None
if 'serial' in kargs:
self.serialNumber = int(kargs['serial'])
self.serialString = serialToDotHex(self.serialNumber)
else:
self.serialNumber = None
self.serialString = None
self.ethernetFWVersion = None
self.usbFWVersion = None
self.deviceName = "SkyMote Bridge"
self.devType = 0x501
self.unitId = 0
self.debug = True
self.modbusPrependZeros = False
self.nameCache = None
if autoOpen:
self.open(**kargs)
def open(self, firstFound = True, serial = None, devNumber = None, handleOnly = False, LJSocket = "localhost:6000"): #"
Device.open(self, 0x501, firstFound = firstFound, localId = None, serial = serial, devNumber = devNumber, handleOnly = handleOnly, LJSocket = LJSocket)
def read(self, numBytes, stream = False, modbus = False):
result = Device.read(self, 64, stream, modbus)
return result[:numBytes]
def spontaneous(self):
while True:
try:
packet = self.read(64, stream = True)
localId = packet[6]
packet = struct.pack("B"*len(packet), *packet)
transId = struct.unpack(">H", packet[0:2])[0]
report = struct.unpack(">HBBfHH"+"f"*8, packet[9:53])
results = dict()
results['unitId'] = localId
results['transId'] = transId
results['RxLQI'] = report[1]
results['TxLQI'] = report[2]
results['Battery'] = report[3]
results['Temp'] = report[6]
results['Light'] = report[7]
results['Bump'] = report[4]
results['Sound'] = report[11]
yield results
except socket.timeout:
# Our read timed out, but keep going.
pass
def readRegister(self, addr, numReg = None, format = None, unitId = None):
if unitId is None:
return Device.readRegister(self, addr, numReg, format, self.unitId)
else:
return Device.readRegister(self, addr, numReg, format, unitId)
def writeRegister(self, addr, value, unitId = None):
if unitId is None:
return Device.writeRegister(self, addr, value, unitId = self.unitId)
else:
return Device.writeRegister(self, addr, value, unitId = unitId)
# ------------------ Convenience Functions ------------------
# These functions call read register for you.
def readSerialNumber(self):
self.serialNumber = self.readRegister(65104, numReg = 4, format = ">Q")
self.serialString = serialToDotHex(self.serialNumber)
return self.serialNumber
def readNumberOfMotes(self):
return self.readRegister(59200, numReg = 2, format = '>I')
def ethernetFirmwareVersion(self):
left, right = self.readRegister(56000, format = '>BB')
self.ethernetFWVersion = "%s.%02d" % (left, right)
return "%s.%02d" % (left, right)
def usbFirmwareVersion(self):
left, right = self.readRegister(57000, format = '>BB')
self.usbFWVersion = "%s.%02d" % (left, right)
return "%s.%02d" % (left, right)
def mainFirmwareVersion(self):
left, right = self.readRegister(65006, format = ">BB")
self.mainFWVersion = "%s.%02d" % (left, right)
return "%s.%02d" % (left, right)
def energyScan(self):
return self.readRegister(59410, numReg = 8, format = ">"+"B"*16)
def getNetworkPassword(self):
results = self.readRegister(50120, numReg = 8, format = ">"+"B"*16)
returnDict = dict()
returnDict['enabled'] = True if results[0] != 0 else False
returnDict['password'] = struct.pack("B"*15, *results[1:])
return returnDict
def setNetworkPassword(self, password, enable = True):
if len(password) > 15:
password = password[:15]
if len(password) < 15:
password += "\x00" * ( 15 - len(password) )
byteList = list(struct.unpack("B" * 15, password))
if enable:
byteList = [ 1 ] + byteList
else:
byteList = [ 0 ] + byteList
byteList = list(struct.unpack(">"+"H" * 8, struct.pack("B"*16, *byteList)))
self.writeRegister(50120, byteList)
def usbBufferStatus(self):
return self.readRegister(57001)
def numUSBRX(self):
return self.readRegister(57002, numReg = 2, format = '>I')
def numUSBTX(self):
return self.readRegister(57004, numReg = 2, format = '>I')
def numPIBRX(self):
return self.readRegister(57006, numReg = 2, format = '>I')
def numPIBTX(self):
return self.readRegister(57008, numReg = 2, format = '>I')
def lastUsbError(self):
return self.readRegister(57010)
def dmOverflows(self):
return self.readRegister(57011)
def numPibTos(self):
return self.readRegister(57014)
def numUsbTos(self):
return self.readRegister(57015)
def vUsb(self):
return self.readRegister(57050, numReg = 2, format = '>f')
def vJack(self):
return self.readRegister(57052, numReg = 2, format = '>f')
def vSt(self):
return self.readRegister(57054, numReg = 2, format = '>f')
# ------------------ Mote Functions ------------------
# These functions help you work with the motes.
def numMotes(self):
return self.readRegister(59200, numReg = 2, format = '>I')
def listMotes(self):
numMotes = self.readRegister(59200, numReg = 2, format = '>I')
if numMotes == 0:
return []
connectedMotes = []
unitIds = self.readRegister(59202, numReg = numMotes, format = ">" + "H" *numMotes )
if isinstance(unitIds, list):
for unitId in unitIds:
connectedMotes.append(Mote(self, unitId))
return connectedMotes
else:
return [Mote(self, unitIds)]
def makeMote(self, unitId):
return Mote(self, unitId)
class Mote(object):
# ------------------ Object Functions ------------------
# These functions are part of object interaction in python
def __init__(self, bridge, unitId):
self.bridge = bridge
self.unitId = unitId
self.productName = "SkyMote Mote"
self.nickname = None
self.checkinInterval = None
self.processInterval = 1000
self.mainFWVersion = None
self.devType = None
self.serialNumber = None
self.serialString = None
def __repr__(self):
return str(self)
def __str__(self):
return "<Mote Object with ID = %s>" % self.unitId
def readRegister(self, addr, numReg = None, format = None):
return self.bridge.readRegister(addr, numReg = numReg, format = format, unitId = self.unitId)
def writeRegister(self, addr, value):
return self.bridge.writeRegister(addr, value, unitId = self.unitId)
def getName(self):
"""
Name: Device.getName()
Args: None
Desc: Returns the name of a device.
Always returns a unicode string.
Works as of the following firmware versions:
U6 - 1.00
U3 - 1.22
UE9 - 2.00
>>> d = u3.U3()
>>> d.open()
>>> d.getName()
u'My LabJack U3'
"""
name = list(self.readRegister(58000, format='B'*48, numReg = 24))
if name[1] == 3:
# Old style string
name = "My %s" % self.productName
print "Old UTF-16 name detected, replacing with %s" % name
self.setName(name)
name = name.decode("UTF-8")
else:
try:
end = name.index(0x00)
name = struct.pack("B"*end, *name[:end]).decode("UTF-8")
except ValueError:
name = "My %s" % self.productName
print "Improperly formatted name detected, replacing with %s" % name
self.setName(name)
name = name.decode("UTF-8")
return name
def setName(self, name = "My LabJack U3"):
"""
Name: Device.setName(name = ""My LabJack U3")
Args: name, the name you'd like to assign the the U3
Desc: Writes a new name to the device.
Names a limited to 30 characters or less.
Works as of the following firmware versions:
U6 - 1.00
U3 - 1.22
UE9 - 2.00
>>> d = u3.U3()
>>> d.open()
>>> d.getName()
u'My LabJack U3'
>>> d.setName("Johann")
>>> d.getName()
u'Johann'
"""
strLen = len(name)
if strLen > 47:
raise LabJackException("The name is too long, must be less than 48 characters.")
newname = name.encode('UTF-8')
bl = list(struct.unpack("B"*strLen, newname)) + [0x00]
strLen += 1
if strLen%2 != 0:
bl = bl + [0x00]
strLen += 1
bl = struct.unpack(">"+"H"*(strLen/2), struct.pack("B" * strLen, *bl))
self.writeRegister(58000, list(bl))
name = property(getName, setName)
def getUnitId(self):
self.unitId = self.readRegister(65103)
return self.unitId
def setUnitId(self, unitId):
self.writeRegister(65103, unitId)
self.unitId = unitId
return True
def close(self):
self.bridge = None
def mainFirmwareVersion(self):
left, right = self.readRegister(65006, format = ">BB")
self.mainFWVersion = "%s.%02d" % (left, right)
return "%s.%02d" % (left, right)
# ------------------ Convenience Functions ------------------
# These functions call read register for you.
def readSerialNumber(self):
self.serialNumber = self.readRegister(65104, numReg = 4, format = ">Q")
self.serialString = serialToDotHex(self.serialNumber)
return self.serialNumber
def startRapidMode(self, minutes = 3):
# Sends the command to put a bridge in rapid mode.
self.writeRegister(59990, minutes)
def stopRapidMode(self):
# Sends the command to disable rapid mode.
self.startRapidMode(0)
def setCheckinInterval(self, milliseconds=1000, processInterval = None):
if processInterval is None:
processInterval = self.processInterval
self.processInterval = processInterval
bytes = list(struct.unpack(">HHHH", struct.pack(">II", processInterval, milliseconds)))
self.writeRegister(50100, bytes)
def readCheckinInterval(self):
self.checkinInterval = self.readRegister(50102)
return self.checkinInterval
def readProcessInterval(self):
self.processInterval = self.readRegister(50100)
return self.processInterval
def sensorSweep(self):
"""
Performs a sweep of all the sensors on the sensor mote.
"""
rxLqi, txLqi, battery, temp, light, motion, sound = self.readRegister(12000, numReg = 14, format = ">" + "f"*7)
results = dict()
results['RxLQI'] = rxLqi
results['TxLQI'] = txLqi
results['Battery'] = battery
results['Temp'] = temp
results['Light'] = light
results['Motion'] = motion
results['Sound'] = sound
return results
def panId(self):
return self.readRegister(50000)
def sleepTime(self):
return self.readRegister(50100, numReg = 2, format = ">I")
def getNetworkPassword(self):
results = self.readRegister(50120, numReg = 8, format = ">"+"B"*16)
returnDict = dict()
returnDict['enabled'] = True if results[0] != 0 else False
returnDict['password'] = struct.pack("B"*15, *results[1:])
return returnDict
def setNetworkPassword(self, password, enable = True):
if len(password) > 15:
password = password[:15]
if len(password) < 15:
password += "\x00" * ( 15 - len(password) )
byteList = list(struct.unpack("B" * 15, password))
if enable:
byteList = [ 1 ] + byteList
else:
byteList = [ 0 ] + byteList
byteList = list(struct.unpack(">"+"H" * 8, struct.pack("B"*16, *byteList)))
print "Writing:", byteList
self.writeRegister(50120, byteList) | 14,404 | 32.422274 | 159 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/build/lib/u12.py | """
Name: u12.py
Desc: Defines the U12 class, which makes working with a U12 much easier. The
functions of the U12 class are divided into two categories: UW and
low-level.
Most of the UW functions are exposed as functions of the U12 class. With
the exception of the "e" functions, UW functions are Windows only. The "e"
functions will work with both the UW and the Exodriver. Therefore, people
wishing to write cross-platform code should restrict themselves to using
only the "e" functions. The UW functions are described in Section 4 of the
U12 User's Guide:
http://labjack.com/support/u12/users-guide/4
All low-level functions of the U12 class begin with the word
raw. For example, the low-level function Counter can be called with
U12.rawCounter(). Currently, low-level functions are limited to the
Exodriver (Linux and Mac OS X). You can find descriptions of the low-level
functions in Section 5 of the U12 User's Guide:
http://labjack.com/support/u12/users-guide/5
"""
import platform
import ctypes
import os, atexit
import math
from time import time
import struct
WINDOWS = "Windows"
ON_WINDOWS = (os.name == 'nt')
class U12Exception(Exception):
"""Custom Exception meant for dealing specifically with U12 Exceptions.
Error codes are either going to be a LabJackUD error code or a -1. The -1 implies
a python wrapper specific error.
def __init__(self, ec = 0, errorString = ''):
self.errorCode = ec
self.errorString = errorString
if not self.errorString:
#try:
self.errorString = getErrorString(ec)
#except:
# self.errorString = str(self.errorCode)
def __str__(self):
return self.errorString
"""
pass
class BitField(object):
"""
Provides a method for working with bit fields.
>>> bf = BitField()
>>> print bf
[ bit7 = 0, bit6 = 0, bit5 = 0, bit4 = 0, bit3 = 0, bit2 = 0, bit1 = 0, bit0 = 0 ]
You can use attribute accessing for easy bit flipping:
>>> bf.bit4 = 1
>>> bf.bit7 = 1
>>> print bf
[ bit7 = 1, bit6 = 0, bit5 = 0, bit4 = 1, bit3 = 0, bit2 = 0, bit1 = 0, bit0 = 0 ]
You can also use list-style accessing. Counting starts on the left:
>>> print bf[0] # List index 0 is bit7
1
>>> print bf[3] # List index 3 is bit4
1
List-style slicing:
>>> print bf[3:]
[1, 0, 0, 0, 0]
List-style setting bits works as you would expect:
>>> bf[1] = 1
>>> print bf
[ bit7 = 1, bit6 = 1, bit5 = 0, bit4 = 1, bit3 = 0, bit2 = 0, bit1 = 0, bit0 = 0 ]
It provides methods for going to and from bytes:
>>> bf = BitField(123)
>>> print bf
[ bit7 = 0, bit6 = 1, bit5 = 1, bit4 = 1, bit3 = 1, bit2 = 0, bit1 = 1, bit0 = 1 ]
>>> bf = BitField()
>>> bf.fromByte(123) # Modifies bf in place
>>> print bf
[ bit7 = 0, bit6 = 1, bit5 = 1, bit4 = 1, bit3 = 1, bit2 = 0, bit1 = 1, bit0 = 1 ]
>>> bf.bit4 = 0
>>> print bf.asByte()
107
You can iterate of the raw bits ( 1 and 0 Vs. '1' and '0') easily:
>>> for i in bf:
... print i
0
1
1
0
1
0
1
1
You can also iterate over the labels and their data values using items():
>>> for label, data in bf.items():
... print label, data
bit7 0
bit6 1
bit5 1
bit4 0
bit3 1
bit2 0
bit1 1
bit0 1
As an added bonus, it can also be cast as an int or hex:
>>> int(bf)
107
>>> hex(bf)
'0x6b'
See the description of the __init__ method for setting the label parameters. """
def __init__(self, rawByte = None, labelPrefix = "bit", labelList = None, zeroLabel = "0", oneLabel = "1"):
"""
Name: BitField.__init__(rawByte = None, labelPrefix = "bit",
labelList = None, zeroLabel = "0",
oneLabel = "1")
Args: rawByte, a value to set the bit field values to.
labelPrefix, what should go before the labels in labelList
labelList, a list of labels to apply to each bit. If None, it
gets set to range(7,-1,-1).
zeroLabel, bits with a value of 0 will have this label
oneLabel, bits with a value of 1 will have this label
Desc: Creates a new bitfield and sets up the labels.
With out any arguments, you get a bit field that looks like this:
>>> bf = BitField()
>>> print bf
[ bit7 = 0, bit6 = 0, bit5 = 0, bit4 = 0, bit3 = 0, bit2 = 0, bit1 = 0,
bit0 = 0 ]
To make the labels, it iterates over all the labelList and adds the
labelPrefix to them. If you have less than 8 labels, then your bit field
will only work up to that many bits.
To make a BitField with labels for FIO0-7 you can do the following:
>>> bf = BitField(labelPrefix = "FIO")
>>> print bf
[ FIO7 = 0, FIO6 = 0, FIO5 = 0, FIO4 = 0, FIO3 = 0, FIO2 = 0, FIO1 = 0,
FIO0 = 0 ]
The labels don't have to be numbers, for example:
>>> names = [ "Goodreau", "Jerri", "Selena", "Allan", "Tania",
"Kathrine", "Jessie", "Zelma" ]
>>> bf = BitField( labelPrefix = "", labelList = names)
>>> print bf
[ Goodreau = 0, Jerri = 0, Selena = 0, Allan = 0, Tania = 0,
Kathrine = 0, Jessie = 0, Zelma = 0 ]
You can change the display value of zero and one to be whatever you
want. For example, if you have a BitField that represents FIO0-7
directions:
>>> dirs = BitField(rawByte = 5, labelPrefix = "FIO",
zeroLabel = "Output", oneLabel = "Input")
>>> print dirs
[ FIO7 = Output, FIO6 = Output, FIO5 = Output, FIO4 = Output,
FIO3 = Output, FIO2 = Input, FIO1 = Output, FIO0 = Input ]
Note, that when you access the value, you will get 1 or 0, not "Input"
or "Output. For example:
>>> print dirs.FIO3
0
"""
# Do labels first, so that self.something = something works.
self.__dict__['labels'] = []
self.labelPrefix = labelPrefix
if labelList is None:
self.labelList = range(8)
else:
self.labelList = list(reversed(labelList))
self.zeroLabel = zeroLabel
self.oneLabel = oneLabel
self.rawValue = 0
self.rawBits = [ 0 ] * 8
self.data = [ self.zeroLabel ] * 8
items = min(8, len(self.labelList))
for i in reversed(range(items)):
self.labels.append("%s%s" % (self.labelPrefix, self.labelList[i]))
if rawByte is not None:
self.fromByte(rawByte)
def fromByte(self, raw):
"""
Name: BitField.fromByte(raw)
Args: raw, the raw byte to make the BitField.
Desc: Takes a byte, and modifies self to match.
>>> bf = BitField()
>>> bf.fromByte(123) # Modifies bf in place
>>> print bf
[ bit7 = 0, bit6 = 1, bit5 = 1, bit4 = 1, bit3 = 1, bit2 = 0, bit1 = 1,
bit0 = 1 ]
"""
self.rawValue = raw
self.rawBits = []
self.data = []
items = min(8, len(self.labelList))
for i in reversed(range(items)):
self.rawBits.append( ((raw >> (i)) & 1) )
self.data.append(self.oneLabel if bool(((raw >> (i)) & 1)) else self.zeroLabel)
def asByte(self):
"""
Name: BitField.asByte()
Args: None
Desc: Returns the value of the bitfield as a byte.
>>> bf = BitField()
>>> bf.fromByte(123) # Modifies bf in place
>>> bf.bit4 = 0
>>> print bf.asByte()
107
"""
byteVal = 0
for i, v in enumerate(reversed(self.rawBits)):
byteVal += ( 1 << i ) * v
return byteVal
def asBin(self):
result = "0b"
for i in self.rawBits:
result += "%s" % i
return result
def __len__(self):
return len(self.data)
def __repr__(self):
result = "["
for i in range(len(self.data)):
result += " %s = %s (%s)," % (self.labels[i], self.data[i], self.rawBits[i])
result = result.rstrip(',')
result += " ]"
return "<BitField object: %s >" % result
def __str__(self):
result = "["
for i in range(len(self.data)):
result += " %s = %s," % (self.labels[i], self.data[i])
result = result.rstrip(',')
result += " ]"
return result
def __getattr__(self, label):
try:
i = self.labels.index(label)
return self.rawBits[i]
except ValueError:
raise AttributeError(label)
def __setattr__(self, label, value):
try:
i = self.labels.index(label)
self.rawBits[i] = int(bool(value))
self.data[i] = self.oneLabel if bool(value) else self.zeroLabel
except ValueError:
self.__dict__[label] = value
def __getitem__(self, key):
return self.rawBits[key]
def __setitem__(self, key, value):
self.rawBits[key] = int(bool(value))
self.data[key] = self.oneLabel if bool(value) else self.zeroLabel
def __iter__(self):
return iter(self.rawBits)
def items(self):
"""
Name: BitField.items()
Args: None
Desc: Returns a list of tuples where the first item is the label and the
second is the string value, like "High" or "Input"
>>> dirs = BitField(rawByte = 5, labelPrefix = "FIO",
zeroLabel = "Output", oneLabel = "Input")
>>> print dirs
[ FIO7 = Output, FIO6 = Output, FIO5 = Output, FIO4 = Output,
FIO3 = Output, FIO2 = Input, FIO1 = Output, FIO0 = Input ]
>>> for label, data in dirs.items():
... print label, data
...
FIO7 Output
FIO6 Output
FIO5 Output
FIO4 Output
FIO3 Output
FIO2 Input
FIO1 Output
FIO0 Input
"""
return zip(self.labels, self.data)
def __int__(self):
return self.asByte()
def __hex__(self):
return hex(self.asByte())
def __add__(self, other):
"""
A helper to prevent having to test if a variable is a bitfield or int.
"""
return other + self.asByte()
def errcheck(ret, func, args):
if ret == -1:
try:
ec = ctypes.get_errno()
raise U12Exception("Exodriver returned error number %s" % ec)
except AttributeError:
raise U12Exception("Exodriver returned an error, but LabJackPython is unable to read the error code. Upgrade to Python 2.6 for this functionality.")
else:
return ret
def _loadLinuxSo():
try:
l = ctypes.CDLL("liblabjackusb.so", use_errno=True)
except TypeError:
l = ctypes.CDLL("liblabjackusb.so")
l.LJUSB_Stream.errcheck = errcheck
l.LJUSB_Read.errcheck = errcheck
return l
def _loadMacDylib():
try:
l = ctypes.CDLL("liblabjackusb.dylib", use_errno=True)
except TypeError:
l = ctypes.CDLL("liblabjackusb.dylib")
l.LJUSB_Stream.errcheck = errcheck
l.LJUSB_Read.errcheck = errcheck
return l
staticLib = None
if os.name == 'posix':
try:
staticLib = _loadLinuxSo()
except OSError, e:
pass # We may be on Mac.
except Exception, e:
raise U12Exception("Could not load the Linux SO for some reason other than it not being installed. Ethernet connectivity only.\n\n The error was: %s" % e)
try:
if staticLib is None:
staticLib = _loadMacDylib()
except OSError, e:
raise U12Exception("Could not load the Exodriver driver. Ethernet connectivity only.\n\nCheck that the Exodriver is installed, and the permissions are set correctly.\nThe error message was: %s" % e)
except Exception, e:
raise U12Exception("Could not load the Mac Dylib for some reason other than it not being installed. Ethernet connectivity only.\n\n The error was: %s" % e)
else:
try:
staticLib = ctypes.windll.LoadLibrary("ljackuw")
except:
raise Exception, "Could not load LabJack UW driver."
class U12(object):
"""
U12 Class for all U12 specific commands.
u12 = U12()
"""
def __init__(self, id = -1, serialNumber = None, debug = False):
self.id = id
self.serialNumber = serialNumber
self.deviceName = "U12"
self.streaming = False
self.handle = None
self.debug = debug
self._autoCloseSetup = False
if not ON_WINDOWS:
# Save some variables to save state.
self.pwmAVoltage = 0
self.pwmBVoltage = 0
self.open(id, serialNumber)
def open(self, id = -1, serialNumber = None):
"""
Opens the U12.
The Windows UW driver opens the device every time a function is called.
The Exodriver, however, works like the UD family of devices and returns
a handle. On Windows, this method does nothing. On Mac OS X and Linux,
this method acquires a device handle and saves it to the U12 object.
"""
if ON_WINDOWS:
pass
else:
if self.debug: print "open called"
devType = ctypes.c_ulong(1)
openDev = staticLib.LJUSB_OpenDevice
openDev.restype = ctypes.c_void_p
if serialNumber is not None:
numDevices = staticLib.LJUSB_GetDevCount(devType)
for i in range(numDevices):
handle = openDev(i+1, 0, devType)
if handle != 0 and handle is not None:
self.handle = ctypes.c_void_p(handle)
try:
serial = self.rawReadSerial()
except Exception:
serial = self.rawReadSerial()
if serial == int(serialNumber):
break
else:
self.close()
if self.handle is None:
raise U12Exception("Couldn't find a U12 with a serial number matching %s" % serialNumber)
elif id != -1:
numDevices = staticLib.LJUSB_GetDevCount(devType)
for i in range(numDevices):
handle = openDev(i+1, 0, devType)
if handle != 0 and handle is not None:
self.handle = ctypes.c_void_p(handle)
try:
unitId = self.rawReadLocalId()
except Exception:
unitId = self.rawReadLocalId()
if unitId == int(id):
break
else:
self.close()
if self.handle is None:
raise U12Exception("Couldn't find a U12 with a local ID matching %s" % id)
elif id == -1:
handle = openDev(1, 0, devType)
if handle == 0 or handle is None:
raise Exception("Couldn't open a U12. Check that one is connected and try again.")
else:
self.handle = ctypes.c_void_p(handle)
# U12 ignores first command, so let's write a command.
command = [ 0 ] * 8
command[5] = 0x57 # 0b01010111
try:
self.write(command)
self.read()
except:
pass
self.id = self.rawReadLocalId()
else:
raise Exception("Invalid combination of parameters.")
if not self._autoCloseSetup:
# Only need to register auto-close once per device.
atexit.register(self.close)
self._autoCloseSetup = True
def close(self):
if ON_WINDOWS:
pass
else:
staticLib.LJUSB_CloseDevice(self.handle)
self.handle = None
def write(self, writeBuffer):
if ON_WINDOWS:
pass
else:
if self.handle is None:
raise U12Exception("The U12's handle is None. Please open a U12 with open()")
if self.debug: print "Writing:", hexWithoutQuotes(writeBuffer)
newA = (ctypes.c_byte*len(writeBuffer))(0)
for i in range(len(writeBuffer)):
newA[i] = ctypes.c_byte(writeBuffer[i])
writeBytes = staticLib.LJUSB_Write(self.handle, ctypes.byref(newA), len(writeBuffer))
if(writeBytes != len(writeBuffer)):
raise U12Exception( "Could only write %s of %s bytes." % (writeBytes, len(writeBuffer) ) )
return writeBuffer
def read(self, numBytes = 8):
if ON_WINDOWS:
pass
else:
if self.handle is None:
raise U12Exception("The U12's handle is None. Please open a U12 with open()")
newA = (ctypes.c_byte*numBytes)()
readBytes = staticLib.LJUSB_Read(self.handle, ctypes.byref(newA), numBytes)
# return a list of integers in command/response mode
result = [(newA[i] & 0xff) for i in range(readBytes)]
if self.debug: print "Received:", hexWithoutQuotes(result)
return result
# Low-level helpers
def rawReadSerial(self):
"""
Name: U12.rawReadSerial()
Args: None
Desc: Reads the serial number from internal memory.
Returns: The U12's serial number as an integer.
Example:
>>> import u12
>>> d = u12.U12()
>>> print d.rawReadSerial()
10004XXXX
"""
results = self.rawReadRAM()
return struct.unpack(">I", struct.pack("BBBB", results['DataByte3'], results['DataByte2'], results['DataByte1'], results['DataByte0']))[0]
def rawReadLocalId(self):
"""
Name: U12.rawReadLocalId()
Args: None
Desc: Reads the Local ID from internal memory.
Returns: The U12's Local ID as an integer.
Example:
>>> import u12
>>> d = u12.U12()
>>> print d.rawReadLocalId()
0
"""
results = self.rawReadRAM(0x08)
return results['DataByte0']
# Begin Section 5 Functions
def rawAISample(self, channel0PGAMUX = 8, channel1PGAMUX = 9, channel2PGAMUX = 10, channel3PGAMUX = 11, UpdateIO = False, LEDState = True, IO3toIO0States = 0, EchoValue = 0):
"""
Name: U12.rawAISample(channel0PGAMUX = 8, channel1PGAMUX = 9,
channel2PGAMUX = 10, channel3PGAMUX = 11,
UpdateIO = False, LEDState = True,
IO3toIO0States = 0, EchoValue = 0)
Args: channel0PGAMUX, A byte that contains channel0 information
channel1PGAMUX, A byte that contains channel1 information
channel2PGAMUX, A byte that contains channel2 information
channel3PGAMUX, A byte that contains channel3 information
IO3toIO0States, A byte that represents the states of IO0 to IO3
UpdateIO, If true, set IO0 to IO 3 to match IO3toIO0States
LEDState, Turns the status LED on or off.
EchoValue, Sometimes, you want what you put in.
Desc: Collects readings from 4 analog inputs. It can also toggle the
status LED and update the state of the IOs. See Section 5.1 of
the User's Guide.
By default it will read AI0-3 (single-ended).
Returns: A dictionary with the following keys:
PGAOvervoltage, A bool representing if the U12 detected overvoltage
IO3toIO0States, a BitField representing the state of IO0 to IO3
Channel0-3, the analog voltage for the channel
EchoValue, a repeat of the value passed in.
Example:
>>> import u12
>>> d = u12.U12()
>>> d.rawAISample()
{
'IO3toIO0States':
<BitField object: [ IO3 = Low (0), IO2 = Low (0),
IO1 = Low (0), IO0 = Low (0) ] >,
'Channel0': 1.46484375,
'Channel1': 1.4501953125,
'Channel2': 1.4599609375,
'Channel3': 1.4306640625,
'PGAOvervoltage': False,
'EchoValue': 0
}
"""
command = [ 0 ] * 8
# Bits 6-4: PGA for 1st Channel
# Bits 3-0: MUX command for 1st Channel
command[0] = int(channel0PGAMUX)
tempNum = command[0] & 7 # 7 = 0b111
channel0Number = tempNum if (command[0] & 0xf) > 7 else tempNum+8
channel0Gain = (command[0] >> 4) & 7 # 7 = 0b111
command[1] = int(channel1PGAMUX)
tempNum = command[1] & 7 # 7 = 0b111
channel1Number = tempNum if (command[1] & 0xf) > 7 else tempNum+8
channel1Gain = (command[1] >> 4) & 7 # 7 = 0b111
command[2] = int(channel2PGAMUX)
tempNum = command[2] & 7 # 7 = 0b111
channel2Number = tempNum if (command[2] & 0xf) > 7 else tempNum+8
channel2Gain = (command[2] >> 4) & 7 # 7 = 0b111
command[3] = int(channel3PGAMUX)
tempNum = command[3] & 7 # 7 = 0b111
channel3Number = tempNum if (command[3] & 0xf) > 7 else tempNum+8
channel3Gain = (command[3] >> 4) & 7 # 7 = 0b111
# Bit 1: Update IO
# Bit 0: LED State
bf = BitField()
bf.bit1 = int(UpdateIO)
bf.bit0 = int(LEDState)
command[4] = int(bf)
# Bit 7-4: 1100 (Command/Response)
# Bit 3-0: Bits for IO3 through IO0 States
bf.fromByte(0)
bf.bit7 = 1
bf.bit6 = 1
bf.fromByte( int(bf) | int(IO3toIO0States) )
command[5] = int(bf)
command[7] = EchoValue
self.write(command)
results = self.read()
bf = BitField()
bf.fromByte(results[0])
if bf.bit7 != 1 or bf.bit6 != 0:
raise U12Exception("Expected a AIStream response, got %s instead." % results[0])
returnDict = {}
returnDict['EchoValue'] = results[1]
returnDict['PGAOvervoltage'] = bool(bf.bit4)
returnDict['IO3toIO0States'] = BitField(results[0], "IO", range(3, -1, -1), "Low", "High")
channel0 = (results[2] >> 4) & 0xf
channel1 = (results[2] & 0xf)
channel2 = (results[5] >> 4) & 0xf
channel3 = (results[5] & 0xf)
channel0 = (channel0 << 8) + results[3]
returnDict['Channel0'] = self.bitsToVolts(channel0Number, channel0Gain, channel0)
channel1 = (channel1 << 8) + results[4]
returnDict['Channel1'] = self.bitsToVolts(channel1Number, channel1Gain, channel1)
channel2 = (channel2 << 8) + results[6]
returnDict['Channel2'] = self.bitsToVolts(channel2Number, channel2Gain, channel2)
channel3 = (channel3 << 8) + results[7]
returnDict['Channel3'] = self.bitsToVolts(channel3Number, channel3Gain, channel3)
return returnDict
def rawDIO(self, D15toD8Directions = 0, D7toD0Directions = 0, D15toD8States = 0, D7toD0States = 0, IO3toIO0DirectionsAndStates = 0, UpdateDigital = False):
"""
Name: U12.rawDIO(D15toD8Directions = 0, D7toD0Directions = 0,
D15toD8States = 0, D7toD0States = 0,
IO3toIO0DirectionsAndStates = 0, UpdateDigital = 1)
Args: D15toD8Directions, A byte where 0 = Output, 1 = Input for D15-8
D7toD0Directions, A byte where 0 = Output, 1 = Input for D7-0
D15toD8States, A byte where 0 = Low, 1 = High for D15-8
D7toD0States, A byte where 0 = Low, 1 = High for D7-0
IO3toIO0DirectionsAndStates, Bits 7-4: Direction, 3-0: State
UpdateDigital, True if you want to update the IO/D line. False to
False to just read their values.
Desc: This commands reads the direction and state of all the digital
I/O. See Section 5.2 of the U12 User's Guide.
By default, it just reads the directions and states.
Returns: A dictionary with the following keys:
D15toD8Directions, a BitField representing the directions of D15-D8
D7toD0Directions, a BitField representing the directions of D7-D0.
D15toD8States, a BitField representing the states of D15-D8.
D7toD0States, a BitField representing the states of D7-D0.
IO3toIO0States, a BitField representing the states of IO3-IO0.
D15toD8OutputLatchStates, BitField of output latch states for D15-8
D7toD0OutputLatchStates, BitField of output latch states for D7-0
Example:
>>> import u12
>>> d = u12.U12()
>>> d.rawDIO()
{
'D15toD8Directions':
<BitField object: [ D15 = Input (1), D14 = Input (1),
D13 = Input (1), D12 = Input (1),
D11 = Input (1), D10 = Input (1),
D9 = Input (1), D8 = Input (1) ] >,
'D7toD0Directions':
<BitField object: [ D7 = Input (1), D6 = Input (1), D5 = Input (1),
D4 = Input (1), D3 = Input (1), D2 = Input (1),
D1 = Input (1), D0 = Input (1) ] >,
'D15toD8States':
<BitField object: [ D15 = Low (0), D14 = Low (0), D13 = Low (0),
D12 = Low (0), D11 = Low (0), D10 = Low (0),
D9 = Low (0), D8 = Low (0) ] >,
'D7toD0States':
<BitField object: [ D7 = Low (0), D6 = Low (0), D5 = Low (0),
D4 = Low (0), D3 = Low (0), D2 = Low (0),
D1 = Low (0), D0 = Low (0) ] >,
'IO3toIO0States':
<BitField object: [ IO3 = Low (0), IO2 = Low (0), IO1 = Low (0),
IO0 = Low (0) ] >,
'D15toD8OutputLatchStates':
<BitField object: [ D15 = 0 (0), D14 = 0 (0), D13 = 0 (0),
D12 = 0 (0), D11 = 0 (0), D10 = 0 (0),
D9 = 0 (0), D8 = 0 (0) ] >,
'D7toD0OutputLatchStates':
<BitField object: [ D7 = 0 (0), D6 = 0 (0), D5 = 0 (0), D4 = 0 (0),
D3 = 0 (0), D2 = 0 (0), D1 = 0 (0),
D0 = 0 (0) ] >
}
"""
command = [ 0 ] * 8
# Bits for D15 through D8 Direction
command[0] = int(D15toD8Directions)
# Bits for D7 through D0 Direction ( 0 = Output, 1 = Input)
command[1] = int(D7toD0Directions)
# Bits for D15 through D8 State ( 0 = Low, 1 = High)
command[2] = int(D15toD8States)
# Bits for D7 through D0 State ( 0 = Low, 1 = High)
command[3] = int(D7toD0States)
# Bits 7-4: Bits for IO3 through IO0 Direction
# Bits 3-0: Bits for IO3 through IO0 State
command[4] = int(IO3toIO0DirectionsAndStates)
# 01X10111 (DIO)
command[5] = 0x57 # 0b01010111
# Bit 0: Update Digital
command[6] = int(bool(UpdateDigital))
#XXXXXXXX
# command[7] = XXXXXXXX
self.write(command)
results = self.read()
returnDict = {}
if results[0] != 87:
raise U12Exception("Expected a DIO response, got %s instead." % results[0])
returnDict['D15toD8States'] = BitField(results[1], "D", range(15, 7, -1), "Low", "High")
returnDict['D7toD0States'] = BitField(results[2], "D", range(7, -1, -1), "Low", "High")
returnDict['D15toD8Directions'] = BitField(results[4], "D", range(15, 7, -1), "Output", "Input")
returnDict['D7toD0Directions'] = BitField(results[5], "D", range(7, -1, -1), "Output", "Input")
returnDict['D15toD8OutputLatchStates'] = BitField(results[6], "D", range(15, 7, -1))
returnDict['D7toD0OutputLatchStates'] = BitField(results[7], "D", range(7, -1, -1))
returnDict['IO3toIO0States'] = BitField((results[3] >> 4), "IO", range(3, -1, -1), "Low", "High")
return returnDict
def rawCounter(self, StrobeEnabled = False, ResetCounter = False):
"""
Name: U12.rawCounter(StrobeEnabled = False, ResetCounter = False)
Args: StrobeEnable, set to True to enable strobe.
ResetCounter, set to True to reset the counter AFTER reading.
Desc: This command controls and reads the 32-bit counter. See
Section 5.3 of the User's Guide.
Returns: A dictionary with the following keys:
D15toD8States, a BitField representing the states of D15-D8.
D7toD0States, a BitField representing the states of D7-D0.
IO3toIO0States, a BitField representing the states of IO3-IO0.
Counter, the value of the counter
Example:
>>> import u12
>>> d = u12.U12()
>>> d.rawCounter()
{
'D15toD8States':
<BitField object: [ D15 = Low (0), D14 = Low (0), D13 = Low (0),
D12 = Low (0), D11 = Low (0), D10 = Low (0),
D9 = Low (0), D8 = Low (0) ] >,
'D7toD0States':
<BitField object: [ D7 = Low (0), D6 = Low (0), D5 = Low (0),
D4 = Low (0), D3 = Low (0), D2 = Low (0),
D1 = Low (0), D0 = Low (0) ] >,
'IO3toIO0States':
<BitField object: [ IO3 = Low (0), IO2 = Low (0), IO1 = Low (0),
IO0 = Low (0) ] >,
'Counter': 0
}
"""
command = [ 0 ] * 8
bf = BitField()
bf.bit1 = int(StrobeEnabled)
bf.bit0 = int(ResetCounter)
command[0] = int(bf)
bf.fromByte(0)
bf.bit6 = 1
bf.bit4 = 1
bf.bit1 = 1
command[5] = int(bf)
self.write(command)
results = self.read()
returnDict = {}
if results[0] != command[5]:
raise U12Exception("Expected a Counter response, got %s instead." % results[0])
returnDict['D15toD8States'] = BitField(results[1], "D", range(15, 7, -1), "Low", "High")
returnDict['D7toD0States'] = BitField(results[2], "D", range(7, -1, -1), "Low", "High")
returnDict['IO3toIO0States'] = BitField((results[3] >> 4), "IO", range(3, -1, -1), "Low", "High")
counter = results[7]
counter += results[6] << 8
counter += results[5] << 16
counter += results[4] << 24
returnDict['Counter'] = counter
return returnDict
def rawCounterPWMDIO(self, D15toD8Directions = 0, D7toD0Directions = 0, D15toD8States = 0, D7toD0States = 0, IO3toIO0DirectionsAndStates = 0, ResetCounter = False, UpdateDigital = 0, PWMA = 0, PWMB = 0):
"""
Name: U12.rawCounterPWMDIO( D15toD8Directions = 0, D7toD0Directions = 0,
D15toD8States = 0, D7toD0States = 0,
IO3toIO0DirectionsAndStates = 0,
ResetCounter = False, UpdateDigital = 0,
PWMA = 0, PWMB = 0)
Args: D15toD8Directions, A byte where 0 = Output, 1 = Input for D15-8
D7toD0Directions, A byte where 0 = Output, 1 = Input for D7-0
D15toD8States, A byte where 0 = Low, 1 = High for D15-8
D7toD0States, A byte where 0 = Low, 1 = High for D7-0
IO3toIO0DirectionsAndStates, Bits 7-4: Direction, 3-0: State
ResetCounter, If True, reset the counter after reading.
UpdateDigital, True if you want to update the IO/D line. False to
False to just read their values.
PWMA, Voltage to set AO0 to output.
PWMB, Voltage to set AO1 to output.
Desc: This command controls all 20 digital I/O, and the 2 PWM outputs.
The response provides the state of all I/O and the current count.
See Section 5.4 of the User's Guide.
By default, sets the AOs to 0 and reads the states and counters.
Returns: A dictionary with the following keys:
D15toD8States, a BitField representing the states of D15-D8.
D7toD0States, a BitField representing the states of D7-D0.
IO3toIO0States, a BitField representing the states of IO3-IO0.
Counter, the value of the counter
Example:
>>> import u12
>>> d = u12.U12()
>>> d.rawCounterPWMDIO()
{
'D15toD8States':
<BitField object: [ D15 = Low (0), D14 = Low (0), D13 = Low (0),
D12 = Low (0), D11 = Low (0), D10 = Low (0),
D9 = Low (0), D8 = Low (0) ] >,
'D7toD0States':
<BitField object: [ D7 = Low (0), D6 = Low (0), D5 = Low (0),
D4 = Low (0), D3 = Low (0), D2 = Low (0),
D1 = Low (0), D0 = Low (0) ] >,
'IO3toIO0States':
<BitField object: [ IO3 = Low (0), IO2 = Low (0),
IO1 = Low (0), IO0 = Low (0) ] >,
'Counter': 0
}
"""
command = [ 0 ] * 8
# Bits for D15 through D8 Direction
command[0] = int(D15toD8Directions)
# Bits for D7 through D0 Direction ( 0 = Output, 1 = Input)
command[1] = int(D7toD0Directions)
# Bits for D15 through D8 State ( 0 = Low, 1 = High)
command[2] = int(D15toD8States)
# Bits for D7 through D0 State ( 0 = Low, 1 = High)
command[3] = int(D7toD0States)
# Bits 7-4: Bits for IO3 through IO0 Direction
# Bits 3-0: Bits for IO3 through IO0 State
command[4] = int(IO3toIO0DirectionsAndStates)
bf = BitField()
bf.bit5 = int(ResetCounter)
bf.bit4 = int(UpdateDigital)
binPWMA = int((1023 * (float(PWMA)/5.0)))
binPWMB = int((1023 * (float(PWMB)/5.0)))
bf2 = BitField()
bf2.fromByte( binPWMA & 3 ) # 3 = 0b11
bf.bit3 = bf2.bit1
bf.bit2 = bf2.bit0
bf2.fromByte( binPWMB & 3 ) # 3 = 0b11
bf.bit1 = bf2.bit1
bf.bit0 = bf2.bit0
command[5] = int(bf)
command[6] = (binPWMA >> 2) & 0xff
command[7] = (binPWMB >> 2) & 0xff
self.write(command)
results = self.read()
returnDict = {}
returnDict['D15toD8States'] = BitField(results[1], "D", range(15, 7, -1), "Low", "High")
returnDict['D7toD0States'] = BitField(results[2], "D", range(7, -1, -1), "Low", "High")
returnDict['IO3toIO0States'] = BitField((results[3] >> 4), "IO", range(3, -1, -1), "Low", "High")
counter = results[7]
counter += results[6] << 8
counter += results[5] << 16
counter += results[4] << 24
returnDict['Counter'] = counter
return returnDict
def rawAIBurst(self, channel0PGAMUX = 8, channel1PGAMUX = 9, channel2PGAMUX = 10, channel3PGAMUX = 11, NumberOfScans = 8, TriggerIONum = 0, TriggerState = 0, UpdateIO = False, LEDState = True, IO3ToIO0States = 0, FeatureReports = False, TriggerOn = False, SampleInterval = 15000):
"""
Name: U12.rawAIBurst( channel0PGAMUX = 8, channel1PGAMUX = 9,
channel2PGAMUX = 10, channel3PGAMUX = 11,
NumberOfScans = 8, TriggerIONum = 0,
TriggerState = 0, UpdateIO = False,
LEDState = True, IO3ToIO0States = 0,
FeatureReports = False, TriggerOn = False,
SampleInterval = 15000 )
Args: channel0PGAMUX, A byte that contains channel0 information
channel1PGAMUX, A byte that contains channel1 information
channel2PGAMUX, A byte that contains channel2 information
channel3PGAMUX, A byte that contains channel3 information
NumberOfScans, The number of scans you wish to take. Rounded up
to a power of 2.
TriggerIONum, IO to trigger burst on.
TriggerState, State to trigger on.
UpdateIO, True if you want to update the IO/D line. False to
False to just read their values.
LEDState, Turns the status LED on or off.
IO3ToIO0States, 4 bits for IO3-0 states
FeatureReports, Use feature reports, or not.
TriggerOn, Use trigger to start acquisition.
SampleInterval, = int(6000000.0/(ScanRate * NumberOfChannels))
must be greater than (or equal to) 733.
Desc: After receiving a AIBurst command, the LabJack collects 4
channels at the specified data rate, and puts data in the buffer.
This continues until the buffer is full, at which time the
LabJack starts sending the data to the host. Data is sent to the
host 1 scan at a time while checking for a command from the host.
If a command is received the burst operation is canceled and the
command is executed normally. If the LED is enabled, it blinks at
4 Hz while waiting for a trigger, is off during acquisition,
blinks at about 8 Hz during data delivery, and is set on when
done or stopped. See Section 5.5 of the User's Guide.
This function sends the AIBurst command, then reads all the
responses. Separating the write and read is not currently
supported (like in the UW driver).
By default, it does single-ended readings on AI0-4 at 100Hz for 8
scans.
Returns: A dictionary with the following keys:
Channel0-3, A list of the readings on the channels
PGAOvervoltages, A list of the over-voltage flags
IO3toIO0State, A list of the IO states
IterationCounters, A list of the values of the iteration counter
Backlogs, value*256 = number of packets in the backlog.
BufferOverflowOrChecksumErrors, If True and Backlog = 31,
then a buffer overflow occurred. If
True and Backlog = 0, then Checksum
error occurred.
Example:
>>> import u12
>>> d = u12.U12()
>>> d.rawAIBurst()
{
'Channel0': [1.484375, 1.513671875, ... , 1.46484375],
'Channel1': [1.455078125, 1.455078125, ... , 1.455078125],
'Channel2': [1.46484375, 1.474609375, ... , 1.46484375],
'Channel3': [1.435546875, 1.42578125, ... , 1.435546875],
'PGAOvervoltages': [False, False, ..., False],
'IO3toIO0States':
[<BitField object: [ IO3 = Low (0), IO2 = Low (0), IO1 = Low (0),
IO0 = Low (0) ] >, ... ],
'IterationCounters': [0, 1, 2, 3, 4, 5, 6, 0],
'Backlogs': [0, 0, 0, 0, 0, 0, 0, 0],
'BufferOverflowOrChecksumErrors': [False, False, ... , False]
}
"""
command = [ 0 ] * 8
# Bits 6-4: PGA for 1st Channel
# Bits 3-0: MUX command for 1st Channel
command[0] = int(channel0PGAMUX)
tempNum = command[0] & 7 # 7 = 0b111
channel0Number = tempNum if (command[0] & 0xf) > 7 else tempNum+8
channel0Gain = (command[0] >> 4) & 7 # 7 = 0b111
command[1] = int(channel1PGAMUX)
tempNum = command[1] & 7 # 7 = 0b111
channel1Number = tempNum if (command[1] & 0xf) > 7 else tempNum+8
channel1Gain = (command[1] >> 4) & 7 # 7 = 0b111
command[2] = int(channel2PGAMUX)
tempNum = command[2] & 7 # 7 = 0b111
channel2Number = tempNum if (command[2] & 0xf) > 7 else tempNum+8
channel2Gain = (command[2] >> 4) & 7 # 7 = 0b111
command[3] = int(channel3PGAMUX)
tempNum = command[3] & 7 # 7 = 0b111
channel3Number = tempNum if (command[3] & 0xf) > 7 else tempNum+8
channel3Gain = (command[3] >> 4) & 7 # 7 = 0b111
if NumberOfScans > 1024 or NumberOfScans < 8:
raise U12Exception("The number of scans must be between 1024 and 8 (inclusive)")
NumScansExponentMod = 10 - int(math.ceil(math.log(NumberOfScans, 2)))
NumScans = 2 ** (10 - NumScansExponentMod)
bf = BitField( rawByte = (NumScansExponentMod << 5) )
# bits 4-3: IO to Trigger on
bf.bit2 = 0
bf.bit1 = int(bool(UpdateIO))
bf.bit0 = int(bool(LEDState))
command[4] = int(bf)
bf2 = BitField(rawByte = int(IO3ToIO0States))
#Bits 7-4: 1010 (Start Burst)
bf2.bit7 = 1
bf2.bit5 = 1
command[5] = int(bf2)
if SampleInterval < 733:
raise U12Exception("SampleInterval must be greater than 733.")
bf3 = BitField( rawByte = ((SampleInterval >> 8) & 0xf) )
bf3.bit7 = int(bool(FeatureReports))
bf3.bit6 = int(bool(TriggerOn))
command[6] = int(bf3)
command[7] = SampleInterval & 0xff
self.write(command)
resultsList = []
for i in range(NumScans):
resultsList.append(self.read())
returnDict = {}
returnDict['BufferOverflowOrChecksumErrors'] = list()
returnDict['PGAOvervoltages'] = list()
returnDict['IO3toIO0States'] = list()
returnDict['IterationCounters'] = list()
returnDict['Backlogs'] = list()
returnDict['Channel0'] = list()
returnDict['Channel1'] = list()
returnDict['Channel2'] = list()
returnDict['Channel3'] = list()
for results in resultsList:
bf = BitField(rawByte = results[0])
if bf.bit7 != 1 or bf.bit6 != 0:
raise U12Exception("Expected a AIBurst response, got %s instead." % results[0])
returnDict['BufferOverflowOrChecksumErrors'].append(bool(bf.bit5))
returnDict['PGAOvervoltages'].append(bool(bf.bit4))
returnDict['IO3toIO0States'].append(BitField(results[0], "IO", range(3, -1, -1), "Low", "High"))
returnDict['IterationCounters'].append((results[1] >> 5))
returnDict['Backlogs'].append(results[1] & 0xf)
channel0 = (results[2] >> 4) & 0xf
channel1 = (results[2] & 0xf)
channel2 = (results[5] >> 4) & 0xf
channel3 = (results[5] & 0xf)
channel0 = (channel0 << 8) + results[3]
returnDict['Channel0'].append(self.bitsToVolts(channel0Number, channel0Gain, channel0))
channel1 = (channel1 << 8) + results[4]
returnDict['Channel1'].append(self.bitsToVolts(channel1Number, channel1Gain, channel1))
channel2 = (channel2 << 8) + results[6]
returnDict['Channel2'].append(self.bitsToVolts(channel2Number, channel2Gain, channel2))
channel3 = (channel3 << 8) + results[7]
returnDict['Channel3'].append(self.bitsToVolts(channel3Number, channel3Gain, channel3))
return returnDict
def rawAIContinuous(self, channel0PGAMUX = 8, channel1PGAMUX = 9, channel2PGAMUX = 10, channel3PGAMUX = 11, FeatureReports = False, CounterRead = False, UpdateIO = False, LEDState = True, IO3ToIO0States = 0, SampleInterval = 15000):
"""
Currently in development.
The function is mostly implemented, but is currently too slow to be
useful.
"""
command = [ 0 ] * 8
# Bits 6-4: PGA for 1st Channel
# Bits 3-0: MUX command for 1st Channel
command[0] = int(channel0PGAMUX)
tempNum = command[0] & 7 # 7 = 0b111
channel0Number = tempNum if (command[0] & 0xf) > 7 else tempNum+8
channel0Gain = (command[0] >> 4) & 7 # 7 = 0b111
command[1] = int(channel1PGAMUX)
tempNum = command[1] & 7 # 7 = 0b111
channel1Number = tempNum if (command[1] & 0xf) > 7 else tempNum+8
channel1Gain = (command[1] >> 4) & 7 # 7 = 0b111
command[2] = int(channel2PGAMUX)
tempNum = command[2] & 7 # 7 = 0b111
channel2Number = tempNum if (command[2] & 0xf) > 7 else tempNum+8
channel2Gain = (command[2] >> 4) & 7 # 7 = 0b111
command[3] = int(channel3PGAMUX)
tempNum = command[3] & 7 # 7 = 0b111
channel3Number = tempNum if (command[3] & 0xf) > 7 else tempNum+8
channel3Gain = (command[3] >> 4) & 7 # 7 = 0b111
bf = BitField()
bf.bit7 = int(bool(FeatureReports))
bf.bit6 = int(bool(CounterRead))
bf.bit1 = int(bool(UpdateIO))
bf.bit0 = int(bool(LEDState))
command[4] = int(bf)
# Bits 7-4: 1001 (Start Continuous)
bf2 = BitField( rawByte = int(IO3ToIO0States) )
bf2.bit7 = 1
bf2.bit4 = 1
command[5] = int(bf2)
command[6] = ( SampleInterval >> 8)
command[7] = SampleInterval & 0xff
byte0bf = BitField()
returnDict = dict()
self.write(command)
while True:
results = self.read()
byte0bf.fromByte(results[0])
returnDict['Byte0'] = byte0bf
returnDict['IterationCounter'] = (results[1] >> 5)
returnDict['Backlog'] = results[1] & 0xf
yield returnDict
def rawPulseout(self, B1 = 10, C1 = 2, B2 = 10, C2 = 2, D7ToD0PulseSelection = 1, ClearFirst = False, NumberOfPulses = 5):
"""
Name: U12.rawPulseout( B1 = 10, C1 = 2, B2 = 10, C2 = 2,
D7ToD0PulseSelection = 1, ClearFirst = False,
NumberOfPulses = 5)
Args: B1, the B component of the first half cycle
C1, the C component of the first half cycle
B2, the B component of the second half cycle
C2, the C component of the second half cycle
D7ToD0PulseSelection, which D lines to pulse.
ClearFirst, True = Start Low.
NumberOfPulses, the number of pulses
Desc: This command creates pulses on any, or all, of D0-D7. The desired
D lines must be set to output with some other function. See
Section 5.7 of the User's Guide.
By default, pulses D0 5 times at 400us high, then 400 us low.
Returns: None
Example:
Have a jumper wire connected from D0 to CNT.
>>> import u12
>>> d = u12.U12()
>>> d.rawDIO(D7toD0Directions = 0, UpdateDigital = True)
>>> d.rawCounter(ResetCounter = True)
>>> d.rawPulseout(ClearFirst = True)
>>> print d.rawCounter()
{ 'IO3toIO0States': ... ,
'Counter': 5,
'D7toD0States': ... ,
'D15toD8States': ...
}
"""
command = [ 0 ] * 8
command[0] = B1
command[1] = C1
command[2] = B2
command[3] = C2
command[4] = int(D7ToD0PulseSelection)
# 01100100 (Pulseout)
bf = BitField()
bf.bit6 = 1
bf.bit5 = 1
bf.bit2 = 1
command[5] = int(bf)
bf2 = BitField( rawByte = ( NumberOfPulses >> 8 ) )
bf2.bit7 = int(bool(ClearFirst))
command[6] = int(bf2)
command[7] = NumberOfPulses & 0xff
self.write(command)
results = self.read()
if command[5] != results[5]:
raise U12Exception("Expected Pulseout response, got %s instead." % results[5])
if results[4] != 0:
errors = BitField(rawByte = command[4], labelPrefix = "D", zeroLabel = "Ok", oneLabel = "Error")
raise U12Exception("D7-D0 Direction error detected: %s" % errors)
return None
def rawReset(self):
"""
Name: U12.rawReset()
Desc: Sits in an infinite loop until micro watchdog timeout after about
2 seconds. See Section 5.8 of the User's Guide.
Note: The function will close the device after it has written the
command.
Returns: None
Example:
>>> import u12
>>> d = u12.U12()
>>> d.rawReset()
"""
command = [ 0 ] * 8
# 0b01011111 ( Reset )
bf = BitField()
bf.bit6 = 1
bf.bit4 = 1
bf.bit3 = 1
bf.bit2 = 1
bf.bit1 = 1
bf.bit0 = 1
command[5] = int(bf)
self.write(command)
self.close()
def rawReenumerate(self):
"""
Name: U12.rawReenumerate()
Desc: Detaches from the USB, reloads config parameters, and then
reattaches so the device can be re-enumerated. See Section 5.9 of
the User's Guide.
Note: The function will close the device after it has written the
command.
Returns: None
Example:
>>> import u12
>>> d = u12.U12()
>>> d.rawReenumerate()
"""
command = [ 0 ] * 8
# 0b01000000 (Re-Enumerate)
bf = BitField()
bf.bit6 = 1
command[5] = int(bf)
self.write(command)
self.close()
def rawWatchdog(self, IgnoreCommands = False, D0Active = False, D0State = False, D1Active = False, D1State = False, D8Active = False, D8State = False, ResetOnTimeout = False, WatchdogActive = False, Timeout = 60):
"""
Name: U12.rawWatchdog( IgnoreCommands = False, D0Active = False,
D0State = False, D1Active = False,
D1State = False, D8Active = False,
D8State = False, ResetOnTimeout = False,
WatchdogActive = False, Timeout = 60)
Desc: Sets the settings for the watchdog, or just reads the firmware
version of the U12. See section 5.10 of the User's Guide.
By defaults, just reads the firmware version.
Returns: A dictionary with the following keys:
FirmwareVersion, the firmware version of the U12.
Example:
>>> import u12
>>> d = u12.U12()
>>> print d.rawWatchdog()
{'FirmwareVersion': '1.10'}
"""
command = [ 0 ] * 8
command[0] = int(bool(IgnoreCommands))
bf = BitField()
bf.bit7 = int(D0Active)
bf.bit6 = int(D0State)
bf.bit5 = int(D1Active)
bf.bit4 = int(D1State)
bf.bit3 = int(D8Active)
bf.bit2 = int(D8State)
bf.bit1 = int(ResetOnTimeout)
bf.bit0 = int(WatchdogActive)
command[4] = int(bf)
# 01X1X011 (Watchdog)
bf2 = BitField()
bf2.bit6 = 1
bf2.bit4 = 1
bf2.bit1 = 1
bf2.bit0 = 1
command[5] = int(bf2)
# Timeout is increments of 2^16 cycles.
# 2^16 cycles is about 0.01 seconds.
binTimeout = int((float(Timeout) / 0.01))
command[6] = ( binTimeout >> 8 ) & 0xff
command[7] = binTimeout & 0xff
self.write(command)
results = self.read()
returnDict = dict()
returnDict['FirmwareVersion'] = "%s.%.2d" % (results[0], results[1])
return returnDict
def rawReadRAM(self, Address = 0):
"""
Name: U12.rawReadRAM(Address = 0)
Args: Address, the starting address to read from
Desc: Reads 4 bytes out of the U12's internal memory. See section 5.11
of the User's Guide.
By default, reads the bytes that make up the serial number.
Returns: A dictionary with the following keys:
DataByte0, the data byte at Address - 0
DataByte1, the data byte at Address - 1
DataByte2, the data byte at Address - 2
DataByte3, the data byte at Address - 3
Example:
>>> import u12, struct
>>> d = u12.U12()
>>> r = d.rawReadRAM()
>>> print r
{'DataByte3': 5, 'DataByte2': 246, 'DataByte1': 139, 'DataByte0': 170}
>>> bytes = [ r['DataByte3'], r['DataByte2'], r['DataByte1'], r['DataByte0'] ]
>>> print struct.unpack(">I", struct.pack("BBBB", *bytes))[0]
100043690
"""
command = [ 0 ] * 8
# 01010000 (Read RAM)
bf = BitField()
bf.bit6 = 1
bf.bit4 = 1
command[5] = int(bf)
command[6] = (Address >> 8) & 0xff
command[7] = Address & 0xff
self.write(command)
results = self.read()
if results[0] != int(bf):
raise U12Exception("Expected ReadRAM response, got %s" % results[0])
if (results[6] != command[6]) or (results[7] != command[7]):
receivedAddress = (results[6] << 8) + results[7]
raise U12Exception("Wanted address %s got address %s" % (Address, receivedAddress))
returnDict = dict()
returnDict['DataByte3'] = results[1]
returnDict['DataByte2'] = results[2]
returnDict['DataByte1'] = results[3]
returnDict['DataByte0'] = results[4]
return returnDict
def rawWriteRAM(self, Data, Address):
"""
Name: U12.rawWriteRAM(Data, Address)
Args: Data, a list of 4 bytes to write to memory.
Address, the starting address to write to.
Desc: Writes 4 bytes to the U12's internal memory. See section 5.13 of
the User's Guide.
No default behavior, you must pass Data and Address.
Returns: A dictionary with the following keys:
DataByte0, the data byte at Address - 0
DataByte1, the data byte at Address - 1
DataByte2, the data byte at Address - 2
DataByte3, the data byte at Address - 3
Example:
>>> import u12
>>> d = u12.U12()
>>> print d.rawWriteRAM([1, 2, 3, 4], 0x200)
{'DataByte3': 4, 'DataByte2': 3, 'DataByte1': 2, 'DataByte0': 1}
"""
command = [ 0 ] * 8
if not isinstance(Data, list) or len(Data) > 4:
raise U12Exception("Data wasn't a list, or was too long.")
Data.reverse()
command[:len(Data)] = Data
# 01010001 (Write RAM)
bf = BitField()
bf.bit6 = 1
bf.bit4 = 1
bf.bit0 = 1
command[5] = int(bf)
command[6] = (Address >> 8) & 0xff
command[7] = Address & 0xff
self.write(command)
results = self.read()
if results[0] != int(bf):
raise U12Exception("Expected ReadRAM response, got %s" % results[0])
if (results[6] != command[6]) or (results[7] != command[7]):
receivedAddress = (results[6] << 8) + results[7]
raise U12Exception("Wanted address %s got address %s" % (Address, receivedAddress))
returnDict = dict()
returnDict['DataByte3'] = results[1]
returnDict['DataByte2'] = results[2]
returnDict['DataByte1'] = results[3]
returnDict['DataByte0'] = results[4]
return returnDict
def rawAsynch(self, Data, AddDelay = False, TimeoutActive = False, SetTransmitEnable = False, PortB = False, NumberOfBytesToWrite = 0, NumberOfBytesToRead = 0):
"""
Name: U12.rawAsynch(Data, AddDelay = False, TimeoutActive = False,
SetTransmitEnable = False, PortB = False,
NumberOfBytesToWrite = 0, NumberOfBytesToRead = 0)
Args: Data, A list of bytes to write.
AddDelay, True to add a 1 bit delay between each transmit byte.
TimeoutActive, True to enable timeout for the receive phase.
SetTransmitEnable, True to set Transmit Enable to high during
transmit and low during receive.
PortB, True to use PortB instead of PortA.
NumberOfBytesToWrite, Number of bytes to write.
NumberOfBytesToRead, Number of bytes to read.
Desc: Requires firmware V1.1 or higher. This function writes and then
reads half-duplex asynchronous data on 1 of two pairs of D lines.
See section 5.13 of the User's Guide.
Returns: A dictionary with the following keys,
DataByte0-3, the first four data bytes read over the RX line
ErrorFlags, a BitField representing the error flags.
Example:
>>> import u12
>>> d = u12.U12()
>>> # Set the full and half A,B,C to 9600
>>> d.rawWriteRAM([0, 1, 1, 200], 0x073)
>>> d.rawWriteRAM([5, 1, 2, 48], 0x076)
>>> print d.rawAsynch([1, 2, 3, 4], NumberOfBytesToWrite = 4, NumberOfBytesToRead = 4)
{
'DataByte3': 4,
'DataByte2': 3,
'DataByte1': 2,
'DataByte0': 1,
'ErrorFlags': <BitField object: [ Timeout Error Flag = 0 (0), ... ] >
}
"""
command = [ 0 ] * 8
if not isinstance(Data, list) or len(Data) > 4:
raise U12Exception("Data wasn't a list, or was too long.")
NumberOfBytesToWrite = NumberOfBytesToRead & 0xff
NumberOfBytesToRead = NumberOfBytesToRead & 0xff
if NumberOfBytesToWrite > 18:
raise U12Exception("Can only write 18 or fewer bytes at a time.")
if NumberOfBytesToRead > 18:
raise U12Exception("Can only read 18 or fewer bytes at a time.")
Data.reverse()
command[:len(Data)] = Data
bf = BitField()
bf.bit3 = int(bool(AddDelay))
bf.bit2 = int(bool(TimeoutActive))
bf.bit1 = int(bool(SetTransmitEnable))
bf.bit0 = int(bool(PortB))
command[4] = int(bf)
#01100001 (Asynch)
bf2 = BitField()
bf2.bit6 = 1
bf2.bit5 = 1
bf2.bit0 = 1
command[5] = int(bf2)
command[6] = NumberOfBytesToWrite
command[7] = NumberOfBytesToRead
self.write(command)
results = self.read()
if command[5] != results[5]:
raise U12Exception("Expected Asynch response, got %s instead." % results[5])
returnDict = dict()
returnDict['DataByte3'] = results[0]
returnDict['DataByte2'] = results[1]
returnDict['DataByte1'] = results[2]
returnDict['DataByte0'] = results[3]
bfLabels = ["Timeout Error Flag", "STRT Error Flag", "FRM Error Flag", "RXTris Error Flag", "TETris Error Flag", "TXTris Error Flag"]
bf = BitField( rawByte = results[4], labelPrefix = "", labelList = bfLabels )
returnDict["ErrorFlags"] = bf
return returnDict
SPIModes = ['A', 'B', 'C', 'D']
def rawSPI(self, Data, AddMsDelay = False, AddHundredUsDelay = False, SPIMode = 'A', NumberOfBytesToWriteRead = 0, ControlCS = False, StateOfActiveCS = False, CSLineNumber = 0):
"""
Name: U12.rawSPI( Data, AddMsDelay = False, AddHundredUsDelay = False,
SPIMode = 'A', NumberOfBytesToWriteRead = 0,
ControlCS = False, StateOfActiveCS = False,
CSLineNumber = 0)
Args: Data, A list of four bytes to write using SPI
AddMsDelay, If True, a 1 ms delay is added between each bit
AddHundredUsDelay, if True, 100us delay is added
SPIMode, 'A', 'B', 'C', or 'D'
NumberOfBytesToWriteRead, number of bytes to write and read.
ControlCS, D0-D7 is automatically controlled as CS. The state and
direction of CS is only tested if control is enabled.
StateOfActiveCS, Active state for CS line.
CSLineNumber, D line to use as CS if enabled (0-7).
Desc: This function performs SPI communication. See Section 5.14 of the
User's Guide.
Returns: A dictionary with the following keys,
DataByte0-3, the first four data bytes read
ErrorFlags, a BitField representing the error flags.
Example:
>>> import u12
>>> d = u12.U12()
>>> d.rawSPI([1,2,3,4], NumberOfBytesToWriteRead = 4)
{
'DataByte3': 4,
'DataByte2': 3,
'DataByte1': 2,
'DataByte0': 1,
'ErrorFlags':
<BitField object: [ CSStateTris Error Flag = 0 (0), ... ] >
}
"""
command = [ 0 ] * 8
if not isinstance(Data, list) or len(Data) > 4:
raise U12Exception("Data wasn't a list, or was too long.")
NumberOfBytesToWriteRead = NumberOfBytesToWriteRead & 0xff
if NumberOfBytesToWriteRead == 0:
NumberOfBytesToWriteRead = len(Data)
if NumberOfBytesToWriteRead > 18 or NumberOfBytesToWriteRead < 1:
raise U12Exception("Can only read/write 1 to 18 bytes at a time.")
Data.reverse()
command[:len(Data)] = Data
bf = BitField()
bf.bit7 = int(bool(AddMsDelay))
bf.bit6 = int(bool(AddHundredUsDelay))
modeIndex = self.SPIModes.index(SPIMode)
bf[7-modeIndex] = 1
command[4] = int(bf)
# 01100010 (SPI)
bf2 = BitField()
bf2.bit6 = 1
bf2.bit5 = 1
bf2.bit1 = 1
command[5] = int(bf2)
command[6] = NumberOfBytesToWriteRead
bf3 = BitField(rawByte = CSLineNumber)
bf3.bit7 = int(bool(ControlCS))
bf3.bit6 = int(bool(StateOfActiveCS))
command[7] = int(bf3)
self.write(command)
results = self.read()
if results[5] != command[5]:
raise U12Exception("Expected SPI response, got %s instead." % results[5])
returnDict = dict()
returnDict['DataByte3'] = results[0]
returnDict['DataByte2'] = results[1]
returnDict['DataByte1'] = results[2]
returnDict['DataByte0'] = results[3]
bfLabels = ["CSStateTris Error Flag", "SCKTris Error Flag", "MISOTris Error Flag", "MOSITris Error Flag"]
bf = BitField( rawByte = results[4], labelPrefix = "", labelList = bfLabels )
returnDict["ErrorFlags"] = bf
return returnDict
def rawSHT1X(self, Data = [3,0,0,0], WaitForMeasurementReady = True, IssueSerialReset = False, Add1MsDelay = False, Add300UsDelay = False, IO3State = 1, IO2State = 1, IO3Direction = 1, IO2Direction = 1, NumberOfBytesToWrite = 1, NumberOfBytesToRead = 3):
"""
Name: U12.rawSHT1X( Data = [3, 0, 0, 0],
WaitForMeasurementReady = True,
IssueSerialReset = False, Add1MsDelay = False,
Add300UsDelay = False, IO3State = 1, IO2State = 1,
IO3Direction = 1, IO2Direction = 1,
NumberOfBytesToWrite = 1, NumberOfBytesToRead = 3)
Args: Data, a list of bytes to write to the SHT.
WaitForMeasurementReady, Wait for the measurement ready signal.
IssueSerialReset, perform a serial reset
Add1MsDelay, adds 1ms delay
Add300UsDelay, adds a 300us delay
IO3State, sets the state of IO3
IO2State, sets the state of IO2
IO3Direction, sets the direction of IO3 ( 1 = Output )
IO2Direction, sets the direction of IO3 ( 1 = Output )
NumberOfBytesToWrite, how many bytes to write
NumberOfBytesToRead, how may bytes to read back
Desc: Sends and receives data from a SHT1X T/RH sensor from Sensirion.
See Section 5.15 of the User's Guide.
By default, reads the temperature from the SHT.
Returns: A dictionary with the following keys,
DataByte0-3, the four data bytes read
ErrorFlags, a BitField representing the error flags.
Example:
Uses an EI-1050 Temp/Humidity probe wired as follows:
Data ( Green ) -> IO0
Clock ( White ) -> IO1
Ground ( Black ) -> GND
Power ( Red ) -> +5V
Enable ( Brown ) -> IO2
>>> import u12
>>> d = u12.U12()
>>> results = d.rawSHT1X()
>>> print results
{
'DataByte3': 0,
'DataByte2': 69,
'DataByte1': 48,
'DataByte0': 25,
'ErrorFlags':
<BitField object: [ Serial Reset Error Flag = 0 (0), ... ] >
}
>>> tempC = (results['DataByte0'] * 256 ) + results['DataByte1']
>>> tempC = (tempC * 0.01) - 40
>>> print tempC
24.48
>>> results = d.rawSHT1X(Data = [5,0,0,0])
>>> print results
{
'DataByte3': 0,
'DataByte2': 200,
'DataByte1': 90,
'DataByte0': 2,
'ErrorFlags':
<BitField object: [ Serial Reset Error Flag = 0 (0), ... ] >
}
>>> sorh = (results['DataByte0'] * 256 ) + results['DataByte1']
>>> rhlinear = (-0.0000028*sorh*sorh)+(0.0405*sorh)-4.0
>>> rh = ((tempC-25.0)*(0.01+(0.00008*sorh)))+rhlinear
>>> print rh
19.3360256
"""
command = [ 0 ] * 8
if NumberOfBytesToWrite != 0:
if not isinstance(Data, list) or len(Data) > 4:
raise U12Exception("Data wasn't a list, or was too long.")
Data.reverse()
command[:len(Data)] = Data
if max(NumberOfBytesToWrite, NumberOfBytesToRead) > 4:
raise U12Exception("Can only read/write up to 4 bytes at a time.")
bf = BitField()
bf.bit7 = int(bool(WaitForMeasurementReady))
bf.bit6 = int(bool(IssueSerialReset))
bf.bit5 = int(bool(Add1MsDelay))
bf.bit4 = int(bool(Add300UsDelay))
bf.bit3 = int(bool(IO3State))
bf.bit2 = int(bool(IO2State))
bf.bit1 = int(bool(IO3Direction))
bf.bit0 = int(bool(IO2Direction))
command[4] = int(bf)
# 01101000 (SHT1X)
bf2 = BitField()
bf2.bit6 = 1
bf2.bit5 = 1
bf2.bit3 = 1
command[5] = int(bf2)
command[6] = NumberOfBytesToWrite
command[7] = NumberOfBytesToRead
self.write(command)
results = self.read()
if results[5] != command[5]:
raise U12Exception("Expected SHT1x response, got %s instead." % results[5])
returnDict = dict()
returnDict['DataByte3'] = results[0]
returnDict['DataByte2'] = results[1]
returnDict['DataByte1'] = results[2]
returnDict['DataByte0'] = results[3]
bfLabels = ["Serial Reset Error Flag", "Measurement Ready Error Flag", "Ack Error Flag"]
bf = BitField( rawByte = results[4], labelPrefix = "", labelList = bfLabels )
returnDict["ErrorFlags"] = bf
return returnDict
def eAnalogIn(self, channel, idNum = None, demo=0, gain=0):
"""
Name: U12.eAnalogIn(channel, idNum = None, demo=0, gain=0)
Args: See section 4.1 of the User's Guide
Desc: This is a simplified version of AISample. Reads the voltage from 1 analog input
>>> import u12
>>> d = u12.U12()
>>> d.eAnalogIn(0)
{'overVoltage': 0, 'idnum': 1, 'voltage': 1.435546875}
"""
if idNum is None:
idNum = self.id
if ON_WINDOWS:
ljid = ctypes.c_long(idNum)
ad0 = ctypes.c_long(999)
ad1 = ctypes.c_float(999)
ecode = staticLib.EAnalogIn(ctypes.byref(ljid), demo, channel, gain, ctypes.byref(ad0), ctypes.byref(ad1))
if ecode != 0: raise U12Exception(ecode)
return {"idnum":ljid.value, "overVoltage":ad0.value, "voltage":ad1.value}
else:
# Bits 6-4: PGA for 1st Channel
# Bits 3-0: MUX command for 1st Channel
channel0PGAMUX = ( ( gain & 7 ) << 4)
channel0PGAMUX += channel-8 if channel > 7 else channel+8
results = self.rawAISample(channel0PGAMUX = channel0PGAMUX)
return {"idnum" : self.id, "overVoltage" : int(results['PGAOvervoltage']), 'voltage' : results['Channel0']}
def eAnalogOut(self, analogOut0, analogOut1, idNum = None, demo=0):
"""
Name: U12.eAnalogOut(analogOut0, analogOut1, idNum = None, demo=0)
Args: See section 4.2 of the User's Guide
Desc: This is a simplified version of AOUpdate. Sets the voltage of both analog outputs.
>>> import u12
>>> d = u12.U12()
>>> d.eAnalogOut(2, 2)
{'idnum': 1}
"""
if idNum is None:
idNum = self.id
if ON_WINDOWS:
ljid = ctypes.c_long(idNum)
ecode = staticLib.EAnalogOut(ctypes.byref(ljid), demo, ctypes.c_float(analogOut0), ctypes.c_float(analogOut1))
if ecode != 0: raise U12Exception(ecode)
return {"idnum":ljid.value}
else:
if analogOut0 < 0:
analogOut0 = self.pwmAVoltage
if analogOut1 < 0:
analogOut1 = self.pwmBVoltage
self.rawCounterPWMDIO(PWMA = analogOut0, PWMB = analogOut1)
self.pwmAVoltage = analogOut0
self.pwmBVoltage = analogOut1
return {"idnum": self.id}
def eCount(self, idNum = None, demo = 0, resetCounter = 0):
"""
Name: U12.eCount(idNum = None, demo = 0, resetCounter = 0)
Args: See section 4.3 of the User's Guide
Desc: This is a simplified version of Counter. Reads & resets the counter (CNT).
>>> import u12
>>> d = u12.U12()
>>> d.eCount()
{'count': 1383596032.0, 'ms': 251487257.0}
"""
# Check id num
if idNum is None:
idNum = self.id
if ON_WINDOWS:
ljid = ctypes.c_long(idNum)
count = ctypes.c_double()
ms = ctypes.c_double()
ecode = staticLib.ECount(ctypes.byref(ljid), demo, resetCounter, ctypes.byref(count), ctypes.byref(ms))
if ecode != 0: raise U12Exception(ecode)
return {"idnum":ljid.value, "count":count.value, "ms":ms.value}
else:
results = self.rawCounter( ResetCounter = resetCounter)
return {"idnum":self.id, "count":results['Counter'], "ms": (time() * 1000)}
def eDigitalIn(self, channel, idNum = None, demo = 0, readD=0):
"""
Name: U12.eDigitalIn(channel, idNum = None, demo = 0, readD=0)
Args: See section 4.4 of the User's Guide
Desc: This is a simplified version of DigitalIO that reads the state of
one digital input. Also configures the requested pin to input and
leaves it that way.
>>> import u12
>>> d = u12.U12()
>>> d.eDigitalIn(0)
{'state': 0, 'idnum': 1}
"""
# Check id num
if idNum is None:
idNum = self.id
if ON_WINDOWS:
ljid = ctypes.c_long(idNum)
state = ctypes.c_long(999)
ecode = staticLib.EDigitalIn(ctypes.byref(ljid), demo, channel, readD, ctypes.byref(state))
if ecode != 0: raise U12Exception(ecode)
return {"idnum":ljid.value, "state":state.value}
else:
oldstate = self.rawDIO()
if readD:
if channel > 7:
channel = channel-7
direction = BitField(rawByte = oldstate['D15toD8Directions'])
direction[7-channel] = 1
results = self.rawDIO(D15toD8Directions = direction, UpdateDigital = True)
state = results["D15toD8States"][7-channel]
else:
direction = BitField(rawByte = oldstate['D7toD0Directions'])
direction[7-channel] = 1
results = self.rawDIO(D7ToD0Directions = direction, UpdateDigital = True)
state = results["D15toD8States"][7-channel]
else:
results = self.rawDIO(IO3toIO0DirectionsAndStates = 255, UpdateDigital = True)
state = results["IO3toIO0States"][3-channel]
return {"idnum" : self.id, "state" : state}
def eDigitalOut(self, channel, state, idNum = None, demo = 0, writeD=0):
"""
Name: U12.eDigitalOut(channel, state, idNum = None, demo = 0, writeD=0)
Args: See section 4.5 of the User's Guide
Desc: This is a simplified version of DigitalIO that sets/clears the
state of one digital output. Also configures the requested pin to
output and leaves it that way.
>>> import u12
>>> d = u12.U12()
>>> d.eDigitalOut(0, 1)
{idnum': 1}
"""
# Check id num
if idNum is None:
idNum = self.id
if ON_WINDOWS:
ljid = ctypes.c_long(idNum)
ecode = staticLib.EDigitalOut(ctypes.byref(ljid), demo, channel, writeD, state)
if ecode != 0: raise U12Exception(ecode)
return {"idnum":ljid.value}
else:
oldstate = self.rawDIO()
if writeD:
if channel > 7:
channel = channel-7
direction = BitField(rawByte = int(oldstate['D15toD8Directions']))
direction[7-channel] = 0
states = BitField(rawByte = int(oldstate['D15toD8States']))
states[7-channel] = state
self.rawDIO(D15toD8Directions = direction, D15toD8States = state, UpdateDigital = True)
else:
direction = BitField(rawByte = int(oldstate['D7toD0Directions']))
direction[7-channel] = 0
states = BitField(rawByte = int(oldstate['D7toD0States']))
states[7-channel] = state
self.rawDIO(D7toD0Directions = direction, D7toD0States = states, UpdateDigital = True)
else:
bf = BitField()
bf[7-(channel+4)] = 0
bf[7-channel] = state
self.rawDIO(IO3toIO0DirectionsAndStates = bf, UpdateDigital = True)
return {"idnum" : self.id}
def aiSample(self, numChannels, channels, idNum=None, demo=0, stateIOin=0, updateIO=0, ledOn=0, gains=[0, 0, 0, 0], disableCal=0):
"""
Name: U12.aiSample(channels, idNum=None, demo=0, stateIOin=0, updateIO=0, ledOn=0, gains=[0, 0, 0, 0], disableCal=0)
Args: See section 4.6 of the User's Guide
Desc: Reads the voltages from 1,2, or 4 analog inputs. Also controls/reads the 4 IO ports.
>>> dev = U12()
>>> dev.aiSample(2, [0, 1])
{'stateIO': [0, 0, 0, 0], 'overVoltage': 0, 'idnum': 1, 'voltages': [1.4208984375, 1.4306640625]}
"""
# Check id num
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
# Check to make sure that everything is checked
if not isIterable(channels): raise TypeError("channels must be iterable")
if not isIterable(gains): raise TypeError("gains must be iterable")
if len(channels) < numChannels: raise ValueError("channels must have atleast numChannels elements")
if len(gains) < numChannels: raise ValueError("gains must have atleast numChannels elements")
# Convert lists to arrays and create other ctypes
channelsArray = listToCArray(channels, ctypes.c_long)
gainsArray = listToCArray(gains, ctypes.c_long)
overVoltage = ctypes.c_long(999)
longArrayType = (ctypes.c_long * 4)
floatArrayType = (ctypes.c_float * 4)
voltages = floatArrayType(0, 0, 0, 0)
stateIOin = ctypes.c_long(stateIOin)
ecode = staticLib.AISample(ctypes.byref(idNum), demo, ctypes.byref(stateIOin), updateIO, ledOn, numChannels, ctypes.byref(channelsArray), ctypes.byref(gainsArray), disableCal, ctypes.byref(overVoltage), ctypes.byref(voltages))
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value, "stateIO":stateIOin.value, "overVoltage":overVoltage.value, "voltages":voltages[0:numChannels]}
def aiBurst(self, numChannels, channels, scanRate, numScans, idNum=None, demo=0, stateIOin=0, updateIO=0, ledOn=0, gains=[0, 0, 0, 0], disableCal=0, triggerIO=0, triggerState=0, timeout=1, transferMode=0):
"""
Name: U12.aiBurst(numChannels, channels, scanRate, numScans, idNum=None, demo=0, stateIOin=[0, 0, 0, 0], updateIO=0, ledOn=0, gains=[0, 0, 0, 0], disableCal=0, triggerIO=0, triggerState=0, timeout=1, transferMode=0)
Args: See section 4.7 of the User's Guide
Desc: Reads a specified number of scans (up to 4096) at a specified scan rate (up to 8192 Hz) from 1,2, or 4 analog inputs
>>> dev = U12()
>>> dev.aiBurst(1, [0], 400, 10)
{'overVoltage': 0, 'scanRate': 400.0, 'stateIOout': <u12.c_long_Array_4096 object at 0x00DB4BC0>, 'idnum': 1, 'voltages': <u12.c_float_Array_4096_Array_4 object at 0x00DB4B70>}
"""
# Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
# check list sizes
if len(channels) < numChannels: raise ValueError("channels must have atleast numChannels elements")
if len(gains) < numChannels: raise ValueError("gains must have atleast numChannels elements")
# Convert lists to arrays and create other ctypes
channelsArray = listToCArray(channels, ctypes.c_long)
gainsArray = listToCArray(gains, ctypes.c_long)
scanRate = ctypes.c_float(scanRate)
pointerArray = (ctypes.c_void_p * 4)
arr4096_type = ctypes.c_float * 4096
voltages_type = arr4096_type * 4
voltages = voltages_type()
stateIOout = (ctypes.c_long * 4096)()
overVoltage = ctypes.c_long(999)
ecode = staticLib.AIBurst(ctypes.byref(idNum), demo, stateIOin, updateIO, ledOn, numChannels, ctypes.byref(channelsArray), ctypes.byref(gainsArray), ctypes.byref(scanRate), disableCal, triggerIO, triggerState, numScans, timeout, ctypes.byref(voltages), ctypes.byref(stateIOout), ctypes.byref(overVoltage), transferMode)
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value, "scanRate":scanRate.value, "voltages":voltages, "stateIOout":stateIOout, "overVoltage":overVoltage.value}
def aiStreamStart(self, numChannels, channels, scanRate, idNum=None, demo=0, stateIOin=0, updateIO=0, ledOn=0, gains=[0, 0, 0, 0], disableCal=0, readCount=0):
"""
Name: U12.aiStreamStart(numChannels, channels, scanRate, idNum=None, demo=0, stateIOin=0, updateIO=0, ledOn=0, gains=[0, 0, 0, 0], disableCal=0, readCount=0)
Args: See section 4.8 of the User's Guide
Desc: Starts a hardware timed continuous acquisition
>>> dev = U12()
>>> dev.aiStreamStart(1, [0], 200)
{'scanRate': 200.0, 'idnum': 1}
"""
# Configure return type
staticLib.AIStreamStart.restype = ctypes.c_long
# check list sizes
if len(channels) < numChannels: raise ValueError("channels must have atleast numChannels elements")
if len(gains) < numChannels: raise ValueError("gains must have atleast numChannels elements")
#if len(stateIOin) < 4: raise ValueError("stateIOin must have atleast 4 elements")
# Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
# Convert lists to arrays and create other ctypes
channelsArray = listToCArray(channels, ctypes.c_long)
gainsArray = listToCArray(gains, ctypes.c_long)
scanRate = ctypes.c_float(scanRate)
ecode = staticLib.AIStreamStart(ctypes.byref(idNum), demo, stateIOin, updateIO, ledOn, numChannels, ctypes.byref(channelsArray), ctypes.byref(gainsArray), ctypes.byref(scanRate), disableCal, 0, readCount)
if ecode != 0: raise U12Exception(ecode) # TODO: Switch this out for exception
# The ID number must be saved for AIStream
self.id = idNum.value
self.streaming = True
return {"idnum":idNum.value, "scanRate":scanRate.value}
def aiStreamRead(self, numScans, localID=None, timeout=1):
"""
Name: U12.aiStreamRead(numScans, localID=None, timeout=1)
Args: See section 4.9 of the User's Guide
Desc: Waits for a specified number of scans to be available and reads them.
>>> dev = U12()
>>> dev.aiStreamStart(1, [0], 200)
>>> dev.aiStreamRead(10)
{'overVoltage': 0, 'ljScanBacklog': 0, 'stateIOout': <u12.c_long_Array_4096 object at 0x00DF4AD0>, 'reserved': 0, 'voltages': <u12.c_float_Array_4096_Array_4 object at 0x00DF4B20>}
"""
# Check to make sure that we are streaming
if not self.streaming:
raise U12Exception(-1, "Streaming has not started")
# Check id number
if localID is None:
localID = self.id
# Create arrays and other ctypes
arr4096_type = ctypes.c_float * 4096
voltages_type = arr4096_type * 4
voltages = voltages_type()
stateIOout = (ctypes.c_long * 4096)()
reserved = ctypes.c_long(0)
ljScanBacklog = ctypes.c_long(99999)
overVoltage = ctypes.c_long(999)
ecode = staticLib.AIStreamRead(localID, numScans, timeout, ctypes.byref(voltages), ctypes.byref(stateIOout), ctypes.byref(reserved), ctypes.byref(ljScanBacklog), ctypes.byref(overVoltage))
if ecode != 0: raise U12Exception(ecode) # TODO: Switch this out for exception
return {"voltages":voltages, "stateIOout":stateIOout, "reserved":reserved.value, "ljScanBacklog":ljScanBacklog.value, "overVoltage":overVoltage.value}
def aiStreamClear(self, localID=None):
"""
Name: U12.aiClear()
Args: See section 4.10 of the User's Guide
Desc: This function stops the continuous acquisition. It should be called once when finished with the stream.
>>> dev = U12()
>>> dev.aiStreamStart(1, [0], 200)
>>> dev.aiStreamRead(10)
>>> dev.aiStreamClear()
"""
# Check to make sure that we are streaming
if not self.streaming:
raise U12Exception(-1, "Streaming has not started")
# Check id number
if localID is None:
localID = self.id
ecode = staticLib.AIStreamClear(localID)
if ecode != 0: raise U12Exception(ecode) # TODO: Switch this out for exception
def aoUpdate(self, idNum=None, demo=0, trisD=None, trisIO=None, stateD=None, stateIO=None, updateDigital=0, resetCounter=0, analogOut0=0, analogOut1=0):
"""
Name: U12.aoUpdate()
Args: See section 4.11 of the User's Guide
Desc: Sets the voltages of the analog outputs. Also controls/reads all 20 digital I/O and the counter.
>>> dev = U12()
>>> dev.aoUpdate()
>>> {'count': 2, 'stateIO': 3, 'idnum': 1, 'stateD': 0}
"""
# Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
# Check tris and state arguments
if updateDigital > 0:
if trisD is None: raise ValueError("keyword argument trisD must be set")
if trisIO is None: raise ValueError("keyword argument trisIO must be set")
if stateD is None: raise ValueError("keyword argument stateD must be set")
if stateIO is None: raise ValueError("keyword argument stateIO must be set")
# Create ctypes
if stateD is None: stateD = ctypes.c_long(0)
else: stateD = ctypes.c_long(stateD)
if stateIO is None: stateIO = ctypes.c_long(0)
else: stateIO = ctypes.c_long(stateIO)
count = ctypes.c_ushort(999)
# Create arrays and other ctypes
ecode = staticLib.AOUpdate(ctypes.byref(idNum), demo, trisD, trisIO, ctypes.byref(stateD), ctypes.byref(stateIO), updateDigital, resetCounter, ctypes.byref(count), ctypes.c_float(analogOut0), ctypes.c_float(analogOut1))
if ecode != 0: raise U12Exception(ecode) # TODO: Switch this out for exception
return {"idnum":idNum.value, "stateD":stateD.value, "stateIO":stateIO.value, "count":count.value}
def asynchConfig(self, fullA, fullB, fullC, halfA, halfB, halfC, idNum=None, demo=None, timeoutMult=1, configA=0, configB=0, configTE=0):
"""
Name: U12.asynchConfig(fullA, fullB, fullC, halfA, halfB, halfC, idNum=None, demo=None, timeoutMult=1, configA=0, configB=0, configTE=0)
Args: See section 4.12 of the User's Guide
Desc: Requires firmware V1.1 or higher. This function writes to the asynch registers and sets the direction of the D lines (input/output) as needed.
>>> dev = U12()
>>> dev.asynchConfig(96,1,1,22,2,1)
>>> {'idNum': 1}
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
ecode = staticLib.AsynchConfig(ctypes.byref(idNum), demo, timeoutMult, configA, configB, configTE, fullA, fullB, fullC, halfA, halfB, halfC)
if ecode != 0: raise U12Exception(ecode) # TODO: Switch this out for exception
return {"idNum":idNum.value}
def asynch(self, baudrate, data, idNum=None, demo=0, portB=0, enableTE=0, enableTO=0, enableDel=0, numWrite=0, numRead=0):
"""
Name: U12.asynchConfig(fullA, fullB, fullC, halfA, halfB, halfC, idNum=None, demo=None, timeoutMult=1, configA=0, configB=0, configTE=0)
Args: See section 4.13 of the User's Guide
Desc: Requires firmware V1.1 or higher. This function writes to the asynch registers and sets the direction of the D lines (input/output) as needed.
>>> dev = U12()
>>> dev.asynch(96,1,1,22,2,1)
>>> dev.asynch(19200, [0, 0])
>>> {'data': <u12.c_long_Array_18 object at 0x00DEFB70>, 'idnum': <type 'long'>}
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
# Check size of data
if len(data) > 18: raise ValueError("data can not be larger than 18 elements")
# Make data 18 elements large
dataArray = [0] * 18
for i in range(0, len(data)):
dataArray[i] = data[i]
print dataArray
dataArray = listToCArray(dataArray, ctypes.c_long)
ecode = staticLib.Asynch(ctypes.byref(idNum), demo, portB, enableTE, enableTO, enableDel, baudrate, numWrite, numRead, ctypes.byref(dataArray))
if ecode != 0: raise U12Exception(ecode) # TODO: Switch this out for exception
return {"idnum":long, "data":dataArray}
GainMapping = [ 1.0, 2.0, 4.0, 5.0, 8.0, 10.0, 16.0, 20.0 ]
def bitsToVolts(self, chnum, chgain, bits):
"""
Name: U12.bitsToVolts(chnum, chgain, bits)
Args: See section 4.14 of the User's Guide
Desc: Converts a 12-bit (0-4095) binary value into a LabJack voltage. No hardware communication is involved.
>>> dev = U12()
>>> dev.bitsToVolts(0, 0, 2662)
>>> {'volts': 2.998046875}
"""
if ON_WINDOWS:
volts = ctypes.c_float()
ecode = staticLib.BitsToVolts(chnum, chgain, bits, ctypes.byref(volts))
if ecode != 0: print ecode
return volts.value
else:
if chnum < 8:
return ( float(bits) * 20.0 / 4096.0 ) - 10.0
else:
volts = ( float(bits) * 40.0 / 4096.0 ) - 20.0
return volts / self.GainMapping[chgain]
def voltsToBits(self, chnum, chgain, volts):
"""
Name: U12.voltsToBits(chnum, chgain, bits)
Args: See section 4.15 of the User's Guide
Desc: Converts a voltage to it's 12-bit (0-4095) binary representation. No hardware communication is involved.
>>> dev = U12()
>>> dev.voltsToBits(0, 0, 3)
>>> {'bits': 2662}
"""
if ON_WINDOWS:
bits = ctypes.c_long(999)
ecode = staticLib.VoltsToBits(chnum, chgain, ctypes.c_float(volts), ctypes.byref(bits))
if ecode != 0: raise U12Exception(ecode)
return bits.value
else:
pass
#*bits = RoundFL((volts+10.0F)/(20.0F/4096.0F));
def counter(self, idNum=None, demo=0, resetCounter=0, enableSTB=1):
"""
Name: U12.counter(idNum=None, demo=0, resetCounter=0, enableSTB=1)
Args: See section 4.15 of the User's Guide
Desc: Converts a voltage to it's 12-bit (0-4095) binary representation. No hardware communication is involved.
>>> dev = U12()
>>> dev.counter(0, 0, 3)
>>> {'bits': 2662}
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
# Create ctypes
stateD = ctypes.c_long(999)
stateIO = ctypes.c_long(999)
count = ctypes.c_ulong(999)
print idNum
ecode = staticLib.Counter(ctypes.byref(idNum), demo, ctypes.byref(stateD), ctypes.byref(stateIO), resetCounter, enableSTB, ctypes.byref(count))
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value, "stateD": stateD.value, "stateIO":stateIO.value, "count":count.value}
def digitalIO(self, idNum=None, demo=0, trisD=None, trisIO=None, stateD=None, stateIO=None, updateDigital=0):
"""
Name: U12.digitalIO(idNum=None, demo=0, trisD=None, trisIO=None, stateD=None, stateIO=None, updateDigital=0)
Args: See section 4.17 of the User's Guide
Desc: Reads and writes to all 20 digital I/O.
>>> dev = U12()
>>> dev.digitalIO()
>>> {'stateIO': 0, 'stateD': 0, 'idnum': 1, 'outputD': 0, 'trisD': 0}
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
# Check tris and state parameters
if updateDigital > 0:
if trisD is None: raise ValueError("keyword argument trisD must be set")
if trisIO is None: raise ValueError("keyword argument trisIO must be set")
if stateD is None: raise ValueError("keyword argument stateD must be set")
if stateIO is None: raise ValueError("keyword argument stateIO must be set")
# Create ctypes
if trisD is None: trisD = ctypes.c_long(999)
else:trisD = ctypes.c_long(trisD)
if stateD is None:stateD = ctypes.c_long(999)
else: stateD = ctypes.c_long(stateD)
if stateIO is None: stateIO = ctypes.c_long(0)
else: stateIO = ctypes.c_long(stateIO)
outputD = ctypes.c_long(999)
# Check trisIO
if trisIO is None: trisIO = 0
ecode = staticLib.DigitalIO(ctypes.byref(idNum), demo, ctypes.byref(trisD), trisIO, ctypes.byref(stateD), ctypes.byref(stateIO), updateDigital, ctypes.byref(outputD))
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value, "trisD":trisD.value, "stateD":stateD.value, "stateIO":stateIO.value, "outputD":outputD.value}
def getDriverVersion(self):
"""
Name: U12.getDriverVersion()
Args: See section 4.18 of the User's Guide
Desc: Returns the version number of ljackuw.dll. No hardware communication is involved.
>>> dev = U12()
>>> dev.getDriverVersion()
>>> 1.21000003815
"""
staticLib.GetDriverVersion.restype = ctypes.c_float
return staticLib.GetDriverVersion()
def getFirmwareVersion(self, idNum=None):
"""
Name: U12.getErrorString(idnum=None)
Args: See section 4.20 of the User's Guide
Desc: Retrieves the firmware version from the LabJack's processor
>>> dev = U12()
>>> dev.getFirmwareVersion()
>>> Unkown error
"""
# Check ID number
if idNum is None: idNum = self.id
idNum = ctypes.c_long(idNum)
staticLib.GetFirmwareVersion.restype = ctypes.c_float
firmware = staticLib.GetFirmwareVersion(ctypes.byref(idNum))
if firmware > 512: raise U12Exception(firmware-512)
return {"idnum" : idNum.value, "firmware" : firmware}
def getWinVersion(self):
"""
Name: U12.getErrorString()
Args: See section 4.21 of the User's Guide
Desc: Uses a Windows API function to get the OS version
>>> dev = U12()
>>> dev.getWinVersion()
>>> {'majorVersion': 5L, 'minorVersion': 1L, 'platformID': 2L, 'buildNumber': 2600L, 'servicePackMajor': 2L, 'servicePackMinor': 0L}
"""
# Create ctypes
majorVersion = ctypes.c_ulong()
minorVersion = ctypes.c_ulong()
buildNumber = ctypes.c_ulong()
platformID = ctypes.c_ulong()
servicePackMajor = ctypes.c_ulong()
servicePackMinor = ctypes.c_ulong()
ecode = staticLib.GetWinVersion(ctypes.byref(majorVersion), ctypes.byref(minorVersion), ctypes.byref(buildNumber), ctypes.byref(platformID), ctypes.byref(servicePackMajor), ctypes.byref(servicePackMinor))
if ecode != 0: raise U12Exception(ecode)
return {"majorVersion":majorVersion.value, "minorVersion":minorVersion.value, "buildNumber":buildNumber.value, "platformID":platformID.value, "servicePackMajor":servicePackMajor.value, "servicePackMinor":servicePackMinor.value}
def listAll(self):
"""
Name: U12.listAll()
Args: See section 4.22 of the User's Guide
Desc: Searches the USB for all LabJacks, and returns the serial number and local ID for each
>>> dev = U12()
>>> dev.listAll()
>>> {'serialnumList': <u12.c_long_Array_127 object at 0x00E2AD50>, 'numberFound': 1, 'localIDList': <u12.c_long_Array_127 object at 0x00E2ADA0>}
"""
# Create arrays and ctypes
productIDList = listToCArray([0]*127, ctypes.c_long)
serialnumList = listToCArray([0]*127, ctypes.c_long)
localIDList = listToCArray([0]*127, ctypes.c_long)
powerList = listToCArray([0]*127, ctypes.c_long)
arr127_type = ctypes.c_long * 127
calMatrix_type = arr127_type * 20
calMatrix = calMatrix_type()
reserved = ctypes.c_long()
numberFound = ctypes.c_long()
ecode = staticLib.ListAll(ctypes.byref(productIDList), ctypes.byref(serialnumList), ctypes.byref(localIDList), ctypes.byref(powerList), ctypes.byref(calMatrix), ctypes.byref(numberFound), ctypes.byref(reserved), ctypes.byref(reserved))
if ecode != 0: raise U12Exception(ecode)
return {"serialnumList": serialnumList, "localIDList":localIDList, "numberFound":numberFound.value}
def localID(self, localID, idNum=None):
"""
Name: U12.localID(localID, idNum=None)
Args: See section 4.23 of the User's Guide
Desc: Changes the local ID of a specified LabJack
>>> dev = U12()
>>> dev.localID(1)
>>> {'idnum':1}
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
ecode = staticLib.LocalID(ctypes.byref(idNum), localID)
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value}
def noThread(self, noThread, idNum=None):
"""
Name: U12.localID(noThread, idNum=None)
Args: See section 4.24 of the User's Guide
Desc: This function is needed when interfacing TestPoint to the LabJack DLL on Windows 98/ME
>>> dev = U12()
>>> dev.noThread(1)
>>> {'idnum':1}
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
ecode = staticLib.NoThread(ctypes.byref(idNum), noThread)
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value}
def pulseOut(self, bitSelect, numPulses, timeB1, timeC1, timeB2, timeC2, idNum=None, demo=0, lowFirst=0):
"""
Name: U12.pulseOut(bitSelect, numPulses, timeB1, timeC1, timeB2, timeC2, idNum=None, demo=0, lowFirst=0)
Args: See section 4.25 of the User's Guide
Desc: This command creates pulses on any/all of D0-D7
>>> dev = U12()
>>> dev.pulseOut(0, 1, 1, 1, 1, 1)
>>> {'idnum':1}
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
ecode = staticLib.PulseOut(ctypes.byref(idNum), demo, lowFirst, bitSelect, numPulses, timeB1, timeC1, timeB2, timeC2)
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value}
def pulseOutStart(self, bitSelect, numPulses, timeB1, timeC1, timeB2, timeC2, idNum=None, demo=0, lowFirst=0):
"""
Name: U12.pulseOutStart(bitSelect, numPulses, timeB1, timeC1, timeB2, timeC2, idNum=None, demo=0, lowFirst=0)
Args: See section 4.26 of the User's Guide
Desc: PulseOutStart and PulseOutFinish are used as an alternative to PulseOut (See PulseOut for more information)
>>> dev = U12()
>>> dev.pulseOutStart(0, 1, 1, 1, 1, 1)
>>> {'idnum':1}
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
ecode = staticLib.PulseOutStart(ctypes.byref(idNum), demo, lowFirst, bitSelect, numPulses, timeB1, timeC1, timeB2, timeC2)
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value}
def pulseOutFinish(self, timeoutMS, idNum=None, demo=0):
"""
Name: U12.pulseOutFinish(timeoutMS, idNum=None, demo=0)
Args: See section 4.27 of the User's Guide
Desc: See PulseOutStart for more information
>>> dev = U12()
>>> dev.pulseOutStart(0, 1, 1, 1, 1, 1)
>>> dev.pulseOutFinish(100)
>>> {'idnum':1}
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
ecode = staticLib.PulseOutFinish(ctypes.byref(idNum), demo, timeoutMS)
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value}
def pulseOutCalc(self, frequency):
"""
Name: U12.pulseOutFinish(frequency)
Args: See section 4.28 of the User's Guide
Desc: This function can be used to calculate the cycle times for PulseOut or PulseOutStart.
>>> dev = U12()
>>> dev.pulseOutCalc(100)
>>> {'frequency': 100.07672882080078, 'timeB': 247, 'timeC': 1}
"""
# Create ctypes
frequency = ctypes.c_float(frequency)
timeB = ctypes.c_long(0)
timeC = ctypes.c_long(0)
ecode = staticLib.PulseOutCalc(ctypes.byref(frequency), ctypes.byref(timeB), ctypes.byref(timeC))
if ecode != 0: raise U12Exception(ecode)
return {"frequency":frequency.value, "timeB":timeB.value, "timeC":timeC.value}
def reEnum(self, idNum=None):
"""
Name: U12.reEnum(idNum=None)
Args: See section 4.29 of the User's Guide
Desc: Causes the LabJack to electrically detach from and re-attach to the USB so it will re-enumerate
>>> dev = U12()
>>> dev.reEnum()
>>> {'idnum': 1}
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
ecode = staticLib.ReEnum(ctypes.byref(idNum))
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value}
def reset(self, idNum=None):
"""
Name: U12.reset(idNum=None)
Args: See section 4.30 of the User's Guide
Desc: Causes the LabJack to reset after about 2 seconds
>>> dev = U12()
>>> dev.reset()
>>> {'idnum': 1}
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
ecode = staticLib.Reset(ctypes.byref(idNum))
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value}
def resetLJ(self, idNum=None):
"""
Name: U12.resetLJ(idNum=None)
Args: See section 4.30 of the User's Guide
Desc: Causes the LabJack to reset after about 2 seconds
>>> dev = U12()
>>> dev.resetLJ()
>>> {'idnum': 1}
"""
return reset(idNum)
def sht1X(self, idNum=None, demo=0, softComm=0, mode=0, statusReg=0):
"""
Name: U12.sht1X(idNum=None, demo=0, softComm=0, mode=0, statusReg=0)
Args: See section 4.31 of the User's Guide
Desc: This function retrieves temperature and/or humidity readings from an SHT1X sensor.
>>> dev = U12()
>>> dev.sht1X()
>>> {'tempC': 24.69999885559082, 'rh': 39.724445343017578, 'idnum': 1, 'tempF': 76.459999084472656}
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
# Create ctypes
tempC = ctypes.c_float(0)
tempF = ctypes.c_float(0)
rh = ctypes.c_float(0)
ecode = staticLib.SHT1X(ctypes.byref(idNum), demo, softComm, mode, statusReg, ctypes.byref(tempC), ctypes.byref(tempF), ctypes.byref(rh))
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value, "tempC":tempC.value, "tempF":tempF.value, "rh":rh.value}
def shtComm(self, numWrite, numRead, datatx, idNum=None, softComm=0, waitMeas=0, serialReset=0, dataRate=0):
"""
Name: U12.shtComm(numWrite, numRead, datatx, idNum=None, softComm=0, waitMeas=0, serialReset=0, dataRate=0)
Args: See section 4.32 of the User's Guide
Desc: Low-level public function to send and receive up to 4 bytes to from an SHT1X sensor
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
# Check size of datatx
if len(datatx) != 4: raise ValueError("datatx must have exactly 4 elements")
# Create ctypes
datatx = listToCArray(datatx, ctypes.c_ubyte)
datarx = (ctypes.c_ubyte * 4)((0) * 4)
ecode = staticLib.SHTComm(ctypes.byref(idNum), softComm, waitMeas, serialReset, dataRate, numWrite, numRead, ctypes.byref(datatx), ctypes.byref(datarx))
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value, "datarx":datarx}
def shtCRC(self, numWrite, numRead, datatx, datarx, statusReg=0):
"""
Name: U12.shtCRC(numWrite, numRead, datatx, datarx, statusReg=0)
Args: See section 4.33 of the User's Guide
Desc: Checks the CRC on an SHT1X communication
"""
# Create ctypes
datatx = listToCArray(datatx, ctypes.c_ubyte)
datarx = listToCArray(datarx, ctypes.c_ubyte)
return staticLib.SHTCRC(statusReg, numWrite, numRead, ctypes.byref(datatx), ctypes.byref(datarx))
def synch(self, mode, numWriteRead, data, idNum=None, demo=0, msDelay=0, husDelay=0, controlCS=0, csLine=None, csState=0, configD=0):
"""
Name: U12.synch(mode, numWriteRead, data, idNum=None, demo=0, msDelay=0, husDelay=0, controlCS=0, csLine=None, csState=0, configD=0)
Args: See section 4.35 of the User's Guide
Desc: This function retrieves temperature and/or humidity readings from an SHT1X sensor.
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
if controlCS > 0 and csLine is None: raise ValueError("csLine must be specified")
# Make sure data is 18 elements
cData = [0] * 18
for i in range(0, len(data)):
cData[i] = data[i]
cData = listToCArray(cData, ctypes.c_long)
ecode = staticLib.Synch(ctypes.byref(idNum), demo, mode, msDelay, husDelay, controlCS, csLine, csState, configD, numWriteRead, ctypes.byref(cData))
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value, "data":cData}
def watchdog(self, active, timeout, activeDn, stateDn, idNum=None, demo=0, reset=0):
"""
Name: U12.watchdog(active, timeout, activeDn, stateDn, idNum=None, demo=0, reset=0)
Args: See section 4.35 of the User's Guide
Desc: Controls the LabJack watchdog function.
>>> dev = U12()
>>> dev.watchdog(1, 1, [0, 0, 0], [0, 0, 0])
>>> {'idnum': 1}
"""
#Check id number
if idNum is None:
idNum = self.id
idNum = ctypes.c_long(idNum)
if len(activeDn) is not 3: raise ValueError("activeDn must have 3 elements")
if len(stateDn) is not 3: raise Value("stateDn must have 3 elements")
ecode = staticLib.Watchdog(ctypes.byref(idNum), demo, active, timeout, reset, activeDn[0], activeDn[1], activeDn[2], stateDn[0], stateDn[1], stateDn[2])
if ecode != 0: raise U12Exception(ecode)
return {"idnum":idNum.value}
def readMem(self, address, idnum = None):
"""
Name: U12.readMem(address, idnum=None)
Args: See section 4.36 of the User's Guide
Desc: Reads 4 bytes from a specified address in the LabJack's nonvolatile memory
>>> dev = U12()
>>> dev.readMem(0)
>>> [5, 246, 16, 59]
"""
if address is None:
raise Exception, "Must give an Address."
if idnum is None:
idnum = self.id
ljid = ctypes.c_ulong(idnum)
ad0 = ctypes.c_ulong()
ad1 = ctypes.c_ulong()
ad2 = ctypes.c_ulong()
ad3 = ctypes.c_ulong()
ec = staticLib.ReadMem(ctypes.byref(ljid), ctypes.c_long(address), ctypes.byref(ad3), ctypes.byref(ad2), ctypes.byref(ad1), ctypes.byref(ad0))
if ec != 0: raise U12Exception(ec)
addr = [0] * 4
addr[0] = int(ad3.value & 0xff)
addr[1] = int(ad2.value & 0xff)
addr[2] = int(ad1.value & 0xff)
addr[3] = int(ad0.value & 0xff)
return addr
def writeMem(self, address, data, idnum=None, unlocked=False):
"""
Name: U12.writeMem(self, address, data, idnum=None, unlocked=False)
Args: See section 4.37 of the User's Guide
Desc: Writes 4 bytes to the LabJack's 8,192 byte nonvolatile memory at a specified address.
>>> dev = U12()
>>> dev.writeMem(0, [5, 246, 16, 59])
>>> 1
"""
if address is None or data is None:
raise Exception, "Must give both an Address and data."
if type(data) is not list or len(data) != 4:
raise Exception, "Data must be a list and have a length of 4"
if idnum is None:
idnum = self.id
ljid = ctypes.c_ulong(idnum)
ec = staticLib.WriteMem(ctypes.byref(ljid), int(unlocked), address, data[3] & 0xff, data[2] & 0xff, data[1] & 0xff, data[0] & 0xff)
if ec != 0: raise U12Exception(ec)
return ljid.value
def LJHash(self, hashStr, size):
outBuff = (ctypes.c_char * 16)()
retBuff = ''
staticLib = ctypes.windll.LoadLibrary("ljackuw")
ec = staticLib.LJHash(ctypes.cast(hashStr, ctypes.POINTER(ctypes.c_char)),
size,
ctypes.cast(outBuff, ctypes.POINTER(ctypes.c_char)),
0)
if ec != 0: raise U12Exception(ec)
for i in range(16):
retBuff += outBuff[i]
return retBuff
def isIterable(var):
try:
iter(var)
return True
except:
return False
def listToCArray(list, dataType):
arrayType = dataType * len(list)
array = arrayType()
for i in range(0,len(list)):
array[i] = list[i]
return array
def cArrayToList(array):
list = []
for item in array:
list.append(item)
return list
def getErrorString(errorcode):
"""
Name: U12.getErrorString(errorcode)
Args: See section 4.19 of the User's Guide
Desc: Converts a LabJack errorcode, returned by another function, into a string describing the error. No hardware communication is involved.
>>> dev = U12()
>>> dev.getErrorString(1)
>>> Unkown error
"""
errorString = ctypes.c_char_p(" "*50)
staticLib.GetErrorString(errorcode, errorString)
return errorString.value
def hexWithoutQuotes(l):
""" Return a string listing hex without all the single quotes.
>>> l = range(10)
>>> print hexWithoutQuotes(l)
[0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9]
"""
return str([hex (i) for i in l]).replace("'", "")
| 114,714 | 37.456252 | 327 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/build/lib/LabJackPython.py | """
Multi-Platform Python wrapper that implements functions from the LabJack
Windows UD Driver, and the Exodriver.
This python wrapper is intended to make working with your LabJack device easy. The functions contained in this module are helper and device agnostic functions. This module provides the base Device class which the U3, U6, and UE9 classes inherit from.
A typical user should start with their device's module, such as u3.py.
"""
# We use the 'with' keyword to manage the thread-safe device lock. It's built-in on 2.6; 2.5 requires an import.
from __future__ import with_statement
import collections
import ctypes
import os
import struct
from decimal import Decimal
import socket
import Modbus
import atexit # For auto-closing devices
import threading # For a thread-safe device lock
LABJACKPYTHON_VERSION = "8-26-2011"
SOCKET_TIMEOUT = 3
LJSOCKET_TIMEOUT = 62
BROADCAST_SOCKET_TIMEOUT = 1
MAX_USB_PACKET_LENGTH = 64
NUMBER_OF_UNIQUE_LABJACK_PRODUCT_IDS = 5
class LabJackException(Exception):
"""Custom Exception meant for dealing specifically with LabJack Exceptions.
Error codes are either going to be a LabJackUD error code or a -1. The -1 implies
a python wrapper specific error.
WINDOWS ONLY
If errorString is not specified then errorString is set by errorCode
"""
def __init__(self, ec = 0, errorString = ''):
self.errorCode = ec
self.errorString = errorString
if not self.errorString:
try:
pString = ctypes.create_string_buffer(256)
staticLib.ErrorToString(ctypes.c_long(self.errorCode), ctypes.byref(pString))
self.errorString = pString.value
except:
self.errorString = str(self.errorCode)
def __str__(self):
return self.errorString
# Raised when a low-level command raises an error.
class LowlevelErrorException(LabJackException): pass
# Raised when the return value of OpenDevice is null.
class NullHandleException(LabJackException):
def __init__(self):
self.errorString = "Couldn't open device. Please check that the device you are trying to open is connected."
def errcheck(ret, func, args):
"""
Whenever a function is called through ctypes, the return value is passed to
this function to be checked for errors.
Support for errno didn't come until 2.6, so Python 2.5 people should
upgrade.
"""
if ret == -1:
try:
ec = ctypes.get_errno()
raise LabJackException(ec, "Exodriver returned error number %s" % ec)
except AttributeError:
raise LabJackException(-1, "Exodriver returned an error, but LabJackPython is unable to read the error code. Upgrade to Python 2.6 for this functionality.")
else:
return ret
def _loadLinuxSo():
"""
Attempts to load the liblabjackusb.so for Linux.
"""
try:
l = ctypes.CDLL("liblabjackusb.so", use_errno=True)
except TypeError:
l = ctypes.CDLL("liblabjackusb.so")
l.LJUSB_Stream.errcheck = errcheck
l.LJUSB_Read.errcheck = errcheck
return l
def _loadMacDylib():
"""
Attempts to load the liblabjackusb.dylib for Mac OS X.
"""
try:
l = ctypes.CDLL("liblabjackusb.dylib", use_errno=True)
except TypeError:
l = ctypes.CDLL("liblabjackusb.dylib")
l.LJUSB_Stream.errcheck = errcheck
l.LJUSB_Read.errcheck = errcheck
return l
def _loadLibrary():
"""_loadLibrary()
Returns a ctypes dll pointer to the library.
"""
if(os.name == 'posix'):
try:
return _loadLinuxSo()
except OSError, e:
pass # We may be on Mac.
except Exception, e:
raise LabJackException("Could not load the Linux SO for some reason other than it not being installed. Ethernet connectivity only.\n\n The error was: %s" % e)
try:
return _loadMacDylib()
except OSError, e:
raise LabJackException("Could not load the Exodriver driver. Ethernet connectivity only.\n\nCheck that the Exodriver is installed, and the permissions are set correctly.\nThe error message was: %s" % e)
except Exception, e:
raise LabJackException("Could not load the Mac Dylib for some reason other than it not being installed. Ethernet connectivity only.\n\n The error was: %s" % e)
if(os.name == 'nt'):
try:
return ctypes.windll.LoadLibrary("labjackud")
except Exception, e:
raise LabJackException("Could not load labjackud driver. Ethernet connectivity availability only.\n\n The error was: %s" % e)
try:
staticLib = _loadLibrary()
except LabJackException, e:
print "%s: %s" % ( type(e), e )
staticLib = None
# Attempt to load the windows Skymote library.
try:
skymoteLib = ctypes.windll.LoadLibrary("liblabjackusb")
except:
skymoteLib = None
class Device(object):
"""Device(handle, localId = None, serialNumber = None, ipAddress = "", type = None)
Creates a simple 0 with the following functions:
write(writeBuffer) -- Writes a buffer.
writeRegister(addr, value) -- Writes a value to a modbus register
read(numBytes) -- Reads until a packet is received.
readRegister(addr, numReg = None, format = None) -- Reads a modbus register.
ping() -- Pings the device. Returns true if communication worked.
close() -- Closes the device.
reset() -- Resets the device.
"""
def __init__(self, handle, localId = None, serialNumber = None, ipAddress = "", devType = None):
# Not saving the handle as a void* causes many problems on 64-bit machines.
if isinstance(handle, int):
self.handle = ctypes.c_void_p(handle)
else:
self.handle = handle
self.localId = localId
self.serialNumber = serialNumber
self.ipAddress = ipAddress
self.devType = devType
self.debug = False
self.streamConfiged = False
self.streamStarted = False
self.streamPacketOffset = 0
self._autoCloseSetup = False
self.modbusPrependZeros = True
self.deviceLock = threading.Lock()
self.deviceName = "LabJack"
def _writeToLJSocketHandle(self, writeBuffer, modbus):
#if modbus is True and self.modbusPrependZeros:
# writeBuffer = [ 0, 0 ] + writeBuffer
packFormat = "B" * len(writeBuffer)
tempString = struct.pack(packFormat, *writeBuffer)
if modbus:
self.handle.modbusSocket.send(tempString)
else:
self.handle.crSocket.send(tempString)
return writeBuffer
def _writeToUE9TCPHandle(self, writeBuffer, modbus):
packFormat = "B" * len(writeBuffer)
tempString = struct.pack(packFormat, *writeBuffer)
if modbus is True:
self.handle.modbus.send(tempString)
else:
self.handle.data.send(tempString)
return writeBuffer
def _writeToExodriver(self, writeBuffer, modbus):
if modbus is True and self.modbusPrependZeros:
writeBuffer = [ 0, 0 ] + writeBuffer
newA = (ctypes.c_byte*len(writeBuffer))(0)
for i in range(len(writeBuffer)):
newA[i] = ctypes.c_byte(writeBuffer[i])
writeBytes = staticLib.LJUSB_Write(self.handle, ctypes.byref(newA), len(writeBuffer))
if(writeBytes != len(writeBuffer)):
raise LabJackException( "Could only write %s of %s bytes." % (writeBytes, len(writeBuffer) ) )
return writeBuffer
def _writeToUDDriver(self, writeBuffer, modbus):
if self.devType == 0x501:
newA = (ctypes.c_byte*len(writeBuffer))(0)
for i in range(len(writeBuffer)):
newA[i] = ctypes.c_byte(writeBuffer[i])
writeBytes = skymoteLib.LJUSB_IntWrite(self.handle, 1, ctypes.byref(newA), len(writeBuffer))
if(writeBytes != len(writeBuffer)):
raise LabJackException( "Could only write %s of %s bytes." % (writeBytes, len(writeBuffer) ) )
else:
if modbus is True and self.devType == 9:
dataWords = len(writeBuffer)
writeBuffer = [0, 0xF8, 0, 0x07, 0, 0] + writeBuffer #modbus low-level function
if dataWords % 2 != 0:
dataWords = (dataWords+1)/2
writeBuffer.append(0)
else:
dataWords = dataWords/2
writeBuffer[2] = dataWords
setChecksum(writeBuffer)
elif modbus is True and self.modbusPrependZeros:
writeBuffer = [ 0, 0 ] + writeBuffer
eGetRaw(self.handle, LJ_ioRAW_OUT, 0, len(writeBuffer), writeBuffer)
return writeBuffer
def write(self, writeBuffer, modbus = False, checksum = True):
"""write([writeBuffer], modbus = False)
Writes the data contained in writeBuffer to the device. writeBuffer must be a list of
bytes.
"""
if self.handle is None:
raise LabJackException("The device handle is None.")
if checksum:
setChecksum(writeBuffer)
if(isinstance(self.handle, LJSocketHandle)):
wb = self._writeToLJSocketHandle(writeBuffer, modbus)
elif(isinstance(self.handle, UE9TCPHandle)):
wb = self._writeToUE9TCPHandle(writeBuffer, modbus)
else:
if os.name == 'posix':
wb = self._writeToExodriver(writeBuffer, modbus)
elif os.name == 'nt':
wb = self._writeToUDDriver(writeBuffer, modbus)
if self.debug: print "Sent: ", hexWithoutQuotes(wb)
def read(self, numBytes, stream = False, modbus = False):
"""read(numBytes, stream = False, modbus = False)
Blocking read until a packet is received.
"""
readBytes = 0
if self.handle is None:
raise LabJackException("The device handle is None.")
if(isinstance(self.handle, LJSocketHandle)):
return self._readFromLJSocketHandle(numBytes, modbus, stream)
elif(isinstance(self.handle, UE9TCPHandle)):
return self._readFromUE9TCPHandle(numBytes, stream, modbus)
else:
if(os.name == 'posix'):
return self._readFromExodriver(numBytes, stream, modbus)
elif os.name == 'nt':
return self._readFromUDDriver(numBytes, stream, modbus)
def _readFromLJSocketHandle(self, numBytes, modbus, spont = False):
"""
Reads from LJSocket. Returns the result as a list.
"""
if modbus:
rcvString = self.handle.modbusSocket.recv(numBytes)
elif spont:
rcvString = self.handle.spontSocket.recv(numBytes)
else:
rcvString = self.handle.crSocket.recv(numBytes)
readBytes = len(rcvString)
packFormat = "B" * readBytes
rcvDataBuff = struct.unpack(packFormat, rcvString)
return list(rcvDataBuff)
def _readFromUE9TCPHandle(self, numBytes, stream, modbus):
if stream is True:
rcvString = self.handle.stream.recv(numBytes)
else:
if modbus is True:
rcvString = self.handle.modbus.recv(numBytes)
else:
rcvString = self.handle.data.recv(numBytes)
readBytes = len(rcvString)
packFormat = "B" * readBytes
rcvDataBuff = struct.unpack(packFormat, rcvString)
return list(rcvDataBuff)
def _readFromExodriver(self, numBytes, stream, modbus):
newA = (ctypes.c_byte*numBytes)()
if(stream):
readBytes = staticLib.LJUSB_Stream(self.handle, ctypes.byref(newA), numBytes)
if readBytes == 0:
return ''
# return the byte string in stream mode
return struct.pack('b' * readBytes, *newA)
else:
readBytes = staticLib.LJUSB_Read(self.handle, ctypes.byref(newA), numBytes)
# return a list of integers in command/response mode
return [(newA[i] & 0xff) for i in range(readBytes)]
def _readFromUDDriver(self, numBytes, stream, modbus):
if self.devType == 0x501:
newA = (ctypes.c_byte*numBytes)()
readBytes = skymoteLib.LJUSB_IntRead(self.handle, 0x81, ctypes.byref(newA), numBytes)
return [(newA[i] & 0xff) for i in range(readBytes)]
else:
if modbus is True and self.devType == 9:
tempBuff = [0] * (8 + numBytes + numBytes%2)
eGetBuff = list()
eGetBuff = eGetRaw(self.handle, LJ_ioRAW_IN, 0, len(tempBuff), tempBuff)[1]
#parse the modbus response out (reponse is the Modbus extended low=level function)
retBuff = list()
if len(eGetBuff) >= 9 and eGetBuff[1] == 0xF8 and eGetBuff[3] == 0x07:
#figuring out the length of the modbus response
mbSize = len(eGetBuff) - 8
if len(eGetBuff) >= 14:
mbSize = min(mbSize, eGetBuff[13] + 6)
i = min(mbSize, numBytes)
i = max(i, 0)
retBuff = eGetBuff[8:8+i] #getting the response only
return retBuff
tempBuff = [0] * numBytes
if stream:
return eGetRaw(self.handle, LJ_ioRAW_IN, 1, numBytes, tempBuff)[1]
return eGetRaw(self.handle, LJ_ioRAW_IN, 0, numBytes, tempBuff)[1]
def readRegister(self, addr, numReg = None, format = None, unitId = None):
""" Reads a specific register from the device and returns the value.
Requires Modbus.py
readHoldingRegister(addr, numReg = None, format = None)
addr: The address you would like to read
numReg: Number of consecutive addresses you would like to read
format: the unpack format of the returned value ( '>f' or '>I')
Modbus is supported for UE9s over USB from Comm Firmware 1.50 and above.
"""
pkt, numBytes = self._buildReadRegisterPacket(addr, numReg, unitId)
response = self._modbusWriteRead(pkt, numBytes)
return self._parseReadRegisterResponse(response, numBytes, addr, format, numReg)
def _buildReadRegisterPacket(self, addr, numReg, unitId):
"""
self._buildReadRegisterPacket(addr, numReg)
Builds a raw modbus "Read Register" packet to be written to a device
returns a tuple:
( < Packet as a list >, < number of bytes to read > )
"""
# Calculates the number of registers for that request, or if numReg is
# specified, checks that it is a valid number.
numReg = Modbus.calcNumberOfRegisters(addr, numReg = numReg)
pkt = Modbus.readHoldingRegistersRequest(addr, numReg = numReg, unitId = unitId)
pkt = [ ord(c) for c in pkt ]
numBytes = 9 + (2 * int(numReg))
return (pkt, numBytes)
def _parseReadRegisterResponse(self, response, numBytes, addr, format, numReg = None):
"""
self._parseReadRegisterReponse(reponse, numBytes, addr, format)
Takes a "Read Register" response and converts it to a value
returns the value
"""
if len(response) != numBytes:
raise LabJackException(9001, "Got incorrect number of bytes from device. Expected %s bytes, got %s bytes. The packet recieved was: %s" % (numBytes, len(response),response))
if isinstance(response, list):
packFormat = ">" + "B" * numBytes
response = struct.pack(packFormat, *response)
if format == None:
format = Modbus.calcFormat(addr, numReg)
value = Modbus.readHoldingRegistersResponse(response, payloadFormat=format)
return value
def writeRegister(self, addr, value, unitId = None):
"""
Writes a value to a register. Returns the value to be written, if successful.
Requires Modbus.py
writeRegister(self, addr, value)
addr: The address you want to write to.
value: The value, or list of values, you want to write.
if you cannot write to that register, a LabJackException is raised.
Modbus is not supported for UE9's over USB. If you try it, a LabJackException is raised.
"""
pkt, numBytes = self._buildWriteRegisterPacket(addr, value, unitId)
response = self._modbusWriteRead(pkt, numBytes)
return self._parseWriteRegisterResponse(response, pkt, value)
def _buildWriteRegisterPacket(self, addr, value, unitId):
"""
self._buildWriteRegisterPacket(addr, value)
Builds a raw modbus "Write Register" packet to be written to a device
returns a tuple:
( < Packet as a list >, < number of bytes to read > )
"""
if type(value) is list:
return self._buildWriteMultipleRegisters(addr, value, unitId)
fmt = Modbus.calcFormat(addr)
if fmt != '>H':
return self._buildWriteFloatToRegister(addr, value, unitId, fmt)
request = Modbus.writeRegisterRequest(addr, value, unitId)
request = [ ord(c) for c in request ]
numBytes = 12
return request, numBytes
def _buildWriteFloatToRegister(self, addr, value, unitId, fmt = '>f'):
numReg = 2
if not isinstance(value, int) and not isinstance(value, float):
raise TypeError("Value must be a float or int.")
# Function, Address, Num Regs, Byte count, Data
payload = struct.pack('>BHHB', 0x10, addr, 0x02, 0x04) + struct.pack(fmt, value)
request = Modbus._buildHeaderBytes(length = len(payload)+1, unitId = unitId)
request += payload
request = [ ord(c) for c in request ]
numBytes = 12
return (request, numBytes)
def _buildWriteMultipleRegisters(self, startAddr, values, unitId = None):
request = Modbus.writeRegistersRequest(startAddr, values, unitId)
request = [ ord(c) for c in request ]
numBytes = 12
return (request, numBytes)
def _parseWriteRegisterResponse(self, response, request, value):
response = list(response)
if request[2] != 0 and request[3] != 0:
protoID = (request[2] << 8) + request[3]
raise Modbus.ModbusException("Got an unexpected protocol ID: %s (expected 0). Please make sure that you have the latest firmware. UE9s need a Comm Firmware of 1.50 or greater.\n\nThe packet you received: %s" % (protoID, hexWithoutQuotes(response)))
if request[7] != response[7]:
raise LabJackException(9002, "Modbus error number %s raised while writing to register. Make sure you're writing to an address that allows writes.\n\nThe packet you received: %s" % (response[8], hexWithoutQuotes(response)))
return value
def setDIOState(IOnum, state):
value = (int(state) & 0x01)
self.writeRegister(6000+IOnum, value)
return True
def _modbusWriteRead(self, request, numBytes):
with self.deviceLock:
self.write(request, modbus = True, checksum = False)
try:
result = self.read(numBytes, modbus = True)
if self.debug: print "Response: ", hexWithoutQuotes(result)
return result
except LabJackException:
self.write(request, modbus = True, checksum = False)
result = self.read(numBytes, modbus = True)
if self.debug: print "Response: ", hexWithoutQuotes(result)
return result
def _checkCommandBytes(self, results, commandBytes):
"""
Checks all the stuff from a command
"""
size = len(commandBytes)
if len(results) == 0:
raise LabJackException("Got a zero length packet.")
elif results[0] == 0xB8 and results[1] == 0xB8:
raise LabJackException("Device detected a bad checksum.")
elif results[1:(size+1)] != commandBytes:
raise LabJackException("Got incorrect command bytes.\nExpected: %s\nGot: %s\nFull packet: %s" % (hexWithoutQuotes(commandBytes), hexWithoutQuotes(results[1:(size+1)]), hexWithoutQuotes(results)))
elif not verifyChecksum(results):
raise LabJackException("Checksum was incorrect.")
elif results[6] != 0:
raise LowlevelErrorException(results[6], "\nThe %s returned an error:\n %s" % (self.deviceName , lowlevelErrorToString(results[6])) )
def _writeRead(self, command, readLen, commandBytes, checkBytes = True, stream=False, checksum = True):
# Acquire the device lock.
with self.deviceLock:
self.write(command, checksum = checksum)
result = self.read(readLen, stream=False)
if self.debug: print "Response: ", hexWithoutQuotes(result)
if checkBytes:
self._checkCommandBytes(result, commandBytes)
return result
def ping(self):
try:
if self.devType == LJ_dtUE9:
writeBuffer = [0x70, 0x70]
self.write(writeBuffer)
try:
self.read(2)
except LabJackException:
self.write(writeBuffer)
self.read(2)
return True
if self.devType == LJ_dtU3:
writeBuffer = [0, 0xf8, 0x01, 0x2a, 0, 0, 0, 0]
writeBuffer = setChecksum(writeBuffer)
self.write(writeBuffer)
self.read(40)
return True
return False
except Exception, e:
print e
return False
def open(self, devType, Ethernet=False, firstFound = True, serial = None, localId = None, devNumber = None, ipAddress = None, handleOnly = False, LJSocket = None):
"""
Device.open(devType, Ethernet=False, firstFound = True, serial = None, localId = None, devNumber = None, ipAddress = None, handleOnly = False, LJSocket = None)
Open a device of type devType.
"""
if self.handle is not None:
raise LabJackException(9000,"Open called on a device with a handle. Please close the device, and try again. Your device is probably already open.\nLook for lines of code that look like this:\nd = u3.U3()\nd.open() # Wrong! Device is already open.")
ct = LJ_ctUSB
if Ethernet:
ct = LJ_ctETHERNET
if LJSocket is not None:
ct = LJ_ctLJSOCKET
d = None
if devNumber:
d = openLabJack(devType, ct, firstFound = False, devNumber = devNumber, handleOnly = handleOnly, LJSocket = LJSocket)
elif serial:
d = openLabJack(devType, ct, firstFound = False, pAddress = serial, handleOnly = handleOnly, LJSocket = LJSocket)
elif localId:
d = openLabJack(devType, ct, firstFound = False, pAddress = localId, handleOnly = handleOnly, LJSocket = LJSocket)
elif ipAddress:
d = openLabJack(devType, ct, firstFound = False, pAddress = ipAddress, handleOnly = handleOnly, LJSocket = LJSocket)
elif LJSocket:
d = openLabJack(devType, ct, handleOnly = handleOnly, LJSocket = LJSocket)
elif firstFound:
d = openLabJack(devType, ct, firstFound = True, handleOnly = handleOnly, LJSocket = LJSocket)
else:
raise LabJackException("You must use first found, or give a localId, devNumber, or IP Address")
self.handle = d.handle
if not handleOnly:
self._loadChangedIntoSelf(d)
self._registerAtExitClose()
def _loadChangedIntoSelf(self, d):
for key, value in d.changed.items():
self.__setattr__(key, value)
def _registerAtExitClose(self):
if not self._autoCloseSetup:
# Only need to register auto-close once per device.
atexit.register(self.close)
self._autoCloseSetup = True
def close(self):
"""close()
This function is not specifically supported in the LabJackUD driver
for Windows and so simply calls the UD function Close. For Mac and unix
drivers, this function MUST be performed when finished with a device.
The reason for this close is because there can not be more than one program
with a given device open at a time. If a device is not closed before
the program is finished it may still be held open and unable to be used
by other programs until properly closed.
For Windows, Linux, and Mac
"""
if isinstance(self.handle, UE9TCPHandle) or isinstance(self.handle, LJSocketHandle):
self.handle.close()
elif os.name == 'posix':
staticLib.LJUSB_CloseDevice(self.handle)
elif self.devType == 0x501:
skymoteLib.LJUSB_CloseDevice(self.handle)
self.handle = None
def reset(self):
"""Reset the LabJack device.
For Windows, Linux, and Mac
Sample Usage:
>>> u3 = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
>>> u3.reset()
@type None
@param Function takes no arguments
@rtype: None
@return: Function returns nothing.
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
ec = staticLib.ResetLabJack(self.handle)
if ec != 0: raise LabJackException(ec)
elif os.name == 'posix':
sndDataBuff = [0] * 4
#Make the reset packet
sndDataBuff[0] = 0x9B
sndDataBuff[1] = 0x99
sndDataBuff[2] = 0x02
try:
self.write(sndDataBuff)
rcvDataBuff = self.read(4)
if(len(rcvDataBuff) != 4):
raise LabJackException(0, "Unable to reset labJack 2")
except Exception, e:
raise LabJackException(0, "Unable to reset labjack: %s" % str(e))
def breakupPackets(self, packets, numBytesPerPacket):
"""
Name: Device.breakupPackets
Args: packets, a string or list of packets
numBytesPerPacket, how big each packe is
Desc: This function will break up a list into smaller chunks and return
each chunk one at a time.
>>> l = range(15)
>>> for packet in d.breakupPackets(l, 5):
... print packet
[ 0, 1, 2, 3, 4 ]
[ 5, 6, 7, 8, 9 ]
[ 10, 11, 12, 13, 14]
"""
start, end = 0, numBytesPerPacket
while end <= len(packets):
yield packets[start:end]
start, end = end, end + numBytesPerPacket
def samplesFromPacket(self, packet):
"""
Name: Device.samplesFromPacket
Args: packet, a packet of stream data
Desc: This function breaks a packet into all the two byte samples it
contains and returns them one at a time.
>>> packet = range(16) # fake packet with 1 sample in it
>>> for sample in d.samplesFromPacket(packet):
... print sample
[ 12, 13 ]
"""
HEADER_SIZE = 12
FOOTER_SIZE = 2
BYTES_PER_PACKET = 2
l = str(packet)
l = l[HEADER_SIZE:]
l = l[:-FOOTER_SIZE]
while len(l) > 0:
yield l[:BYTES_PER_PACKET]
l = l[BYTES_PER_PACKET:]
def streamStart(self):
"""
Name: Device.streamStart()
Args: None
Desc: Starts streaming on the device.
Note: You must call streamConfig() before calling this function.
"""
if not self.streamConfiged:
raise LabJackException("Stream must be configured before it can be started.")
if self.streamStarted:
raise LabJackException("Stream already started.")
command = [ 0xA8, 0xA8 ]
results = self._writeRead(command, 4, [], False, False, False)
if results[2] != 0:
raise LowlevelErrorException(results[2], "StreamStart returned an error:\n %s" % lowlevelErrorToString(results[2]) )
self.streamStarted = True
def streamData(self, convert=True):
"""
Name: Device.streamData()
Args: convert, should the packets be converted as they are read.
set to False to get much faster speeds, but you will
have to process the results later.
Desc: Reads stream data from a LabJack device. See our stream example
to get an idea of how this function should be called. The return
value of streamData is a dictionary with the following keys:
* errors: The number of errors in this block.
* numPackets: The number of USB packets collected to return this
block.
* missed: The number of readings that were missed because of
buffer overflow on the LabJack.
* firstPacket: The PacketCounter value in the first USB packet.
* result: The raw bytes returned from read(). The only way to get
data if called with convert = False.
* AINi, where i is an entry in the passed in PChannels. If called
with convert = True, this is a list of all the readings
in this block.
Note: You must start the stream by calling streamStart() before calling
this function.
"""
if not self.streamStarted:
raise LabJackException("Please start streaming before reading.")
numBytes = 14 + (self.streamSamplesPerPacket * 2)
while True:
result = self.read(numBytes * self.packetsPerRequest, stream = True)
if len(result) == 0:
yield None
continue
numPackets = len(result) // numBytes
errors = 0
missed = 0
firstPacket = ord(result[10])
for i in range(numPackets):
e = ord(result[11+(i*numBytes)])
if e != 0:
errors += 1
if self.debug and e != 60 and e != 59: print e
if e == 60:
missed += struct.unpack('<I', result[6+(i*numBytes):10+(i*numBytes)] )[0]
returnDict = dict(numPackets = numPackets, result = result, errors = errors, missed = missed, firstPacket = firstPacket )
if convert:
returnDict.update(self.processStreamData(result, numBytes = numBytes))
yield returnDict
def streamStop(self):
"""
Name: Device.streamStop()
Args: None
Desc: Stops streaming on the device.
"""
command = [ 0xB0, 0xB0 ]
results = self._writeRead(command, 4, [], False, False, False)
if results[2] != 0:
raise LowlevelErrorException(results[2], "StreamStop returned an error:\n %s" % lowlevelErrorToString(results[2]) )
self.streamStarted = False
def getName(self):
"""
Name: Device.getName()
Args: None
Desc: Returns the name of a device.
Always returns a unicode string.
Works as of the following firmware versions:
U6 - 1.00
U3 - 1.22
UE9 - 2.00
>>> d = u3.U3()
>>> d.open()
>>> d.getName()
u'My LabJack U3'
"""
name = list(self.readRegister(58000, format='B'*48, numReg = 24))
if name[1] == 3:
# Old style string
name = "My %s" % self.deviceName
if self.debug: print "Old UTF-16 name detected, replacing with %s" % name
self.setName(name)
name = name.decode("UTF-8")
else:
try:
end = name.index(0x00)
name = struct.pack("B"*end, *name[:end]).decode("UTF-8")
except ValueError:
name = "My %s" % self.deviceName
if self.debug: print "Invalid name detected, replacing with %s" % name
self.setName(name)
name = name.decode("UTF-8")
return name
def setName(self, name = "My LabJack U3"):
"""
Name: Device.setName(name = ""My LabJack U3")
Args: name, the name you'd like to assign the the U3
Desc: Writes a new name to the device.
Names a limited to 30 characters or less.
Works as of the following firmware versions:
U6 - 1.00
U3 - 1.22
UE9 - 2.00
>>> d = u3.U3()
>>> d.open()
>>> d.getName()
u'My LabJack U3'
>>> d.setName("Johann")
>>> d.getName()
u'Johann'
"""
strLen = len(name)
if strLen > 47:
raise LabJackException("The name is too long, must be less than 48 characters.")
newname = name.encode('UTF-8')
bl = list(struct.unpack("B"*strLen, newname)) + [0x00]
strLen += 1
if strLen%2 != 0:
bl = bl + [0x00]
strLen += 1
bl = struct.unpack(">"+"H"*(strLen/2), struct.pack("B" * strLen, *bl))
self.writeRegister(58000, list(bl))
name = property(getName, setName)
def setDefaults(self, SetToFactoryDefaults = False):
"""
Name: Device.setDefaults(SetToFactoryDefaults = False)
Args: SetToFactoryDefaults, set to True reset to factory defaults.
Desc: Executing this function causes the current or last used values
(or the factory defaults) to be stored in flash as the power-up
defaults.
>>> myU6 = U6()
>>> myU6.setDefaults()
"""
command = [ 0 ] * 8
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x01
command[3] = 0x0E
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = 0xBA
command[7] = 0x26
if SetToFactoryDefaults:
command[6] = 0x82
command[7] = 0xC7
self._writeRead(command, 8, [ 0xF8, 0x01, 0x0E ] )
def setToFactoryDefaults(self):
return self.setDefaults(SetToFactoryDefaults = True)
validDefaultBlocks = range(8)
def readDefaults(self, BlockNum, ReadCurrent = False):
"""
Name: Device.readDefaults(BlockNum)
Args: BlockNum, which block to read. Must be 0-7.
ReadCurrent, True = read current configuration
Desc: Reads the power-up defaults from flash.
>>> myU6 = U6()
>>> myU6.readDefaults(0)
[ 0, 0, ... , 0]
"""
if BlockNum not in self.validDefaultBlocks:
raise LabJackException("Defaults must be in range 0-7")
byte7 = (int(bool(ReadCurrent)) << 7) + BlockNum
command = [ 0, 0xF8, 0x01, 0x0E, 0, 0, 0, byte7 ]
result = self._writeRead(command, 40, [ 0xF8, 0x11, 0x0E ])
return result[8:]
def readCurrent(self, BlockNum):
self.readDefaults(BlockNum, ReadCurrent = True)
def loadGenericDevice(self, device):
""" Take a generic Device object, and loads it into the current object.
The generic Device is consumed in the process.
"""
self.handle = device.handle
self._loadChangedIntoSelf(device)
self._registerAtExitClose()
device = None
# --------------------- BEGIN LabJackPython ---------------------------------
def setChecksum(command):
"""Returns a command with checksums places in the proper locations
For Windows, Mac, and Linux
Sample Usage:
>>> from LabJackPython import *
>>> command = [0] * 12
>>> command[1] = 0xf8
>>> command[2] = 0x03
>>> command[3] = 0x0b
>>> command = SetChecksum(command)
>>> command
[7, 248, 3, 11, 0, 0, 0, 0, 0, 0, 0, 0]
@type command: List
@param command: The command by which to calculate the checksum
@rtype: List
@return: A command list with checksums in the proper locations.
"""
if len(command) < 8:
raise LabJackException("Command does not contain enough bytes.")
try:
a = command[1]
a = (a & 0x78) >> 3
#Check if the command is an extended command
if a == 15:
command = setChecksum16(command)
command = setChecksum8(command, 6)
return command
else:
command = setChecksum8(command, len(command))
return command
except LabJackException, e:
raise e
except Exception, e:
raise LabJackException("SetChecksum Exception:" + str(e))
def verifyChecksum(buffer):
"""Verifies the checksum of a given buffer using the traditional U3/UE9 Command Structure.
"""
buff0 = buffer[0]
buff4 = buffer[4]
buff5 = buffer[5]
tempBuffer = setChecksum(buffer)
if (buff0 == tempBuffer[0]) and (buff4 == tempBuffer[4]) \
and (buff5 == tempBuffer[5]):
return True
return False
# 1 = LJ_ctUSB
def listAll(deviceType, connectionType = 1):
"""listAll(deviceType, connectionType) -> [[local ID, Serial Number, IP Address], ...]
Searches for all devices of a given type over a given connection type and returns a list
of all devices found.
WORKS on WINDOWS, MAC, UNIX
"""
if connectionType == LJ_ctLJSOCKET:
ipAddress, port = deviceType.split(":")
port = int(port)
serverSocket = socket.socket()
serverSocket.connect((ipAddress, port))
serverSocket.settimeout(10)
f = serverSocket.makefile(bufsize = 0)
f.write("scan\r\n")
l = f.readline().strip()
try:
status, numLines = l.split(' ')
except ValueError:
raise Exception("Got invalid line from server: %s" % l)
if status.lower().startswith('ok'):
lines = []
marked = None
for i in range(int(numLines)):
l = f.readline().strip()
dev = parseline(l)
lines.append(dev)
f.close()
serverSocket.close()
#print "Result of scan:"
#print lines
return lines
if deviceType == 12:
if U12DriverPresent():
u12Driver = ctypes.windll.LoadLibrary("ljackuw")
# Setup all the ctype arrays
pSerialNumbers = (ctypes.c_long * 127)(0)
pIDs = (ctypes.c_long * 127)(0)
pProdID = (ctypes.c_long * 127)(0)
pPowerList = (ctypes.c_long * 127)(0)
pCalMatrix = (ctypes.c_long * 2540)(0)
pNumFound = ctypes.c_long()
pFcdd = ctypes.c_long(0)
pHvc = ctypes.c_long(0)
#Output dictionary
deviceList = {}
ec = u12Driver.ListAll(ctypes.cast(pProdID, ctypes.POINTER(ctypes.c_long)),
ctypes.cast(pSerialNumbers, ctypes.POINTER(ctypes.c_long)),
ctypes.cast(pIDs, ctypes.POINTER(ctypes.c_long)),
ctypes.cast(pPowerList, ctypes.POINTER(ctypes.c_long)),
ctypes.cast(pCalMatrix, ctypes.POINTER(ctypes.c_long)),
ctypes.byref(pNumFound),
ctypes.byref(pFcdd),
ctypes.byref(pHvc))
if ec != 0: raise LabJackException(ec)
for i in range(pNumFound.value):
deviceList[pSerialNumbers[i]] = { 'SerialNumber' : pSerialNumbers[i], 'Id' : pIDs[i], 'ProdId' : pProdID[i], 'powerList' : pPowerList[i] }
return deviceList
else:
return {}
if(os.name == 'nt'):
if deviceType == 0x501:
if skymoteLib is None:
raise ImportError("Couldn't load liblabjackusb.dll. Please install, and try again.")
num = skymoteLib.LJUSB_GetDevCount(0x501)
deviceList = dict()
for i in range(num):
try:
device = openLabJack(0x501, 1, firstFound = False, pAddress = None, devNumber = i+1)
device.close()
deviceList[str(device.serialNumber)] = device.__dict__
except LabJackException:
pass
return deviceList
pNumFound = ctypes.c_long()
pSerialNumbers = (ctypes.c_long * 128)()
pIDs = (ctypes.c_long * 128)()
pAddresses = (ctypes.c_double * 128)()
#The actual return variables so the user does not have to use ctypes
serialNumbers = []
ids = []
addresses = []
ec = staticLib.ListAll(deviceType, connectionType,
ctypes.byref(pNumFound),
ctypes.cast(pSerialNumbers, ctypes.POINTER(ctypes.c_long)),
ctypes.cast(pIDs, ctypes.POINTER(ctypes.c_long)),
ctypes.cast(pAddresses, ctypes.POINTER(ctypes.c_long)))
if ec != 0 and ec != 1010: raise LabJackException(ec)
deviceList = dict()
for i in xrange(pNumFound.value):
if pSerialNumbers[i] != 1010:
deviceValue = dict(localId = pIDs[i], serialNumber = pSerialNumbers[i], ipAddress = DoubleToStringAddress(pAddresses[i]), devType = deviceType)
deviceList[pSerialNumbers[i]] = deviceValue
return deviceList
if(os.name == 'posix'):
if deviceType == LJ_dtUE9:
return __listAllUE9Unix(connectionType)
if deviceType == LJ_dtU3:
return __listAllU3Unix()
if deviceType == 6:
return __listAllU6Unix()
if deviceType == 0x501:
return __listAllBridgesUnix()
def isHandleValid(handle):
if(os.name == 'nt'):
return True
else:
return staticLib.LJUSB_IsHandleValid(handle)
def deviceCount(devType = None):
"""Returns the number of devices connected. """
if(os.name == 'nt'):
if devType is None:
numdev = len(listAll(3))
numdev += len(listAll(9))
numdev += len(listAll(6))
if skymoteLib is not None:
numdev += len(listAll(0x501))
return numdev
else:
return len(listAll(devType))
else:
if devType == None:
numdev = staticLib.LJUSB_GetDevCount(3)
numdev += staticLib.LJUSB_GetDevCount(9)
numdev += staticLib.LJUSB_GetDevCount(6)
numdev += staticLib.LJUSB_GetDevCount(0x501)
return numdev
else:
return staticLib.LJUSB_GetDevCount(devType)
def getDevCounts():
if os.name == "nt":
# Right now there is no good way to count all the U12s on a Windows box
return { 3 : len(listAll(3)), 6 : len(listAll(6)), 9 : len(listAll(9)), 1 : 0, 0x501 : len(listAll(0x501))}
else:
devCounts = (ctypes.c_uint*NUMBER_OF_UNIQUE_LABJACK_PRODUCT_IDS)()
devIds = (ctypes.c_uint*NUMBER_OF_UNIQUE_LABJACK_PRODUCT_IDS)()
n = ctypes.c_uint(NUMBER_OF_UNIQUE_LABJACK_PRODUCT_IDS)
r = staticLib.LJUSB_GetDevCounts(ctypes.byref(devCounts), ctypes.byref(devIds), n)
returnDict = dict()
for i in range(NUMBER_OF_UNIQUE_LABJACK_PRODUCT_IDS):
returnDict[int(devIds[i])] = int(devCounts[i])
return returnDict
def openAllLabJacks():
if os.name == "nt":
# Windows doesn't provide a nice way to open all the devices.
devs = dict()
devs[3] = listAll(3)
devs[6] = listAll(6)
devs[9] = listAll(9)
devs[0x501] = listAll(0x501)
devices = list()
for prodId, numConnected in devs.items():
for i, serial in enumerate(numConnected.keys()):
d = Device(None, devType = prodId)
if prodId == 0x501:
d.open(prodId, devNumber = i)
d = _makeDeviceFromHandle(d.handle, prodId)
else:
d.open(prodId, serial = serial)
d = _makeDeviceFromHandle(d.handle, prodId)
devices.append(d)
else:
maxHandles = 10
devHandles = (ctypes.c_void_p*maxHandles)()
devIds = (ctypes.c_uint*maxHandles)()
n = ctypes.c_uint(maxHandles)
numOpened = staticLib.LJUSB_OpenAllDevices(ctypes.byref(devHandles), ctypes.byref(devIds), n)
devices = list()
for i in range(numOpened):
devices.append(_makeDeviceFromHandle(devHandles[i], int(devIds[i])))
return devices
def _openLabJackUsingLJSocket(deviceType, firstFound, pAddress, LJSocket, handleOnly ):
if LJSocket is not '':
ip, port = LJSocket.split(":")
port = int(port)
handle = LJSocketHandle(ip, port, deviceType, firstFound, pAddress)
else:
handle = LJSocketHandle('localhost', 6000, deviceType, firstFound, pAddress)
return handle
def _openLabJackUsingUDDriver(deviceType, connectionType, firstFound, pAddress, devNumber ):
if devNumber is not None:
devs = listAll(deviceType)
pAddress = devs.keys()[(devNumber-1)]
handle = ctypes.c_long()
pAddress = str(pAddress)
ec = staticLib.OpenLabJack(deviceType, connectionType,
pAddress, firstFound, ctypes.byref(handle))
if ec != 0: raise LabJackException(ec)
devHandle = handle.value
return devHandle
def _openLabJackUsingExodriver(deviceType, firstFound, pAddress, devNumber):
devType = ctypes.c_ulong(deviceType)
openDev = staticLib.LJUSB_OpenDevice
openDev.restype = ctypes.c_void_p
if(devNumber != None):
handle = openDev(devNumber, 0, devType)
if handle <= 0:
raise NullHandleException()
return handle
elif(firstFound):
handle = openDev(1, 0, devType)
if handle <= 0:
print "handle: %s" % handle
raise NullHandleException()
return handle
else:
numDevices = staticLib.LJUSB_GetDevCount(deviceType)
for i in range(numDevices):
handle = openDev(i + 1, 0, devType)
try:
if handle <= 0:
raise NullHandleException()
device = _makeDeviceFromHandle(handle, deviceType)
except:
continue
if device.localId == pAddress or device.serialNumber == pAddress or device.ipAddress == pAddress:
return device
else:
device.close()
raise LabJackException(LJE_LABJACK_NOT_FOUND)
def _openUE9OverEthernet(firstFound, pAddress, devNumber):
if firstFound is not True and pAddress is not None:
#Check if valid IP address and attempt to get TCP handle
try:
socket.inet_aton(pAddress)
return UE9TCPHandle(pAddress)
except:
pass
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.settimeout(BROADCAST_SOCKET_TIMEOUT)
sndDataBuff = [0] * 6
sndDataBuff[0] = 0x22
sndDataBuff[1] = 0x78
sndDataBuff[3] = 0xa9
outBuff = ""
for item in sndDataBuff:
outBuff += chr(item)
s.sendto(outBuff, ("255.255.255.255", 52362))
try:
count = 1
while True:
rcvDataBuff = s.recv(128)
rcvDataBuff = [ord(val) for val in rcvDataBuff]
if verifyChecksum(rcvDataBuff):
#Parse the packet
macAddress = rcvDataBuff[28:34]
macAddress.reverse()
# The serial number is four bytes:
# 0x10 and the last three bytes of the MAC address
serialBytes = chr(0x10)
for j in macAddress[3:]:
serialBytes += chr(j)
serialNumber = struct.unpack(">I", serialBytes)[0]
#Parse out the IP address
ipAddress = ""
for j in range(13, 9, -1):
ipAddress += str(int(rcvDataBuff[j]))
ipAddress += "."
ipAddress = ipAddress[0:-1]
#Local ID
localId = rcvDataBuff[8] & 0xff
# Check if we have found the device we are looking for.
# pAddress represents either Local ID, Serial Number, or the
# IP Address. This is so there are no conflicting identifiers.
if firstFound \
or devNumber == count \
or pAddress in [localId, serialNumber, ipAddress]:
handle = UE9TCPHandle(ipAddress)
return handle
count += 1
else:
# Got a bad checksum.
pass
except LabJackException, e:
raise LabJackException(LJE_LABJACK_NOT_FOUND, "%s" % e)
except:
raise LabJackException("LJE_LABJACK_NOT_FOUND: Couldn't find the specified LabJack.")
def _openWirelessBridgeOnWindows(firstFound, pAddress, devNumber):
if skymoteLib is None:
raise ImportError("Couldn't load liblabjackusb.dll. Please install, and try again.")
devType = ctypes.c_ulong(0x501)
openDev = skymoteLib.LJUSB_OpenDevice
openDev.restype = ctypes.c_void_p
if(devNumber != None):
handle = openDev(devNumber, 0, devType)
if handle <= 0:
raise NullHandleException()
return handle
elif(firstFound):
handle = openDev(1, 0, devType)
if handle <= 0:
raise NullHandleException()
return handle
else:
raise LabjackException("Bridges don't have identifiers yet.")
if handleOnly:
raise LabjackException("Can't use handleOnly with an id.")
numDevices = skymoteLib.LJUSB_GetDevCount(deviceType)
for i in range(numDevices):
handle = openDev(i + 1, 0, devType)
try:
if handle <= 0:
raise NullHandleException()
device = _makeDeviceFromHandle(handle, deviceType)
except:
continue
if device.localId == pAddress or device.serialNumber == pAddress or device.ipAddress == pAddress:
return device
else:
device.close()
raise LabJackException(LJE_LABJACK_NOT_FOUND)
#Windows, Linux, and Mac
def openLabJack(deviceType, connectionType, firstFound = True, pAddress = None, devNumber = None, handleOnly = False, LJSocket = None):
"""openLabJack(deviceType, connectionType, firstFound = True, pAddress = 1, LJSocket = None)
Note: On Windows, Ue9 over Ethernet, pAddress MUST be the IP address.
"""
rcvDataBuff = []
handle = None
if connectionType == LJ_ctLJSOCKET:
# LJSocket handles work indepenent of OS
handle = _openLabJackUsingLJSocket(deviceType, firstFound, pAddress, LJSocket, handleOnly )
elif os.name == 'posix' and connectionType == LJ_ctUSB:
# Linux/Mac need to work in the low level driver.
handle = _openLabJackUsingExodriver(deviceType, firstFound, pAddress, devNumber)
if isinstance( handle, Device ):
return handle
elif os.name == 'nt':
#If windows operating system then use the UD Driver
if deviceType == 0x501:
handle = _openWirelessBridgeOnWindows(firstFound, pAddress, devNumber)
handle = ctypes.c_void_p(handle)
elif staticLib is not None:
handle = _openLabJackUsingUDDriver(deviceType, connectionType, firstFound, pAddress, devNumber )
elif connectionType == LJ_ctETHERNET and deviceType == LJ_dtUE9 :
handle = _openUE9OverEthernet(firstFound, pAddress, devNumber)
if not handleOnly:
return _makeDeviceFromHandle(handle, deviceType)
else:
return Device(handle, devType = deviceType)
def _makeDeviceFromHandle(handle, deviceType):
""" A helper function to get set all the info about a device from a handle"""
device = Device(handle, devType = deviceType)
device.changed = dict()
if(deviceType == LJ_dtUE9):
sndDataBuff = [0] * 38
sndDataBuff[0] = 0x89
sndDataBuff[1] = 0x78
sndDataBuff[2] = 0x10
sndDataBuff[3] = 0x01
try:
device.write(sndDataBuff, checksum = False)
rcvDataBuff = device.read(38)
# Local ID
device.localId = rcvDataBuff[8] & 0xff
# MAC Address
device.macAddress = "%02X:%02X:%02X:%02X:%02X:%02X" % (rcvDataBuff[33], rcvDataBuff[32], rcvDataBuff[31], rcvDataBuff[30], rcvDataBuff[29], rcvDataBuff[28])
# Parse out serial number
device.serialNumber = struct.unpack("<I", struct.pack("BBBB", rcvDataBuff[28], rcvDataBuff[29], rcvDataBuff[30], 0x10))[0]
#Parse out the IP address
device.ipAddress = "%s.%s.%s.%s" % (rcvDataBuff[13], rcvDataBuff[12], rcvDataBuff[11], rcvDataBuff[10] )
# Comm FW Version
device.commFWVersion = "%s.%02d" % (rcvDataBuff[37], rcvDataBuff[36])
device.changed['localId'] = device.localId
device.changed['macAddress'] = device.macAddress
device.changed['serialNumber'] = device.serialNumber
device.changed['ipAddress'] = device.ipAddress
device.changed['commFWVersion'] = device.commFWVersion
except Exception, e:
device.close()
raise e
elif deviceType == LJ_dtU3:
sndDataBuff = [0] * 26
sndDataBuff[0] = 0x0b
sndDataBuff[1] = 0xf8
sndDataBuff[2] = 0x0a
sndDataBuff[3] = 0x08
try:
device.write(sndDataBuff, checksum = False)
rcvDataBuff = device.read(38)
except LabJackException, e:
device.close()
raise e
device.localId = rcvDataBuff[21] & 0xff
serialNumber = struct.pack("<BBBB", *rcvDataBuff[15:19])
device.serialNumber = struct.unpack('<I', serialNumber)[0]
device.ipAddress = ""
device.firmwareVersion = "%d.%02d" % (rcvDataBuff[10], rcvDataBuff[9])
device.hardwareVersion = "%d.%02d" % (rcvDataBuff[14], rcvDataBuff[13])
device.versionInfo = rcvDataBuff[37]
device.deviceName = 'U3'
if device.versionInfo == 1:
device.deviceName += 'B'
elif device.versionInfo == 2:
device.deviceName += '-LV'
elif device.versionInfo == 18:
device.deviceName += '-HV'
device.changed['localId'] = device.localId
device.changed['serialNumber'] = device.serialNumber
device.changed['ipAddress'] = device.ipAddress
device.changed['firmwareVersion'] = device.firmwareVersion
device.changed['versionInfo'] = device.versionInfo
device.changed['deviceName'] = device.deviceName
device.changed['hardwareVersion'] = device.hardwareVersion
elif deviceType == 6:
command = [ 0 ] * 26
command[1] = 0xF8
command[2] = 0x0A
command[3] = 0x08
try:
device.write(command)
rcvDataBuff = device.read(38)
except LabJackException, e:
device.close()
raise e
device.localId = rcvDataBuff[21] & 0xff
serialNumber = struct.pack("<BBBB", *rcvDataBuff[15:19])
device.serialNumber = struct.unpack('<I', serialNumber)[0]
device.ipAddress = ""
device.firmwareVersion = "%s.%02d" % (rcvDataBuff[10], rcvDataBuff[9])
device.bootloaderVersion = "%s.%02d" % (rcvDataBuff[12], rcvDataBuff[11])
device.hardwareVersion = "%s.%02d" % (rcvDataBuff[14], rcvDataBuff[13])
device.versionInfo = rcvDataBuff[37]
device.deviceName = 'U6'
if device.versionInfo == 12:
device.deviceName = 'U6-Pro'
device.changed['localId'] = device.localId
device.changed['serialNumber'] = device.serialNumber
device.changed['ipAddress'] = device.ipAddress
device.changed['firmwareVersion'] = device.firmwareVersion
device.changed['versionInfo'] = device.versionInfo
device.changed['deviceName'] = device.deviceName
device.changed['hardwareVersion'] = device.hardwareVersion
device.changed['bootloaderVersion'] = device.bootloaderVersion
elif deviceType == 0x501:
pkt, readlen = device._buildReadRegisterPacket(65104, 4, 0)
device.modbusPrependZeros = False
device.write(pkt, modbus = True, checksum = False)
for i in range(5):
try:
serial = None
response = device.read(64, False, True)
serial = device._parseReadRegisterResponse(response[:readlen], readlen, 65104, '>Q', numReg = 4)
break
except Modbus.ModbusException:
pass
if serial is None:
raise LabJackException("Error reading serial number.")
device.serialNumber = serial
device.localId = 0
device.deviceName = "SkyMote Bridge"
device.changed['localId'] = device.localId
device.changed['deviceName'] = device.deviceName
device.changed['serialNumber'] = device.serialNumber
return device
def AddRequest(Handle, IOType, Channel, Value, x1, UserData):
"""AddRequest(handle, ioType, channel, value, x1, userData)
Windows Only
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
v = ctypes.c_double(Value)
ud = ctypes.c_double(UserData)
ec = staticLib.AddRequest(Handle, IOType, Channel, v, x1, ud)
if ec != 0: raise LabJackException(ec)
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def AddRequestS(Handle, pIOType, Channel, Value, x1, UserData):
"""Add a request to the LabJackUD request stack
For Windows
Sample Usage to get the AIN value from channel 0:
>>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
>>> AddRequestS(u3Handle,"LJ_ioGET_AIN", 0, 0.0, 0, 0.0)
>>> Go()
>>> value = GetResult(u3Handle, LJ_ioGET_AIN, 0)
>>> print "Value:" + str(value)
Value:0.366420765873
@type Handle: number
@param Handle: Handle to the LabJack device.
@type IOType: String
@param IOType: IO Request to the LabJack.
@type Channel: number
@param Channel: Channel for the IO request.
@type Value: number
@param Value: Used for some requests
@type x1: number
@param x1: Used for some requests
@type UserData: number
@param UserData: Used for some requests
@rtype: None
@return: Function returns nothing.
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
v = ctypes.c_double(Value)
ud = ctypes.c_double(UserData)
ec = staticLib.AddRequestS(Handle, pIOType, Channel,
v, x1, ud)
if ec != 0: raise LabJackException(ec)
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def AddRequestSS(Handle, pIOType, pChannel, Value, x1, UserData):
"""Add a request to the LabJackUD request stack
For Windows
Sample Usage to get the AIN value from channel 0:
>>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
>>> AddRequestSS(u3Handle,"LJ_ioGET_CONFIG", "LJ_chFIRMWARE_VERSION", 0.0, 0, 0.0)
>>> Go()
>>> value = GetResultS(u3Handle, "LJ_ioGET_CONFIG", LJ_chFIRMWARE_VERSION)
>>> print "Value:" + str(value)
Value:1.27
@type Handle: number
@param Handle: Handle to the LabJack device.
@type IOType: String
@param IOType: IO Request to the LabJack.
@type Channel: String
@param Channel: Channel for the IO request.
@type Value: number
@param Value: Used for some requests
@type x1: number
@param x1: Used for some requests
@type UserData: number
@param UserData: Used for some requests
@rtype: None
@return: Function returns nothing.
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
v = ctypes.c_double(Value)
ud = ctypes.c_double(UserData)
ec = staticLib.AddRequestSS(Handle, pIOType, pChannel,
v, x1, ud)
if ec != 0: raise LabJackException(ec)
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def Go():
"""Complete all requests currently on the LabJackUD request stack
For Windows Only
Sample Usage:
>>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
>>> AddRequestSS(u3Handle,"LJ_ioGET_CONFIG", "LJ_chFIRMWARE_VERSION", 0.0, 0, 0.0)
>>> Go()
>>> value = GetResultS(u3Handle, "LJ_ioGET_CONFIG", LJ_chFIRMWARE_VERSION)
>>> print "Value:" + str(value)
Value:1.27
@rtype: None
@return: Function returns nothing.
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
ec = staticLib.Go()
if ec != 0: raise LabJackException(ec)
else:
raise LabJackException("Function only supported for Windows")
#Windows
def GoOne(Handle):
"""Performs the next request on the LabJackUD request stack
For Windows Only
Sample Usage:
>>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
>>> AddRequestSS(u3Handle,"LJ_ioGET_CONFIG", "LJ_chFIRMWARE_VERSION", 0.0, 0, 0.0)
>>> GoOne(u3Handle)
>>> value = GetResultS(u3Handle, "LJ_ioGET_CONFIG", LJ_chFIRMWARE_VERSION)
>>> print "Value:" + str(value)
Value:1.27
@type Handle: number
@param Handle: Handle to the LabJack device.
@rtype: None
@return: Function returns nothing.
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
ec = staticLib.GoOne(Handle)
if ec != 0: raise LabJackException(ec)
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def eGet(Handle, IOType, Channel, pValue, x1):
"""Perform one call to the LabJack Device
eGet is equivilent to an AddRequest followed by a GoOne.
For Windows Only
Sample Usage:
>>> eGet(u3Handle, LJ_ioGET_AIN, 0, 0, 0)
0.39392614550888538
@type Handle: number
@param Handle: Handle to the LabJack device.
@type IOType: number
@param IOType: IO Request to the LabJack.
@type Channel: number
@param Channel: Channel for the IO request.
@type Value: number
@param Value: Used for some requests
@type x1: number
@param x1: Used for some requests
@rtype: number
@return: Returns the value requested.
- value
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
pv = ctypes.c_double(pValue)
#ppv = ctypes.pointer(pv)
ec = staticLib.eGet(Handle, IOType, Channel, ctypes.byref(pv), x1)
#staticLib.eGet.argtypes = [ctypes.c_long, ctypes.c_long, ctypes.c_long, ctypes.c_double, ctypes.c_long]
#ec = staticLib.eGet(Handle, IOType, Channel, pValue, x1)
if ec != 0: raise LabJackException(ec)
#print "EGet:" + str(ppv)
#print "Other:" + str(ppv.contents)
return pv.value
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
#Raw method -- Used because x1 is an output
def eGetRaw(Handle, IOType, Channel, pValue, x1):
"""Perform one call to the LabJack Device as a raw command
eGetRaw is equivilent to an AddRequest followed by a GoOne.
For Windows Only
Sample Usage (Calling a echo command):
>>> sendBuff = [0] * 2
>>> sendBuff[0] = 0x70
>>> sendBuff[1] = 0x70
>>> eGetRaw(ue9Handle, LJ_ioRAW_OUT, 0, len(sendBuff), sendBuff)
(2.0, [112, 112])
@type Handle: number
@param Handle: Handle to the LabJack device.
@type IOType: number
@param IOType: IO Request to the LabJack.
@type Channel: number
@param Channel: Channel for the IO request.
@type pValue: number
@param Value: Length of the buffer.
@type x1: number
@param x1: Buffer to send.
@rtype: Tuple
@return: The tuple (numBytes, returnBuffer)
- numBytes (number)
- returnBuffer (List)
@raise LabJackException:
"""
ec = 0
x1Type = "int"
if os.name == 'nt':
digitalConst = [35, 36, 37, 45]
pv = ctypes.c_double(pValue)
#If IOType is digital then call eget with x1 as a long
if IOType in digitalConst:
ec = staticLib.eGet(Handle, IOType, Channel, ctypes.byref(pv), x1)
else: #Otherwise as an array
try:
#Verify x1 is an array
if len(x1) < 1:
raise LabJackException(0, "x1 is not a valid variable for the given IOType")
except Exception:
raise LabJackException(0, "x1 is not a valid variable for the given IOType")
#Initialize newA
newA = None
if type(x1[0]) == int:
newA = (ctypes.c_byte*len(x1))()
for i in range(0, len(x1), 1):
newA[i] = ctypes.c_byte(x1[i])
else:
x1Type = "float"
newA = (ctypes.c_double*len(x1))()
for i in range(0, len(x1), 1):
newA[i] = ctypes.c_double(x1[i])
ec = staticLib.eGet(Handle, IOType, Channel, ctypes.byref(pv), ctypes.byref(newA))
if IOType == LJ_ioRAW_IN and Channel == 1:
# We return the raw byte string if we are streaming
x1 = struct.pack('b' * len(x1), *newA)
elif IOType == LJ_ioRAW_IN and Channel == 0:
x1 = [0] * int(pv.value)
for i in range(len(x1)):
x1[i] = newA[i] & 0xff
else:
x1 = [0] * len(x1)
for i in range(len(x1)):
x1[i] = newA[i]
if(x1Type == "int"):
x1[i] = x1[i] & 0xff
if ec != 0: raise LabJackException(ec)
return pv.value, x1
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def eGetS(Handle, pIOType, Channel, pValue, x1):
"""Perform one call to the LabJack Device
eGet is equivilent to an AddRequest followed by a GoOne.
For Windows Only
Sample Usage:
>>> eGet(u3Handle, "LJ_ioGET_AIN", 0, 0, 0)
0.39392614550888538
@type Handle: number
@param Handle: Handle to the LabJack device.
@type pIOType: String
@param pIOType: IO Request to the LabJack.
@type Channel: number
@param Channel: Channel for the IO request.
@type Value: number
@param Value: Used for some requests
@type x1: number
@param x1: Used for some requests
@rtype: number
@return: Returns the value requested.
- value
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
pv = ctypes.c_double(pValue)
ec = staticLib.eGetS(Handle, pIOType, Channel, ctypes.byref(pv), x1)
if ec != 0: raise LabJackException(ec)
return pv.value
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def eGetSS(Handle, pIOType, pChannel, pValue, x1):
"""Perform one call to the LabJack Device
eGet is equivilent to an AddRequest followed by a GoOne.
For Windows Only
Sample Usage:
>>> eGetSS(u3Handle,"LJ_ioGET_CONFIG", "LJ_chFIRMWARE_VERSION", 0, 0)
1.27
@type Handle: number
@param Handle: Handle to the LabJack device.
@type pIOType: String
@param pIOType: IO Request to the LabJack.
@type Channel: String
@param Channel: Channel for the IO request.
@type Value: number
@param Value: Used for some requests
@type x1: number
@param x1: Used for some requests
@rtype: number
@return: Returns the value requested.
- value
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
pv = ctypes.c_double(pValue)
ec = staticLib.eGetSS(Handle, pIOType, pChannel, ctypes.byref(pv), x1)
if ec != 0: raise LabJackException(ec)
return pv.value
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
#Not currently implemented
def eGetRawS(Handle, pIOType, Channel, pValue, x1):
"""Function not yet implemented.
For Windows only.
"""
pass
#Windows
def ePut(Handle, IOType, Channel, Value, x1):
"""Put one value to the LabJack device
ePut is equivilent to an AddRequest followed by a GoOne.
For Windows Only
Sample Usage:
>>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
>>> eGet(u3Handle, LJ_ioGET_CONFIG, LJ_chLOCALID, 0, 0)
0.0
>>> ePut(u3Handle, LJ_ioPUT_CONFIG, LJ_chLOCALID, 8, 0)
>>> eGet(u3Handle, LJ_ioGET_CONFIG, LJ_chLOCALID, 0, 0)
8.0
@type Handle: number
@param Handle: Handle to the LabJack device.
@type IOType: number
@param IOType: IO Request to the LabJack.
@type Channel: number
@param Channel: Channel for the IO request.
@type Value: number
@param Value: Used for some requests
@type x1: number
@param x1: Used for some requests
@rtype: None
@return: Function returns nothing.
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
pv = ctypes.c_double(Value)
ec = staticLib.ePut(Handle, IOType, Channel, pv, x1)
if ec != 0: raise LabJackException(ec)
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def ePutS(Handle, pIOType, Channel, Value, x1):
"""Put one value to the LabJack device
ePut is equivilent to an AddRequest followed by a GoOne.
For Windows Only
Sample Usage:
>>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
>>> eGet(u3Handle, LJ_ioGET_CONFIG, LJ_chLOCALID, 0, 0)
0.0
>>> ePutS(u3Handle, "LJ_ioPUT_CONFIG", LJ_chLOCALID, 8, 0)
>>> eGet(u3Handle, LJ_ioGET_CONFIG, LJ_chLOCALID, 0, 0)
8.0
@type Handle: number
@param Handle: Handle to the LabJack device.
@type IOType: String
@param IOType: IO Request to the LabJack.
@type Channel: number
@param Channel: Channel for the IO request.
@type Value: number
@param Value: Used for some requests
@type x1: number
@param x1: Used for some requests
@rtype: None
@return: Function returns nothing.
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
pv = ctypes.c_double(Value)
ec = staticLib.ePutS(Handle, pIOType, Channel, pv, x1)
if ec != 0: raise LabJackException(ec)
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def ePutSS(Handle, pIOType, pChannel, Value, x1):
"""Put one value to the LabJack device
ePut is equivilent to an AddRequest followed by a GoOne.
For Windows Only
Sample Usage:
>>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
>>> eGet(u3Handle, LJ_ioGET_CONFIG, LJ_chLOCALID, 0, 0)
0.0
>>> ePutSS(u3Handle, "LJ_ioPUT_CONFIG", "LJ_chLOCALID", 8, 0)
>>> eGet(u3Handle, LJ_ioGET_CONFIG, LJ_chLOCALID, 0, 0)
8.0
@type Handle: number
@param Handle: Handle to the LabJack device.
@type IOType: String
@param IOType: IO Request to the LabJack.
@type Channel: String
@param Channel: Channel for the IO request.
@type Value: number
@param Value: Used for some requests
@type x1: number
@param x1: Used for some requests
@rtype: None
@return: Function returns nothing.
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
pv = ctypes.c_double(Value)
ec = staticLib.ePutSS(Handle, pIOType, pChannel, pv, x1)
if ec != 0: raise LabJackException(ec)
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def GetResult(Handle, IOType, Channel):
"""Put one value to the LabJack device
ePut is equivilent to an AddRequest followed by a GoOne.
For Windows Only
Sample Usage:
>>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
>>> AddRequestSS(u3Handle,"LJ_ioGET_CONFIG", "LJ_chFIRMWARE_VERSION", 0.0, 0, 0.0)
>>> GoOne(u3Handle)
>>> value = GetResult(u3Handle, LJ_ioGET_CONFIG, LJ_chFIRMWARE_VERSION)
>>> print "Value:" + str(value)
Value:1.27
@type Handle: number
@param Handle: Handle to the LabJack device.
@type IOType: number
@param IOType: IO Request to the LabJack.
@type Channel: number
@param Channel: Channel for the IO request.
@rtype: number
@return: The value requested.
- value
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
pv = ctypes.c_double()
ec = staticLib.GetResult(Handle, IOType, Channel, ctypes.byref(pv))
if ec != 0: raise LabJackException(ec)
return pv.value
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def GetResultS(Handle, pIOType, Channel):
"""Put one value to the LabJack device
ePut is equivilent to an AddRequest followed by a GoOne.
For Windows Only
Sample Usage:
>>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
>>> AddRequestSS(u3Handle,"LJ_ioGET_CONFIG", "LJ_chFIRMWARE_VERSION", 0.0, 0, 0.0)
>>> GoOne(u3Handle)
>>> value = GetResultS(u3Handle, "LJ_ioGET_CONFIG", LJ_chFIRMWARE_VERSION)
>>> print "Value:" + str(value)
Value:1.27
@type Handle: number
@param Handle: Handle to the LabJack device.
@type pIOType: String
@param pIOType: IO Request to the LabJack.
@type Channel: number
@param Channel: Channel for the IO request.
@rtype: number
@return: The value requested.
- value
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
pv = ctypes.c_double()
ec = staticLib.GetResultS(Handle, pIOType, Channel, ctypes.byref(pv))
if ec != 0: raise LabJackException(ec)
return pv.value
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def GetResultSS(Handle, pIOType, pChannel):
"""Put one value to the LabJack device
ePut is equivilent to an AddRequest followed by a GoOne.
For Windows Only
Sample Usage:
>>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
>>> AddRequestSS(u3Handle,"LJ_ioGET_CONFIG", "LJ_chFIRMWARE_VERSION", 0.0, 0, 0.0)
>>> GoOne(u3Handle)
>>> value = GetResultSS(u3Handle, "LJ_ioGET_CONFIG", "LJ_chFIRMWARE_VERSION")
>>> print "Value:" + str(value)
Value:1.27
@type Handle: number
@param Handle: Handle to the LabJack device.
@type pIOType: String
@param pIOType: IO Request to the LabJack.
@type Channel: String
@param Channel: Channel for the IO request.
@rtype: number
@return: The value requested.
- value
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
pv = ctypes.c_double()
ec = staticLib.GetResultS(Handle, pIOType, pChannel, ctypes.byref(pv))
if ec != 0: raise LabJackException(ec)
return pv.value
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def GetFirstResult(Handle):
"""List All LabJack devices of a specific type over a specific connection type.
For Windows only.
Sample Usage (Shows getting the localID (8) and firmware version (1.27) of a U3 device):
>>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
>>> AddRequest(u3Handle, LJ_ioGET_CONFIG, LJ_chLOCALID, 0, 0, 0)
>>> AddRequest(u3Handle, LJ_ioGET_CONFIG, LJ_chFIRMWARE_VERSION, 0, 0, 0)
>>> Go()
>>> GetFirstResult(u3Handle)
(1001, 0, 8.0, 0, 0.0)
>>> GetNextResult(u3Handle)
(1001, 11, 1.27, 0, 0.0)
@type DeviceType: number
@param DeviceType: The LabJack device.
@type ConnectionType: number
@param ConnectionType: The connection method (Ethernet/USB).
@rtype: Tuple
@return: The tuple (ioType, channel, value, x1, userData)
- ioType (number): The io of the result.
- serialNumber (number): The channel of the result.
- value (number): The requested result.
- x1 (number): Used only in certain requests.
- userData (number): Used only in certain requests.
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
pio = ctypes.c_long()
pchan = ctypes.c_long()
pv = ctypes.c_double()
px = ctypes.c_long()
pud = ctypes.c_double()
ec = staticLib.GetFirstResult(Handle, ctypes.byref(pio),
ctypes.byref(pchan), ctypes.byref(pv),
ctypes.byref(px), ctypes.byref(pud))
if ec != 0: raise LabJackException(ec)
return pio.value, pchan.value, pv.value, px.value, pud.value
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def GetNextResult(Handle):
"""List All LabJack devices of a specific type over a specific connection type.
For Windows only.
Sample Usage (Shows getting the localID (8) and firmware version (1.27) of a U3 device):
>>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
>>> AddRequest(u3Handle, LJ_ioGET_CONFIG, LJ_chLOCALID, 0, 0, 0)
>>> AddRequest(u3Handle, LJ_ioGET_CONFIG, LJ_chFIRMWARE_VERSION, 0, 0, 0)
>>> Go()
>>> GetFirstResult(u3Handle)
(1001, 0, 8.0, 0, 0.0)
>>> GetNextResult(u3Handle)
(1001, 11, 1.27, 0, 0.0)
@type DeviceType: number
@param DeviceType: The LabJack device.
@type ConnectionType: number
@param ConnectionType: The connection method (Ethernet/USB).
@rtype: Tuple
@return: The tuple (ioType, channel, value, x1, userData)
- ioType (number): The io of the result.
- serialNumber (number): The channel of the result.
- value (number): The requested result.
- x1 (number): Used only in certain requests.
- userData (number): Used only in certain requests.
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
pio = ctypes.c_long()
pchan = ctypes.c_long()
pv = ctypes.c_double()
px = ctypes.c_long()
pud = ctypes.c_double()
ec = staticLib.GetNextResult(Handle, ctypes.byref(pio),
ctypes.byref(pchan), ctypes.byref(pv),
ctypes.byref(px), ctypes.byref(pud))
if ec != 0: raise LabJackException(ec)
return pio.value, pchan.value, pv.value, px.value, pud.value
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def DoubleToStringAddress(number):
"""Converts a number (base 10) to an IP string.
For Windows
Sample Usage:
>>> DoubleToStringAddress(3232235985)
'192.168.1.209'
@type number: number
@param number: Number to be converted.
@rtype: String
@return: The IP string converted from the number (base 10).
@raise LabJackException:
"""
number = int(number)
address = "%i.%i.%i.%i" % ((number >> 8*3 & 0xFF), (number >> 8*2 & 0xFF), (number >> 8 & 0xFF), (number & 0xFF))
return address
def StringToDoubleAddress(pString):
"""Converts an IP string to a number (base 10).
Sample Usage:
>>> StringToDoubleAddress("192.168.1.209")
3232235985L
@type pString: String
@param pString: String to be converted.
@rtype: number
@return: The number (base 10) that represents the IP string.
@raise LabJackException:
"""
parts = pString.split('.')
if len(parts) is not 4:
raise LabJackException(0, "IP address not correctly formatted")
try:
value = (int(parts[0]) << 8*3) + (int(parts[1]) << 8*2) + (int(parts[2]) << 8) + int(parts[3])
except ValueError:
raise LabJackException(0, "IP address not correctly formatted")
return value
#Windows
def StringToConstant(pString):
"""Converts an LabJackUD valid string to its constant value.
For Windows
Sample Usage:
>>> StringToConstant("LJ_dtU3")
3
@type pString: String
@param pString: String to be converted.
@rtype: number
@return: The number (base 10) that represents the LabJackUD string.
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
a = ctypes.create_string_buffer(pString, 256)
return staticLib.StringToConstant(a)
else:
raise LabJackException(0, "Function only supported for Windows")
# To hold all the error codes and what they mean:
ERROR_TO_STRING_DICT = dict()
ERROR_TO_STRING_DICT['1'] = ("SCRATCH_WRT_FAIL", "")
ERROR_TO_STRING_DICT['2'] = ("SCRATCH_ERASE_FAIL", "")
ERROR_TO_STRING_DICT['3'] = ("DATA_BUFFER_OVERFLOW", "")
ERROR_TO_STRING_DICT['4'] = ("ADC0_BUFFER_OVERFLOW", "")
ERROR_TO_STRING_DICT['5'] = ("FUNCTION_INVALID", "")
ERROR_TO_STRING_DICT['6'] = ("SWDT_TIME_INVALID", "This error is caused when an invalid time was passed to the watchdog.")
ERROR_TO_STRING_DICT['7'] = ("XBR_CONFIG_ERROR", "")
ERROR_TO_STRING_DICT['16'] = ("FLASH_WRITE_FAIL", "For some reason, the LabJack was unable to write the specified page of its internal flash.")
ERROR_TO_STRING_DICT['17'] = ("FLASH_ERASE_FAIL", "For some reason, the LabJack was unable to erase the specified page of its internal flash.")
ERROR_TO_STRING_DICT['18'] = ("FLASH_JMP_FAIL", "For some reason, the LabJack was unable to jump to a different section of flash. This may be an indication the flash is corrupted.")
ERROR_TO_STRING_DICT['19'] = ("FLASH_PSP_TIMEOUT", "")
ERROR_TO_STRING_DICT['20'] = ("FLASH_ABORT_RECEIVED", "")
ERROR_TO_STRING_DICT['21'] = ("FLASH_PAGE_MISMATCH", "")
ERROR_TO_STRING_DICT['22'] = ("FLASH_BLOCK_MISMATCH", "")
ERROR_TO_STRING_DICT['23'] = ("FLASH_PAGE_NOT_IN_CODE_AREA", "Usually, this error is raised when you try to write new firmware before upgrading the bootloader.")
ERROR_TO_STRING_DICT['24'] = ("MEM_ILLEGAL_ADDRESS", "")
ERROR_TO_STRING_DICT['25'] = ("FLASH_LOCKED", "Tried to write to flash before unlocking it.")
ERROR_TO_STRING_DICT['26'] = ("INVALID_BLOCK", "")
ERROR_TO_STRING_DICT['27'] = ("FLASH_ILLEGAL_PAGE", "")
ERROR_TO_STRING_DICT['28'] = ("FLASH_TOO_MANY_BYTES", "")
ERROR_TO_STRING_DICT['29'] = ("FLASH_INVALID_STRING_NUM", "")
ERROR_TO_STRING_DICT['40'] = ("SHT1x_COMM_TIME_OUT", "LabJack never received the ACK it was expecting from the SHT. This is usually due to incorrect wiring. Double check that all wires are securely connected to the correct pins.")
ERROR_TO_STRING_DICT['41'] = ("SHT1x_NO_ACK", "")
ERROR_TO_STRING_DICT['42'] = ("SHT1x_CRC_FAILED", "")
ERROR_TO_STRING_DICT['43'] = ("SHT1x_TOO_MANY_W_BYTES", "")
ERROR_TO_STRING_DICT['44'] = ("SHT1x_TOO_MANY_R_BYTES", "")
ERROR_TO_STRING_DICT['45'] = ("SHT1x_INVALID_MODE", "")
ERROR_TO_STRING_DICT['46'] = ("SHT1x_INVALID_LINE", "")
ERROR_TO_STRING_DICT['48'] = ("STREAM_IS_ACTIVE", "This error is raised when you call StreamStart after the stream has already been started.")
ERROR_TO_STRING_DICT['49'] = ("STREAM_TABLE_INVALID", "")
ERROR_TO_STRING_DICT['50'] = ("STREAM_CONFIG_INVALID", "")
ERROR_TO_STRING_DICT['52'] = ("STREAM_NOT_RUNNING", "This error is raised when you call StopStream after the stream has already been stopped.")
ERROR_TO_STRING_DICT['53'] = ("STREAM_INVALID_TRIGGER", "")
ERROR_TO_STRING_DICT['54'] = ("STREAM_ADC0_BUFFER_OVERFLOW", "")
ERROR_TO_STRING_DICT['55'] = ("STREAM_SCAN_OVERLAP", "This error is raised when a scan interrupt is fired before the LabJack has completed the previous scan. The most common cause of this error is a configuration with a high sampling rate and a large number of channels.")
ERROR_TO_STRING_DICT['56'] = ("STREAM_SAMPLE_NUM_INVALID", "")
ERROR_TO_STRING_DICT['57'] = ("STREAM_BIPOLAR_GAIN_INVALID", "")
ERROR_TO_STRING_DICT['58'] = ("STREAM_SCAN_RATE_INVALID", "")
ERROR_TO_STRING_DICT['59'] = ("STREAM_AUTORECOVER_ACTIVE", "This error is to inform you that the autorecover feature has been activated. Autorecovery is usually triggered by not reading data fast enough from the LabJack.")
ERROR_TO_STRING_DICT['60'] = ("STREAM_AUTORECOVER_REPORT", "This error marks the packet as an autorecovery report packet which contains how many packets were lost.")
ERROR_TO_STRING_DICT['63'] = ("STREAM_AUTORECOVER_OVERFLOW", "")
ERROR_TO_STRING_DICT['64'] = ("TIMER_INVALID_MODE", "")
ERROR_TO_STRING_DICT['65'] = ("TIMER_QUADRATURE_AB_ERROR", "")
ERROR_TO_STRING_DICT['66'] = ("TIMER_QUAD_PULSE_SEQUENCE", "")
ERROR_TO_STRING_DICT['67'] = ("TIMER_BAD_CLOCK_SOURCE", "")
ERROR_TO_STRING_DICT['68'] = ("TIMER_STREAM_ACTIVE", "")
ERROR_TO_STRING_DICT['69'] = ("TIMER_PWMSTOP_MODULE_ERROR", "")
ERROR_TO_STRING_DICT['70'] = ("TIMER_SEQUENCE_ERROR", "")
ERROR_TO_STRING_DICT['71'] = ("TIMER_LINE_SEQUENCE_ERROR", "")
ERROR_TO_STRING_DICT['72'] = ("TIMER_SHARING_ERROR", "")
ERROR_TO_STRING_DICT['80'] = ("EXT_OSC_NOT_STABLE", "")
ERROR_TO_STRING_DICT['81'] = ("INVALID_POWER_SETTING", "")
ERROR_TO_STRING_DICT['82'] = ("PLL_NOT_LOCKED", "")
ERROR_TO_STRING_DICT['96'] = ("INVALID_PIN", "")
ERROR_TO_STRING_DICT['97'] = ("PIN_CONFIGURED_FOR_ANALOG", "This error is raised when you try to do a digital operation on a pin that's configured for analog. Use a command like ConfigIO to set the pin to digital.")
ERROR_TO_STRING_DICT['98'] = ("PIN_CONFIGURED_FOR_DIGITAL", "This error is raised when you try to do an analog operation on a pin which is configured for digital. Use a command like ConfigIO to set the pin to analog.")
ERROR_TO_STRING_DICT['99'] = ("IOTYPE_SYNCH_ERROR", "")
ERROR_TO_STRING_DICT['100'] = ("INVALID_OFFSET", "")
ERROR_TO_STRING_DICT['101'] = ("IOTYPE_NOT_VALID", "")
ERROR_TO_STRING_DICT['102'] = ("TC_PIN_OFFSET_MUST_BE_4-8", "This error is raised when you try to configure the Timer/Counter pin offset to be 0-3.")
def lowlevelErrorToString( errorcode ):
"""Converts a low-level errorcode into a string.
"""
try:
name, advice = ERROR_TO_STRING_DICT[str(errorcode)]
except KeyError:
name = "UNKNOWN_ERROR"
advice = "Unrecognized error code (%s)" % errorcode
if advice is not "":
msg = "%s (%s)\n%s" % (name, errorcode, advice)
else:
msg = "%s (%s)" % (name, errorcode)
return msg
#Windows
def ErrorToString(ErrorCode):
"""Converts an LabJackUD valid error code to a String.
For Windows
Sample Usage:
>>> ErrorToString(1007)
'LabJack not found'
@type ErrorCode: number
@param ErrorCode: Valid LabJackUD error code.
@rtype: String
@return: The string that represents the valid LabJackUD error code
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
pString = ctypes.create_string_buffer(256)
staticLib.ErrorToString(ctypes.c_long(ErrorCode), ctypes.byref(pString))
return pString.value
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows, Linux, and Mac
def GetDriverVersion():
"""Converts an LabJackUD valid error code to a String.
For Windows, Linux, and Mac
Sample Usage:
>>> GetDriverVersion()
2.64
>>> GetDriverVersion()
Mac
@rtype: number/String
@return: Value of the driver version as a String
- For Mac machines the return type is "Mac"
- For Windows and Linux systems the return type is a number that represents the driver version
"""
if os.name == 'nt':
staticLib.GetDriverVersion.restype = ctypes.c_float
return str(staticLib.GetDriverVersion())
elif os.name == 'posix':
staticLib.LJUSB_GetLibraryVersion.restype = ctypes.c_float
return "%.2f" % staticLib.LJUSB_GetLibraryVersion()
#Windows
def TCVoltsToTemp(TCType, TCVolts, CJTempK):
"""Converts a thermo couple voltage reading to an appropriate temperature reading.
For Windows
Sample Usage:
>>> TCVoltsToTemp(LJ_ttK, 0.003141592, 297.038889)
373.13353222244825
@type TCType: number
@param TCType: The type of thermo couple used.
@type TCVolts: number
@param TCVolts: The voltage reading from the thermo couple
@type CJTempK: number
@param CJTempK: The cold junction temperature reading in Kelvin
@rtype: number
@return: The thermo couples temperature reading
- pTCTempK
@raise LabJackException:
"""
if os.name == 'nt':
staticLib = ctypes.windll.LoadLibrary("labjackud")
pTCTempK = ctypes.c_double()
ec = staticLib.TCVoltsToTemp(ctypes.c_long(TCType), ctypes.c_double(TCVolts),
ctypes.c_double(CJTempK), ctypes.byref(pTCTempK))
if ec != 0: raise LabJackException(ec)
return pTCTempK.value
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows
def Close():
"""Resets the driver and closes all open handles.
For Windows
Sample Usage:
>>> Close()
@rtype: None
@return: The function returns nothing.
"""
opSys = os.name
if(opSys == 'nt'):
staticLib = ctypes.windll.LoadLibrary("labjackud")
staticLib.Close()
else:
raise LabJackException(0, "Function only supported for Windows")
#Windows, Linux and Mac
def DriverPresent():
try:
ctypes.windll.LoadLibrary("labjackud")
return True
except:
try:
ctypes.cdll.LoadLibrary("liblabjackusb.so")
return True
except:
try:
ctypes.cdll.LoadLibrary("liblabjackusb.dylib")
return True
except:
return False
return False
return False
def U12DriverPresent():
try:
ctypes.windll.LoadLibrary("ljackuw")
return True
except:
return False
#Windows only
def LJHash(hashStr, size):
"""An approximation of the md5 hashing algorithms.
For Windows
An approximation of the md5 hashing algorithm. Used
for authorizations on UE9 version 1.73 and higher and u3
version 1.35 and higher.
@type hashStr: String
@param hashStr: String to be hashed.
@type size: number
@param size: Amount of bytes to hash from the hashStr
@rtype: String
@return: The hashed string.
"""
print "Hash String:" + str(hashStr)
outBuff = (ctypes.c_char * 16)()
retBuff = ''
staticLib = ctypes.windll.LoadLibrary("labjackud")
ec = staticLib.LJHash(ctypes.cast(hashStr, ctypes.POINTER(ctypes.c_char)),
size,
ctypes.cast(outBuff, ctypes.POINTER(ctypes.c_char)),
0)
if ec != 0: raise LabJackException(ec)
for i in range(16):
retBuff += outBuff[i]
return retBuff
def __listAllUE9Unix(connectionType):
"""Private listAll function for use on unix and mac machines to find UE9s.
"""
deviceList = {}
rcvDataBuff = []
if connectionType == LJ_ctUSB:
numDevices = staticLib.LJUSB_GetDevCount(LJ_dtUE9)
for i in xrange(numDevices):
try:
device = openLabJack(LJ_dtUE9, 1, firstFound = False, devNumber = i+1)
device.close()
deviceList[str(device.serialNumber)] = device.__dict__
except LabJackException:
pass
elif connectionType == LJ_ctETHERNET:
#Create a socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.settimeout(BROADCAST_SOCKET_TIMEOUT)
sndDataBuff = [0] * 6
sndDataBuff[0] = 0x22
sndDataBuff[1] = 0x78
sndDataBuff[3] = 0xa9
outBuff = ""
for item in sndDataBuff:
outBuff += chr(item)
s.sendto(outBuff, ("255.255.255.255", 52362))
try:
while True:
rcvDataBuff = s.recv(128)
try:
rcvDataBuff = [ord(val) for val in rcvDataBuff]
if verifyChecksum(rcvDataBuff):
#Parse the packet
macAddress = rcvDataBuff[28:34]
macAddress.reverse()
# The serial number is four bytes:
# 0x10 and the last three bytes of the MAC address
serialBytes = chr(0x10)
for j in macAddress[3:]:
serialBytes += chr(j)
serial = struct.unpack(">I", serialBytes)[0]
#Parse out the IP address
ipAddress = ""
for j in range(13, 9, -1):
ipAddress += str(int(rcvDataBuff[j]))
ipAddress += "."
ipAddress = ipAddress[0:-1]
#Local ID
localId = rcvDataBuff[8] & 0xff
deviceList[serial] = dict(devType = LJ_dtUE9, localId = localId, \
serialNumber = serial, ipAddress = ipAddress)
except Exception, e:
pass
except:
pass
return deviceList
def __listAllU3Unix():
"""Private listAll function for unix and mac machines. Works on the U3 only.
"""
deviceList = {}
numDevices = staticLib.LJUSB_GetDevCount(LJ_dtU3)
for i in xrange(numDevices):
try:
device = openLabJack(LJ_dtU3, 1, firstFound = False, devNumber = i+1)
device.close()
deviceList[str(device.serialNumber)] = device.__dict__
except LabJackException:
pass
return deviceList
def __listAllU6Unix():
""" List all for U6s """
deviceList = {}
numDevices = staticLib.LJUSB_GetDevCount(LJ_dtU6)
for i in xrange(numDevices):
try:
device = openLabJack(LJ_dtU6, 1, firstFound = False, devNumber = i+1)
device.close()
deviceList[str(device.serialNumber)] = device.__dict__
except LabJackException:
pass
return deviceList
def __listAllBridgesUnix():
""" List all for Bridges """
deviceList = {}
numDevices = staticLib.LJUSB_GetDevCount(0x501)
for i in xrange(numDevices):
try:
device = openLabJack(0x501, 1, firstFound = False, devNumber = i+1)
device.close()
deviceList[str(device.serialNumber)] = device.__dict__
except LabJackException:
pass
return deviceList
def setChecksum16(buffer):
total = 0;
for i in range(6, len(buffer)):
total += (buffer[i] & 0xff)
buffer[4] = (total & 0xff)
buffer[5] = ((total >> 8) & 0xff)
return buffer
def setChecksum8(buffer, numBytes):
total = 0
for i in range(1, numBytes):
total += (buffer[i] & 0xff)
buffer[0] = (total & 0xff) + ((total >> 8) & 0xff)
buffer[0] = (buffer[0] & 0xff) + ((buffer[0] >> 8) & 0xff)
return buffer
class LJSocketHandle(object):
"""
Class to replace a device handle with a socket to a LJSocket server.
"""
def __init__(self, ipAddress, port, devType, firstFound, pAddress):
try:
serverSocket = socket.socket()
serverSocket.connect((ipAddress, port))
serverSocket.settimeout(SOCKET_TIMEOUT)
f = serverSocket.makefile(bufsize = 0)
f.write("scan\r\n")
l = f.readline().strip()
try:
status, numLines = l.split(' ')
except ValueError:
raise Exception("Got invalid line from server: %s" % l)
if status.lower().startswith('ok'):
lines = []
marked = None
for i in range(int(numLines)):
l = f.readline().strip()
dev = parseline(l)
if devType == dev['prodId']:
lines.append(dev)
if not firstFound and (dev['localId'] == pAddress or dev['serial'] == pAddress):
marked = dev
f.close()
serverSocket.close()
#print "Result of scan:"
#print lines
if firstFound and len(lines) > 0:
marked = lines[0]
elif marked is not None:
pass
else:
raise Exception("LabJack not found.")
if marked['crPort'] != 'x':
self.crSocket = socket.socket()
self.crSocket.connect((ipAddress, marked['crPort']))
self.crSocket.settimeout(LJSOCKET_TIMEOUT)
else:
self.crSocket = None
if marked['modbusPort'] != 'x':
self.modbusSocket = socket.socket()
self.modbusSocket.connect((ipAddress, marked['modbusPort']))
self.modbusSocket.settimeout(LJSOCKET_TIMEOUT)
else:
self.modbusSocket = None
if marked['spontPort'] != 'x':
self.spontSocket = socket.socket()
self.spontSocket.connect((ipAddress, marked['spontPort']))
self.spontSocket.settimeout(LJSOCKET_TIMEOUT)
else:
self.spontSocket = None
else:
raise Exception("Got an error from LJSocket. It said '%s'" % l)
except Exception, e:
raise LabJackException(ec = LJE_LABJACK_NOT_FOUND, errorString = "Couldn't connect to a LabJack at %s:%s. The error was: %s" % (ipAddress, port, str(e)))
def close(self):
if self.crSocket is not None:
self.crSocket.close()
if self.modbusSocket is not None:
self.modbusSocket.close()
if self.spontSocket is not None:
self.spontSocket.close()
def parseline(line):
try:
prodId, crPort, modbusPort, spontPort, localId, serial = line.split(' ')
if not crPort.startswith('x'):
crPort = int(crPort)
if not modbusPort.startswith('x'):
modbusPort = int(modbusPort)
if not spontPort.startswith('x'):
spontPort = int(spontPort)
except ValueError:
raise Exception("")
return { 'prodId' : int(prodId), 'crPort' : crPort, 'modbusPort' : modbusPort, 'spontPort' : spontPort, 'localId' : int(localId), 'serial' : int(serial) }
#Class for handling UE9 TCP Connections
class UE9TCPHandle(object):
"""__UE9TCPHandle(ipAddress)
Creates two sockets for the streaming and non streaming port on the UE9.
Only works on default ports (Data 52360, Stream 52361).
"""
def __init__(self, ipAddress, timeout = SOCKET_TIMEOUT):
try:
self.data = socket.socket()
self.data.connect((ipAddress, 52360))
self.data.settimeout(timeout)
self.stream = socket.socket()
self.stream.connect((ipAddress, 52361))
self.stream.settimeout(timeout)
try:
self.modbus = socket.socket()
self.modbus.connect((ipAddress, 502))
self.modbus.settimeout(timeout)
except socket.error, e:
raise LabJackException("Couldn't connect to the Modbus port on the UE9. Please upgrade to UE9 Comm firmware to 1.43 or higher.")
except LabJackException, e:
raise e
except Exception, e:
print e
raise LabJackException("Couldn't open sockets to the UE9 at IP Address %s. Error was: %s" % (ipAddress, e))
def close(self):
try:
self.data.close()
self.stream.close()
self.modbus.close()
except Exception, e:
print "UE9 Handle close exception: ", e
pass
def toDouble(bytes):
"""
Name: toDouble(buffer)
Args: buffer, an array with 8 bytes
Desc: Converts the 8 byte array into a floating point number.
"""
right, left = struct.unpack("<Ii", struct.pack("B" * 8, *bytes[0:8]))
return float(left) + float(right)/(2**32)
def hexWithoutQuotes(l):
""" Return a string listing hex without all the single quotes.
>>> l = range(10)
>>> print hexWithoutQuotes(l)
[0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9]
"""
return str([hex (i) for i in l]).replace("'", "")
#device types
LJ_dtUE9 = 9
"""Device type for the UE9"""
LJ_dtU3 = 3
"""Device type for the U3"""
LJ_dtU6 = 6
"""Device type for the U6"""
# connection types:
LJ_ctUSB = 1 # UE9 + U3
"""Connection type for the UE9 and U3"""
LJ_ctETHERNET = 2 # UE9 only
"""Connection type for the UE9"""
LJ_ctUSB_RAW = 101 # UE9 + U3
"""Connection type for the UE9 and U3
Raw connection types are used to open a device but not communicate with it
should only be used if the normal connection types fail and for testing.
If a device is opened with the raw connection types, only LJ_ioRAW_OUT
and LJ_ioRAW_IN io types should be used
"""
LJ_ctETHERNET_RAW = 102 # UE9 only
"""Connection type for the UE9
Raw connection types are used to open a device but not communicate with it
should only be used if the normal connection types fail and for testing.
If a device is opened with the raw connection types, only LJ_ioRAW_OUT
and LJ_ioRAW_IN io types should be used
"""
LJ_ctLJSOCKET = 200
"""Connection type for USB LabJack connected to LJSocket server.
"""
# io types:
LJ_ioGET_AIN = 10 # UE9 + U3. This is single ended version.
"""IO type for the UE9 and U3
This is the single ended version
"""
LJ_ioGET_AIN_DIFF = 15 # U3 only. Put second channel in x1. If 32 is passed as x1, Vref will be added to the result.
"""IO type for the U3
Put second channel in x1. If 32 is passed as x1, Vref will be added to the result.
"""
LJ_ioPUT_AIN_RANGE = 2000 # UE9
"""IO type for the UE9"""
LJ_ioGET_AIN_RANGE = 2001 # UE9
"""IO type for the UE9"""
# sets or reads the analog or digital mode of the FIO and EIO pins. FIO is Channel 0-7, EIO 8-15
LJ_ioPUT_ANALOG_ENABLE_BIT = 2013 # U3
"""IO type for the U3
Sets or reads the analog or digital mode of the FIO and EIO pins. FIO is Channel 0-7, EIO 8-15
"""
LJ_ioGET_ANALOG_ENABLE_BIT = 2014 # U3
"""IO type for the U3
Sets or reads the analog or digital mode of the FIO and EIO pins. FIO is Channel 0-7, EIO 8-15
"""
# sets or reads the analog or digital mode of the FIO and EIO pins. Channel is starting
# bit #, x1 is number of bits to read. The pins are set by passing a bitmask as a double
# for the value. The first bit of the int that the double represents will be the setting
# for the pin number sent into the channel variable.
LJ_ioPUT_ANALOG_ENABLE_PORT = 2015 # U3
""" IO type for the U3
sets or reads the analog or digital mode of the FIO and EIO pins. Channel is starting
bit #, x1 is number of bits to read. The pins are set by passing a bitmask as a double
for the value. The first bit of the int that the double represents will be the setting
for the pin number sent into the channel variable.
"""
LJ_ioGET_ANALOG_ENABLE_PORT = 2016 # U3
""" IO type for the U3
sets or reads the analog or digital mode of the FIO and EIO pins. Channel is starting
bit #, x1 is number of bits to read. The pins are set by passing a bitmask as a double
for the value. The first bit of the int that the double represents will be the setting
for the pin number sent into the channel variable.
"""
LJ_ioPUT_DAC = 20 # UE9 + U3
"""IO type for the U3 and UE9"""
LJ_ioPUT_DAC_ENABLE = 2002 # UE9 + U3 (U3 on Channel 1 only)
"""IO type for the U3 and UE9
U3 on channel 1 only.
"""
LJ_ioGET_DAC_ENABLE = 2003 # UE9 + U3 (U3 on Channel 1 only)
"""IO type for the U3 and UE9
U3 on channel 1 only.
"""
LJ_ioGET_DIGITAL_BIT = 30 # UE9 + U3 # changes direction of bit to input as well
LJ_ioGET_DIGITAL_BIT_DIR = 31 # U3
LJ_ioGET_DIGITAL_BIT_STATE = 32 # does not change direction of bit, allowing readback of output
# channel is starting bit #, x1 is number of bits to read
LJ_ioGET_DIGITAL_PORT = 35 # UE9 + U3 # changes direction of bits to input as well
LJ_ioGET_DIGITAL_PORT_DIR = 36 # U3
LJ_ioGET_DIGITAL_PORT_STATE = 37 # U3 does not change direction of bits, allowing readback of output
# digital put commands will set the specified digital line(s) to output
LJ_ioPUT_DIGITAL_BIT = 40 # UE9 + U3
# channel is starting bit #, value is output value, x1 is bits to write
LJ_ioPUT_DIGITAL_PORT = 45 # UE9 + U3
# Used to create a pause between two events in a U3 low-level feedback
# command. For example, to create a 100 ms positive pulse on FIO0, add a
# request to set FIO0 high, add a request for a wait of 100000, add a
# request to set FIO0 low, then Go. Channel is ignored. Value is
# microseconds to wait and should range from 0 to 8388480. The actual
# resolution of the wait is 128 microseconds.
LJ_ioPUT_WAIT = 70 # U3
# counter. Input only.
LJ_ioGET_COUNTER = 50 # UE9 + U3
LJ_ioPUT_COUNTER_ENABLE = 2008 # UE9 + U3
LJ_ioGET_COUNTER_ENABLE = 2009 # UE9 + U3
# this will cause the designated counter to reset. If you want to reset the counter with
# every read, you have to use this command every time.
LJ_ioPUT_COUNTER_RESET = 2012 # UE9 + U3
# on UE9: timer only used for input. Output Timers don't use these. Only Channel used.
# on U3: Channel used (0 or 1).
LJ_ioGET_TIMER = 60 # UE9 + U3
LJ_ioPUT_TIMER_VALUE = 2006 # UE9 + U3. Value gets new value
LJ_ioPUT_TIMER_MODE = 2004 # UE9 + U3. On both Value gets new mode.
LJ_ioGET_TIMER_MODE = 2005 # UE9
# IOTypes for use with SHT sensor. For LJ_ioSHT_GET_READING, a channel of LJ_chSHT_TEMP (5000) will
# read temperature, and LJ_chSHT_RH (5001) will read humidity.
# The LJ_ioSHT_DATA_CHANNEL and LJ_ioSHT_SCK_CHANNEL iotypes use the passed channel
# to set the appropriate channel for the data and SCK lines for the SHT sensor.
# Default digital channels are FIO0 for the data channel and FIO1 for the clock channel.
LJ_ioSHT_GET_READING = 500 # UE9 + U3.
LJ_ioSHT_DATA_CHANNEL = 501 # UE9 + U3. Default is FIO0
LJ_ioSHT_CLOCK_CHANNEL = 502 # UE9 + U3. Default is FIO1
# Uses settings from LJ_chSPI special channels (set with LJ_ioPUT_CONFIG) to communcaite with
# something using an SPI interface. The value parameter is the number of bytes to transfer
# and x1 is the address of the buffer. The data from the buffer will be sent, then overwritten
# with the data read. The channel parameter is ignored.
LJ_ioSPI_COMMUNICATION = 503 # UE9
LJ_ioI2C_COMMUNICATION = 504 # UE9 + U3
LJ_ioASYNCH_COMMUNICATION = 505 # UE9 + U3
LJ_ioTDAC_COMMUNICATION = 506 # UE9 + U3
# Set's the U3 to it's original configuration. This means sending the following
# to the ConfigIO and TimerClockConfig low level functions
#
# ConfigIO
# Byte #
# 6 WriteMask 15 Write all parameters.
# 8 TimerCounterConfig 0 No timers/counters. Offset=0.
# 9 DAC1Enable 0 DAC1 disabled.
# 10 FIOAnalog 0 FIO all digital.
# 11 EIOAnalog 0 EIO all digital.
#
#
# TimerClockConfig
# Byte #
# 8 TimerClockConfig 130 Set clock to 24 MHz.
# 9 TimerClockDivisor 0 Divisor = 0.
#
LJ_ioPIN_CONFIGURATION_RESET = 2017 # U3
# the raw in/out are unusual, channel # corresponds to the particular comm port, which
# depends on the device. For example, on the UE9, 0 is main comm port, and 1 is the streaming comm.
# Make sure and pass a porter to a char buffer in x1, and the number of bytes desired in value. A call
# to GetResult will return the number of bytes actually read/written. The max you can send out in one call
# is 512 bytes to the UE9 and 16384 bytes to the U3.
LJ_ioRAW_OUT = 100 # UE9 + U3
LJ_ioRAW_IN = 101 # UE9 + U3
# sets the default power up settings based on the current settings of the device AS THIS DLL KNOWS. This last part
# basically means that you should set all parameters directly through this driver before calling this. This writes
# to flash which has a limited lifetime, so do not do this too often. Rated endurance is 20,000 writes.
LJ_ioSET_DEFAULTS = 103 # U3
# requests to create the list of channels to stream. Usually you will use the CLEAR_STREAM_CHANNELS request first, which
# will clear any existing channels, then use ADD_STREAM_CHANNEL multiple times to add your desired channels. Some devices will
# use value, x1 for other parameters such as gain. Note that you can do CLEAR, and then all your ADDs in a single Go() as long
# as you add the requests in order.
LJ_ioADD_STREAM_CHANNEL = 200
LJ_ioCLEAR_STREAM_CHANNELS = 201
LJ_ioSTART_STREAM = 202
LJ_ioSTOP_STREAM = 203
LJ_ioADD_STREAM_CHANNEL_DIFF = 206
# Get stream data has several options. If you just want to get a single channel's data (if streaming multiple channels), you
# can pass in the desired channel #, then the number of data points desired in Value, and a pointer to an array to put the
# data into as X1. This array needs to be an array of doubles. Therefore, the array needs to be 8 * number of
# requested data points in byte length. What is returned depends on the StreamWaitMode. If None, this function will only return
# data available at the time of the call. You therefore must call GetResult() for this function to retrieve the actually number
# of points retreived. If Pump or Sleep, it will return only when the appropriate number of points have been read or no
# new points arrive within 100ms. Since there is this timeout, you still need to use GetResult() to determine if the timeout
# occured. If AllOrNone, you again need to check GetResult.
# You can also retreive the entire scan by passing LJ_chALL_CHANNELS. In this case, the Value determines the number of SCANS
# returned, and therefore, the array must be 8 * number of scans requested * number of channels in each scan. Likewise
# GetResult() will return the number of scans, not the number of data points returned.
# Note: data is stored interleaved across all streaming channels. In other words, if you are streaming two channels, 0 and 1,
# and you request LJ_chALL_CHANNELS, you will get, Channel0, Channel1, Channel0, Channel1, etc. Once you have requested the
# data, any data returned is removed from the internal buffer, and the next request will give new data.
# Note: if reading the data channel by channel and not using LJ_chALL_CHANNELS, the data is not removed from the internal buffer
# until the data from the last channel in the scan is requested. This means that if you are streaming three channels, 0, 1 and 2,
# and you request data from channel 0, then channel 1, then channel 0 again, the request for channel 0 the second time will
# return the exact same amount of data. Also note, that the amount of data that will be returned for each channel request will be
# the same until you've read the last channel in the scan, at which point your next block may be a different size.
# Note: although more convenient, requesting individual channels is slightly slower then using LJ_chALL_CHANNELS. Since you
# are probably going to have to split the data out anyway, we have saved you the trouble with this option.
# Note: if you are only scanning one channel, the Channel parameter is ignored.
LJ_ioGET_STREAM_DATA = 204
# U3 only:
# Channel = 0 buzz for a count, Channel = 1 buzz continuous
# Value is the Period
# X1 is the toggle count when channel = 0
LJ_ioBUZZER = 300 # U3
# config iotypes:
LJ_ioPUT_CONFIG = 1000 # UE9 + U3
LJ_ioGET_CONFIG = 1001 # UE9 + U3
# channel numbers used for CONFIG types:
# UE9 + U3
LJ_chLOCALID = 0 # UE9 + U3
LJ_chHARDWARE_VERSION = 10 # UE9 + U3 (Read Only)
LJ_chSERIAL_NUMBER = 12 # UE9 + U3 (Read Only)
LJ_chFIRMWARE_VERSION = 11 # UE9 + U3 (Read Only)
LJ_chBOOTLOADER_VERSION = 15 # UE9 + U3 (Read Only)
# UE9 specific:
LJ_chCOMM_POWER_LEVEL = 1 #UE9
LJ_chIP_ADDRESS = 2 #UE9
LJ_chGATEWAY = 3 #UE9
LJ_chSUBNET = 4 #UE9
LJ_chPORTA = 5 #UE9
LJ_chPORTB = 6 #UE9
LJ_chDHCP = 7 #UE9
LJ_chPRODUCTID = 8 #UE9
LJ_chMACADDRESS = 9 #UE9
LJ_chCOMM_FIRMWARE_VERSION = 11
LJ_chCONTROL_POWER_LEVEL = 13 #UE9
LJ_chCONTROL_FIRMWARE_VERSION = 14 #UE9 (Read Only)
LJ_chCONTROL_BOOTLOADER_VERSION = 15 #UE9 (Read Only)
LJ_chCONTROL_RESET_SOURCE = 16 #UE9 (Read Only)
LJ_chUE9_PRO = 19 # UE9 (Read Only)
# U3 only:
# sets the state of the LED
LJ_chLED_STATE = 17 # U3 value = LED state
LJ_chSDA_SCL = 18 # U3 enable / disable SDA/SCL as digital I/O
# Used to access calibration and user data. The address of an array is passed in as x1.
# For the UE9, a 1024-element buffer of bytes is passed for user data and a 128-element
# buffer of doubles is passed for cal constants.
# For the U3, a 256-element buffer of bytes is passed for user data and a 12-element
# buffer of doubles is passed for cal constants.
# The layout of cal ants are defined in the users guide for each device.
# When the LJ_chCAL_CONSTANTS special channel is used with PUT_CONFIG, a
# special value (0x4C6C) must be passed in to the Value parameter. This makes it
# more difficult to accidently erase the cal constants. In all other cases the Value
# parameter is ignored.
LJ_chCAL_CONSTANTS = 400 # UE9 + U3
LJ_chUSER_MEM = 402 # UE9 + U3
# Used to write and read the USB descriptor strings. This is generally for OEMs
# who wish to change the strings.
# Pass the address of an array in x1. Value parameter is ignored.
# The array should be 128 elements of bytes. The first 64 bytes are for the
# iManufacturer string, and the 2nd 64 bytes are for the iProduct string.
# The first byte of each 64 byte block (bytes 0 and 64) contains the number
# of bytes in the string. The second byte (bytes 1 and 65) is the USB spec
# value for a string descriptor (0x03). Bytes 2-63 and 66-127 contain unicode
# encoded strings (up to 31 characters each).
LJ_chUSB_STRINGS = 404 # U3
# timer/counter related
LJ_chNUMBER_TIMERS_ENABLED = 1000 # UE9 + U3
LJ_chTIMER_CLOCK_BASE = 1001 # UE9 + U3
LJ_chTIMER_CLOCK_DIVISOR = 1002 # UE9 + U3
LJ_chTIMER_COUNTER_PIN_OFFSET = 1003 # U3
# AIn related
LJ_chAIN_RESOLUTION = 2000 # ue9 + u3
LJ_chAIN_SETTLING_TIME = 2001 # ue9 + u3
LJ_chAIN_BINARY = 2002 # ue9 + u3
# DAC related
LJ_chDAC_BINARY = 3000 # ue9 + u3
# SHT related
LJ_chSHT_TEMP = 5000 # ue9 + u3
LJ_chSHT_RH = 5001 # ue9 + u3
# SPI related
LJ_chSPI_AUTO_CS = 5100 # UE9
LJ_chSPI_DISABLE_DIR_CONFIG = 5101 # UE9
LJ_chSPI_MODE = 5102 # UE9
LJ_chSPI_CLOCK_FACTOR = 5103 # UE9
LJ_chSPI_MOSI_PINNUM = 5104 # UE9
LJ_chSPI_MISO_PINNUM = 5105 # UE9
LJ_chSPI_CLK_PINNUM = 5106 # UE9
LJ_chSPI_CS_PINNUM = 5107 # UE9
# I2C related :
# used with LJ_ioPUT_CONFIG
LJ_chI2C_ADDRESS_BYTE = 5108 # UE9 + U3
LJ_chI2C_SCL_PIN_NUM = 5109 # UE9 + U3
LJ_chI2C_SDA_PIN_NUM = 5110 # UE9 + U3
LJ_chI2C_OPTIONS = 5111 # UE9 + U3
LJ_chI2C_SPEED_ADJUST = 5112 # UE9 + U3
# used with LJ_ioI2C_COMMUNICATION :
LJ_chI2C_READ = 5113 # UE9 + U3
LJ_chI2C_WRITE = 5114 # UE9 + U3
LJ_chI2C_GET_ACKS = 5115 # UE9 + U3
LJ_chI2C_WRITE_READ = 5130 # UE9 + U3
# ASYNCH related :
# Used with LJ_ioASYNCH_COMMUNICATION
LJ_chASYNCH_RX = 5117 # UE9 + U3
LJ_chASYNCH_TX = 5118 # UE9 + U3
LJ_chASYNCH_FLUSH = 5128 # UE9 + U3
LJ_chASYNCH_ENABLE = 5129 # UE9 + U3
# Used with LJ_ioPUT_CONFIG and LJ_ioGET_CONFIG
LJ_chASYNCH_BAUDFACTOR = 5127 # UE9 + U3
# stream related. Note, Putting to any of these values will stop any running streams.
LJ_chSTREAM_SCAN_FREQUENCY = 4000
LJ_chSTREAM_BUFFER_SIZE = 4001
LJ_chSTREAM_CLOCK_OUTPUT = 4002
LJ_chSTREAM_EXTERNAL_TRIGGER = 4003
LJ_chSTREAM_WAIT_MODE = 4004
# readonly stream related
LJ_chSTREAM_BACKLOG_COMM = 4105
LJ_chSTREAM_BACKLOG_CONTROL = 4106
LJ_chSTREAM_BACKLOG_UD = 4107
LJ_chSTREAM_SAMPLES_PER_PACKET = 4108
# special channel #'s
LJ_chALL_CHANNELS = -1
LJ_INVALID_CONSTANT = -999
#Thermocouple Type constants.
LJ_ttB = 6001
"""Type B thermocouple constant"""
LJ_ttE = 6002
"""Type E thermocouple constant"""
LJ_ttJ = 6003
"""Type J thermocouple constant"""
LJ_ttK = 6004
"""Type K thermocouple constant"""
LJ_ttN = 6005
"""Type N thermocouple constant"""
LJ_ttR = 6006
"""Type R thermocouple constant"""
LJ_ttS = 6007
"""Type S thermocouple constant"""
LJ_ttT = 6008
"""Type T thermocouple constant"""
# other constants:
# ranges (not all are supported by all devices):
LJ_rgBIP20V = 1 # -20V to +20V
LJ_rgBIP10V = 2 # -10V to +10V
LJ_rgBIP5V = 3 # -5V to +5V
LJ_rgBIP4V = 4 # -4V to +4V
LJ_rgBIP2P5V = 5 # -2.5V to +2.5V
LJ_rgBIP2V = 6 # -2V to +2V
LJ_rgBIP1P25V = 7# -1.25V to +1.25V
LJ_rgBIP1V = 8 # -1V to +1V
LJ_rgBIPP625V = 9# -0.625V to +0.625V
LJ_rgUNI20V = 101 # 0V to +20V
LJ_rgUNI10V = 102 # 0V to +10V
LJ_rgUNI5V = 103 # 0V to +5V
LJ_rgUNI4V = 104 # 0V to +4V
LJ_rgUNI2P5V = 105 # 0V to +2.5V
LJ_rgUNI2V = 106 # 0V to +2V
LJ_rgUNI1P25V = 107# 0V to +1.25V
LJ_rgUNI1V = 108 # 0V to +1V
LJ_rgUNIP625V = 109# 0V to +0.625V
LJ_rgUNIP500V = 110 # 0V to +0.500V
LJ_rgUNIP3125V = 111 # 0V to +0.3125V
# timer modes (UE9 only):
LJ_tmPWM16 = 0 # 16 bit PWM
LJ_tmPWM8 = 1 # 8 bit PWM
LJ_tmRISINGEDGES32 = 2 # 32-bit rising to rising edge measurement
LJ_tmFALLINGEDGES32 = 3 # 32-bit falling to falling edge measurement
LJ_tmDUTYCYCLE = 4 # duty cycle measurement
LJ_tmFIRMCOUNTER = 5 # firmware based rising edge counter
LJ_tmFIRMCOUNTERDEBOUNCE = 6 # firmware counter with debounce
LJ_tmFREQOUT = 7 # frequency output
LJ_tmQUAD = 8 # Quadrature
LJ_tmTIMERSTOP = 9 # stops another timer after n pulses
LJ_tmSYSTIMERLOW = 10 # read lower 32-bits of system timer
LJ_tmSYSTIMERHIGH = 11 # read upper 32-bits of system timer
LJ_tmRISINGEDGES16 = 12 # 16-bit rising to rising edge measurement
LJ_tmFALLINGEDGES16 = 13 # 16-bit falling to falling edge measurement
# timer clocks:
LJ_tc750KHZ = 0 # UE9: 750 khz
LJ_tcSYS = 1 # UE9: system clock
LJ_tc2MHZ = 10 # U3: Hardware Version 1.20 or lower
LJ_tc6MHZ = 11 # U3: Hardware Version 1.20 or lower
LJ_tc24MHZ = 12 # U3: Hardware Version 1.20 or lower
LJ_tc500KHZ_DIV = 13# U3: Hardware Version 1.20 or lower
LJ_tc2MHZ_DIV = 14 # U3: Hardware Version 1.20 or lower
LJ_tc6MHZ_DIV = 15 # U3: Hardware Version 1.20 or lower
LJ_tc24MHZ_DIV = 16 # U3: Hardware Version 1.20 or lower
# stream wait modes
LJ_swNONE = 1 # no wait, return whatever is available
LJ_swALL_OR_NONE = 2 # no wait, but if all points requested aren't available, return none.
LJ_swPUMP = 11 # wait and pump the message pump. Prefered when called from primary thread (if you don't know
# if you are in the primary thread of your app then you probably are. Do not use in worker
# secondary threads (i.e. ones without a message pump).
LJ_swSLEEP = 12 # wait by sleeping (don't do this in the primary thread of your app, or it will temporarily
# hang) This is usually used in worker secondary threads.
# BETA CONSTANTS
# Please note that specific usage of these constants and their values might change
# SWDT related
LJ_chSWDT_RESET_COMM = 5200 # UE9 - Reset Comm on watchdog reset
LJ_chSWDT_RESET_CONTROL = 5201 # UE9 - Reset Control on watchdog trigger
LJ_chSWDT_UDPATE_DIO0 = 5202 # UE9 - Update DIO0 settings after reset
LJ_chSWDT_UPDATE_DIO1 = 5203 # UE9 - Update DIO1 settings after reset
LJ_chSWDT_DIO0 = 5204 # UE9 - DIO0 channel and state (value) to be set after reset
LJ_chSWDT_DIO1 = 5205 # UE9 - DIO1 channel and state (value) to be set after reset
LJ_chSWDT_UPDATE_DAC0 = 5206 # UE9 - Update DAC1 settings after reset
LJ_chSWDT_UPDATE_DAC1 = 5207 # UE9 - Update DAC1 settings after reset
LJ_chSWDT_DAC0 = 5208 # UE9 - voltage to set DAC0 at on watchdog reset
LJ_chSWDT_DAC1 = 5209 # UE9 - voltage to set DAC1 at on watchdog reset
LJ_chSWDT_DACS_ENABLE = 5210 # UE9 - Enable DACs on watchdog reset
LJ_chSWDT_ENABLE = 5211 # UE9 - used with LJ_ioSWDT_CONFIG to enable watchdog. Value paramter is number of seconds to trigger
LJ_chSWDT_DISABLE = 5212 # UE9 - used with LJ_ioSWDT_CONFIG to enable watchdog.
LJ_ioSWDT_CONFIG = 504 # UE9 - Use LJ_chSWDT_ENABLE or LJ_chSWDT_DISABLE
LJ_tc4MHZ = 20 # U3: Hardware Version 1.21 or higher
LJ_tc12MHZ = 21 # U3: Hardware Version 1.21 or higher
LJ_tc48MHZ = 22 # U3: Hardware Version 1.21 or higher
LJ_tc1000KHZ_DIV = 23# U3: Hardware Version 1.21 or higher
LJ_tc4MHZ_DIV = 24 # U3: Hardware Version 1.21 or higher
LJ_tc12MHZ_DIV = 25 # U3: Hardware Version 1.21 or higher
LJ_tc48MHZ_DIV = 26 # U3: Hardware Version 1.21 or higher
# END BETA CONSTANTS
# error codes: These will always be in the range of -1000 to 3999 for labView compatibility (+6000)
LJE_NOERROR = 0
LJE_INVALID_CHANNEL_NUMBER = 2 # occurs when a channel that doesn't exist is specified (i.e. DAC #2 on a UE9), or data from streaming is requested on a channel that isn't streaming
LJE_INVALID_RAW_INOUT_PARAMETER = 3
LJE_UNABLE_TO_START_STREAM = 4
LJE_UNABLE_TO_STOP_STREAM = 5
LJE_NOTHING_TO_STREAM = 6
LJE_UNABLE_TO_CONFIG_STREAM = 7
LJE_BUFFER_OVERRUN = 8 # occurs when stream buffer overruns (this is the driver buffer not the hardware buffer). Stream is stopped.
LJE_STREAM_NOT_RUNNING = 9
LJE_INVALID_PARAMETER = 10
LJE_INVALID_STREAM_FREQUENCY = 11
LJE_INVALID_AIN_RANGE = 12
LJE_STREAM_CHECKSUM_ERROR = 13 # occurs when a stream packet fails checksum. Stream is stopped
LJE_STREAM_COMMAND_ERROR = 14 # occurs when a stream packet has invalid command values. Stream is stopped.
LJE_STREAM_ORDER_ERROR = 15 # occurs when a stream packet is received out of order (typically one is missing). Stream is stopped.
LJE_AD_PIN_CONFIGURATION_ERROR = 16 # occurs when an analog or digital request was made on a pin that isn't configured for that type of request
LJE_REQUEST_NOT_PROCESSED = 17 # When a LJE_AD_PIN_CONFIGURATION_ERROR occurs, all other IO requests after the request that caused the error won't be processed. Those requests will return this error.
# U3 Specific Errors
LJE_SCRATCH_ERROR = 19
"""U3 error"""
LJE_DATA_BUFFER_OVERFLOW = 20
"""U3 error"""
LJE_ADC0_BUFFER_OVERFLOW = 21
"""U3 error"""
LJE_FUNCTION_INVALID = 22
"""U3 error"""
LJE_SWDT_TIME_INVALID = 23
"""U3 error"""
LJE_FLASH_ERROR = 24
"""U3 error"""
LJE_STREAM_IS_ACTIVE = 25
"""U3 error"""
LJE_STREAM_TABLE_INVALID = 26
"""U3 error"""
LJE_STREAM_CONFIG_INVALID = 27
"""U3 error"""
LJE_STREAM_BAD_TRIGGER_SOURCE = 28
"""U3 error"""
LJE_STREAM_INVALID_TRIGGER = 30
"""U3 error"""
LJE_STREAM_ADC0_BUFFER_OVERFLOW = 31
"""U3 error"""
LJE_STREAM_SAMPLE_NUM_INVALID = 33
"""U3 error"""
LJE_STREAM_BIPOLAR_GAIN_INVALID = 34
"""U3 error"""
LJE_STREAM_SCAN_RATE_INVALID = 35
"""U3 error"""
LJE_TIMER_INVALID_MODE = 36
"""U3 error"""
LJE_TIMER_QUADRATURE_AB_ERROR = 37
"""U3 error"""
LJE_TIMER_QUAD_PULSE_SEQUENCE = 38
"""U3 error"""
LJE_TIMER_BAD_CLOCK_SOURCE = 39
"""U3 error"""
LJE_TIMER_STREAM_ACTIVE = 40
"""U3 error"""
LJE_TIMER_PWMSTOP_MODULE_ERROR = 41
"""U3 error"""
LJE_TIMER_SEQUENCE_ERROR = 42
"""U3 error"""
LJE_TIMER_SHARING_ERROR = 43
"""U3 error"""
LJE_TIMER_LINE_SEQUENCE_ERROR = 44
"""U3 error"""
LJE_EXT_OSC_NOT_STABLE = 45
"""U3 error"""
LJE_INVALID_POWER_SETTING = 46
"""U3 error"""
LJE_PLL_NOT_LOCKED = 47
"""U3 error"""
LJE_INVALID_PIN = 48
"""U3 error"""
LJE_IOTYPE_SYNCH_ERROR = 49
"""U3 error"""
LJE_INVALID_OFFSET = 50
"""U3 error"""
LJE_FEEDBACK_IOTYPE_NOT_VALID = 51
"""U3 error
Has been described as mearly a flesh wound.
"""
LJE_SHT_CRC = 52
LJE_SHT_MEASREADY = 53
LJE_SHT_ACK = 54
LJE_SHT_SERIAL_RESET = 55
LJE_SHT_COMMUNICATION = 56
LJE_AIN_WHILE_STREAMING = 57
LJE_STREAM_TIMEOUT = 58
LJE_STREAM_CONTROL_BUFFER_OVERFLOW = 59
LJE_STREAM_SCAN_OVERLAP = 60
LJE_FIRMWARE_DOESNT_SUPPORT_IOTYPE = 61
LJE_FIRMWARE_DOESNT_SUPPORT_CHANNEL = 62
LJE_FIRMWARE_DOESNT_SUPPORT_VALUE = 63
LJE_MIN_GROUP_ERROR = 1000 # all errors above this number will stop all requests, below this number are request level errors.
LJE_UNKNOWN_ERROR = 1001 # occurs when an unknown error occurs that is caught, but still unknown.
LJE_INVALID_DEVICE_TYPE = 1002 # occurs when devicetype is not a valid device type
LJE_INVALID_HANDLE = 1003 # occurs when invalid handle used
LJE_DEVICE_NOT_OPEN = 1004 # occurs when Open() fails and AppendRead called despite.
LJE_NO_DATA_AVAILABLE = 1005 # this is cause when GetData() called without calling DoRead(), or when GetData() passed channel that wasn't read
LJE_NO_MORE_DATA_AVAILABLE = 1006
LJE_LABJACK_NOT_FOUND = 1007 # occurs when the labjack is not found at the given id or address.
LJE_COMM_FAILURE = 1008 # occurs when unable to send or receive the correct # of bytes
LJE_CHECKSUM_ERROR = 1009
LJE_DEVICE_ALREADY_OPEN = 1010
LJE_COMM_TIMEOUT = 1011
LJE_USB_DRIVER_NOT_FOUND = 1012
LJE_INVALID_CONNECTION_TYPE = 1013
LJE_INVALID_MODE = 1014
# warning are negative
LJE_DEVICE_NOT_CALIBRATED = -1 # defaults used instead
LJE_UNABLE_TO_READ_CALDATA = -2 # defaults used instead
# depreciated constants:
LJ_ioANALOG_INPUT = 10
"""Deprecated constant"""
LJ_ioANALOG_OUTPUT = 20 # UE9 + U3
"""Deprecated constant"""
LJ_ioDIGITAL_BIT_IN = 30 # UE9 + U3
"""Deprecated constant"""
LJ_ioDIGITAL_PORT_IN = 35 # UE9 + U3
"""Deprecated constant"""
LJ_ioDIGITAL_BIT_OUT = 40 # UE9 + U3
"""Deprecated constant"""
LJ_ioDIGITAL_PORT_OUT = 45 # UE9 + U3
"""Deprecated constant"""
LJ_ioCOUNTER = 50 # UE9 + U3
"""Deprecated constant"""
LJ_ioTIMER = 60 # UE9 + U3
"""Deprecated constant"""
LJ_ioPUT_COUNTER_MODE = 2010 # UE9
"""Deprecated constant"""
LJ_ioGET_COUNTER_MODE = 2011 # UE9
"""Deprecated constant"""
LJ_ioGET_TIMER_VALUE = 2007 # UE9
"""Deprecated constant"""
LJ_ioCYCLE_PORT = 102 # UE9
"""Deprecated constant"""
LJ_chTIMER_CLOCK_CONFIG = 1001 # UE9 + U3
"""Deprecated constant"""
LJ_ioPUT_CAL_CONSTANTS = 400
"""Deprecated constant"""
LJ_ioGET_CAL_CONSTANTS = 401
"""Deprecated constant"""
LJ_ioPUT_USER_MEM = 402
"""Deprecated constant"""
LJ_ioGET_USER_MEM = 403
"""Deprecated constant"""
LJ_ioPUT_USB_STRINGS = 404
"""Deprecated constant"""
LJ_ioGET_USB_STRINGS = 405
"""Deprecated constant"""
| 131,061 | 35.095291 | 272 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/build/lib/Modbus.py | # File: Modbus.py
# Author: LabJack Corp.
# Created: 05.05.2008
# Last Modified: 12/3/2009
from __future__ import with_statement
from threading import Lock
from struct import pack, unpack #, unpack_from # unpack_from is new in 2.5
from datetime import datetime
AES_CHANNEL = 64000
IP_PART1_CHANNEL = 64008
IP_PART2_CHANNEL = 64009
PORT_CHANNEL = 64010
HEARTBEAT_CHANNEL = 64016
DEBUG_CHANNEL = 64017
DEVICE_TYPE_CHANNEL = 65000
SERIAL_NUMBER_CHANNEL = 65001
READ_PACKET = 3
WRITE_PACKET = 6
HEADER_LENGTH = 9
BYTES_PER_REGISTER = 2
GLOBAL_TRANSACTION_ID_LOCK = Lock()
MAX_TRANS_ID = 64760
def _calcBaseTransId():
t = datetime.now()
d = "%s%s%s%s" % (t.hour, t.minute, t.second, t.microsecond)
d = int(d) % MAX_TRANS_ID
return d
BASE_TRANS_ID = _calcBaseTransId()
CURRENT_TRANS_IDS = set()
def _buildHeaderBytes(length = 6, unitId = None):
with GLOBAL_TRANSACTION_ID_LOCK:
global BASE_TRANS_ID, CURRENT_TRANS_IDS
if unitId is None:
basicHeader = (BASE_TRANS_ID, 0, length, 0x00)
else:
basicHeader = (BASE_TRANS_ID, 0, length, unitId)
CURRENT_TRANS_IDS.add(BASE_TRANS_ID)
BASE_TRANS_ID = ( BASE_TRANS_ID + 1 ) % MAX_TRANS_ID
return pack('>HHHB', *basicHeader)
def _checkTransId(transId):
with GLOBAL_TRANSACTION_ID_LOCK:
global CURRENT_TRANS_IDS
if transId in CURRENT_TRANS_IDS:
CURRENT_TRANS_IDS.remove(transId)
else:
raise ModbusException("Got an unexpected transaction ID. Id = %s, Set = %s" % (transId, CURRENT_TRANS_IDS))
def readHoldingRegistersRequest(addr, numReg = None, unitId = None):
if numReg is None:
numReg = calcNumberOfRegisters(addr)
packet = _buildHeaderBytes(unitId = unitId) + pack('>BHH', 0x03, addr, numReg)
return packet
def readHoldingRegistersResponse(packet, payloadFormat=None):
# Example: Device type is 9
# [0, 0, 5, 255, 3, 2, 9]
# H H H c c c payload
# 0 1 2 3 4 5 6+
HEADER_LENGTH = 9
header = unpack('>HHHBBB', packet[:HEADER_LENGTH])
#print "header", [ c for c in header ]
#print "header", header
# Check that protocol ID is 0
if header[1] != 0:
raise ModbusException("Got an unexpected protocol ID: %s (expected 0). Please make sure that you have the latest firmware. UE9s need a Comm Firmware of 1.50 or greater.\n\nThe packet you received: %s" % (header[1], repr(packet)))
# Check for valid Trans ID
_checkTransId(header[0])
#Check for exception
if header[4] == 0x83:
raise ModbusException("Error reading register: A Modbus error %s was raised.\n\nThe packet you received: %s" % (header[5], repr(packet)))
#Check for proper command
if header[4] != 0x03:
raise ModbusException("Not a read holding registers packet.\n\nGot: %s" % repr(packet))
#Check for proper length
payloadLength = header[5]
if (payloadLength + HEADER_LENGTH) != len(packet):
#print "packet length is", len(packet)
#print "payload and header is", payloadLength + HEADER_LENGTH
raise ModbusException("Packet length not valid. Expected %s, Got %s\n\nThe packet you received: %s" % (payloadLength + HEADER_LENGTH, len(packet), repr(packet)))
if payloadFormat is None:
payloadFormat = '>' + 'H' * (payloadLength/2)
# When we write '>s', we mean a variable-length string.
# We just didn't know the length when we wrote it.
if payloadFormat == '>s':
payloadFormat = '>' + 's' * payloadLength
#print "Info: "
#print payloadFormat
#print type(packet)
#print [ ord(c) for c in packet ]
# Mike C.: unpack_from new in 2.5. Won't work on Joyent.
#payload = unpack_from(payloadFormat, packet, offset = HEADER_LENGTH)
payload = unpack(payloadFormat, packet[HEADER_LENGTH:])
if len(payload) == 1:
return payload[0]
else:
return list(payload)
def readInputRegistersRequest(addr, numReg = None):
if numReg is None:
numReg = calcNumberOfRegisters(addr)
packet = _buildHeaderBytes() + pack('>BHH', 0x04, addr, numReg)
#print "making readHoldingRegistersRequest packet"
#print [ ord(c) for c in packet ]
return packet
def readInputRegistersResponse(packet, payloadFormat=None):
# Example: Device type is 9
# [0, 0, 5, 255, 3, 2, 9]
# H H H c c c payload
# 0 1 2 3 4 5 6+
HEADER_LENGTH = 9
header = unpack('>HHHBBB', packet[:HEADER_LENGTH])
#print "header", [ c for c in header ]
#print "header", header
# Check for valid Trans ID
_checkTransId(header[0])
#Check for exception
if header[4] == 0x83:
raise ModbusException(header[5])
#Check for proper command
if header[4] != 0x04:
raise ModbusException("Not a read holding registers packet.")
#Check for proper length
payloadLength = header[5]
if (payloadLength + HEADER_LENGTH) != len(packet):
#print "packet length is", len(packet)
#print "payload and header is", payloadLength + HEADER_LENGTH
raise ModbusException("Packet length not valid.")
if payloadFormat is None:
payloadFormat = '>' + 'H' * (payloadLength/2)
# When we write '>s', we mean a variable-length string.
# We just didn't know the length when we wrote it.
if payloadFormat == '>s':
payloadFormat = '>' + 's' * payloadLength
#print payloadFormat
#print [ ord(c) for c in packet ]
# Mike C.: unpack_from new in 2.5. Won't work on Joyent.
#payload = unpack_from(payloadFormat, packet, offset = HEADER_LENGTH)
payload = unpack(payloadFormat, packet[HEADER_LENGTH:])
return payload
def writeRegisterRequest(addr, value, unitId = None):
if not isinstance(value, int):
raise TypeError("Value written must be an integer.")
packet = _buildHeaderBytes(unitId = unitId) + pack('>BHH', 0x06, addr, value)
return packet
def writeRegistersRequest(startAddr, values, unitId = None):
numReg = len(values)
for v in values:
if not isinstance(v, int):
raise TypeError("Value written must be an integer.")
if unitId is None:
unitId = 0xff
header = _buildHeaderBytes(length = 7+(numReg*2), unitId = unitId)
header += pack('>BHHB', *(16, startAddr, numReg, numReg*2) )
format = '>' + 'H' * numReg
packet = header + pack(format, *values)
return packet
def writeAesStingRegisterRequest(addr, a, b):
packet = TCP_HEADER + pack('>BHcc', 0x06, addr, a, b)
return packet
def writeRegisterRequestValue(data):
"""Return the value to be written in a writeRegisterRequest Packet."""
packet = unpack('>H', data[10:])
return packet[0]
class ModbusException(Exception):
def __init__(self, exceptCode):
self.exceptCode = exceptCode
def __str__(self):
return repr(self.exceptCode)
def calcNumberOfRegisters(addr, numReg = None):
return calcNumberOfRegistersAndFormat(addr, numReg)[0]
def calcFormat(addr, numReg = None):
return calcNumberOfRegistersAndFormat(addr, numReg)[1]
def calcNumberOfRegistersAndFormat(addr, numReg = None):
# TODO add special cases for channels above
if addr < 1000:
# Analog Inputs
minNumReg = 2
format = 'f'
elif addr >= 5000 and addr < 6000:
# DAC Values
minNumReg = 2
format = 'f'
elif addr >= 7000 and addr < 8000:
# Timers / Counters
minNumReg = 2
format = 'I'
elif addr in range(64008,64018) or addr == 65001:
# Serial Number
minNumReg = 2
format = 'I'
elif addr in range(10000,10010):
# VBatt/Temp/RH/Light/Pressure
minNumReg = 2
format = 'f'
elif addr in range(12000,13000):
# RXLQI/TXLQI/VBatt/Temp/Light/Motion/Sound/RH/Pressure
minNumReg = 2
format = 'f'
elif addr in range(50100, 50103):
# Check-in interval
minNumReg = 2
format = 'I'
elif addr in range(57002, 57010):
# TX/RX Bridge stuff
minNumReg = 2
format = 'I'
elif addr in range(57050, 57056):
# VUSB/VJack/VST
minNumReg = 2
format = 'f'
elif addr == 59990:
# Rapid mode
minNumReg = 1
format = 'H'
elif addr == 59200:
# NumberOfKnownDevices
minNumReg = 2
format = 'I'
else:
minNumReg = 1
format = 'H'
if numReg:
if (numReg%minNumReg) == 0:
return (numReg, '>' + ( format * (numReg/minNumReg) ))
else:
raise ModbusException("For address %s, the number of registers must be divisible by %s" % (addr, minNumReg))
else:
return ( minNumReg, '>'+format)
def getStartingAddress(packet):
"""Get the address of a modbus request"""
return ((ord(packet[8]) << 8) + ord(packet[9]))
def getRequestType(packet):
"""Get the request type of a modbus request."""
return ord(packet[7])
def getTransactionId(packet):
"""Pulls out the transaction id of the packet"""
if isinstance(packet, list):
return unpack(">H", pack("BB", *packet[:2]) )[0]
else:
return unpack(">H", packet[:2])[0]
def getProtocolId(packet):
"""Pulls out the transaction id of the packet"""
if isinstance(packet, list):
return unpack(">H", pack("BB", *packet[2:4]) )[0]
else:
return unpack(">H", packet[2:4])[0]
def parseIntoPackets(packet):
while True:
if isinstance(packet, list):
firstLength = packet[5]+6
else:
firstLength = ord(packet[5])+6
if len(packet) == firstLength:
yield packet
raise StopIteration
else:
yield packet[:firstLength]
packet = packet[firstLength:]
def parseSpontaneousDataPacket(packet):
if isinstance(packet, list):
localId = packet[6]
packet = pack("B"*len(packet), *packet)
else:
localId = ord(packet[6])
transId = unpack(">H", packet[0:2])[0]
report = unpack(">HBBfHH"+"f"*8, packet[9:53])
results = dict()
results['unitId'] = localId
results['transId'] = transId
results['Rxlqi'] = report[1]
results['Txlqi'] = report[2]
results['Battery'] = report[3]
results['Temperature'] = report[6]
results['Light'] = report[7]
results['Bump'] = report[4]
results['Sound'] = report[11]
return results
| 10,761 | 29.573864 | 237 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/build/lib/u6.py | """
Name: u6.py
Desc: Defines the U6 class, which makes working with a U6 much easier. All of
the low-level functions for the U6 are implemented as functions of the U6
class. There are also a handful additional functions which improve upon
the interface provided by the low-level functions.
To learn about the low-level functions, please see Section 5.2 of the U6 User's Guide:
http://labjack.com/support/u6/users-guide/5.2
"""
from LabJackPython import *
import struct, ConfigParser
def openAllU6():
"""
A helpful function which will open all the connected U6s. Returns a
dictionary where the keys are the serialNumber, and the value is the device
object.
"""
returnDict = dict()
for i in range(deviceCount(6)):
d = U6(firstFound = False, devNumber = i+1)
returnDict[str(d.serialNumber)] = d
return returnDict
def dumpPacket(buffer):
"""
Name: dumpPacket(buffer)
Args: byte array
Desc: Returns hex value of all bytes in the buffer
"""
return repr([ hex(x) for x in buffer ])
def getBit(n, bit):
"""
Name: getBit(n, bit)
Args: n, the original integer you want the bit of
bit, the index of the bit you want
Desc: Returns the bit at position "bit" of integer "n"
>>> n = 5
>>> bit = 2
>>> getBit(n, bit)
1
>>> bit = 0
>>> getBit(n, bit)
1
"""
return int(bool((int(n) & (1 << bit)) >> bit))
def toBitList(inbyte):
"""
Name: toBitList(inbyte)
Args: a byte
Desc: Converts a byte into list for access to individual bits
>>> inbyte = 5
>>> toBitList(inbyte)
[1, 0, 1, 0, 0, 0, 0, 0]
"""
return [ getBit(inbyte, b) for b in range(8) ]
def dictAsString(d):
"""Helper function that returns a string representation of a dictionary"""
s = "{"
for key, val in sorted(d.items()):
s += "%s: %s, " % (key, val)
s = s.rstrip(", ") # Nuke the trailing comma
s += "}"
return s
class CalibrationInfo(object):
""" A class to hold the calibration info for a U6 """
def __init__(self):
# A flag to tell difference between nominal and actual values.
self.nominal = True
# Positive Channel calibration
self.ain10vSlope = 3.1580578 * (10 ** -4)
self.ain10vOffset = -10.5869565220
self.ain1vSlope = 3.1580578 * (10 ** -5)
self.ain1vOffset = -1.05869565220
self.ain100mvSlope = 3.1580578 * (10 ** -6)
self.ain100mvOffset = -0.105869565220
self.ain10mvSlope = 3.1580578 * (10 ** -7)
self.ain10mvOffset = -0.0105869565220
self.ainSlope = [self.ain10vSlope, self.ain1vSlope, self.ain100mvSlope, self.ain10mvSlope]
self.ainOffset = [ self.ain10vOffset, self.ain1vOffset, self.ain100mvOffset, self.ain10mvOffset ]
# Negative Channel calibration
self.ain10vNegSlope = -3.15805800 * (10 ** -4)
self.ain10vCenter = 33523.0
self.ain1vNegSlope = -3.15805800 * (10 ** -5)
self.ain1vCenter = 33523.0
self.ain100mvNegSlope = -3.15805800 * (10 ** -6)
self.ain100mvCenter = 33523.0
self.ain10mvNegSlope = -3.15805800 * (10 ** -7)
self.ain10mvCenter = 33523.0
self.ainNegSlope = [ self.ain10vNegSlope, self.ain1vNegSlope, self.ain100mvNegSlope, self.ain10mvNegSlope ]
self.ainCenter = [ self.ain10vCenter, self.ain1vCenter, self.ain100mvCenter, self.ain10mvCenter ]
# Miscellaneous
self.dac0Slope = 13200.0
self.dac0Offset = 0
self.dac1Slope = 13200.0
self.dac1Offset = 0
self.currentOutput0 = 0.0000100000
self.currentOutput1 = 0.0002000000
self.temperatureSlope = -92.379
self.temperatureOffset = 465.129
# Hi-Res ADC stuff
# Positive Channel calibration
self.proAin10vSlope = 3.1580578 * (10 ** -4)
self.proAin10vOffset = -10.5869565220
self.proAin1vSlope = 3.1580578 * (10 ** -5)
self.proAin1vOffset = -1.05869565220
self.proAin100mvSlope = 3.1580578 * (10 ** -6)
self.proAin100mvOffset = -0.105869565220
self.proAin10mvSlope = 3.1580578 * (10 ** -7)
self.proAin10mvOffset = -0.0105869565220
# Negative Channel calibration
self.proAin10vNegSlope = -3.15805800 * (10 ** -4)
self.proAin10vCenter = 33523.0
self.proAin1vNegSlope = -3.15805800 * (10 ** -5)
self.proAin1vCenter = 33523.0
self.proAin100mvNegSlope = -3.15805800 * (10 ** -6)
self.proAin100mvCenter = 33523.0
self.proAin10mvNegSlope = -3.15805800 * (10 ** -7)
self.proAin10mvCenter = 33523.0
def __str__(self):
return str(self.__dict__)
class U6(Device):
"""
U6 Class for all U6 specific low-level commands.
Example:
>>> import u6
>>> d = u6.U6()
>>> print d.configU6()
{'SerialNumber': 320032102, ... , 'FirmwareVersion': '1.26'}
"""
def __init__(self, debug = False, autoOpen = True, **kargs):
"""
Name: U6.__init__(self, debug = False, autoOpen = True, **kargs)
Args: debug, Do you want debug information?
autoOpen, If true, then the constructor will call open for you
**kargs, The arguments to be passed to open.
Desc: Your basic constructor.
"""
Device.__init__(self, None, devType = 6)
self.firmwareVersion = 0
self.bootloaderVersion = 0
self.hardwareVersion = 0
self.productId = 0
self.fioDirection = [None] * 8
self.fioState = [None] * 8
self.eioDirection = [None] * 8
self.eioState = [None] * 8
self.cioDirection = [None] * 8
self.cioState = [None] * 8
self.dac1Enable = 0
self.dac0 = 0
self.dac1 = 0
self.calInfo = CalibrationInfo()
self.productName = "U6"
self.debug = debug
if autoOpen:
self.open(**kargs)
def open(self, localId = None, firstFound = True, serial = None, devNumber = None, handleOnly = False, LJSocket = None):
"""
Name: U6.open(localId = None, firstFound = True, devNumber = None,
handleOnly = False, LJSocket = None)
Args: firstFound, If True, use the first found U6
serial, open a U6 with the given serial number
localId, open a U6 with the given local id.
devNumber, open a U6 with the given devNumber
handleOnly, if True, LabJackPython will only open a handle
LJSocket, set to "<ip>:<port>" to connect to LJSocket
Desc: Opens a U6 for reading and writing.
>>> myU6 = u6.U6(autoOpen = False)
>>> myU6.open()
"""
Device.open(self, 6, firstFound = firstFound, serial = serial, localId = localId, devNumber = devNumber, handleOnly = handleOnly, LJSocket = LJSocket )
def configU6(self, LocalID = None):
"""
Name: U6.configU6(LocalID = None)
Args: LocalID, if set, will write the new value to U6
Desc: Writes the Local ID, and reads some hardware information.
>>> myU6 = u6.U6()
>>> myU6.configU6()
{'BootloaderVersion': '6.15',
'FirmwareVersion': '0.88',
'HardwareVersion': '2.0',
'LocalID': 1,
'ProductID': 6,
'SerialNumber': 360005087,
'VersionInfo': 4}
"""
command = [ 0 ] * 26
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x0A
command[3] = 0x08
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
if LocalID != None:
command[6] = (1 << 3)
command[8] = LocalID
#command[7] = Reserved
#command[9-25] = Reserved
try:
result = self._writeRead(command, 38, [0xF8, 0x10, 0x08])
except LabJackException, e:
if e.errorCode is 4:
print "NOTE: ConfigU6 returned an error of 4. This probably means you are using U6 with a *really old* firmware. Please upgrade your U6's firmware as soon as possible."
result = self._writeRead(command, 38, [0xF8, 0x10, 0x08], checkBytes = False)
else:
raise e
self.firmwareVersion = "%s.%02d" % (result[10], result[9])
self.bootloaderVersion = "%s.%02d" % (result[12], result[11])
self.hardwareVersion = "%s.%02d" % (result[14], result[13])
self.serialNumber = struct.unpack("<I", struct.pack(">BBBB", *result[15:19]))[0]
self.productId = struct.unpack("<H", struct.pack(">BB", *result[19:21]))[0]
self.localId = result[21]
self.versionInfo = result[37]
self.deviceName = 'U6'
if self.versionInfo == 12:
self.deviceName = 'U6-Pro'
return { 'FirmwareVersion' : self.firmwareVersion, 'BootloaderVersion' : self.bootloaderVersion, 'HardwareVersion' : self.hardwareVersion, 'SerialNumber' : self.serialNumber, 'ProductID' : self.productId, 'LocalID' : self.localId, 'VersionInfo' : self.versionInfo, 'DeviceName' : self.deviceName }
def configIO(self, NumberTimersEnabled = None, EnableCounter1 = None, EnableCounter0 = None, TimerCounterPinOffset = None, EnableUART = None):
"""
Name: U6.configIO(NumberTimersEnabled = None, EnableCounter1 = None, EnableCounter0 = None, TimerCounterPinOffset = None)
Args: NumberTimersEnabled, Number of timers to enable
EnableCounter1, Set to True to enable counter 1, F to disable
EnableCounter0, Set to True to enable counter 0, F to disable
TimerCounterPinOffset, where should the timers/counters start
if all args are None, command just reads.
Desc: Writes and reads the current IO configuration.
>>> myU6 = u6.U6()
>>> myU6.configIO()
{'Counter0Enabled': False,
'Counter1Enabled': False,
'NumberTimersEnabled': 0,
'TimerCounterPinOffset': 0}
"""
command = [ 0 ] * 16
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x05
command[3] = 0x0B
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
if NumberTimersEnabled != None:
command[6] = 1
command[7] = NumberTimersEnabled
if EnableCounter0 != None:
command[6] = 1
if EnableCounter0:
command[8] = 1
if EnableCounter1 != None:
command[6] = 1
if EnableCounter1:
command[8] |= (1 << 1)
if TimerCounterPinOffset != None:
command[6] = 1
command[9] = TimerCounterPinOffset
if EnableUART is not None:
command[6] |= 1
command[6] |= (1 << 5)
result = self._writeRead(command, 16, [0xf8, 0x05, 0x0B])
return { 'NumberTimersEnabled' : result[8], 'Counter0Enabled' : bool(result[9] & 1), 'Counter1Enabled' : bool( (result[9] >> 1) & 1), 'TimerCounterPinOffset' : result[10] }
def configTimerClock(self, TimerClockBase = None, TimerClockDivisor = None):
"""
Name: U6.configTimerClock(TimerClockBase = None, TimerClockDivisor = None)
Args: TimerClockBase, which timer base to use
TimerClockDivisor, set the divisor
if all args are None, command just reads.
Also, if you cannot set the divisor without setting the base.
Desc: Writes and read the timer clock configuration.
>>> myU6 = u6.U6()
>>> myU6.configTimerClock()
{'TimerClockDivisor': 256, 'TimerClockBase': 2}
"""
command = [ 0 ] * 10
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x02
command[3] = 0x0A
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
#command[6] = Reserved
#command[7] = Reserved
if TimerClockBase != None:
command[8] = (1 << 7)
command[8] |= TimerClockBase & 7
if TimerClockDivisor != None:
command[9] = TimerClockDivisor
result = self._writeRead(command, 10, [0xF8, 0x2, 0x0A])
divisor = result[9]
if divisor == 0:
divisor = 256
return { 'TimerClockBase' : (result[8] & 7), 'TimerClockDivisor' : divisor }
def _buildBuffer(self, sendBuffer, readLen, commandlist):
for cmd in commandlist:
if isinstance(cmd, FeedbackCommand):
sendBuffer += cmd.cmdBytes
readLen += cmd.readLen
elif isinstance(cmd, list):
sendBuffer, readLen = self._buildBuffer(sendBuffer, readLen, cmd)
return (sendBuffer, readLen)
def _buildFeedbackResults(self, rcvBuffer, commandlist, results, i):
for cmd in commandlist:
if isinstance(cmd, FeedbackCommand):
results.append(cmd.handle(rcvBuffer[i:i+cmd.readLen]))
i += cmd.readLen
elif isinstance(cmd, list):
self._buildFeedbackResults(rcvBuffer, cmd, results, i)
return results
def getFeedback(self, *commandlist):
"""
Name: getFeedback(commandlist)
Args: the FeedbackCommands to run
Desc: Forms the commandlist into a packet, sends it to the U6, and reads the response.
>>> myU6 = U6()
>>> ledCommand = u6.LED(False)
>>> internalTempCommand = u6.AIN(30, 31, True)
>>> myU6.getFeedback(ledCommand, internalTempCommand)
[None, 23200]
OR if you like the list version better:
>>> myU6 = U6()
>>> ledCommand = u6.LED(False)
>>> internalTempCommand = u6.AIN(30, 31, True)
>>> commandList = [ ledCommand, internalTempCommand ]
>>> myU6.getFeedback(commandList)
[None, 23200]
"""
sendBuffer = [0] * 7
sendBuffer[1] = 0xF8
readLen = 9
sendBuffer, readLen = self._buildBuffer(sendBuffer, readLen, commandlist)
if len(sendBuffer) % 2:
sendBuffer += [0]
sendBuffer[2] = len(sendBuffer) / 2 - 3
if readLen % 2:
readLen += 1
if len(sendBuffer) > MAX_USB_PACKET_LENGTH:
raise LabJackException("ERROR: The feedback command you are attempting to send is bigger than 64 bytes ( %s bytes ). Break your commands up into separate calls to getFeedback()." % len(sendBuffer))
if readLen > MAX_USB_PACKET_LENGTH:
raise LabJackException("ERROR: The feedback command you are attempting to send would yield a response that is greater than 64 bytes ( %s bytes ). Break your commands up into separate calls to getFeedback()." % readLen)
rcvBuffer = self._writeRead(sendBuffer, readLen, [], checkBytes = False, stream = False, checksum = True)
# Check the response for errors
try:
self._checkCommandBytes(rcvBuffer, [0xF8])
if rcvBuffer[3] != 0x00:
raise LabJackException("Got incorrect command bytes")
except LowlevelErrorException, e:
if isinstance(commandlist[0], list):
culprit = commandlist[0][ (rcvBuffer[7] -1) ]
else:
culprit = commandlist[ (rcvBuffer[7] -1) ]
raise LowlevelErrorException("\nThis Command\n %s\nreturned an error:\n %s" % ( culprit, lowlevelErrorToString(rcvBuffer[6]) ) )
results = []
i = 9
return self._buildFeedbackResults(rcvBuffer, commandlist, results, i)
def readMem(self, BlockNum, ReadCal=False):
"""
Name: U6.readMem(BlockNum, ReadCal=False)
Args: BlockNum, which block to read
ReadCal, set to True to read the calibration data
Desc: Reads 1 block (32 bytes) from the non-volatile user or
calibration memory. Please read section 5.2.6 of the user's
guide before you do something you may regret.
>>> myU6 = U6()
>>> myU6.readMem(0)
[ < userdata stored in block 0 > ]
NOTE: Do not call this function while streaming.
"""
command = [ 0 ] * 8
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x01
command[3] = 0x2A
if ReadCal:
command[3] = 0x2D
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = 0x00
command[7] = BlockNum
result = self._writeRead(command, 40, [ 0xF8, 0x11, command[3] ])
return result[8:]
def readCal(self, BlockNum):
return self.readMem(BlockNum, ReadCal = True)
def writeMem(self, BlockNum, Data, WriteCal=False):
"""
Name: U6.writeMem(BlockNum, Data, WriteCal=False)
Args: BlockNum, which block to write
Data, a list of bytes to write
WriteCal, set to True to write calibration.
Desc: Writes 1 block (32 bytes) from the non-volatile user or
calibration memory. Please read section 5.2.7 of the user's
guide before you do something you may regret.
>>> myU6 = U6()
>>> myU6.writeMem(0, [ < userdata to be stored in block 0 > ])
NOTE: Do not call this function while streaming.
"""
if not isinstance(Data, list):
raise LabJackException("Data must be a list of bytes")
command = [ 0 ] * 40
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x11
command[3] = 0x28
if WriteCal:
command[3] = 0x2B
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = 0x00
command[7] = BlockNum
command[8:] = Data
self._writeRead(command, 8, [0xF8, 0x11, command[3]])
def writeCal(self, BlockNum, Data):
return self.writeMem(BlockNum, Data, WriteCal = True)
def eraseMem(self, EraseCal=False):
"""
Name: U6.eraseMem(EraseCal=False)
Args: EraseCal, set to True to erase the calibration memory.
Desc: The U6 uses flash memory that must be erased before writing.
Please read section 5.2.8 of the user's guide before you do
something you may regret.
>>> myU6 = U6()
>>> myU6.eraseMem()
NOTE: Do not call this function while streaming.
"""
if eraseCal:
command = [ 0 ] * 8
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x01
command[3] = 0x2C
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = 0x4C
command[7] = 0x6C
else:
command = [ 0 ] * 6
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x00
command[3] = 0x29
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
self._writeRead(command, 8, [0xF8, 0x01, command[3]])
def eraseCal(self):
return self.eraseMem(EraseCal=True)
def streamConfig(self, NumChannels = 1, ResolutionIndex = 0, SamplesPerPacket = 25, SettlingFactor = 0, InternalStreamClockFrequency = 0, DivideClockBy256 = False, ScanInterval = 1, ChannelNumbers = [0], ChannelOptions = [0], SampleFrequency = None):
"""
Name: U6.streamConfig(
NumChannels = 1, ResolutionIndex = 0,
SamplesPerPacket = 25, SettlingFactor = 0,
InternalStreamClockFrequency = 0, DivideClockBy256 = False,
ScanInterval = 1, ChannelNumbers = [0],
ChannelOptions = [0], SampleFrequency = None )
Args: NumChannels, the number of channels to stream
ResolutionIndex, the resolution of the samples
SettlingFactor, the settling factor to be used
ChannelNumbers, a list of channel numbers to stream
ChannelOptions, a list of channel options bytes
Set Either:
SampleFrequency, the frequency in Hz to sample
-- OR --
SamplesPerPacket, how many samples make one packet
InternalStreamClockFrequency, 0 = 4 MHz, 1 = 48 MHz
DivideClockBy256, True = divide the clock by 256
ScanInterval, clock/ScanInterval = frequency.
Desc: Configures streaming on the U6. On a decent machine, you can
expect to stream a range of 0.238 Hz to 15 Hz. Without the
conversion, you can get up to 55 Hz.
"""
if NumChannels != len(ChannelNumbers) or NumChannels != len(ChannelOptions):
raise LabJackException("NumChannels must match length of ChannelNumbers and ChannelOptions")
if len(ChannelNumbers) != len(ChannelOptions):
raise LabJackException("len(ChannelNumbers) doesn't match len(ChannelOptions)")
if SampleFrequency != None:
if SampleFrequency < 1000:
if SampleFrequency < 25:
SamplesPerPacket = SampleFrequency
DivideClockBy256 = True
ScanInterval = 15625/SampleFrequency
else:
DivideClockBy256 = False
ScanInterval = 4000000/SampleFrequency
# Force Scan Interval into correct range
ScanInterval = min( ScanInterval, 65535 )
ScanInterval = int( ScanInterval )
ScanInterval = max( ScanInterval, 1 )
# Same with Samples per packet
SamplesPerPacket = max( SamplesPerPacket, 1)
SamplesPerPacket = int( SamplesPerPacket )
SamplesPerPacket = min ( SamplesPerPacket, 25)
command = [ 0 ] * (14 + NumChannels*2)
#command[0] = Checksum8
command[1] = 0xF8
command[2] = NumChannels+4
command[3] = 0x11
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = NumChannels
command[7] = ResolutionIndex
command[8] = SamplesPerPacket
#command[9] = Reserved
command[10] = SettlingFactor
command[11] = (InternalStreamClockFrequency & 1) << 3
if DivideClockBy256:
command[11] |= 1 << 1
t = struct.pack("<H", ScanInterval)
command[12] = ord(t[0])
command[13] = ord(t[1])
for i in range(NumChannels):
command[14+(i*2)] = ChannelNumbers[i]
command[15+(i*2)] = ChannelOptions[i]
self._writeRead(command, 8, [0xF8, 0x01, 0x11])
# Set up the variables for future use.
self.streamSamplesPerPacket = SamplesPerPacket
self.streamChannelNumbers = ChannelNumbers
self.streamChannelOptions = ChannelOptions
self.streamConfiged = True
if InternalStreamClockFrequency == 1:
freq = float(48000000)
else:
freq = float(4000000)
if DivideClockBy256:
freq /= 256
freq = freq/ScanInterval
self.packetsPerRequest = max(1, int(freq/SamplesPerPacket))
self.packetsPerRequest = min(self.packetsPerRequest, 48)
def processStreamData(self, result, numBytes = None):
"""
Name: U6.processStreamData(result, numPackets = None)
Args: result, the string returned from streamData()
numBytes, the number of bytes per packet
Desc: Breaks stream data into individual channels and applies
calibrations.
>>> reading = d.streamData(convert = False)
>>> print proccessStreamData(reading['result'])
defaultDict(list, {'AIN0' : [3.123, 3.231, 3.232, ...]})
"""
if numBytes is None:
numBytes = 14 + (self.streamSamplesPerPacket * 2)
returnDict = collections.defaultdict(list)
j = self.streamPacketOffset
for packet in self.breakupPackets(result, numBytes):
for sample in self.samplesFromPacket(packet):
if j >= len(self.streamChannelNumbers):
j = 0
if self.streamChannelNumbers[j] in (193, 194):
value = struct.unpack('<BB', sample )
elif self.streamChannelNumbers[j] >= 200:
value = struct.unpack('<H', sample )[0]
else:
if (self.streamChannelOptions[j] >> 7) == 1:
# do signed
value = struct.unpack('<H', sample )[0]
else:
# do unsigned
value = struct.unpack('<H', sample )[0]
gainIndex = (self.streamChannelOptions[j] >> 4) & 0x3
value = self.binaryToCalibratedAnalogVoltage(gainIndex, value, is16Bits=True)
returnDict["AIN%s" % self.streamChannelNumbers[j]].append(value)
j += 1
self.streamPacketOffset = j
return returnDict
def watchdog(self, Write = False, ResetOnTimeout = False, SetDIOStateOnTimeout = False, TimeoutPeriod = 60, DIOState = 0, DIONumber = 0):
"""
Name: U6.watchdog(Write = False, ResetOnTimeout = False, SetDIOStateOnTimeout = False, TimeoutPeriod = 60, DIOState = 0, DIONumber = 0)
Args: Write, Set to True to write new values to the watchdog.
ResetOnTimeout, True means reset the device on timeout
SetDIOStateOnTimeout, True means set the sate of a DIO on timeout
TimeoutPeriod, Time, in seconds, to wait before timing out.
DIOState, 1 = High, 0 = Low
DIONumber, which DIO to set.
Desc: Controls a firmware based watchdog timer.
"""
command = [ 0 ] * 16
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x05
command[3] = 0x09
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
if Write:
command[6] = 1
if ResetOnTimeout:
command[7] = (1 << 5)
if SetDIOStateOnTimeout:
command[7] |= (1 << 4)
t = struct.pack("<H", TimeoutPeriod)
command[8] = ord(t[0])
command[9] = ord(t[1])
command[10] = ((DIOState & 1 ) << 7)
command[10] |= (DIONumber & 0xf)
result = self._writeRead(command, 16, [ 0xF8, 0x05, 0x09])
watchdogStatus = {}
if result[7] == 0:
watchdogStatus['WatchDogEnabled'] = False
watchdogStatus['ResetOnTimeout'] = False
watchdogStatus['SetDIOStateOnTimeout'] = False
else:
watchdogStatus['WatchDogEnabled'] = True
if (( result[7] >> 5 ) & 1):
watchdogStatus['ResetOnTimeout'] = True
else:
watchdogStatus['ResetOnTimeout'] = False
if (( result[7] >> 4 ) & 1):
watchdogStatus['SetDIOStateOnTimeout'] = True
else:
watchdogStatus['SetDIOStateOnTimeout'] = False
watchdogStatus['TimeoutPeriod'] = struct.unpack('<H', struct.pack("BB", *result[8:10]))
if (( result[10] >> 7 ) & 1):
watchdogStatus['DIOState'] = 1
else:
watchdogStatus['DIOState'] = 0
watchdogStatus['DIONumber'] = ( result[10] & 15 )
return watchdogStatus
SPIModes = { 'A' : 0, 'B' : 1, 'C' : 2, 'D' : 3 }
def spi(self, SPIBytes, AutoCS=True, DisableDirConfig = False, SPIMode = 'A', SPIClockFactor = 0, CSPINNum = 0, CLKPinNum = 1, MISOPinNum = 2, MOSIPinNum = 3):
"""
Name: U6.spi(SPIBytes, AutoCS=True, DisableDirConfig = False,
SPIMode = 'A', SPIClockFactor = 0, CSPINNum = 0,
CLKPinNum = 1, MISOPinNum = 2, MOSIPinNum = 3)
Args: SPIBytes, A list of bytes to send.
AutoCS, If True, the CS line is automatically driven low
during the SPI communication and brought back high
when done.
DisableDirConfig, If True, function does not set the direction
of the line.
SPIMode, 'A', 'B', 'C', or 'D'.
SPIClockFactor, Sets the frequency of the SPI clock.
CSPINNum, which pin is CS
CLKPinNum, which pin is CLK
MISOPinNum, which pin is MISO
MOSIPinNum, which pin is MOSI
Desc: Sends and receives serial data using SPI synchronous
communication. See Section 5.2.17 of the user's guide.
"""
if not isinstance(SPIBytes, list):
raise LabJackException("SPIBytes MUST be a list of bytes")
numSPIBytes = len(SPIBytes)
oddPacket = False
if numSPIBytes%2 != 0:
SPIBytes.append(0)
numSPIBytes = numSPIBytes + 1
oddPacket = True
command = [ 0 ] * (13 + numSPIBytes)
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 4 + (numSPIBytes/2)
command[3] = 0x3A
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
if AutoCS:
command[6] |= (1 << 7)
if DisableDirConfig:
command[6] |= (1 << 6)
command[6] |= ( self.SPIModes[SPIMode] & 3 )
command[7] = SPIClockFactor
#command[8] = Reserved
command[9] = CSPINNum
command[10] = CLKPinNum
command[11] = MISOPinNum
command[12] = MOSIPinNum
command[13] = numSPIBytes
if oddPacket:
command[13] = numSPIBytes - 1
command[14:] = SPIBytes
result = self._writeRead(command, 8+numSPIBytes, [ 0xF8, 1+(numSPIBytes/2), 0x3A ])
return { 'NumSPIBytesTransferred' : result[7], 'SPIBytes' : result[8:] }
def asynchConfig(self, Update = True, UARTEnable = True, DesiredBaud = None, BaudFactor = 63036):
"""
Name: U6.asynchConfig(Update = True, UARTEnable = True,
DesiredBaud = None, BaudFactor = 63036)
Args: Update, If True, new values are written.
UARTEnable, If True, UART will be enabled.
DesiredBaud, If set, will apply the formualt to
calculate BaudFactor.
BaudFactor, = 2^16 - 48000000/(2 * Desired Baud). Ignored
if DesiredBaud is set.
Desc: Configures the U6 UART for asynchronous communication. See
section 5.2.18 of the User's Guide.
"""
if UARTEnable:
self.configIO(EnableUART = True)
command = [ 0 ] * 10
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x02
command[3] = 0x14
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
#commmand[6] = 0x00
if Update:
command[7] = (1 << 7)
if UARTEnable:
command[7] |= (1 << 6)
if DesiredBaud != None:
BaudFactor = (2**16) - 48000000/(2 * DesiredBaud)
t = struct.pack("<H", BaudFactor)
command[8] = ord(t[0])
command[9] = ord(t[1])
results = self._writeRead(command, 10, [0xF8, 0x02, 0x14])
if command[8] != results[8] and command[9] != results[9]:
raise LabJackException("BaudFactor didn't stick.")
def asynchTX(self, AsynchBytes):
"""
Name: U6.asynchTX(AsynchBytes)
Args: AsynchBytes, List of bytes to send
Desc: Sends bytes to the U6 UART which will be sent asynchronously
on the transmit line. Section 5.2.19 of the User's Guide.
"""
numBytes = len(AsynchBytes)
oddPacket = False
if numBytes%2 != 0:
oddPacket = True
AsynchBytes.append(0)
numBytes = numBytes + 1
command = [ 0 ] * (8+numBytes)
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 1 + (numBytes/2)
command[3] = 0x15
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
#commmand[6] = 0x00
command[7] = numBytes
if oddPacket:
command[7] = numBytes-1
command[8:] = AsynchBytes
result = self._writeRead(command, 10, [ 0xF8, 0x02, 0x15])
return { 'NumAsynchBytesSent' : result[7], 'NumAsynchBytesInRXBuffer' : result[8] }
def asynchRX(self, Flush = False):
"""
Name: U6.asynchTX(AsynchBytes)
Args: Flush, If True, empties the entire 256-byte RX buffer.
Desc: Sends bytes to the U6 UART which will be sent asynchronously
on the transmit line. Section 5.2.20 of the User's Guide.
"""
command = [ 0, 0xF8, 0x01, 0x16, 0, 0, 0, int(Flush)]
result = self._writeRead(command, 40, [ 0xF8, 0x11, 0x16 ])
return { 'NumAsynchBytesInRXBuffer' : result[7], 'AsynchBytes' : result[8:] }
def i2c(self, Address, I2CBytes, EnableClockStretching = False, NoStopWhenRestarting = False, ResetAtStart = False, SpeedAdjust = 0, SDAPinNum = 0, SCLPinNum = 1, NumI2CBytesToReceive = 0, AddressByte = None):
"""
Name: U6.i2c(Address, I2CBytes, EnableClockStretching = False, NoStopWhenRestarting = False, ResetAtStart = False, SpeedAdjust = 0, SDAPinNum = 0, SCLPinNum = 1, NumI2CBytesToReceive = 0, AddressByte = None)
Args: Address, the address (Not shifted over)
I2CBytes, a list of bytes to send
EnableClockStretching, True enables clock stretching
NoStopWhenRestarting, True means no stop sent when restarting
ResetAtStart, if True, an I2C bus reset will be done
before communicating.
SpeedAdjust, Allows the communication frequency to be reduced.
SDAPinNum, Which pin will be data
SCLPinNum, Which pin is clock
NumI2CBytesToReceive, Number of I2C bytes to expect back.
AddressByte, The address as you would put it in the lowlevel
packet. Overrides Address. Optional.
Desc: Sends and receives serial data using I2C synchronous
communication. Section 5.2.21 of the User's Guide.
"""
numBytes = len(I2CBytes)
oddPacket = False
if numBytes%2 != 0:
oddPacket = True
I2CBytes.append(0)
numBytes = numBytes+1
command = [ 0 ] * (14+numBytes)
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 4 + (numBytes/2)
command[3] = 0x3B
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
if EnableClockStretching:
command[6] |= (1 << 3)
if NoStopWhenRestarting:
command[6] |= (1 << 2)
if ResetAtStart:
command[6] |= (1 << 1)
command[7] = SpeedAdjust
command[8] = SDAPinNum
command[9] = SCLPinNum
if AddressByte != None:
command[10] = AddressByte
else:
command[10] = Address << 1
#command[11] = Reserved
command[12] = numBytes
if oddPacket:
command[12] = numBytes-1
command[13] = NumI2CBytesToReceive
command[14:] = I2CBytes
oddResponse = False
if NumI2CBytesToReceive%2 != 0:
NumI2CBytesToReceive = NumI2CBytesToReceive+1
oddResponse = True
result = self._writeRead(command, (12+NumI2CBytesToReceive), [0xF8, (3+(NumI2CBytesToReceive/2)), 0x3B])
if NumI2CBytesToReceive != 0:
return { 'AckArray' : result[8:12], 'I2CBytes' : result[12:] }
else:
return { 'AckArray' : result[8:12] }
def sht1x(self, DataPinNum = 0, ClockPinNum = 1, SHTOptions = 0xc0):
"""
Name: U6.sht1x(DataPinNum = 0, ClockPinNum = 1, SHTOptions = 0xc0)
Args: DataPinNum, Which pin is the Data line
ClockPinNum, Which line is the Clock line
SHTOptions (and proof people read documentation):
bit 7 = Read Temperature
bit 6 = Read Realtive Humidity
bit 2 = Heater. 1 = on, 0 = off
bit 1 = Reserved at 0
bit 0 = Resolution. 1 = 8 bit RH, 12 bit T; 0 = 12 RH, 14 bit T
Desc: Reads temperature and humidity from a Sensirion SHT1X sensor.
Section 5.2.22 of the User's Guide.
"""
command = [ 0 ] * 10
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x02
command[3] = 0x39
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = DataPinNum
command[7] = ClockPinNum
#command[8] = Reserved
command[9] = SHTOptions
result = self._writeRead(command, 16, [ 0xF8, 0x05, 0x39])
val = (result[11]*256) + result[10]
temp = -39.60 + 0.01*val
val = (result[14]*256) + result[13]
humid = -4 + 0.0405*val + -.0000028*(val*val)
humid = (temp - 25)*(0.01 + 0.00008*val) + humid
return { 'StatusReg' : result[8], 'StatusCRC' : result[9], 'Temperature' : temp, 'TemperatureCRC' : result[12], 'Humidity' : humid, 'HumidityCRC' : result[15] }
# --------------------------- Old U6 code -------------------------------
def _readCalDataBlock(self, n):
"""
Internal routine to read the specified calibration block (0-2)
"""
sendBuffer = [0] * 8
sendBuffer[1] = 0xF8 # command byte
sendBuffer[2] = 0x01 # number of data words
sendBuffer[3] = 0x2D # extended command number
sendBuffer[6] = 0x00
sendBuffer[7] = n # Blocknum = 0
self.write(sendBuffer)
buff = self.read(40)
return buff[8:]
def getCalibrationData(self):
"""
Name: getCalibrationData(self)
Args: None
Desc: Gets the slopes and offsets for AIN and DACs,
as well as other calibration data
>>> myU6 = U6()
>>> myU6.getCalibrationData()
>>> myU6.calInfo
<ainDiffOffset: -2.46886488446,...>
"""
if self.debug is True:
print "Calibration data retrieval"
self.calInfo.nominal = False
#reading block 0 from memory
rcvBuffer = self._readCalDataBlock(0)
# Positive Channel calibration
self.calInfo.ain10vSlope = toDouble(rcvBuffer[:8])
self.calInfo.ain10vOffset = toDouble(rcvBuffer[8:16])
self.calInfo.ain1vSlope = toDouble(rcvBuffer[16:24])
self.calInfo.ain1vOffset = toDouble(rcvBuffer[24:])
#reading block 1 from memory
rcvBuffer = self._readCalDataBlock(1)
self.calInfo.ain100mvSlope = toDouble(rcvBuffer[:8])
self.calInfo.ain100mvOffset = toDouble(rcvBuffer[8:16])
self.calInfo.ain10mvSlope = toDouble(rcvBuffer[16:24])
self.calInfo.ain10mvOffset = toDouble(rcvBuffer[24:])
self.calInfo.ainSlope = [self.calInfo.ain10vSlope, self.calInfo.ain1vSlope, self.calInfo.ain100mvSlope, self.calInfo.ain10mvSlope]
self.calInfo.ainOffset = [ self.calInfo.ain10vOffset, self.calInfo.ain1vOffset, self.calInfo.ain100mvOffset, self.calInfo.ain10mvOffset ]
#reading block 2 from memory
rcvBuffer = self._readCalDataBlock(2)
# Negative Channel calibration
self.calInfo.ain10vNegSlope = toDouble(rcvBuffer[:8])
self.calInfo.ain10vCenter = toDouble(rcvBuffer[8:16])
self.calInfo.ain1vNegSlope = toDouble(rcvBuffer[16:24])
self.calInfo.ain1vCenter = toDouble(rcvBuffer[24:])
#reading block 3 from memory
rcvBuffer = self._readCalDataBlock(3)
self.calInfo.ain100mvNegSlope = toDouble(rcvBuffer[:8])
self.calInfo.ain100mvCenter = toDouble(rcvBuffer[8:16])
self.calInfo.ain10mvNegSlope = toDouble(rcvBuffer[16:24])
self.calInfo.ain10mvCenter = toDouble(rcvBuffer[24:])
self.calInfo.ainNegSlope = [ self.calInfo.ain10vNegSlope, self.calInfo.ain1vNegSlope, self.calInfo.ain100mvNegSlope, self.calInfo.ain10mvNegSlope ]
self.calInfo.ainCenter = [ self.calInfo.ain10vCenter, self.calInfo.ain1vCenter, self.calInfo.ain100mvCenter, self.calInfo.ain10mvCenter ]
#reading block 4 from memory
rcvBuffer = self._readCalDataBlock(4)
# Miscellaneous
self.calInfo.dac0Slope = toDouble(rcvBuffer[:8])
self.calInfo.dac0Offset = toDouble(rcvBuffer[8:16])
self.calInfo.dac1Slope = toDouble(rcvBuffer[16:24])
self.calInfo.dac1Offset = toDouble(rcvBuffer[24:])
#reading block 5 from memory
rcvBuffer = self._readCalDataBlock(5)
self.calInfo.currentOutput0 = toDouble(rcvBuffer[:8])
self.calInfo.currentOutput1 = toDouble(rcvBuffer[8:16])
self.calInfo.temperatureSlope = toDouble(rcvBuffer[16:24])
self.calInfo.temperatureOffset = toDouble(rcvBuffer[24:])
if self.productName == "U6-Pro":
# Hi-Res ADC stuff
#reading block 6 from memory
rcvBuffer = self._readCalDataBlock(6)
# Positive Channel calibration
self.calInfo.proAin10vSlope = toDouble(rcvBuffer[:8])
self.calInfo.proAin10vOffset = toDouble(rcvBuffer[8:16])
self.calInfo.proAin1vSlope = toDouble(rcvBuffer[16:24])
self.calInfo.proAin1vOffset = toDouble(rcvBuffer[24:])
#reading block 7 from memory
rcvBuffer = self._readCalDataBlock(7)
self.calInfo.proAin100mvSlope = toDouble(rcvBuffer[:8])
self.calInfo.proAin100mvOffset = toDouble(rcvBuffer[8:16])
self.calInfo.proAin10mvSlope = toDouble(rcvBuffer[16:24])
self.calInfo.proAin10mvOffset = toDouble(rcvBuffer[24:])
self.calInfo.proAinSlope = [self.calInfo.proAin10vSlope, self.calInfo.proAin1vSlope, self.calInfo.proAin100mvSlope, self.calInfo.proAin10mvSlope]
self.calInfo.proAinOffset = [ self.calInfo.proAin10vOffset, self.calInfo.proAin1vOffset, self.calInfo.proAin100mvOffset, self.calInfo.proAin10mvOffset ]
#reading block 8 from memory
rcvBuffer = self._readCalDataBlock(8)
# Negative Channel calibration
self.calInfo.proAin10vNegSlope = toDouble(rcvBuffer[:8])
self.calInfo.proAin10vCenter = toDouble(rcvBuffer[8:16])
self.calInfo.proAin1vNegSlope = toDouble(rcvBuffer[16:24])
self.calInfo.proAin1vCenter = toDouble(rcvBuffer[24:])
#reading block 9 from memory
rcvBuffer = self._readCalDataBlock(9)
self.calInfo.proAin100mvNegSlope = toDouble(rcvBuffer[:8])
self.calInfo.proAin100mvCenter = toDouble(rcvBuffer[8:16])
self.calInfo.proAin10mvNegSlope = toDouble(rcvBuffer[16:24])
self.calInfo.proAin10mvCenter = toDouble(rcvBuffer[24:])
self.calInfo.proAinNegSlope = [ self.calInfo.proAin10vNegSlope, self.calInfo.proAin1vNegSlope, self.calInfo.proAin100mvNegSlope, self.calInfo.proAin10mvNegSlope ]
self.calInfo.proAinCenter = [ self.calInfo.proAin10vCenter, self.calInfo.proAin1vCenter, self.calInfo.proAin100mvCenter, self.calInfo.proAin10mvCenter ]
def binaryToCalibratedAnalogVoltage(self, gainIndex, bytesVoltage, is16Bits=False):
"""
Name: binaryToCalibratedAnalogVoltage(gainIndex, bytesVoltage, is16Bits = False)
Args: gainIndex, which gain did you use?
bytesVoltage, bytes returned from the U6
is16bits, set to True if bytesVolotage is 16 bits (not 24)
Desc: Converts binary voltage to an analog value.
"""
if not is16Bits:
bits = float(bytesVoltage)/256
else:
bits = float(bytesVoltage)
center = self.calInfo.ainCenter[gainIndex]
negSlope = self.calInfo.ainNegSlope[gainIndex]
posSlope = self.calInfo.ainSlope[gainIndex]
if self.productName == "U6-Pro":
center = self.calInfo.proAinCenter[gainIndex]
negSlope = self.calInfo.proAinNegSlope[gainIndex]
posSlope = self.calInfo.proAinSlope[gainIndex]
if bits < center:
return (center - bits) * negSlope
else:
return (bits - center) * posSlope
def binaryToCalibratedAnalogTemperature(self, bytesTemperature):
voltage = self.binaryToCalibratedAnalogVoltage(0, bytesTemperature)
return self.calInfo.temperatureSlope * float(voltage) + self.calInfo.temperatureOffset
def softReset(self):
"""
Name: softReset
Args: none
Desc: Send a soft reset.
>>> myU6 = U6()
>>> myU6.softReset()
"""
command = [ 0x00, 0x99, 0x01, 0x00 ]
command = setChecksum8(command, 4)
self.write(command, False, False)
results = self.read(4)
if results[3] != 0:
raise LowlevelErrorException(results[3], "The softReset command returned an error:\n %s" % lowlevelErrorToString(results[3]))
def hardReset(self):
"""
Name: hardReset
Args: none
Desc: Send a hard reset.
>>> myU6 = U6()
>>> myU6.hardReset()
"""
command = [ 0x00, 0x99, 0x02, 0x00 ]
command = setChecksum8(command, 4)
self.write(command, False, False)
results = self.read(4)
if results[3] != 0:
raise LowlevelErrorException(results[3], "The softHard command returned an error:\n %s" % lowlevelErrorToString(results[3]))
self.close()
def setLED(self, state):
"""
Name: setLED(self, state)
Args: state: 1 = On, 0 = Off
Desc: Sets the state of the LED. (5.2.5.4 of user's guide)
>>> myU6 = U6()
>>> myU6.setLED(0)
... (LED turns off) ...
"""
self.getFeedback(LED(state))
def getTemperature(self):
"""
Name: getTemperature
Args: none
Desc: Reads the U6's internal temperature sensor in Kelvin.
See Section 2.6.4 of the U6 User's Guide.
>>> myU6.getTemperature()
299.87723471224308
"""
if self.calInfo.nominal:
# Read the actual calibration constants if we haven't already.
self.getCalibrationData()
result = self.getFeedback(AIN24AR(14))
return self.binaryToCalibratedAnalogTemperature(result[0]['AIN'])
def getAIN(self, positiveChannel, resolutionIndex = 0, gainIndex = 0, settlingFactor = 0, differential = False):
"""
Name: getAIN
Args: positiveChannel, resolutionIndex = 0, gainIndex = 0, settlingFactor = 0, differential = False
Desc: Reads an AIN and applies the calibration constants to it.
>>> myU6.getAIN(14)
299.87723471224308
"""
result = self.getFeedback(AIN24AR(positiveChannel, resolutionIndex, gainIndex, settlingFactor, differential))
return self.binaryToCalibratedAnalogVoltage(result[0]['GainIndex'], result[0]['AIN'])
def readDefaultsConfig(self):
"""
Name: U6.readDefaultsConfig( )
Args: None
Desc: Reads the power-up defaults stored in flash.
"""
results = dict()
defaults = self.readDefaults(0)
results['FIODirection'] = defaults[4]
results['FIOState'] = defaults[5]
results['EIODirection'] = defaults[8]
results['EIOState'] = defaults[9]
results['CIODirection'] = defaults[12]
results['CIOState'] = defaults[13]
results['ConfigWriteMask'] = defaults[16]
results['NumOfTimersEnable'] = defaults[17]
results['CounterMask'] = defaults[18]
results['PinOffset'] = defaults[19]
defaults = self.readDefaults(1)
results['ClockSource'] = defaults[0]
results['Divisor'] = defaults[1]
results['TMR0Mode'] = defaults[16]
results['TMR0ValueL'] = defaults[17]
results['TMR0ValueH'] = defaults[18]
results['TMR1Mode'] = defaults[20]
results['TMR1ValueL'] = defaults[21]
results['TMR1ValueH'] = defaults[22]
results['TMR2Mode'] = defaults[24]
results['TMR2ValueL'] = defaults[25]
results['TMR2ValueH'] = defaults[26]
results['TMR3Mode'] = defaults[28]
results['TMR3ValueL'] = defaults[29]
results['TMR3ValueH'] = defaults[30]
defaults = self.readDefaults(2)
results['DAC0'] = struct.unpack( ">H", struct.pack("BB", *defaults[16:18]) )[0]
results['DAC1'] = struct.unpack( ">H", struct.pack("BB", *defaults[20:22]) )[0]
defaults = self.readDefaults(3)
for i in range(14):
results["AIN%sGainRes" % i] = defaults[i]
results["AIN%sOptions" % i] = defaults[i+16]
return results
def exportConfig(self):
"""
Name: U6.exportConfig( )
Args: None
Desc: Takes a configuration and puts it into a ConfigParser object.
"""
# Make a new configuration file
parser = ConfigParser.SafeConfigParser()
# Change optionxform so that options preserve their case.
parser.optionxform = str
# Local Id and name
section = "Identifiers"
parser.add_section(section)
parser.set(section, "Local ID", str(self.localId))
parser.set(section, "Name", str(self.getName()))
parser.set(section, "Device Type", str(self.devType))
# FIO Direction / State
section = "FIOs"
parser.add_section(section)
dirs, states = self.getFeedback( PortDirRead(), PortStateRead() )
for key, value in dirs.items():
parser.set(section, "%s Directions" % key, str(value))
for key, value in states.items():
parser.set(section, "%s States" % key, str(value))
# DACs
section = "DACs"
parser.add_section(section)
dac0 = self.readRegister(5000)
dac0 = max(dac0, 0)
dac0 = min(dac0, 5)
parser.set(section, "DAC0", "%0.2f" % dac0)
dac1 = self.readRegister(5002)
dac1 = max(dac1, 0)
dac1 = min(dac1, 5)
parser.set(section, "DAC1", "%0.2f" % dac1)
# Timer Clock Configuration
section = "Timer Clock Speed Configuration"
parser.add_section(section)
timerclockconfig = self.configTimerClock()
for key, value in timerclockconfig.items():
parser.set(section, key, str(value))
# Timers / Counters
section = "Timers And Counters"
parser.add_section(section)
ioconfig = self.configIO()
for key, value in ioconfig.items():
parser.set(section, key, str(value))
for i in range(ioconfig['NumberTimersEnabled']):
mode, value = self.readRegister(7100 + (2 * i), numReg = 2, format = ">HH")
parser.set(section, "Timer%s Mode" % i, str(mode))
parser.set(section, "Timer%s Value" % i, str(value))
return parser
def loadConfig(self, configParserObj):
"""
Name: U6.loadConfig( configParserObj )
Args: configParserObj, A Config Parser object to load in
Desc: Takes a configuration and updates the U6 to match it.
"""
parser = configParserObj
# Set Identifiers:
section = "Identifiers"
if parser.has_section(section):
if parser.has_option(section, "device type"):
if parser.getint(section, "device type") != self.devType:
raise Exception("Not a U6 Config file.")
if parser.has_option(section, "local id"):
self.configU6( LocalID = parser.getint(section, "local id"))
if parser.has_option(section, "name"):
self.setName( parser.get(section, "name") )
# Set FIOs:
section = "FIOs"
if parser.has_section(section):
fiodirs = 0
eiodirs = 0
ciodirs = 0
fiostates = 0
eiostates = 0
ciostates = 0
if parser.has_option(section, "fios directions"):
fiodirs = parser.getint(section, "fios directions")
if parser.has_option(section, "eios directions"):
eiodirs = parser.getint(section, "eios directions")
if parser.has_option(section, "cios directions"):
ciodirs = parser.getint(section, "cios directions")
if parser.has_option(section, "fios states"):
fiostates = parser.getint(section, "fios states")
if parser.has_option(section, "eios states"):
eiostates = parser.getint(section, "eios states")
if parser.has_option(section, "cios states"):
ciostates = parser.getint(section, "cios states")
self.getFeedback( PortStateWrite([fiostates, eiostates, ciostates]), PortDirWrite([fiodirs, eiodirs, ciodirs]) )
# Set DACs:
section = "DACs"
if parser.has_section(section):
if parser.has_option(section, "dac0"):
self.writeRegister(5000, parser.getfloat(section, "dac0"))
if parser.has_option(section, "dac1"):
self.writeRegister(5002, parser.getfloat(section, "dac1"))
# Set Timer Clock Configuration
section = "Timer Clock Speed Configuration"
if parser.has_section(section):
if parser.has_option(section, "timerclockbase") and parser.has_option(section, "timerclockdivisor"):
self.configTimerClock(TimerClockBase = parser.getint(section, "timerclockbase"), TimerClockDivisor = parser.getint(section, "timerclockdivisor"))
# Set Timers / Counters
section = "Timers And Counters"
if parser.has_section(section):
nte = None
c0e = None
c1e = None
cpo = None
if parser.has_option(section, "NumberTimersEnabled"):
nte = parser.getint(section, "NumberTimersEnabled")
if parser.has_option(section, "TimerCounterPinOffset"):
cpo = parser.getint(section, "TimerCounterPinOffset")
if parser.has_option(section, "Counter0Enabled"):
c0e = parser.getboolean(section, "Counter0Enabled")
if parser.has_option(section, "Counter1Enabled"):
c1e = parser.getboolean(section, "Counter1Enabled")
self.configIO(NumberTimersEnabled = nte, EnableCounter1 = c1e, EnableCounter0 = c0e, TimerCounterPinOffset = cpo)
mode = None
value = None
for i in range(4):
if parser.has_option(section, "timer%i mode" % i):
mode = parser.getint(section, "timer%i mode" % i)
if parser.has_option(section, "timer%i value" % i):
value = parser.getint(section, "timer%i value" % i)
self.getFeedback( TimerConfig(i, mode, value) )
class FeedbackCommand(object):
'''
The base FeedbackCommand class
Used to make Feedback easy. Make a list of these
and call getFeedback.
'''
readLen = 0
def handle(self, input):
return None
validChannels = range(144)
class AIN(FeedbackCommand):
'''
Analog Input Feedback command
AIN(PositiveChannel)
PositiveChannel : the positive channel to use
NOTE: This function kept for compatibility. Please use
the new AIN24 and AIN24AR.
returns 16-bit unsigned int sample
>>> d.getFeedback( u6.AIN( PositiveChannel ) )
[ 19238 ]
'''
def __init__(self, PositiveChannel):
if PositiveChannel not in validChannels:
raise LabJackException("Invalid Positive Channel specified")
self.positiveChannel = PositiveChannel
self.cmdBytes = [ 0x01, PositiveChannel, 0 ]
readLen = 2
def __repr__(self):
return "<u6.AIN( PositiveChannel = %s )>" % self.positiveChannel
def handle(self, input):
result = (input[1] << 8) + input[0]
return result
class AIN24(FeedbackCommand):
'''
Analog Input 24-bit Feedback command
ainCommand = AIN24(PositiveChannel, ResolutionIndex = 0, GainIndex = 0, SettlingFactor = 0, Differential = False)
See section 5.2.5.2 of the user's guide.
NOTE: If you use a gain index of 15 (autorange), you should be using
the AIN24AR command instead.
positiveChannel : The positive channel to use
resolutionIndex : 0=default, 1-8 for high-speed ADC,
9-12 for high-res ADC on U6-Pro.
gainIndex : 0=x1, 1=x10, 2=x100, 3=x1000, 15=autorange
settlingFactor : 0=5us, 1=10us, 2=100us, 3=1ms, 4=10ms
differential : If this bit is set, a differential reading is done where
the negative channel is positiveChannel+1
returns 24-bit unsigned int sample
>>> d.getFeedback( u6.AIN24(PositiveChannel, ResolutionIndex = 0,
GainIndex = 0, SettlingFactor = 0,
Differential = False ) )
[ 193847 ]
'''
def __init__(self, PositiveChannel, ResolutionIndex = 0, GainIndex = 0, SettlingFactor = 0, Differential = False):
if PositiveChannel not in validChannels:
raise LabJackException("Invalid Positive Channel specified")
self.positiveChannel = PositiveChannel
self.resolutionIndex = ResolutionIndex
self.gainIndex = GainIndex
self.settlingFactor = SettlingFactor
self.differential = Differential
byte2 = ( ResolutionIndex & 0xf )
byte2 = ( ( GainIndex & 0xf ) << 4 ) + byte2
byte3 = (int(Differential) << 7) + SettlingFactor
self.cmdBytes = [ 0x02, PositiveChannel, byte2, byte3 ]
def __repr__(self):
return "<u6.AIN24( PositiveChannel = %s, ResolutionIndex = %s, GainIndex = %s, SettlingFactor = %s, Differential = %s )>" % (self.positiveChannel, self.resolutionIndex, self.gainIndex, self.settlingFactor, self.differential)
readLen = 3
def handle(self, input):
#Put it all into an integer.
result = (input[2] << 16 ) + (input[1] << 8 ) + input[0]
return result
class AIN24AR(FeedbackCommand):
'''
Autorange Analog Input 24-bit Feedback command
ainARCommand = AIN24AR(0, ResolutionIndex = 0, GainIndex = 0, SettlingFactor = 0, Differential = False)
See section 5.2.5.3 of the user's guide
PositiveChannel : The positive channel to use
ResolutionIndex : 0=default, 1-8 for high-speed ADC,
9-13 for high-res ADC on U6-Pro.
GainIndex : 0=x1, 1=x10, 2=x100, 3=x1000, 15=autorange
SettlingFactor : 0=5us, 1=10us, 2=100us, 3=1ms, 4=10ms
Differential : If this bit is set, a differential reading is done where
the negative channel is positiveChannel+1
returns a dictionary:
{
'AIN' : < 24-bit binary reading >,
'ResolutionIndex' : < actual resolution setting used for the reading >,
'GainIndex' : < actual gain used for the reading >,
'Status' : < reserved for future use >
}
>>> d.getFeedback( u6.AIN24AR( PositiveChannel, ResolutionIndex = 0,
GainIndex = 0, SettlingFactor = 0,
Differential = False ) )
{ 'AIN' : 193847, 'ResolutionIndex' : 0, 'GainIndex' : 0, 'Status' : 0 }
'''
def __init__(self, PositiveChannel, ResolutionIndex = 0, GainIndex = 0, SettlingFactor = 0, Differential = False):
if PositiveChannel not in validChannels:
raise LabJackException("Invalid Positive Channel specified")
self.positiveChannel = PositiveChannel
self.resolutionIndex = ResolutionIndex
self.gainIndex = GainIndex
self.settlingFactor = SettlingFactor
self.differential = Differential
byte2 = ( ResolutionIndex & 0xf )
byte2 = ( ( GainIndex & 0xf ) << 4 ) + byte2
byte3 = (int(Differential) << 7) + SettlingFactor
self.cmdBytes = [ 0x03, PositiveChannel, byte2, byte3 ]
def __repr__(self):
return "<u6.AIN24AR( PositiveChannel = %s, ResolutionIndex = %s, GainIndex = %s, SettlingFactor = %s, Differential = %s )>" % (self.positiveChannel, self.resolutionIndex, self.gainIndex, self.settlingFactor, self.differential)
readLen = 5
def handle(self, input):
#Put it all into an integer.
result = (input[2] << 16 ) + (input[1] << 8 ) + input[0]
resolutionIndex = input[3] & 0xf
gainIndex = ( input[3] >> 4 ) & 0xf
status = input[4]
return { 'AIN' : result, 'ResolutionIndex' : resolutionIndex, 'GainIndex' : gainIndex, 'Status' : status }
class WaitShort(FeedbackCommand):
'''
WaitShort Feedback command
specify the number of 128us time increments to wait
>>> d.getFeedback( u6.WaitShort( Time ) )
[ None ]
'''
def __init__(self, Time):
self.time = Time % 256
self.cmdBytes = [ 5, Time % 256 ]
def __repr__(self):
return "<u6.WaitShort( Time = %s )>" % self.time
class WaitLong(FeedbackCommand):
'''
WaitLong Feedback command
specify the number of 32ms time increments to wait
>>> d.getFeedback( u6.WaitLog( Time ) )
[ None ]
'''
def __init__(self, Time):
self.time = Time
self.cmdBytes = [ 6, Time % 256 ]
def __repr__(self):
return "<u6.WaitLog( Time = %s )>" % self.time
class LED(FeedbackCommand):
'''
LED Toggle
specify whether the LED should be on or off by truth value
1 or True = On, 0 or False = Off
>>> d.getFeedback( u6.LED( State ) )
[ None ]
'''
def __init__(self, State):
self.state = State
self.cmdBytes = [ 9, int(bool(State)) ]
def __repr__(self):
return "<u6.LED( State = %s )>" % self.state
class BitStateRead(FeedbackCommand):
'''
BitStateRead Feedback command
read the state of a single bit of digital I/O. Only digital
lines return valid readings.
IONumber: 0-7=FIO, 8-15=EIO, 16-19=CIO
return 0 or 1
>>> d.getFeedback( u6.BitStateRead( IONumber ) )
[ 1 ]
'''
def __init__(self, IONumber):
self.ioNumber = IONumber
self.cmdBytes = [ 10, IONumber % 20 ]
def __repr__(self):
return "<u6.BitStateRead( IONumber = %s )>" % self.ioNumber
readLen = 1
def handle(self, input):
return int(bool(input[0]))
class BitStateWrite(FeedbackCommand):
'''
BitStateWrite Feedback command
write a single bit of digital I/O. The direction of the
specified line is forced to output.
IONumber: 0-7=FIO, 8-15=EIO, 16-19=CIO
State: 0 or 1
>>> d.getFeedback( u6.BitStateWrite( IONumber, State ) )
[ None ]
'''
def __init__(self, IONumber, State):
self.ioNumber = IONumber
self.state = State
self.cmdBytes = [ 11, (IONumber % 20) + (int(bool(State)) << 7) ]
def __repr__(self):
return "<u6.BitStateWrite( IONumber = %s, State = %s )>" % self.ioNumber
class BitDirRead(FeedbackCommand):
'''
Read the digital direction of one I/O
IONumber: 0-7=FIO, 8-15=EIO, 16-19=CIO
returns 1 = Output, 0 = Input
>>> d.getFeedback( u6.BitDirRead( IONumber ) )
[ 1 ]
'''
def __init__(self, IONumber):
self.ioNumber = IONumber
self.cmdBytes = [ 12, IONumber % 20 ]
def __repr__(self):
return "<u6.BitDirRead( IONumber = %s )>" % self.ioNumber
readLen = 1
def handle(self, input):
return int(bool(input[0]))
class BitDirWrite(FeedbackCommand):
'''
BitDirWrite Feedback command
Set the digital direction of one I/O
IONumber: 0-7=FIO, 8-15=EIO, 16-19=CIO
Direction: 1 = Output, 0 = Input
>>> d.getFeedback( u6.BitDirWrite( IONumber, Direction ) )
[ None ]
'''
def __init__(self, IONumber, Direction):
self.ioNumber = IONumber
self.direction = Direction
self.cmdBytes = [ 13, (IONumber % 20) + (int(bool(Direction)) << 7) ]
def __repr__(self):
return "<u6.BitDirWrite( IONumber = %s, Direction = %s )>" % (self.ioNumber, self.direction)
class PortStateRead(FeedbackCommand):
"""
PortStateRead Feedback command
Reads the state of all digital I/O.
>>> d.getFeedback( u6.PortStateRead() )
[ { 'FIO' : 10, 'EIO' : 0, 'CIO' : 0 } ]
"""
def __init__(self):
self.cmdBytes = [ 26 ]
def __repr__(self):
return "<u6.PortStateRead()>"
readLen = 3
def handle(self, input):
return {'FIO' : input[0], 'EIO' : input[1], 'CIO' : input[2] }
class PortStateWrite(FeedbackCommand):
"""
PortStateWrite Feedback command
State: A list of 3 bytes representing FIO, EIO, CIO
WriteMask: A list of 3 bytes, representing which to update.
The Default is all ones.
>>> d.getFeedback( u6.PortStateWrite( State,
WriteMask = [ 0xff, 0xff, 0xff] ) )
[ None ]
"""
def __init__(self, State, WriteMask = [ 0xff, 0xff, 0xff]):
self.state = State
self.writeMask = WriteMask
self.cmdBytes = [ 27 ] + WriteMask + State
def __repr__(self):
return "<u6.PortStateWrite( State = %s, WriteMask = %s )>" % (self.state, self.writeMask)
class PortDirRead(FeedbackCommand):
"""
PortDirRead Feedback command
Reads the direction of all digital I/O.
>>> d.getFeedback( u6.PortDirRead() )
[ { 'FIO' : 10, 'EIO' : 0, 'CIO' : 0 } ]
"""
def __init__(self):
self.cmdBytes = [ 28 ]
def __repr__(self):
return "<u6.PortDirRead()>"
readLen = 3
def handle(self, input):
return {'FIO' : input[0], 'EIO' : input[1], 'CIO' : input[2] }
class PortDirWrite(FeedbackCommand):
"""
PortDirWrite Feedback command
Direction: A list of 3 bytes representing FIO, EIO, CIO
WriteMask: A list of 3 bytes, representing which to update. Default is all ones.
>>> d.getFeedback( u6.PortDirWrite( Direction,
WriteMask = [ 0xff, 0xff, 0xff] ) )
[ None ]
"""
def __init__(self, Direction, WriteMask = [ 0xff, 0xff, 0xff]):
self.direction = Direction
self.writeMask = WriteMask
self.cmdBytes = [ 29 ] + WriteMask + Direction
def __repr__(self):
return "<u6.PortDirWrite( Direction = %s, WriteMask = %s )>" % (self.direction, self.writeMask)
class DAC8(FeedbackCommand):
'''
8-bit DAC Feedback command
Controls a single analog output
Dac: 0 or 1
Value: 0-255
>>> d.getFeedback( u6.DAC8( Dac, Value ) )
[ None ]
'''
def __init__(self, Dac, Value):
self.dac = Dac
self.value = Value % 256
self.cmdBytes = [ 34 + (Dac % 2), Value % 256 ]
def __repr__(self):
return "<u6.DAC8( Dac = %s, Value = %s )>" % (self.dac, self.value)
class DAC0_8(DAC8):
"""
8-bit DAC Feedback command for DAC0
Controls DAC0 in 8-bit mode.
Value: 0-255
>>> d.getFeedback( u6.DAC0_8( Value ) )
[ None ]
"""
def __init__(self, Value):
DAC8.__init__(self, 0, Value)
def __repr__(self):
return "<u6.DAC0_8( Value = %s )>" % self.value
class DAC1_8(DAC8):
"""
8-bit DAC Feedback command for DAC1
Controls DAC1 in 8-bit mode.
Value: 0-255
>>> d.getFeedback( u6.DAC1_8( Value ) )
[ None ]
"""
def __init__(self, Value):
DAC8.__init__(self, 1, Value)
def __repr__(self):
return "<u6.DAC1_8( Value = %s )>" % self.value
class DAC16(FeedbackCommand):
'''
16-bit DAC Feedback command
Controls a single analog output
Dac: 0 or 1
Value: 0-65535
>>> d.getFeedback( u6.DAC16( Dac, Value ) )
[ None ]
'''
def __init__(self, Dac, Value):
self.dac = Dac
self.value = Value
self.cmdBytes = [ 38 + (Dac % 2), Value % 256, Value >> 8 ]
def __repr__(self):
return "<u6.DAC8( Dac = %s, Value = %s )>" % (self.dac, self.value)
class DAC0_16(DAC16):
"""
16-bit DAC Feedback command for DAC0
Controls DAC0 in 16-bit mode.
Value: 0-65535
>>> d.getFeedback( u6.DAC0_16( Value ) )
[ None ]
"""
def __init__(self, Value):
DAC16.__init__(self, 0, Value)
def __repr__(self):
return "<u6.DAC0_16( Value = %s )>" % self.value
class DAC1_16(DAC16):
"""
16-bit DAC Feedback command for DAC1
Controls DAC1 in 16-bit mode.
Value: 0-65535
>>> d.getFeedback( u6.DAC1_16( Value ) )
[ None ]
"""
def __init__(self, Value):
DAC16.__init__(self, 1, Value)
def __repr__(self):
return "<u6.DAC1_16( Value = %s )>" % self.value
class Timer(FeedbackCommand):
"""
For reading the value of the Timer. It provides the ability to update/reset
a given timer, and read the timer value.
( Section 5.2.5.17 of the User's Guide)
timer: Either 0 or 1 for counter0 or counter1
UpdateReset: Set True if you want to update the value
Value: Only updated if the UpdateReset bit is 1. The meaning of this
parameter varies with the timer mode.
Mode: Set to the timer mode to handle any special processing. See classes
QuadratureInputTimer and TimerStopInput1.
Returns an unsigned integer of the timer value, unless Mode has been
specified and there are special return values. See Section 2.9.1 for
expected return values.
>>> d.getFeedback( u6.Timer( timer, UpdateReset = False, Value = 0 \
... , Mode = None ) )
[ 12314 ]
"""
def __init__(self, timer, UpdateReset = False, Value=0, Mode = None):
if timer != 0 and timer != 1:
raise LabJackException("Timer should be either 0 or 1.")
if UpdateReset and Value == None:
raise LabJackException("UpdateReset set but no value.")
self.timer = timer
self.updateReset = UpdateReset
self.value = Value
self.mode = Mode
self.cmdBytes = [ (42 + (2*timer)), UpdateReset, Value % 256, Value >> 8 ]
readLen = 4
def __repr__(self):
return "<u6.Timer( timer = %s, UpdateReset = %s, Value = %s, Mode = %s )>" % (self.timer, self.updateReset, self.value, self.mode)
def handle(self, input):
inStr = struct.pack('B' * len(input), *input)
if self.mode == 8:
return struct.unpack('<i', inStr )[0]
elif self.mode == 9:
maxCount, current = struct.unpack('<HH', inStr )
return current, maxCount
else:
return struct.unpack('<I', inStr )[0]
class Timer0(Timer):
"""
For reading the value of the Timer0. It provides the ability to
update/reset Timer0, and read the timer value.
( Section 5.2.5.17 of the User's Guide)
UpdateReset: Set True if you want to update the value
Value: Only updated if the UpdateReset bit is 1. The meaning of this
parameter varies with the timer mode.
Mode: Set to the timer mode to handle any special processing. See classes
QuadratureInputTimer and TimerStopInput1.
>>> d.getFeedback( u6.Timer0( UpdateReset = False, Value = 0, \
... Mode = None ) )
[ 12314 ]
"""
def __init__(self, UpdateReset = False, Value = 0, Mode = None):
Timer.__init__(self, 0, UpdateReset, Value, Mode)
def __repr__(self):
return "<u6.Timer0( UpdateReset = %s, Value = %s, Mode = %s )>" % (self.updateReset, self.value, self.mode)
class Timer1(Timer):
"""
For reading the value of the Timer1. It provides the ability to
update/reset Timer1, and read the timer value.
( Section 5.2.5.17 of the User's Guide)
UpdateReset: Set True if you want to update the value
Value: Only updated if the UpdateReset bit is 1. The meaning of this
parameter varies with the timer mode.
Mode: Set to the timer mode to handle any special processing. See classes
QuadratureInputTimer and TimerStopInput1.
>>> d.getFeedback( u6.Timer1( UpdateReset = False, Value = 0, \
... Mode = None ) )
[ 12314 ]
"""
def __init__(self, UpdateReset = False, Value = 0, Mode = None):
Timer.__init__(self, 1, UpdateReset, Value, Mode)
def __repr__(self):
return "<u6.Timer1( UpdateReset = %s, Value = %s, Mode = %s )>" % (self.updateReset, self.value, self.mode)
class QuadratureInputTimer(Timer):
"""
For reading Quadrature input timers. They are special because their values
are signed.
( Section 2.9.1.8 of the User's Guide)
Args:
UpdateReset: Set True if you want to reset the counter.
Value: Set to 0, and UpdateReset to True to reset the counter.
Returns a signed integer.
>>> # Setup the two timers to be quadrature
>>> d.getFeedback( u6.Timer0Config( 8 ), u6.Timer1Config( 8 ) )
[None, None]
>>> # Read the value
>>> d.getFeedback( u6.QuadratureInputTimer() )
[-21]
"""
def __init__(self, UpdateReset = False, Value = 0):
Timer.__init__(self, 0, UpdateReset, Value, Mode = 8)
def __repr__(self):
return "<u6.QuadratureInputTimer( UpdateReset = %s, Value = %s )>" % (self.updateReset, self.value)
class TimerStopInput1(Timer1):
"""
For reading a stop input timer. They are special because the value returns
the current edge count and the stop value.
( Section 2.9.1.9 of the User's Guide)
Args:
UpdateReset: Set True if you want to update the value.
Value: The stop value. Only updated if the UpdateReset bit is 1.
Returns a tuple where the first value is current edge count, and the second
value is the stop value.
>>> # Setup the timer to be Stop Input
>>> d.getFeedback( u6.Timer0Config( 9, Value = 30 ) )
[None]
>>> # Read the timer
>>> d.getFeedback( u6.TimerStopInput1() )
[(0, 30)]
"""
def __init__(self, UpdateReset = False, Value = 0):
Timer.__init__(self, 1, UpdateReset, Value, Mode = 9)
def __repr__(self):
return "<u6.TimerStopInput1( UpdateReset = %s, Value = %s )>" % (self.updateReset, self.value)
class TimerConfig(FeedbackCommand):
"""
This IOType configures a particular timer.
timer = # of the timer to configure
TimerMode = See Section 2.9 for more information about the available modes.
Value = The meaning of this parameter varies with the timer mode.
>>> d.getFeedback( u6.TimerConfig( timer, TimerMode, Value = 0 ) )
[ None ]
"""
def __init__(self, timer, TimerMode, Value=0):
'''Creates command bytes for configureing a Timer'''
#Conditions come from pages 33-34 of user's guide
if timer not in range(4):
raise LabJackException("Timer should be either 0-3.")
if TimerMode > 14 or TimerMode < 0:
raise LabJackException("Invalid Timer Mode.")
self.timer = timer
self.timerMode = TimerMode
self.value = Value
self.cmdBytes = [43 + (timer * 2), TimerMode, Value % 256, Value >> 8]
def __repr__(self):
return "<u6.TimerConfig( timer = %s, TimerMode = %s, Value = %s )>" % (self.timer, self.timerMode, self.value)
class Timer0Config(TimerConfig):
"""
This IOType configures Timer0.
TimerMode = See Section 2.9 for more information about the available modes.
Value = The meaning of this parameter varies with the timer mode.
>>> d.getFeedback( u6.Timer0Config( TimerMode, Value = 0 ) )
[ None ]
"""
def __init__(self, TimerMode, Value = 0):
TimerConfig.__init__(self, 0, TimerMode, Value)
def __repr__(self):
return "<u6.Timer0Config( TimerMode = %s, Value = %s )>" % (self.timerMode, self.value)
class Timer1Config(TimerConfig):
"""
This IOType configures Timer1.
TimerMode = See Section 2.9 for more information about the available modes.
Value = The meaning of this parameter varies with the timer mode.
>>> d.getFeedback( u6.Timer1Config( TimerMode, Value = 0 ) )
[ None ]
"""
def __init__(self, TimerMode, Value = 0):
TimerConfig.__init__(self, 1, TimerMode, Value)
def __repr__(self):
return "<u6.Timer1Config( TimerMode = %s, Value = %s )>" % (self.timerMode, self.value)
class Counter(FeedbackCommand):
'''
Counter Feedback command
Reads a hardware counter, optionally resetting it
counter: 0 or 1
Reset: True ( or 1 ) = Reset, False ( or 0 ) = Don't Reset
Returns the current count from the counter if enabled. If reset,
this is the value before the reset.
>>> d.getFeedback( u6.Counter( counter, Reset = False ) )
[ 2183 ]
'''
def __init__(self, counter, Reset):
self.counter = counter
self.reset = Reset
self.cmdBytes = [ 54 + (counter % 2), int(bool(Reset))]
def __repr__(self):
return "<u6.Counter( counter = %s, Reset = %s )>" % (self.counter, self.reset)
readLen = 4
def handle(self, input):
inStr = ''.join([chr(x) for x in input])
return struct.unpack('<I', inStr )[0]
class Counter0(Counter):
'''
Counter0 Feedback command
Reads hardware counter0, optionally resetting it
Reset: True ( or 1 ) = Reset, False ( or 0 ) = Don't Reset
Returns the current count from the counter if enabled. If reset,
this is the value before the reset.
>>> d.getFeedback( u6.Counter0( Reset = False ) )
[ 2183 ]
'''
def __init__(self, Reset = False):
Counter.__init__(self, 0, Reset)
def __repr__(self):
return "<u6.Counter0( Reset = %s )>" % self.reset
class Counter1(Counter):
'''
Counter1 Feedback command
Reads hardware counter1, optionally resetting it
Reset: True ( or 1 ) = Reset, False ( or 0 ) = Don't Reset
Returns the current count from the counter if enabled. If reset,
this is the value before the reset.
>>> d.getFeedback( u6.Counter1( Reset = False ) )
[ 2183 ]
'''
def __init__(self, Reset = False):
Counter.__init__(self, 1, Reset)
def __repr__(self):
return "<u6.Counter1( Reset = %s )>" % self.reset
class DSP(FeedbackCommand):
'''
DSP Feedback command
Acquires 1000 samples from the specified AIN at 50us intervals and performs
the specified analysis on the acquired data.
AcquireNewData: True, acquire new data; False, operate on existing data
DSPAnalysis: 1, True RMS; 2, DC Offset; 3, Peak To Peak; 4, Period (ms)
PLine: Positive Channel
Gain: The gain you would like to use
Resolution: The resolution index to use
SettlingFactor: The SettlingFactor to use
Differential: True, do differential readings; False, single-ended readings
See section 5.2.5.20 of the U3 User's Guide
(http://labjack.com/support/u6/users-guide/5.2.5.20)
>>> d.getFeedback( u6.DSP( PLine, Resolution = 0, Gain = 0,
SettlingFactor = 0, Differential = False,
DSPAnalysis = 1, AcquireNewData = True) )
[ 2183 ]
'''
def __init__(self, PLine, Resolution = 0, Gain = 0, SettlingFactor = 0, Differential = False, DSPAnalysis = 1, AcquireNewData = True):
self.pline = PLine
self.resolution = Resolution
self.gain = Gain
self.settlingFactor = SettlingFactor
self.differential = Differential
self.dspAnalysis = DSPAnalysis
self.acquireNewData = AcquireNewData
byte1 = DSPAnalysis + ( int(AcquireNewData) << 7 )
byte4 = ( Gain << 4 ) + Resolution
byte5 = ( int(Differential) << 7 ) + SettlingFactor
self.cmdBytes = [ 62, byte1, PLine, 0, byte4, byte5, 0, 0 ]
def __repr__(self):
return "<u6.DSP( PLine = %s, Resolution = %s, Gain = %s, SettlingFactor = %s, Differential = %s, DSPAnalysis = %s, AcquireNewData = %s )>" % (self.pline, self.resolution, self.gain, self.settlingFactor, self.differential, self.dspAnalysis, self.acquireNewData)
readLen = 4
def handle(self, input):
inStr = ''.join([chr(x) for x in input])
return struct.unpack('<I', inStr )[0]
| 83,591 | 35.344348 | 305 | py |
SDR | SDR-master/DataReadout/ReadoutControls/lib/LabJackPython-8-26-2011/build/lib/u3.py | """
Name: u3.py
Desc: Defines the U3 class, which makes working with a U3 much easier. All of
the low-level functions for the U3 are implemented as functions of the U3
class. There are also a handful additional functions which improve upon
the interface provided by the low-level functions.
To learn about the low-level functions, please see Section 5.2 of the U3 User's Guide:
http://labjack.com/support/u3/users-guide/5.2
Section Number Mapping:
1 = Object Functions
2 = User's Guide Functions
3 = Convenience Functions
4 = Private Helper Functions
"""
from LabJackPython import *
import struct, ConfigParser
FIO0, FIO1, FIO2, FIO3, FIO4, FIO5, FIO6, FIO7, \
EIO0, EIO1, EIO2, EIO3, EIO4, EIO5, EIO6, EIO7, \
CIO0, CIO1, CIO2, CIO3 = range(20)
def openAllU3():
"""
A helpful function which will open all the connected U3s. Returns a
dictionary where the keys are the serialNumber, and the value is the device
object.
"""
returnDict = dict()
for i in range(deviceCount(3)):
d = U3(firstFound = False, devNumber = i+1)
returnDict[str(d.serialNumber)] = d
return returnDict
class U3(Device):
"""
U3 Class for all U3 specific low-level commands.
Example:
>>> import u3
>>> d = u3.U3()
>>> print d.configU3()
{'SerialNumber': 320032102, ... , 'FirmwareVersion': '1.26'}
"""
def __init__(self, debug = False, autoOpen = True, **kargs):
"""
Name: U3.__init__(debug = False, autoOpen = True, **openArgs)
Args: debug, enables debug output
autoOpen, if true, the class will try to open a U3 using openArgs
**openArgs, the arguments to pass to the open call. See U3.open()
Desc: Instantiates a new U3 object. If autoOpen == True, then it will
also open a U3.
Examples:
Simplest:
>>> import u3
>>> d = u3.U3()
For debug output:
>>> import u3
>>> d = u3.U3(debug = True)
To open a U3 with Local ID = 2:
>>> import u3
>>> d = u3.U3(localId = 2)
"""
Device.__init__(self, None, devType = 3)
self.debug = debug
self.calData = None
self.ledState = True
if autoOpen:
self.open(**kargs)
__init__.section = 1
def open(self, firstFound = True, serial = None, localId = None, devNumber = None, handleOnly = False, LJSocket = None):
"""
Name: U3.open(firstFound = True, localId = None, devNumber = None,
handleOnly = False, LJSocket = None)
Args: firstFound, If True, use the first found U3
serial, open a U3 with the given serial number
localId, open a U3 with the given local id.
devNumber, open a U3 with the given devNumber
handleOnly, if True, LabJackPython will only open a handle
LJSocket, set to "<ip>:<port>" to connect to LJSocket
Desc: Use to open a U3. If handleOnly is false, it will call configU3
and save the resulting information to the object. This allows the
use of d.serialNumber, d.firmwareVersion, etc.
Examples:
Simplest:
>>> import u3
>>> d = u3.U3(autoOpen = False)
>>> d.open()
Handle-only, with a serial number = 320095789:
>>> import u3
>>> d = u3.U3(autoOpen = False)
>>> d.open(handleOnly = True, serial = 320095789)
Using LJSocket:
>>> import u3
>>> d = u3.U3(autoOpen = False)
>>> d.open(LJSocket = "localhost:6000")
"""
Device.open(self, 3, firstFound = firstFound, serial = serial, localId = localId, devNumber = devNumber, handleOnly = handleOnly, LJSocket = LJSocket )
open.section = 1
def configU3(self, LocalID = None, TimerCounterConfig = None, FIOAnalog = None, FIODirection = None, FIOState = None, EIOAnalog = None, EIODirection = None, EIOState = None, CIODirection = None, CIOState = None, DAC1Enable = None, DAC0 = None, DAC1 = None, TimerClockConfig = None, TimerClockDivisor = None, CompatibilityOptions = None ):
"""
Name: U3.configU3(LocalID = None, TimerCounterConfig = None, FIOAnalog = None, FIODirection = None, FIOState = None, EIOAnalog = None, EIODirection = None, EIOState = None, CIODirection = None, CIOState = None, DAC1Enable = None, DAC0 = None, DAC1 = None, TimerClockConfig = None, TimerClockDivisor = None, CompatibilityOptions = None)
Args: See section 5.2.2 of the users guide.
Desc: Sends the low-level configU3 command. Also saves relevant
information to the U3 object for later use.
Example:
Simplest:
>>> import u3
>>> d = u3.U3()
>>> print d.configU3()
{
'LocalID': 1,
'SerialNumber': 320035782,
'DeviceName': 'U3-LV',
'FIODirection': 0,
'FirmwareVersion': '1.24',
... ,
'ProductID': 3
}
Configure all FIOs and EI0s to analog on boot:
>>> import u3
>>> d = u3.U3()
>>> print d.configU3( FIOAnalog = 255, EIOAnalog = 255)
{
'FIOAnalog': 255,
'EIOAnalog': 255,
... ,
'ProductID': 3
}
"""
writeMask = 0
if FIOAnalog is not None or FIODirection is not None or FIOState is not None or EIOAnalog is not None or EIODirection is not None or EIOState is not None or CIODirection is not None or CIOState is not None:
writeMask |= 2
if DAC1Enable is not None or DAC0 is not None or DAC1 is not None:
writeMask |= 4
if LocalID is not None:
writeMask |= 8
command = [ 0 ] * 26
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x0A
command[3] = 0x08
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = writeMask
#command[7] = WriteMask1
if LocalID is not None:
command[8] = LocalID
if TimerCounterConfig is not None:
command[9] = TimerCounterConfig
if FIOAnalog is not None:
command[10] = FIOAnalog
if FIODirection is not None:
command[11] = FIODirection
if FIOState is not None:
command[12] = FIOState
if EIOAnalog is not None:
command[13] = EIOAnalog
if EIODirection is not None:
command[14] = EIODirection
if EIOState is not None:
command[15] = EIOState
if CIODirection is not None:
command[16] = CIODirection
if CIOState is not None:
command[17] = CIOState
if DAC1Enable is not None:
command[18] = DAC1Enable
if DAC0 is not None:
command[19] = DAC0
if DAC1 is not None:
command[20] = DAC1
if TimerClockConfig is not None:
command[21] = TimerClockConfig
if TimerClockDivisor is not None:
command[22] = TimerClockDivisor
if CompatibilityOptions is not None:
command[23] = CompatibilityOptions
result = self._writeRead(command, 38, [0xF8, 0x10, 0x08])
# Error-free, time to parse the response
self.firmwareVersion = "%d.%02d" % (result[10], result[9])
self.bootloaderVersion = "%d.%02d" % (result[12], result[11])
self.hardwareVersion = "%d.%02d" % (result[14], result[13])
self.serialNumber = struct.unpack("<I", struct.pack(">BBBB", *result[15:19]))[0]
self.productId = struct.unpack("<H", struct.pack(">BB", *result[19:21]))[0]
self.localId = result[21]
self.timerCounterMask = result[22]
self.fioAnalog = result[23]
self.fioDirection = result[24]
self.fioState = result[25]
self.eioAnalog = result[26]
self.eioDirection = result[27]
self.eioState = result[28]
self.cioDirection = result[29]
self.cioState = result[30]
self.dac1Enable = result[31]
self.dac0 = result[32]
self.dac1 = result[33]
self.timerClockConfig = result[34]
self.timerClockDivisor = result[35]
if result[35] == 0:
self.timerClockDivisor = 256
self.compatibilityOptions = result[36]
self.versionInfo = result[37]
self.deviceName = 'U3'
if self.versionInfo == 1:
self.deviceName += 'B'
elif self.versionInfo == 2:
self.deviceName += '-LV'
elif self.versionInfo == 18:
self.deviceName += '-HV'
return { 'FirmwareVersion' : self.firmwareVersion, 'BootloaderVersion' : self.bootloaderVersion, 'HardwareVersion' : self.hardwareVersion, 'SerialNumber' : self.serialNumber, 'ProductID' : self.productId, 'LocalID' : self.localId, 'TimerCounterMask' : self.timerCounterMask, 'FIOAnalog' : self.fioAnalog, 'FIODirection' : self.fioDirection, 'FIOState' : self.fioState, 'EIOAnalog' : self.eioAnalog, 'EIODirection' : self.eioDirection, 'EIOState' : self.eioState, 'CIODirection' : self.cioDirection, 'CIOState' : self.cioState, 'DAC1Enable' : self.dac1Enable, 'DAC0' : self.dac0, 'DAC1' : self.dac1, 'TimerClockConfig' : self.timerClockConfig, 'TimerClockDivisor' : self.timerClockDivisor, 'CompatibilityOptions' : self.compatibilityOptions, 'VersionInfo' : self.versionInfo, 'DeviceName' : self.deviceName }
configU3.section = 2
def configIO(self, TimerCounterPinOffset = None, EnableCounter1 = None, EnableCounter0 = None, NumberOfTimersEnabled = None, FIOAnalog = None, EIOAnalog = None, EnableUART = None):
"""
Name: U3.configIO(TimerCounterPinOffset = 4, EnableCounter1 = None, EnableCounter0 = None, NumberOfTimersEnabled = None, FIOAnalog = None, EIOAnalog = None, EnableUART = None)
Args: See section 5.2.3 of the user's guide.
Desc: The configIO command.
Examples:
Simplest:
>>> import u3
>>> d = u3.U3()
>>> print d.configIO()
{
'NumberOfTimersEnabled': 0,
'TimerCounterPinOffset': 4,
'DAC1Enable': 0,
'FIOAnalog': 239,
'EIOAnalog': 0,
'TimerCounterConfig': 64,
'EnableCounter1': False,
'EnableCounter0': False
}
Set all FIOs and EIOs to digital (until power cycle):
>>> import u3
>>> d = u3.U3()
>>> print d.configIO(FIOAnalog = 0, EIOAnalog = 0)
{
'NumberOfTimersEnabled': 0,
'TimerCounterPinOffset': 4,
'DAC1Enable': 0,
'FIOAnalog': 0,
'EIOAnalog': 0,
'TimerCounterConfig': 64,
'EnableCounter1': False,
'EnableCounter0': False
}
"""
writeMask = 0
if EIOAnalog is not None:
writeMask |= 1
writeMask |= 8
if FIOAnalog is not None:
writeMask |= 1
writeMask |= 4
if EnableUART is not None:
writeMask |= 1
writeMask |= (1 << 5)
if TimerCounterPinOffset is not None or EnableCounter1 is not None or EnableCounter0 is not None or NumberOfTimersEnabled is not None :
writeMask |= 1
command = [ 0 ] * 12
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x03
command[3] = 0x0B
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = writeMask
#command[7] = Reserved
command[8] = 0
if EnableUART is not None:
command[9] = int(EnableUART) << 2
if TimerCounterPinOffset is None:
command[8] |= ( 4 & 15 ) << 4
else:
command[8] |= ( TimerCounterPinOffset & 15 ) << 4
if EnableCounter1 is not None:
command[8] |= 1 << 3
if EnableCounter0 is not None:
command[8] |= 1 << 2
if NumberOfTimersEnabled is not None:
command[8] |= ( NumberOfTimersEnabled & 3 )
if FIOAnalog is not None:
command[10] = FIOAnalog
if EIOAnalog is not None:
command[11] = EIOAnalog
result = self._writeRead(command, 12, [0xF8, 0x03, 0x0B])
self.timerCounterConfig = result[8]
self.numberTimersEnabled = self.timerCounterConfig & 3
self.counter0Enabled = bool( (self.timerCounterConfig >> 2) & 1 )
self.counter1Enabled = bool( (self.timerCounterConfig >> 3) & 1 )
self.timerCounterPinOffset = ( self.timerCounterConfig >> 4 )
self.dac1Enable = result[9]
self.fioAnalog = result[10]
self.eioAnalog = result[11]
return { 'TimerCounterConfig' : self.timerCounterConfig, 'DAC1Enable' : self.dac1Enable, 'FIOAnalog' : self.fioAnalog, 'EIOAnalog' : self.eioAnalog, 'NumberOfTimersEnabled' : self.numberTimersEnabled, 'EnableCounter0' : self.counter0Enabled, 'EnableCounter1' : self.counter1Enabled, 'TimerCounterPinOffset' : self.timerCounterPinOffset }
configIO.section = 2
def configTimerClock(self, TimerClockBase = None, TimerClockDivisor = None):
"""
Name: U3.configTimerClock(TimerClockBase = None, TimerClockDivisor = None)
Args: TimeClockBase, the base for the timer clock.
TimerClockDivisor, the divisor for the clock.
Desc: Writes and reads the time clock configuration. See section 5.2.4
of the user's guide.
Note: TimerClockBase and TimerClockDivisor must be set at the same time.
"""
command = [ 0 ] * 10
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x02
command[3] = 0x0A
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
#command[6] = Reserved
#command[7] = Reserved
if TimerClockBase is not None:
command[8] = ( 1 << 7 ) + ( TimerClockBase & 7 )
if TimerClockDivisor is not None:
command[9] = TimerClockDivisor
elif TimerClockDivisor is not None:
raise LabJackException("You can't set just the divisor, must set both.")
result = self._writeRead(command, 10, [0xf8, 0x02, 0x0A])
self.timerClockBase = ( result[8] & 7 )
self.timerClockDivisor = result[9]
return { 'TimerClockBase' : self.timerClockBase, 'TimerClockDivisor' : self.timerClockDivisor }
configTimerClock.section = 2
def toggleLED(self):
"""
Name: U3.toggleLED()
Args: None
Desc: Toggles the state LED on and off.
Example:
>>> import u3
>>> d = u3.U3()
>>> d.toggleLED()
"""
self.getFeedback( LED( not self.ledState ) )
self.ledState = not self.ledState
toggleLED.section = 3
def setFIOState(self, fioNum, state = 1):
"""
Name: U3.setFIOState(fioNum, state = 1)
Args: fioNum, which FIO to change
state, 1 = High, 0 = Low
Desc: A convenience function to set the state of an FIO. Will also
set the direction to output.
Example:
>>> import u3
>>> d = u3.U3()
>>> d.setFIOState(4, state = 1)
"""
self.getFeedback(BitDirWrite(fioNum, 1), BitStateWrite(fioNum, state))
setFIOState.section = 3
def getFIOState(self, fioNum):
"""
Name: U3.getFIOState(fioNum)
Args: fioNum, which FIO to read
Desc: A convenience function to read the state of an FIO.
Example:
>>> import u3
>>> d = u3.U3()
>>> print d.getFIOState(4)
1
"""
return self.getFeedback(BitStateRead(fioNum))[0]
getFIOState.section = 3
def getTemperature(self):
"""
Name: U3.getTemperature()
Args: None
Desc: Reads the internal temperature sensor on the U3. Returns the
temperature in Kelvin.
"""
# Get the calibration data first, otherwise the conversion is way off (10 degC on my U3)
if self.calData is None:
self.getCalibrationData()
bits, = self.getFeedback( AIN(30, 31) )
return self.binaryToCalibratedAnalogTemperature(bits)
def getAIN(self, posChannel, negChannel = 31, longSettle=False, quickSample=False):
"""
Name: U3.getAIN(posChannel, negChannel = 31, longSettle=False,
quickSample=False)
Args: posChannel, the positive channel to read from.
negChannel, the negitive channel to read from.
longSettle, set to True for longSettle
quickSample, set to True for quickSample
Desc: A convenience function to read an AIN.
Example:
>>> import u3
>>> d = u3.U3()
>>> print d.getAIN( 0 )
0.0501680038869
"""
isSpecial = False
if negChannel == 32:
isSpecial = True
negChannel = 30
bits = self.getFeedback(AIN(posChannel, negChannel, longSettle, quickSample))[0]
singleEnded = True
if negChannel != 31:
singleEnded = False
lvChannel = True
try:
if self.deviceName.endswith("-HV") and posChannel < 4:
lvChannel = False
except AttributeError:
pass
if isSpecial:
negChannel = 32
return self.binaryToCalibratedAnalogVoltage(bits, isLowVoltage = lvChannel, isSingleEnded = singleEnded, isSpecialSetting = isSpecial, channelNumber = posChannel)
getAIN.section = 3
def configAnalog(self, *args):
"""
Convenience method to configIO() that adds the given input numbers
in the range FIO0-EIO7 (0-15) to the analog team. That is, it adds
the given bit positions to those already set in the FIOAnalog
and EIOAnalog bitfields.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.configIO()
Sent: [0x47, 0xf8, 0x3, 0xb, 0x40, 0x0, 0x0, 0x0, 0x40, 0x0, 0x0, 0x0]
Result: [0x56, 0xf8, 0x3, 0xb, 0x4f, 0x0, 0x0, 0x0, 0x40, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 0, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 64, 'EnableCounter1': False, 'EnableCounter0': False}
>>> d.configAnalog(u3.FIO4, u3.FIO5)
Sent: [0x47, 0xf8, 0x3, 0xb, 0x40, 0x0, 0x0, 0x0, 0x40, 0x0, 0x0, 0x0]
Result: [0x56, 0xf8, 0x3, 0xb, 0x4f, 0x0, 0x0, 0x0, 0x40, 0x0, 0xf, 0x0]
Sent: [0x93, 0xf8, 0x3, 0xb, 0x8c, 0x0, 0xd, 0x0, 0x40, 0x0, 0x3f, 0x0]
Result: [0x86, 0xf8, 0x3, 0xb, 0x7f, 0x0, 0x0, 0x0, 0x40, 0x0, 0x3f, 0x0]
{'NumberOfTimersEnabled': 0, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 63, 'EIOAnalog': 0, 'TimerCounterConfig': 64, 'EnableCounter1': False, 'EnableCounter0': False}
"""
configIODict = self.configIO()
# Without args, return the same as configIO()
if len(args) == 0:
return configIODict
FIOAnalog, EIOAnalog = configIODict['FIOAnalog'], configIODict['EIOAnalog']
#
for i in args:
if i > EIO7:
pass # Invalid. Must be in the range FIO0-EIO7.
elif i < EIO0:
FIOAnalog |= 2**i
else:
EIOAnalog |= 2**(i-EIO0) # Start the EIO counting at 0, not 8
return self.configIO(FIOAnalog = FIOAnalog, EIOAnalog = EIOAnalog)
def configDigital(self, *args):
"""
The converse of configAnalog(). The convenience method to configIO,
adds the given input numbers in the range FIO0-EIO7 (0-15) to the
digital team. That is, it removes the given bit positions from those
already set in the FIOAnalog and EIOAnalog bitfields.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.configIO()
Sent: [0x47, 0xf8, 0x3, 0xb, 0x40, 0x0, 0x0, 0x0, 0x40, 0x0, 0x0, 0x0]
Result: [0x56, 0xf8, 0x3, 0xb, 0x4f, 0x0, 0x0, 0x0, 0x40, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 0, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 64, 'EnableCounter1': False, 'EnableCounter0': False}
>>> d.configAnalog(u3.FIO4, u3.FIO5, u3.EIO0)
Sent: [0x47, 0xf8, 0x3, 0xb, 0x40, 0x0, 0x0, 0x0, 0x40, 0x0, 0x0, 0x0]
Result: [0x56, 0xf8, 0x3, 0xb, 0x4f, 0x0, 0x0, 0x0, 0x40, 0x0, 0xf, 0x0]
Sent: [0x94, 0xf8, 0x3, 0xb, 0x8d, 0x0, 0xd, 0x0, 0x40, 0x0, 0x3f, 0x1]
Result: [0x87, 0xf8, 0x3, 0xb, 0x80, 0x0, 0x0, 0x0, 0x40, 0x0, 0x3f, 0x1]
{'NumberOfTimersEnabled': 0, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 63, 'EIOAnalog': 1, 'TimerCounterConfig': 64, 'EnableCounter1': False, 'EnableCounter0': False}
>>> d.configDigital(u3.FIO4, u3.FIO5, u3.EIO0)
Sent: [0x47, 0xf8, 0x3, 0xb, 0x40, 0x0, 0x0, 0x0, 0x40, 0x0, 0x0, 0x0]
Result: [0x87, 0xf8, 0x3, 0xb, 0x80, 0x0, 0x0, 0x0, 0x40, 0x0, 0x3f, 0x1]
Sent: [0x63, 0xf8, 0x3, 0xb, 0x5c, 0x0, 0xd, 0x0, 0x40, 0x0, 0xf, 0x0]
Result: [0x56, 0xf8, 0x3, 0xb, 0x4f, 0x0, 0x0, 0x0, 0x40, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 0, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 64, 'EnableCounter1': False, 'EnableCounter0': False}
"""
configIODict = self.configIO()
# Without args, return the same as configIO()
if len(args) == 0:
return configIODict
FIOAnalog, EIOAnalog = configIODict['FIOAnalog'], configIODict['EIOAnalog']
#
for i in args:
if i > EIO7:
pass # Invalid. Must be in the range FIO0-EIO7.
elif i < EIO0:
if FIOAnalog & 2**i: # If it is set
FIOAnalog ^= 2**i # Remove it
else:
if EIOAnalog & 2**(i-EIO0): # Start the EIO counting at 0, not 8
EIOAnalog ^= 2**(i-EIO0)
return self.configIO(FIOAnalog = FIOAnalog, EIOAnalog = EIOAnalog)
def _buildBuffer(self, sendBuffer, readLen, commandlist):
"""
Builds up the buffer to be written for getFeedback
"""
for cmd in commandlist:
if isinstance(cmd, FeedbackCommand):
sendBuffer += cmd.cmdBytes
readLen += cmd.readLen
elif isinstance(cmd, list):
sendBuffer, readLen = self._buildBuffer(sendBuffer, readLen, cmd)
return (sendBuffer, readLen)
_buildBuffer.section = 4
def _buildFeedbackResults(self, rcvBuffer, commandlist, results, i):
"""
Builds the result list from the results of getFeedback
"""
for cmd in commandlist:
if isinstance(cmd, FeedbackCommand):
results.append(cmd.handle(rcvBuffer[i:i+cmd.readLen]))
i += cmd.readLen
elif isinstance(cmd, list):
self._buildFeedbackResults(rcvBuffer, cmd, results, i)
return results
_buildFeedbackResults.section = 4
def getFeedback(self, *commandlist):
"""
Name: U3.getFeedback(commandlist)
Args: the FeedbackCommands to run
Desc: Forms the commandlist into a packet, sends it to the U3, and reads the response.
Examples:
>>> myU3 = u3.U3()
>>> ledCommand = u3.LED(False)
>>> ain0Command = u3.AIN(0, 31, True)
>>> myU3.getFeedback(ledCommand, ain0Command)
[None, 9376]
OR if you like the list version better:
>>> myU3 = U3()
>>> ledCommand = u3.LED(False)
>>> ain0Command = u3.AIN(30, 31, True)
>>> commandList = [ ledCommand, ain0Command ]
>>> myU3.getFeedback(commandList)
[None, 9376]
"""
sendBuffer = [0] * 7
sendBuffer[1] = 0xF8
readLen = 9
sendBuffer, readLen = self._buildBuffer(sendBuffer, readLen, commandlist)
if len(sendBuffer) % 2:
sendBuffer += [0]
sendBuffer[2] = len(sendBuffer) / 2 - 3
if readLen % 2:
readLen += 1
if len(sendBuffer) > MAX_USB_PACKET_LENGTH:
raise LabJackException("ERROR: The feedback command you are attempting to send is bigger than 64 bytes ( %s bytes ). Break your commands up into separate calls to getFeedback()." % len(sendBuffer))
if readLen > MAX_USB_PACKET_LENGTH:
raise LabJackException("ERROR: The feedback command you are attempting to send would yield a response that is greater than 64 bytes ( %s bytes ). Break your commands up into separate calls to getFeedback()." % readLen)
rcvBuffer = self._writeRead(sendBuffer, readLen, [], checkBytes = False, stream = False, checksum = True)
# Check the response for errors
try:
self._checkCommandBytes(rcvBuffer, [0xF8])
if rcvBuffer[3] != 0x00:
raise LabJackException("Got incorrect command bytes")
except LowlevelErrorException, e:
if isinstance(commandlist[0], list):
culprit = commandlist[0][ (rcvBuffer[7] -1) ]
else:
culprit = commandlist[ (rcvBuffer[7] -1) ]
raise LowlevelErrorException("\nThis Command\n %s\nreturned an error:\n %s" % (culprit , lowlevelErrorToString(rcvBuffer[6])))
results = []
i = 9
return self._buildFeedbackResults(rcvBuffer, commandlist, results, i)
getFeedback.section = 2
def readMem(self, blockNum, readCal=False):
"""
Name: U3.readMem(blockNum, readCal=False)
Args: blockNum, which block to read from
readCal, set to True to read from calibration instead.
Desc: Reads 1 block (32 bytes) from the non-volatile user or
calibration memory. Please read section 5.2.6 of the user's guide
before you do something you may regret.
NOTE: Do not call this function while streaming.
"""
command = [ 0 ] * 8
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x01
command[3] = 0x2A
if readCal:
command[3] = 0x2D
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = 0x00
command[7] = blockNum
result = self._writeRead(command, 40, [0xF8, 0x11, command[3]])
return result[8:]
readMem.section = 2
def readCal(self, blockNum):
"""
Name: U3.readCal(blockNum)
Args: blockNum, which block to read
Desc: See the description of readMem and section 5.2.6 of the user's
guide.
Note: Do not call this function while streaming.
"""
return self.readMem(blockNum, readCal = True)
readCal.section = 2
def writeMem(self, blockNum, data, writeCal=False):
"""
Name: U3.writeMem(blockNum, data, writeCal=False)
Args: blockNum, which block to write
data, a list of bytes to write.
writeCal, set to True to write to calibration instead
Desc: Writes 1 block (32 bytes) from the non-volatile user or
calibration memory. Please read section 5.2.7 of the user's guide
before you do something you may regret. Memory must be erased
before writing.
Note: Do not call this function while streaming.
"""
if not isinstance(data, list):
raise LabJackException("Data must be a list of bytes")
command = [ 0 ] * 40
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x11
command[3] = 0x28
if writeCal:
command[3] = 0x2B
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = 0x00
command[7] = blockNum
command[8:] = data
self._writeRead(command, 8, [0xF8, 0x01, command[3]])
writeMem.section = 2
def writeCal(self, blockNum):
"""
Name: U3.writeCal(blockNum, data)
Args: blockNum, which block to write
data, a list of bytes
Desc: See the description of writeMem and section 5.2.7 of the user's
guide.
Note: Do not call this function while streaming.
"""
return self.writeMem(blockNum, data, writeCal = True)
writeCal.section = 2
def eraseMem(self, eraseCal=False):
"""
Name: U3.eraseMem(eraseCal=False)
Args: eraseCal, set to True to erase the calibration memory instead
Desc: The U3 uses flash memory that must be erased before writing.
Please read section 5.2.8 of the user's guide before you do
something you may regret.
Note: Do not call this function while streaming.
"""
if eraseCal:
command = [ 0 ] * 8
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x01
command[3] = 0x2C
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = 0x4C
command[7] = 0x6C
else:
command = [ 0 ] * 6
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x00
command[3] = 0x29
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
self._writeRead(command, 8, [0xF8, 0x01, command[3]])
eraseMem.section = 2
def eraseCal(self):
"""
Name: U3.eraseCal()
Args: None
Desc: See the description of writeMem and section 5.2.8 of the user's
guide.
Note: Do not call this function while streaming.
"""
return self.eraseMem(eraseCal = True)
eraseCal.section = 2
def reset(self, hardReset = False):
"""
Name: U3.reset(hardReset = False)
Args: hardReset, set to True for a hard reset.
Desc: Causes a soft or hard reset. A soft reset consists of
re-initializing most variables without re-enumeration. A hard
reset is a reboot of the processor and does cause re-enumeration.
See section 5.2.9 of the User's guide.
"""
command = [ 0 ] * 4
#command[0] = Checksum8
command[1] = 0x99
command[2] = 1
if hardReset:
command[2] = 2
command[3] = 0x00
command = setChecksum8(command, 4)
self._writeRead(command, 4, [], False, False, False)
reset.section = 2
def streamConfig(self, NumChannels = 1, SamplesPerPacket = 25, InternalStreamClockFrequency = 0, DivideClockBy256 = False, Resolution = 3, ScanInterval = 1, PChannels = [30], NChannels = [31], SampleFrequency = None):
"""
Name: U3.streamConfig(NumChannels = 1, SamplesPerPacket = 25,
InternalStreamClockFrequency = 0,
DivideClockBy256 = False, Resolution = 3,
ScanInterval = 1, PChannels = [30],
NChannels = [31], SampleFrequency = None)
Args: NumChannels, the number of channels to stream
Resolution, the resolution of the samples (0 - 3)
PChannels, a list of channel numbers to stream
NChannels, a list of channel options bytes
Set Either:
SampleFrequency, the frequency in Hz to sample
-- OR --
SamplesPerPacket, how many samples make one packet
InternalStreamClockFrequency, 0 = 4 MHz, 1 = 48 MHz
DivideClockBy256, True = divide the clock by 256
ScanInterval, clock/ScanInterval = frequency.
Desc: Stream mode operates on a table of channels that are scanned
at the specified scan rate. Before starting a stream, you need
to call this function to configure the table and scan clock.
Note: Requires U3 hardware version 1.21 or greater.
"""
if len(PChannels) != NumChannels:
raise LabJackException("Length of PChannels didn't match NumChannels")
if len(NChannels) != NumChannels:
raise LabJackException("Length of NChannels didn't match NumChannels")
if len(PChannels) != len(NChannels):
raise LabJackException("Length of PChannels didn't match the length of NChannels")
if SampleFrequency != None:
if SampleFrequency < 1000:
if SampleFrequency < 25:
SamplesPerPacket = SampleFrequency
DivideClockBy256 = True
ScanInterval = 15625/SampleFrequency
else:
DivideClockBy256 = False
ScanInterval = 4000000/SampleFrequency
# Force Scan Interval into correct range
ScanInterval = min( ScanInterval, 65535 )
ScanInterval = int( ScanInterval )
ScanInterval = max( ScanInterval, 1 )
# Same with Samples per packet
SamplesPerPacket = max( SamplesPerPacket, 1)
SamplesPerPacket = int( SamplesPerPacket )
SamplesPerPacket = min ( SamplesPerPacket, 25)
command = [ 0 ] * ( 12 + (NumChannels * 2) )
#command[0] = Checksum8
command[1] = 0xF8
command[2] = NumChannels+3
command[3] = 0x11
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = NumChannels
command[7] = SamplesPerPacket
#command[8] = Reserved
command[9] |= ( InternalStreamClockFrequency & 0x01 ) << 3
if DivideClockBy256:
command[9] |= 1 << 2
command[9] |= ( Resolution & 3 )
t = struct.pack("<H", ScanInterval)
command[10] = ord(t[0])
command[11] = ord(t[1])
for i in range(NumChannels):
command[12+(i*2)] = PChannels[i]
command[13+(i*2)] = NChannels[i]
self._writeRead(command, 8, [0xF8, 0x01, 0x11])
self.streamSamplesPerPacket = SamplesPerPacket
self.streamChannelNumbers = PChannels
self.streamNegChannels = NChannels
self.streamConfiged = True
if InternalStreamClockFrequency == 1:
freq = float(48000000)
else:
freq = float(4000000)
if DivideClockBy256:
freq /= 256
freq = freq/ScanInterval
self.packetsPerRequest = max(1, int(freq/SamplesPerPacket))
self.packetsPerRequest = min(self.packetsPerRequest, 48)
streamConfig.section = 2
def processStreamData(self, result, numBytes = None):
"""
Name: U3.processStreamData(result, numBytes = None)
Args: result, the string returned from streamData()
numBytes, the number of bytes per packet.
Desc: Breaks stream data into individual channels and applies
calibrations.
>>> reading = d.streamData(convert = False)
>>> print proccessStreamData(reading['result'])
defaultDict(list, {'AIN0' : [3.123, 3.231, 3.232, ...]})
"""
if numBytes is None:
numBytes = 14 + (self.streamSamplesPerPacket * 2)
returnDict = collections.defaultdict(list)
for packet in self.breakupPackets(result, numBytes):
for sample in self.samplesFromPacket(packet):
if self.streamPacketOffset >= len(self.streamChannelNumbers):
self.streamPacketOffset = 0
if self.streamChannelNumbers[self.streamPacketOffset] in (193, 194):
value = struct.unpack('<BB', sample )
elif self.streamChannelNumbers[self.streamPacketOffset] >= 200:
value = struct.unpack('<H', sample )[0]
else:
if self.streamNegChannels[self.streamPacketOffset] != 31:
# do signed
value = struct.unpack('<H', sample )[0]
singleEnded = False
else:
# do unsigned
value = struct.unpack('<H', sample )[0]
singleEnded = True
lvChannel = True
if self.deviceName.lower().endswith('hv') and self.streamChannelNumbers[self.streamPacketOffset] < 4:
lvChannel = False
value = self.binaryToCalibratedAnalogVoltage(value, isLowVoltage = lvChannel, isSingleEnded = singleEnded, channelNumber = self.streamChannelNumbers[self.streamPacketOffset])
returnDict["AIN%s" % self.streamChannelNumbers[self.streamPacketOffset]].append(value)
self.streamPacketOffset += 1
return returnDict
processStreamData.section = 3
def watchdog(self, ResetOnTimeout = False, SetDIOStateOnTimeout = False, TimeoutPeriod = 60, DIOState = 0, DIONumber = 0, onlyRead=False):
"""
Name: U3.watchdog(ResetOnTimeout = False, SetDIOStateOnTimeout = False,
TimeoutPeriod = 60, DIOState = 0, DIONumber = 0,
onlyRead = False)
Args: Check out section 5.2.14 of the user's guide.
Set onlyRead to True to perform only a read
Desc: This function will write the configuration of the watchdog,
unless onlyRead is set to True.
Returns a dictionary:
{
'WatchDogEnabled' : True if the watchdog is enabled, otherwise False
'ResetOnTimeout' : If True, the device will reset on timeout.
'SetDIOStateOnTimeout' : If True, the state of a DIO will be set
'TimeoutPeriod' : Timeout Period in seconds
'DIOState' : The state the DIO will be set to on timeout
'DIONumber' : Which DIO will be set on timeout
}
NOTE: Requires U3 hardware version 1.21 or greater.
"""
command = [ 0 ] * 16
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x05
command[3] = 0x09
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
if not onlyRead:
command[6] = 1
if ResetOnTimeout:
command[7] |= 1 << 5
if SetDIOStateOnTimeout:
command[7] |= 1 << 4
t = struct.pack("<H", TimeoutPeriod)
command[8] = ord(t[0])
command[9] = ord(t[1])
command[10] = (( DIOState & 1 ) << 7) + ( DIONumber & 15)
result = self._writeRead(command, 16, [0xF8, 0x05, 0x09])
watchdogStatus = {}
if result[7] == 0 or result[7] == 255:
watchdogStatus['WatchDogEnabled'] = False
watchdogStatus['ResetOnTimeout'] = False
watchdogStatus['SetDIOStateOnTimeout'] = False
else:
watchdogStatus['WatchDogEnabled'] = True
if (( result[7] >> 5 ) & 1):
watchdogStatus['ResetOnTimeout'] = True
else:
watchdogStatus['ResetOnTimeout'] = False
if (( result[7] >> 4 ) & 1):
watchdogStatus['SetDIOStateOnTimeout'] = True
else:
watchdogStatus['SetDIOStateOnTimeout'] = False
watchdogStatus['TimeoutPeriod'] = struct.unpack('<H', struct.pack("BB", *result[8:10]))
if (( result[10] >> 7 ) & 1):
watchdogStatus['DIOState'] = 1
else:
watchdogStatus['DIOState'] = 0
watchdogStatus['DIONumber'] = ( result[10] & 15 )
return watchdogStatus
watchdog.section = 2
SPIModes = { 'A' : 0, 'B' : 1, 'C' : 2, 'D' : 3 }
def spi(self, SPIBytes, AutoCS=True, DisableDirConfig = False, SPIMode = 'A', SPIClockFactor = 0, CSPINNum = 4, CLKPinNum = 5, MISOPinNum = 6, MOSIPinNum = 7):
"""
Name: U3.spi(SPIBytes, AutoCS=True, DisableDirConfig = False,
SPIMode = 'A', SPIClockFactor = 0, CSPINNum = 4,
CLKPinNum = 5, MISOPinNum = 6, MOSIPinNum = 7)
Args: SPIBytes, a list of bytes to be transferred.
See Section 5.2.15 of the user's guide.
Desc: Sends and receives serial data using SPI synchronous
communication.
NOTE: Requires U3 hardware version 1.21 or greater.
"""
if not isinstance(SPIBytes, list):
raise LabJackException("SPIBytes MUST be a list of bytes")
numSPIBytes = len(SPIBytes)
oddPacket = False
if numSPIBytes%2 != 0:
SPIBytes.append(0)
numSPIBytes = numSPIBytes + 1
oddPacket = True
command = [ 0 ] * (13 + numSPIBytes)
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 4 + (numSPIBytes/2)
command[3] = 0x3A
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
if AutoCS:
command[6] |= (1 << 7)
if DisableDirConfig:
command[6] |= (1 << 6)
command[6] |= ( self.SPIModes[SPIMode] & 3 )
command[7] = SPIClockFactor
#command[8] = Reserved
command[9] = CSPINNum
command[10] = CLKPinNum
command[11] = MISOPinNum
command[12] = MOSIPinNum
command[13] = numSPIBytes
if oddPacket:
command[13] = numSPIBytes - 1
command[14:] = SPIBytes
result = self._writeRead(command, 8+numSPIBytes, [ 0xF8, 1+(numSPIBytes/2), 0x3A ])
return result[8:]
spi.section = 2
def asynchConfig(self, Update = True, UARTEnable = True, DesiredBaud = 9600, olderHardware = False, configurePins = True ):
"""
Name: U3.asynchConfig(Update = True, UARTEnable = True,
DesiredBaud = 9600, olderHardware = False,
configurePins = True)
Args: See section 5.2.16 of the User's Guide.
olderHardware, If using hardware 1.21, please set olderHardware
to True and read the timer configuration first.
configurePins, Will call the configIO to set up pins for you.
Desc: Configures the U3 UART for asynchronous communication.
returns a dictionary:
{
'Update' : True means new parameters were written
'UARTEnable' : True means the UART is enabled
'BaudFactor' : The baud factor being used
}
Note: Requires U3 hardware version 1.21+.
"""
if configurePins:
self.configIO(EnableUART=True)
command = [ 0 ] * 10
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x02
command[3] = 0x14
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
#command[6] = 0x00
if Update:
command[7] |= ( 1 << 7 )
if UARTEnable:
command[7] |= ( 1 << 6 )
#command[8] = Reserved
if olderHardware:
command[9] = (2**8) - self.timerClockBase/DesiredBaud
else:
BaudFactor = (2**16) - 48000000/(2 * DesiredBaud)
t = struct.pack("<H", BaudFactor)
command[8] = ord(t[0])
command[9] = ord(t[1])
if olderHardware:
result = self._writeRead(command, 10, [0xF8, 0x02, 0x14])
else:
result = self._writeRead(command, 10, [0xF8, 0x02, 0x14])
returnDict = {}
if ( ( result[7] >> 7 ) & 1 ):
returnDict['Update'] = True
else:
returnDict['Update'] = False
if ( ( result[7] >> 6 ) & 1):
returnDict['UARTEnable'] = True
else:
returnDict['UARTEnable'] = False
if olderHardware:
returnDict['BaudFactor'] = result[9]
else:
returnDict['BaudFactor'] = struct.unpack("<H", struct.pack("BB", *result[8:]))[0]
return returnDict
asynchConfig.section = 2
def asynchTX(self, AsynchBytes):
"""
Name: U3.asynchTX(AsynchBytes)
Args: AsynchBytes, must be a list of bytes to transfer.
Desc: Sends bytes to the U3 UART which will be sent asynchronously on
the transmit line. See section 5.2.17 of the user's guide.
returns a dictionary:
{
'NumAsynchBytesSent' : Number of Asynch Bytes Sent
'NumAsynchBytesInRXBuffer' : How many bytes are currently in the
RX buffer.
}
Note: Requres U3 hardware version 1.21 or greater.
"""
if not isinstance(AsynchBytes, list):
raise LabJackException("AsynchBytes must be a list")
numBytes = len(AsynchBytes)
oddPacket = False
if numBytes%2 != 0:
AsynchBytes.append(0)
numBytes = numBytes+1
oddPacket = True
command = [ 0 ] * ( 8 + numBytes)
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 1 + ( numBytes/2 )
command[3] = 0x15
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
#command[6] = 0x00
command[7] = numBytes
if oddPacket:
command[7] = numBytes - 1
command[8:] = AsynchBytes
result = self._writeRead(command, 10, [0xF8, 0x02, 0x15])
return { 'NumAsynchBytesSent' : result[7], 'NumAsynchBytesInRXBuffer' : result[8] }
asynchTX.section = 2
def asynchRX(self, Flush = False):
"""
Name: U3.asynchRX(Flush = False)
Args: Flush, Set to True to flush
Desc: Reads the oldest 32 bytes from the U3 UART RX buffer
(received on receive terminal). The buffer holds 256 bytes. See
section 5.2.18 of the User's Guide.
returns a dictonary:
{
'AsynchBytes' : List of received bytes
'NumAsynchBytesInRXBuffer' : Number of AsynchBytes are in the RX
Buffer.
}
Note: Requres U3 hardware version 1.21 or greater.
"""
command = [ 0 ] * 8
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x01
command[3] = 0x16
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
#command[6] = 0x00
if Flush:
command[7] = 1
result = self._writeRead(command, 40, [0xF8, 0x11, 0x16])
return { 'AsynchBytes' : result[8:], 'NumAsynchBytesInRXBuffer' : result[7] }
asynchRX.section = 2
def i2c(self, Address, I2CBytes, EnableClockStretching = False, NoStopWhenRestarting = False, ResetAtStart = False, SpeedAdjust = 0, SDAPinNum = 6, SCLPinNum = 7, NumI2CBytesToReceive = 0, AddressByte = None):
"""
Name: U3.i2c(Address, I2CBytes, ResetAtStart = False,
EnableClockStretching = False, SpeedAdjust = 0,
SDAPinNum = 6, SCLPinNum = 7, NumI2CBytesToReceive = 0,
AddressByte = None)
Args: Address, the address (not shifted over)
I2CBytes, must be a list of bytes to send.
See section 5.2.19 of the user's guide.
AddressByte, use this if you don't want a shift applied.
This address will be put it in the low-level
packet directly and overrides Address. Optional.
Desc: Sends and receives serial data using I2C synchronous
communication.
Note: Requires hardware version 1.21 or greater.
"""
if not isinstance(I2CBytes, list):
raise LabJackException("I2CBytes must be a list")
numBytes = len(I2CBytes)
oddPacket = False
if numBytes%2 != 0:
I2CBytes.append(0)
numBytes = numBytes + 1
oddPacket = True
command = [ 0 ] * (14 + numBytes)
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 4 + (numBytes/2)
command[3] = 0x3B
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
if ResetAtStart:
command[6] |= (1 << 1)
if NoStopWhenRestarting:
command[6] |= (1 << 2)
if EnableClockStretching:
command[6] |= (1 << 3)
command[7] = SpeedAdjust
command[8] = SDAPinNum
command[9] = SCLPinNum
if AddressByte != None:
command[10] = AddressByte
else:
command[10] = Address << 1
command[12] = numBytes
if oddPacket:
command[12] = numBytes-1
command[13] = NumI2CBytesToReceive
command[14:] = I2CBytes
oddResponse = False
if NumI2CBytesToReceive%2 != 0:
NumI2CBytesToReceive = NumI2CBytesToReceive+1
oddResponse = True
result = self._writeRead(command, 12+NumI2CBytesToReceive, [0xF8, (3+(NumI2CBytesToReceive/2)), 0x3B])
if len(result) > 12:
if oddResponse:
return { 'AckArray' : result[8:12], 'I2CBytes' : result[12:-1] }
else:
return { 'AckArray' : result[8:12], 'I2CBytes' : result[12:] }
else:
return { 'AckArray' : result[8:], 'I2CBytes' : [] }
i2c.section = 2
def sht1x(self, DataPinNum = 4, ClockPinNum = 5, SHTOptions = 0xc0):
"""
Name: U3.sht1x(DataPinNum = 4, ClockPinNum = 5, SHTOptions = 0xc0)
Args: See section 5.2.20 of the user's guide.
SHTOptions, see below.
Desc: Reads temperature and humidity from a Sensirion SHT1X sensor
(which is used by the EI-1050).
Returns a dictonary:
{
'StatusReg' : SHT1X status register
'StatusRegCRC' : SHT1X status register CRC value
'Temperature' : The temperature in C
'TemperatureCRC' : The CRC value for the temperature
'Humidity' : The humidity
'HumidityCRC' : The CRC value for the humidity
}
Note: Requires hardware version 1.21 or greater.
SHTOptions (and proof people read documentation):
bit 7 = Read Temperature
bit 6 = Read Realtive Humidity
bit 2 = Heater. 1 = on, 0 = off
bit 1 = Reserved at 0
bit 0 = Resolution. 1 = 8 bit RH, 12 bit T; 0 = 12 RH, 14 bit T
"""
command = [ 0 ] * 10
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x02
command[3] = 0x39
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = DataPinNum
command[7] = ClockPinNum
#command[8] = Reserved
command[9] = SHTOptions
result = self._writeRead(command, 16, [0xF8, 0x05, 0x39])
val = (result[11]*256) + result[10]
temp = -39.60 + 0.01*val
val = (result[14]*256) + result[13]
humid = -4 + 0.0405*val + -.0000028*(val*val)
humid = (temp - 25)*(0.01 + 0.00008*val) + humid
return { 'StatusReg' : result[8], 'StatusRegCRC' : result[9], 'Temperature' : temp, 'TemperatureCRC' : result[12] , 'Humidity' : humid, 'HumidityCRC' : result[15] }
sht1x.section = 2
def binaryToCalibratedAnalogVoltage(self, bits, isLowVoltage = True, isSingleEnded = True, isSpecialSetting = False, channelNumber = 0):
"""
Name: U3.binaryToCalibratedAnalogVoltage(bits, isLowVoltage = True,
isSingleEnded = True,
isSpecialSetting = False,
channelNumber = 0)
Args: bits, the binary value of the reading.
isLowVoltage, True if the reading came from a low-voltage channel
isSingleEnded, True if the reading is not differential
isSpecialSetting, True if the reading came from special range
channelNumber, used to apply the correct calibration for HV
Desc: Converts the bits returned from AIN functions into a calibrated
voltage.
Example:
>>> import u3
>>> d = u3.U3()
>>> bits = d.getFeedback( u3.AIN(0, 31))[0]
>>> print bits
1248
>>> print d.binaryToCalibratedAnalogVoltage(bits)
0.046464288000000006
"""
hasCal = self.calData is not None
if isLowVoltage:
if isSingleEnded and not isSpecialSetting:
if hasCal:
return ( bits * self.calData['lvSESlope'] ) + self.calData['lvSEOffset']
else:
return ( bits * 0.000037231 ) + 0
elif isSpecialSetting:
if hasCal:
return ( bits * self.calData['lvDiffSlope'] ) + self.calData['lvDiffOffset'] + self.calData['vRefAtCAl']
else:
return (bits * 0.000074463)
else:
if hasCal:
return ( bits * self.calData['lvDiffSlope'] ) + self.calData['lvDiffOffset']
else:
return (bits * 0.000074463) - 2.44
else:
if isSingleEnded and not isSpecialSetting:
if hasCal:
return ( bits * self.calData['hvAIN%sSlope' % channelNumber] ) + self.calData['hvAIN%sOffset' % channelNumber]
else:
return ( bits * 0.000314 ) + -10.3
elif isSpecialSetting:
if hasCal:
hvSlope = self.calData['hvAIN%sSlope' % channelNumber]
hvOffset = self.calData['hvAIN%sOffset' % channelNumber]
diffR = ( bits * self.calData['lvDiffSlope'] ) + self.calData['lvDiffOffset'] + self.calData['vRefAtCAl']
reading = diffR * hvSlope / self.calData['lvSESlope'] + hvOffset
return reading
else:
return (bits * 0.000074463) * (0.000314 / 0.000037231) + -10.3
else:
raise Exception, "Can't do differential on high voltage channels"
binaryToCalibratedAnalogVoltage.section = 3
def binaryToCalibratedAnalogTemperature(self, bytesTemperature):
hasCal = self.calData is not None
if hasCal:
return self.calData['tempSlope'] * float(bytesTemperature)
else:
return float(bytesTemperature) * 0.013021
def voltageToDACBits(self, volts, dacNumber = 0, is16Bits = False):
"""
Name: U3.voltageToDACBits(volts, dacNumber = 0, is16Bits = False)
Args: volts, the voltage you would like to set the DAC to.
dacNumber, 0 or 1, helps apply the correct calibration
is16Bits, True if you are going to use the 16-bit DAC command
Desc: Takes a voltage, and turns it into the bits needed for the DAC
Feedback commands.
"""
if self.calData is not None:
if is16Bits:
bits = ( volts * self.calData['dac%sSlope' % dacNumber] * 256) + self.calData['dac%sOffset' % dacNumber] * 256
else:
bits = ( volts * self.calData['dac%sSlope' % dacNumber] ) + self.calData['dac%sOffset' % dacNumber]
else:
bits = ( volts / 4.95 ) * 256
return int(bits)
voltageToDACBits.section = 3
def getCalibrationData(self):
"""
Name: U3.getCalibrationData()
Args: None
Desc: Reads in the U3's calibrations, so they can be applied to
readings. Section 2.6.2 of the User's Guide is helpful. Sets up
an internal calData dict for any future calls that need
calibration.
"""
self.calData = dict()
calData = self.readCal(0)
self.calData['lvSESlope'] = toDouble(calData[0:8])
self.calData['lvSEOffset'] = toDouble(calData[8:16])
self.calData['lvDiffSlope'] = toDouble(calData[16:24])
self.calData['lvDiffOffset'] = toDouble(calData[24:32])
calData = self.readCal(1)
self.calData['dac0Slope'] = toDouble(calData[0:8])
self.calData['dac0Offset'] = toDouble(calData[8:16])
self.calData['dac1Slope'] = toDouble(calData[16:24])
self.calData['dac1Offset'] = toDouble(calData[24:32])
calData = self.readCal(2)
self.calData['tempSlope'] = toDouble(calData[0:8])
self.calData['vRefAtCAl'] = toDouble(calData[8:16])
self.calData['vRef1.5AtCal'] = toDouble(calData[16:24])
self.calData['vRegAtCal'] = toDouble(calData[24:32])
try:
#these blocks do not exist on hardware revisions < 1.30
calData = self.readCal(3)
self.calData['hvAIN0Slope'] = toDouble(calData[0:8])
self.calData['hvAIN1Slope'] = toDouble(calData[8:16])
self.calData['hvAIN2Slope'] = toDouble(calData[16:24])
self.calData['hvAIN3Slope'] = toDouble(calData[24:32])
calData = self.readCal(4)
self.calData['hvAIN0Offset'] = toDouble(calData[0:8])
self.calData['hvAIN1Offset'] = toDouble(calData[8:16])
self.calData['hvAIN2Offset'] = toDouble(calData[16:24])
self.calData['hvAIN3Offset'] = toDouble(calData[24:32])
except LowlevelErrorException, ex:
if ex.errorCode != 26:
#not an invalid block error, so do not disregard
raise ex
return self.calData
getCalibrationData.section = 3
def readDefaultsConfig(self):
"""
Name: U3.readDefaultsConfig( )
Args: None
Desc: Reads the power-up defaults stored in flash.
"""
results = dict()
defaults = self.readDefaults(0)
results['FIODirection'] = defaults[4]
results['FIOState'] = defaults[5]
results['FIOAnalog'] = defaults[6]
results['EIODirection'] = defaults[8]
results['EIOState'] = defaults[9]
results['EIOAnalog'] = defaults[10]
results['CIODirection'] = defaults[12]
results['CIOState'] = defaults[13]
results['NumOfTimersEnable'] = defaults[17]
results['CounterMask'] = defaults[18]
results['PinOffset'] = defaults[19]
results['Options'] = defaults[20]
defaults = self.readDefaults(1)
results['ClockSource'] = defaults[0]
results['Divisor'] = defaults[1]
results['TMR0Mode'] = defaults[16]
results['TMR0ValueL'] = defaults[17]
results['TMR0ValueH'] = defaults[18]
results['TMR1Mode'] = defaults[20]
results['TMR1ValueL'] = defaults[21]
results['TMR1ValueH'] = defaults[22]
defaults = self.readDefaults(2)
results['DAC0'] = struct.unpack( ">H", struct.pack("BB", *defaults[16:18]) )[0]
results['DAC1'] = struct.unpack( ">H", struct.pack("BB", *defaults[20:22]) )[0]
defaults = self.readDefaults(3)
for i in range(16):
results["AIN%sNegChannel" % i] = defaults[i]
return results
readDefaultsConfig.section = 3
def exportConfig(self):
"""
Name: U3.exportConfig( )
Args: None
Desc: Takes the current configuration and puts it into a ConfigParser
object. Useful for saving the setup of your U3.
"""
# Make a new configuration file
parser = ConfigParser.SafeConfigParser()
# Change optionxform so that options preserve their case.
parser.optionxform = str
# Local Id and name
self.configU3()
section = "Identifiers"
parser.add_section(section)
parser.set(section, "Local ID", str(self.localId))
parser.set(section, "Name", str(self.getName()))
parser.set(section, "Device Type", str(self.devType))
# FIO Direction / State
section = "FIOs"
parser.add_section(section)
dirs, states = self.getFeedback( PortDirRead(), PortStateRead() )
parser.set(section, "FIOs Analog", str( self.readRegister(50590) ))
parser.set(section, "EIOs Analog", str( self.readRegister(50591) ))
for key, value in dirs.items():
parser.set(section, "%s Directions" % key, str(value))
for key, value in states.items():
parser.set(section, "%s States" % key, str(value))
# DACs
section = "DACs"
parser.add_section(section)
dac0 = self.readRegister(5000)
dac0 = max(dac0, 0)
dac0 = min(dac0, 5)
parser.set(section, "DAC0", "%0.2f" % dac0)
dac1 = self.readRegister(5002)
dac1 = max(dac1, 0)
dac1 = min(dac1, 5)
parser.set(section, "DAC1", "%0.2f" % dac1)
# Timer Clock Configuration
section = "Timer Clock Speed Configuration"
parser.add_section(section)
timerclockconfig = self.configTimerClock()
for key, value in timerclockconfig.items():
parser.set(section, key, str(value))
# Timers / Counters
section = "Timers And Counters"
parser.add_section(section)
timerCounterConfig = self.configIO()
nte = timerCounterConfig['NumberOfTimersEnabled']
ec0 = timerCounterConfig['EnableCounter0']
ec1 = timerCounterConfig['EnableCounter1']
cpo = timerCounterConfig['TimerCounterPinOffset']
parser.set(section, "NumberTimersEnabled", str(nte) )
parser.set(section, "Counter0Enabled", str(ec0) )
parser.set(section, "Counter1Enabled", str(ec1) )
parser.set(section, "TimerCounterPinOffset", str(cpo) )
for i in range(nte):
mode, value = self.readRegister(7100 + (2*i), numReg = 2, format = ">HH")
parser.set(section, "Timer%i Mode" % i, str(mode))
parser.set(section, "Timer%i Value" % i, str(value))
return parser
exportConfig.section = 3
def loadConfig(self, configParserObj):
"""
Name: U3.loadConfig( configParserObj )
Args: configParserObj, A Config Parser object to load in
Desc: Takes a configuration and updates the U3 to match it.
"""
parser = configParserObj
# Set Identifiers:
section = "Identifiers"
if parser.has_section(section):
if parser.has_option(section, "device type"):
if parser.getint(section, "device type") != self.devType:
raise Exception("Not a U3 Config file.")
if parser.has_option(section, "local id"):
self.configU3( LocalID = parser.getint(section, "local id"))
if parser.has_option(section, "name"):
self.setName( parser.get(section, "name") )
# Set FIOs:
section = "FIOs"
if parser.has_section(section):
fioanalog = 0
eioanalog = 0
fiodirs = 0
eiodirs = 0
ciodirs = 0
fiostates = 0
eiostates = 0
ciostates = 0
if parser.has_option(section, "fios analog"):
fioanalog = parser.getint(section, "fios analog")
if parser.has_option(section, "eios analog"):
eioanalog = parser.getint(section, "eios analog")
if parser.has_option(section, "fios directions"):
fiodirs = parser.getint(section, "fios directions")
if parser.has_option(section, "eios directions"):
eiodirs = parser.getint(section, "eios directions")
if parser.has_option(section, "cios directions"):
ciodirs = parser.getint(section, "cios directions")
if parser.has_option(section, "fios states"):
fiostates = parser.getint(section, "fios states")
if parser.has_option(section, "eios states"):
eiostates = parser.getint(section, "eios states")
if parser.has_option(section, "cios states"):
ciostates = parser.getint(section, "cios states")
self.configIO(FIOAnalog = fioanalog, EIOAnalog = eioanalog)
self.getFeedback( PortStateWrite([fiostates, eiostates, ciostates]), PortDirWrite([fiodirs, eiodirs, ciodirs]) )
# Set DACs:
section = "DACs"
if parser.has_section(section):
if parser.has_option(section, "dac0"):
self.writeRegister(5000, parser.getfloat(section, "dac0"))
if parser.has_option(section, "dac1"):
self.writeRegister(5002, parser.getfloat(section, "dac1"))
# Set Timer Clock Configuration
section = "Timer Clock Speed Configuration"
if parser.has_section(section):
if parser.has_option(section, "timerclockbase") and parser.has_option(section, "timerclockdivisor"):
self.configTimerClock(TimerClockBase = parser.getint(section, "timerclockbase"), TimerClockDivisor = parser.getint(section, "timerclockdivisor"))
# Set Timers / Counters
section = "Timers And Counters"
if parser.has_section(section):
nte = None
c0e = None
c1e = None
cpo = None
if parser.has_option(section, "NumberTimersEnabled"):
nte = parser.getint(section, "NumberTimersEnabled")
if parser.has_option(section, "TimerCounterPinOffset"):
cpo = parser.getint(section, "TimerCounterPinOffset")
if parser.has_option(section, "Counter0Enabled"):
c0e = parser.getboolean(section, "Counter0Enabled")
if parser.has_option(section, "Counter1Enabled"):
c1e = parser.getboolean(section, "Counter1Enabled")
self.configIO(NumberOfTimersEnabled = nte, EnableCounter1 = c1e, EnableCounter0 = c0e, TimerCounterPinOffset = cpo)
mode = None
value = None
if parser.has_option(section, "timer0 mode"):
mode = parser.getint(section, "timer0 mode")
if parser.has_option(section, "timer0 value"):
value = parser.getint(section, "timer0 value")
self.getFeedback( Timer0Config(mode, value) )
if parser.has_option(section, "timer1 mode"):
mode = parser.getint(section, "timer1 mode")
if parser.has_option(section, "timer1 value"):
value = parser.getint(section, "timer1 value")
self.getFeedback( Timer1Config(mode, value) )
loadConfig.section = 3
class FeedbackCommand(object):
"""
The FeedbackCommand class is the base for all the Feedback commands.
"""
readLen = 0
def handle(self, input):
return None
class AIN(FeedbackCommand):
'''
Analog Input Feedback command
specify the positive and negative channels to use
(0-16, 30 and 31 are possible)
also specify whether to turn on longSettle or quick Sample
returns 16-bit signed int sample
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.AIN(PositiveChannel = 0, NegativeChannel=31, LongSettling=False, QuickSample=False))
Sent: [0x1b, 0xf8, 0x2, 0x0, 0x20, 0x0, 0x0, 0x1, 0x0, 0x1f]
Response: [0xab, 0xf8, 0x3, 0x0, 0xaf, 0x0, 0x0, 0x0, 0x0, 0x20, 0x8f, 0x0]
[36640]
'''
def __init__(self, PositiveChannel, NegativeChannel=31,
LongSettling=False, QuickSample=False):
self.positiveChannel = PositiveChannel
self.negativeChannel = NegativeChannel
self.longSettling = LongSettling
self.quickSample = QuickSample
validChannels = range(16) + [30, 31]
if PositiveChannel not in validChannels:
raise Exception("Invalid Positive Channel specified")
if NegativeChannel not in validChannels:
raise Exception("Invalid Negative Channel specified")
b = PositiveChannel
b |= (int(bool(LongSettling)) << 6)
b |= (int(bool(QuickSample)) << 7)
self.cmdBytes = [ 0x01, b, NegativeChannel ]
readLen = 2
def __repr__(self):
return "<u3.AIN( PositiveChannel = %s, NegativeChannel = %s, LongSettling = %s, QuickSample = %s )>" % ( self.positiveChannel, self.negativeChannel, self.longSettling, self.quickSample )
def handle(self, input):
result = (input[1] << 8) + input[0]
return result
class WaitShort(FeedbackCommand):
'''
WaitShort Feedback command
specify the number of 128us time increments to wait
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.WaitShort(Time = 9))
Sent: [0x9, 0xf8, 0x2, 0x0, 0xe, 0x0, 0x0, 0x5, 0x9, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
'''
def __init__(self, Time):
self.time = Time % 256
self.cmdBytes = [ 5, Time % 256 ]
def __repr__(self):
return "<u3.WaitShort( Time = %s )>" % self.time
class WaitLong(FeedbackCommand):
'''
WaitLong Feedback command
specify the number of 32ms time increments to wait
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.WaitLong(Time = 70))
Sent: [0x47, 0xf8, 0x2, 0x0, 0x4c, 0x0, 0x0, 0x6, 0x46, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
'''
def __init__(self, Time):
self.time = Time % 256
self.cmdBytes = [ 6, Time % 256 ]
def __repr__(self):
return "<u3.WaitLong( Time = %s )>" % self.time
class LED(FeedbackCommand):
'''
LED Toggle
specify whether the LED should be on or off by truth value
1 or True = On, 0 or False = Off
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.LED(State = False))
Sent: [0x4, 0xf8, 0x2, 0x0, 0x9, 0x0, 0x0, 0x9, 0x0, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
>>> d.getFeedback(u3.LED(State = True))
Sent: [0x5, 0xf8, 0x2, 0x0, 0xa, 0x0, 0x0, 0x9, 0x1, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
'''
def __init__(self, State):
self.state = State
self.cmdBytes = [ 9, int(bool(State)) ]
def __repr__(self):
return "<u3.LED( State = %s )>" % self.state
class BitStateRead(FeedbackCommand):
'''
BitStateRead Feedback command
read the state of a single bit of digital I/O. Only digital
lines return valid readings.
IONumber: 0-7=FIO, 8-15=EIO, 16-19=CIO
return 0 or 1
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.BitStateRead(IONumber = 5))
Sent: [0xa, 0xf8, 0x2, 0x0, 0xf, 0x0, 0x0, 0xa, 0x5, 0x0]
Response: [0xfb, 0xf8, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1]
[1]
'''
def __init__(self, IONumber):
self.ioNumber = IONumber
self.cmdBytes = [ 10, IONumber % 20 ]
readLen = 1
def __repr__(self):
return "<u3.BitStateRead( IONumber = %s )>" % self.ioNumber
def handle(self, input):
return int(bool(input[0]))
class BitStateWrite(FeedbackCommand):
'''
BitStateWrite Feedback command
write a single bit of digital I/O. The direction of the
specified line is forced to output.
IONumber: 0-7=FIO, 8-15=EIO, 16-19=CIO
State: 0 or 1
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.BitStateWrite(IONumber = 5, State = 0))
Sent: [0xb, 0xf8, 0x2, 0x0, 0x10, 0x0, 0x0, 0xb, 0x5, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
'''
def __init__(self, IONumber, State):
self.ioNumber = IONumber
self.state = State
self.cmdBytes = [ 11, (IONumber % 20) + (int(bool(State)) << 7) ]
def __repr__(self):
return "<u3.BitStateWrite( IONumber = %s, State = %s )>" % (self.ioNumber, self.state)
class BitDirRead(FeedbackCommand):
'''
Read the digital direction of one I/O
IONumber: 0-7=FIO, 8-15=EIO, 16-19=CIO
returns 1 = Output, 0 = Input
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.BitDirRead(IONumber = 5))
Sent: [0xc, 0xf8, 0x2, 0x0, 0x11, 0x0, 0x0, 0xc, 0x5, 0x0]
Response: [0xfb, 0xf8, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1]
[1]
'''
def __init__(self, IONumber):
self.ioNumber = IONumber
self.cmdBytes = [ 12, IONumber % 20 ]
readLen = 1
def __repr__(self):
return "<u3.BitDirRead( IONumber = %s )>" % self.ioNumber
def handle(self, input):
return int(bool(input[0]))
class BitDirWrite(FeedbackCommand):
'''
BitDirWrite Feedback command
Set the digital direction of one I/O
IONumber: 0-7=FIO, 8-15=EIO, 16-19=CIO
Direction: 1 = Output, 0 = Input
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.BitDirWrite(IONumber = 5, Direction = 0))
Sent: [0xd, 0xf8, 0x2, 0x0, 0x12, 0x0, 0x0, 0xd, 0x5, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
'''
def __init__(self, IONumber, Direction):
self.ioNumber = IONumber
self.direction = Direction
self.cmdBytes = [ 13, (IONumber % 20) + (int(bool(Direction)) << 7) ]
def __repr__(self):
return "<u3.BitDirWrite( IONumber = %s, Direction = %s )>" % (self.ioNumber, self.direction)
class PortStateRead(FeedbackCommand):
"""
PortStateRead Feedback command
Reads the state of all digital I/O.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.PortStateRead())
Sent: [0x14, 0xf8, 0x1, 0x0, 0x1a, 0x0, 0x0, 0x1a]
Response: [0xeb, 0xf8, 0x3, 0x0, 0xee, 0x1, 0x0, 0x0, 0x0, 0xe0, 0xff, 0xf]
[{'CIO': 15, 'FIO': 224, 'EIO': 255}]
"""
def __init__(self):
self.cmdBytes = [ 26 ]
readLen = 3
def handle(self, input):
return {'FIO' : input[0], 'EIO' : input[1], 'CIO' : input[2] }
def __repr__(self):
return "<u3.PortStateRead()>"
class PortStateWrite(FeedbackCommand):
"""
PortStateWrite Feedback command
State: A list of 3 bytes representing FIO, EIO, CIO
WriteMask: A list of 3 bytes, representing which to update.
The Default is all ones.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.PortStateWrite(State = [0xab, 0xcd, 0xef], WriteMask = [0xff, 0xff, 0xff]))
Sent: [0x81, 0xf8, 0x4, 0x0, 0x7f, 0x5, 0x0, 0x1b, 0xff, 0xff, 0xff, 0xab, 0xcd, 0xef]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
"""
def __init__(self, State, WriteMask = [0xff, 0xff, 0xff]):
self.state = State
self.writeMask = WriteMask
self.cmdBytes = [ 27 ] + WriteMask + State
def __repr__(self):
return "<u3.PortStateWrite( State = %s, WriteMask = %s )>" % (self.state, self.writeMask)
class PortDirRead(FeedbackCommand):
"""
PortDirRead Feedback command
Reads the direction of all digital I/O.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.PortDirRead())
Sent: [0x16, 0xf8, 0x1, 0x0, 0x1c, 0x0, 0x0, 0x1c]
Response: [0xfb, 0xf8, 0x3, 0x0, 0xfe, 0x1, 0x0, 0x0, 0x0, 0xf0, 0xff, 0xf]
[{'CIO': 15, 'FIO': 240, 'EIO': 255}]
"""
def __init__(self):
self.cmdBytes = [ 28 ]
readLen = 3
def __repr__(self):
return "<u3.PortDirRead()>"
def handle(self, input):
return {'FIO' : input[0], 'EIO' : input[1], 'CIO' : input[2] }
class PortDirWrite(FeedbackCommand):
"""
PortDirWrite Feedback command
Direction: A list of 3 bytes representing FIO, EIO, CIO
WriteMask: A list of 3 bytes, representing which to update. Default is all ones.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.PortDirWrite(Direction = [0xaa, 0xcc, 0xff], WriteMask = [0xff, 0xff, 0xff]))
Sent: [0x91, 0xf8, 0x4, 0x0, 0x8f, 0x5, 0x0, 0x1d, 0xff, 0xff, 0xff, 0xaa, 0xcc, 0xff]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
"""
def __init__(self, Direction, WriteMask = [ 0xff, 0xff, 0xff]):
self.direction = Direction
self.writeMask = WriteMask
self.cmdBytes = [ 29 ] + WriteMask + Direction
def __repr__(self):
return "<u3.PortDirWrite( Direction = %s, WriteMask = %s )>" % (self.direction, self.writeMask)
class DAC8(FeedbackCommand):
'''
8-bit DAC Feedback command
Controls a single analog output
Dac: 0 or 1
Value: 0-255
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.DAC8(Dac = 0, Value = 0x55))
Sent: [0x72, 0xf8, 0x2, 0x0, 0x77, 0x0, 0x0, 0x22, 0x55, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
'''
def __init__(self, Dac, Value):
self.dac = Dac
self.value = Value % 256
self.cmdBytes = [ 34 + (Dac % 2), Value % 256 ]
def __repr__(self):
return "<u3.DAC8( Dac = %s, Value = %s )>" % (self.dac, self.value)
class DAC0_8(DAC8):
"""
8-bit DAC Feedback command for DAC0
Controls DAC0 in 8-bit mode.
Value: 0-255
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.DAC0_8(Value = 0x33))
Sent: [0x50, 0xf8, 0x2, 0x0, 0x55, 0x0, 0x0, 0x22, 0x33, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
"""
def __init__(self, Value):
DAC8.__init__(self, 0, Value)
def __repr__(self):
return "<u3.DAC0_8( Value = %s )>" % self.value
class DAC1_8(DAC8):
"""
8-bit DAC Feedback command for DAC1
Controls DAC1 in 8-bit mode.
Value: 0-255
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.DAC1_8(Value = 0x22))
Sent: [0x40, 0xf8, 0x2, 0x0, 0x45, 0x0, 0x0, 0x23, 0x22, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
"""
def __init__(self, Value):
DAC8.__init__(self, 1, Value)
def __repr__(self):
return "<u3.DAC1_8( Value = %s )>" % self.value
class DAC16(FeedbackCommand):
'''
16-bit DAC Feedback command
Controls a single analog output
Dac: 0 or 1
Value: 0-65535
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.DAC16(Dac = 0, Value = 0x5566))
Sent: [0xdc, 0xf8, 0x2, 0x0, 0xe1, 0x0, 0x0, 0x26, 0x66, 0x55]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
'''
def __init__(self, Dac, Value):
self.dac = Dac
self.value = Value
self.cmdBytes = [ 38 + (Dac % 2), Value % 256, Value >> 8 ]
def __repr__(self):
return "<u3.DAC16( Dac = %s, Value = %s )>" % (self.dac, self.value)
class DAC0_16(DAC16):
"""
16-bit DAC Feedback command for DAC0
Controls DAC0 in 16-bit mode.
Value: 0-65535
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.DAC0_16(Value = 0x1122))
Sent: [0x54, 0xf8, 0x2, 0x0, 0x59, 0x0, 0x0, 0x26, 0x22, 0x11]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
"""
def __init__(self, Value):
DAC16.__init__(self, 0, Value)
def __repr__(self):
return "<u3.DAC0_16( Value = %s )>" % self.value
class DAC1_16(DAC16):
"""
16-bit DAC Feedback command for DAC1
Controls DAC1 in 16-bit mode.
Value: 0-65535
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.getFeedback(u3.DAC1_16(Value = 0x2233))
Sent: [0x77, 0xf8, 0x2, 0x0, 0x7c, 0x0, 0x0, 0x27, 0x33, 0x22]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
"""
def __init__(self, Value):
DAC16.__init__(self, 1, Value)
def __repr__(self):
return "<u3.DAC1_16( Value = %s )>" % self.value
class Timer(FeedbackCommand):
"""
For reading the value of the Timer. It provides the ability to update/reset
a given timer, and read the timer value.
(Section 5.2.5.14 of the User's Guide)
timer: Either 0 or 1 for timer 0 or timer 1
UpdateReset: Set True if you want to update the value
Value: Only updated if the UpdateReset bit is 1. The meaning of this
parameter varies with the timer mode.
Mode: Set to the timer mode to handle any special processing. See classes
QuadratureInputTimer and TimerStopInput1.
Returns an unsigned integer of the timer value, unless Mode has been
specified and there are special return values. See Section 2.9.1 for
expected return values.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.configIO(NumberOfTimersEnabled = 1)
Sent: [0x49, 0xf8, 0x3, 0xb, 0x42, 0x0, 0x1, 0x0, 0x41, 0x0, 0x0, 0x0]
Response: [0x57, 0xf8, 0x3, 0xb, 0x50, 0x0, 0x0, 0x0, 0x41, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 1, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 65, 'EnableCounter1': False, 'EnableCounter0': False}
>>> d.getFeedback(u3.Timer(timer = 0, UpdateReset = False, Value = 0, Mode = None))
Sent: [0x26, 0xf8, 0x3, 0x0, 0x2a, 0x0, 0x0, 0x2a, 0x0, 0x0, 0x0, 0x0]
Response: [0xfc, 0xf8, 0x4, 0x0, 0xfe, 0x1, 0x0, 0x0, 0x0, 0x63, 0xdd, 0x4c, 0x72, 0x0]
[1917640035]
"""
def __init__(self, timer, UpdateReset = False, Value=0, Mode = None):
self.timer = timer
self.updateReset = UpdateReset
self.value = Value
self.mode = Mode
if timer != 0 and timer != 1:
raise LabJackException("Timer should be either 0 or 1.")
if UpdateReset and Value == None:
raise LabJackException("UpdateReset set but no value.")
self.cmdBytes = [ (42 + (2*timer)), UpdateReset, Value % 256, Value >> 8 ]
readLen = 4
def __repr__(self):
return "<u3.Timer( timer = %s, UpdateReset = %s, Value = %s, Mode = %s )>" % (self.timer, self.updateReset, self.value, self.mode)
def handle(self, input):
inStr = struct.pack('B' * len(input), *input)
if self.mode == 8:
return struct.unpack('<i', inStr )[0]
elif self.mode == 9:
maxCount, current = struct.unpack('<HH', inStr )
return current, maxCount
else:
return struct.unpack('<I', inStr )[0]
class Timer0(Timer):
"""
For reading the value of the Timer0. It provides the ability to
update/reset Timer0, and read the timer value.
(Section 5.2.5.14 of the User's Guide)
UpdateReset: Set True if you want to update the value
Value: Only updated if the UpdateReset bit is 1. The meaning of this
parameter varies with the timer mode.
Mode: Set to the timer mode to handle any special processing. See classes
QuadratureInputTimer and TimerStopInput1.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.configIO(NumberOfTimersEnabled = 1)
Sent: [0x49, 0xf8, 0x3, 0xb, 0x42, 0x0, 0x1, 0x0, 0x41, 0x0, 0x0, 0x0]
Response: [0x57, 0xf8, 0x3, 0xb, 0x50, 0x0, 0x0, 0x0, 0x41, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 1, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 65, 'EnableCounter1': False, 'EnableCounter0': False}
>>> d.getFeedback(u3.Timer0(UpdateReset = False, Value = 0, Mode = None))
Sent: [0x26, 0xf8, 0x3, 0x0, 0x2a, 0x0, 0x0, 0x2a, 0x0, 0x0, 0x0, 0x0]
Response: [0x51, 0xf8, 0x4, 0x0, 0x52, 0x2, 0x0, 0x0, 0x0, 0xf6, 0x90, 0x46, 0x86, 0x0]
[2252771574]
"""
def __init__(self, UpdateReset = False, Value = 0, Mode = None):
Timer.__init__(self, 0, UpdateReset, Value, Mode)
def __repr__(self):
return "<u3.Timer0( UpdateReset = %s, Value = %s, Mode = %s )>" % (self.updateReset, self.value, self.mode)
class Timer1(Timer):
"""
For reading the value of the Timer1. It provides the ability to
update/reset Timer1, and read the timer value.
(Section 5.2.5.14 of the User's Guide)
UpdateReset: Set True if you want to update the value
Value: Only updated if the UpdateReset bit is 1. The meaning of this
parameter varies with the timer mode.
Mode: Set to the timer mode to handle any special processing. See classes
QuadratureInputTimer and TimerStopInput1.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.configIO(NumberOfTimersEnabled = 2)
Sent: [0x4a, 0xf8, 0x3, 0xb, 0x43, 0x0, 0x1, 0x0, 0x42, 0x0, 0x0, 0x0]
Response: [0x58, 0xf8, 0x3, 0xb, 0x51, 0x0, 0x0, 0x0, 0x42, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 2, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 66, 'EnableCounter1': False, 'EnableCounter0': False}
>>> d.getFeedback(u3.Timer1(UpdateReset = False, Value = 0, Mode = None))
Sent: [0x28, 0xf8, 0x3, 0x0, 0x2c, 0x0, 0x0, 0x2c, 0x0, 0x0, 0x0, 0x0]
Response: [0x8d, 0xf8, 0x4, 0x0, 0x8e, 0x2, 0x0, 0x0, 0x0, 0xf3, 0x31, 0xd0, 0x9a, 0x0]
[2597335539]
"""
def __init__(self, UpdateReset = False, Value = 0, Mode = None):
Timer.__init__(self, 1, UpdateReset, Value, Mode)
def __repr__(self):
return "<u3.Timer1( UpdateReset = %s, Value = %s, Mode = %s )>" % (self.updateReset, self.value, self.mode)
class QuadratureInputTimer(Timer):
"""
For reading Quadrature input timers. They are special because their values
are signed.
(Section 2.9.1.8 of the User's Guide)
Args:
UpdateReset: Set True if you want to reset the counter.
Value: Set to 0, and UpdateReset to True to reset the counter.
Returns a signed integer.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.configIO(NumberOfTimersEnabled = 2)
Sent: [0x4a, 0xf8, 0x3, 0xb, 0x43, 0x0, 0x1, 0x0, 0x42, 0x0, 0x0, 0x0]
Response: [0x58, 0xf8, 0x3, 0xb, 0x51, 0x0, 0x0, 0x0, 0x42, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 2, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 66, 'EnableCounter1': False, 'EnableCounter0': False}
>>> # Setup the two timers to be quadrature
>>> d.getFeedback(u3.Timer0Config(8), u3.Timer1Config(8))
Sent: [0x66, 0xf8, 0x5, 0x0, 0x68, 0x0, 0x0, 0x2b, 0x8, 0x0, 0x0, 0x2d, 0x8, 0x0, 0x0, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None, None]
>>> # Read the value
[0]
>>> d.getFeedback(u3.QuadratureInputTimer())
Sent: [0x26, 0xf8, 0x3, 0x0, 0x2a, 0x0, 0x0, 0x2a, 0x0, 0x0, 0x0, 0x0]
Response: [0xf5, 0xf8, 0x4, 0x0, 0xf5, 0x3, 0x0, 0x0, 0x0, 0xf8, 0xff, 0xff, 0xff, 0x0]
[-8]
>>> d.getFeedback(u3.QuadratureInputTimer())
Sent: [0x26, 0xf8, 0x3, 0x0, 0x2a, 0x0, 0x0, 0x2a, 0x0, 0x0, 0x0, 0x0]
Response: [0x9, 0xf8, 0x4, 0x0, 0xc, 0x0, 0x0, 0x0, 0x0, 0xc, 0x0, 0x0, 0x0, 0x0]
[12]
"""
def __init__(self, UpdateReset = False, Value = 0):
Timer.__init__(self, 0, UpdateReset, Value, Mode = 8)
def __repr__(self):
return "<u3.QuadratureInputTimer( UpdateReset = %s, Value = %s )>" % (self.updateReset, self.value)
class TimerStopInput1(Timer1):
"""
For reading a stop input timer. They are special because the value returns
the current edge count and the stop value.
(Section 2.9.1.9 of the User's Guide)
Args:
UpdateReset: Set True if you want to update the value.
Value: The stop value. Only updated if the UpdateReset bit is 1.
Returns a tuple where the first value is current edge count, and the second
value is the stop value.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.configIO(NumberOfTimersEnabled = 2)
Sent: [0x4a, 0xf8, 0x3, 0xb, 0x43, 0x0, 0x1, 0x0, 0x42, 0x0, 0x0, 0x0]
Response: [0x58, 0xf8, 0x3, 0xb, 0x51, 0x0, 0x0, 0x0, 0x42, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 2, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 66, 'EnableCounter1': False, 'EnableCounter0': False}
>>> # Setup the timer to be Stop Input
>>> d.getFeedback(u3.Timer1Config(9, Value = 30))
Sent: [0x50, 0xf8, 0x3, 0x0, 0x54, 0x0, 0x0, 0x2d, 0x9, 0x1e, 0x0, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
>>> d.getFeedback(u3.TimerStopInput1())
Sent: [0x28, 0xf8, 0x3, 0x0, 0x2c, 0x0, 0x0, 0x2c, 0x0, 0x0, 0x0, 0x0]
Response: [0x1b, 0xf8, 0x4, 0x0, 0x1e, 0x0, 0x0, 0x0, 0x0, 0x1e, 0x0, 0x0, 0x0, 0x0]
[(0, 0)]
"""
def __init__(self, UpdateReset = False, Value = 0):
Timer.__init__(self, 1, UpdateReset, Value, Mode = 9)
def __repr__(self):
return "<u3.TimerStopInput1( UpdateReset = %s, Value = %s )>" % (self.updateReset, self.value)
class TimerConfig(FeedbackCommand):
"""
This IOType configures a particular timer.
timer = # of the timer to configure
TimerMode = See Section 2.9 for more information about the available modes.
Value = The meaning of this parameter varies with the timer mode.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.configIO(NumberOfTimersEnabled = 1)
Sent: [0x49, 0xf8, 0x3, 0xb, 0x42, 0x0, 0x1, 0x0, 0x41, 0x0, 0x0, 0x0]
Response: [0x57, 0xf8, 0x3, 0xb, 0x50, 0x0, 0x0, 0x0, 0x41, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 1, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 65, 'EnableCounter1': False, 'EnableCounter0': False}
>>> d.getFeedback(u3.TimerConfig(timer = 0, TimerMode = 0, Value = 0))
Sent: [0x27, 0xf8, 0x3, 0x0, 0x2b, 0x0, 0x0, 0x2b, 0x0, 0x0, 0x0, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
>>> d.getFeedback(u3.TimerConfig(timer = 0, TimerMode = 0, Value = 65535))
Sent: [0x27, 0xf8, 0x3, 0x0, 0x29, 0x2, 0x0, 0x2b, 0x0, 0xff, 0xff, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
"""
def __init__(self, timer, TimerMode, Value=0):
'''Creates command bytes for configureing a Timer'''
#Conditions come from pages 33-34 of user's guide
if timer != 0 and timer != 1:
raise LabJackException("Timer should be either 0 or 1.")
if TimerMode > 14 or TimerMode < 0:
raise LabJackException("Invalid Timer Mode.")
self.timer = timer
self.timerMode = TimerMode
self.value = Value
self.cmdBytes = [43 + (timer * 2), TimerMode, Value % 256, Value >> 8]
def __repr__(self):
return "<u3.TimerConfig( timer = %s, TimerMode = %s, Value = %s )>" % (self.timer, self.timerMode, self.value)
class Timer0Config(TimerConfig):
"""
This IOType configures Timer0.
TimerMode = See Section 2.9 for more information about the available modes.
Value = The meaning of this parameter varies with the timer mode.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.configIO(NumberOfTimersEnabled = 1)
Sent: [0x49, 0xf8, 0x3, 0xb, 0x42, 0x0, 0x1, 0x0, 0x41, 0x0, 0x0, 0x0]
Response: [0x57, 0xf8, 0x3, 0xb, 0x50, 0x0, 0x0, 0x0, 0x41, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 1, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 65, 'EnableCounter1': False, 'EnableCounter0': False}
>>> d.getFeedback(u3.Timer0Config(TimerMode = 1, Value = 0))
Sent: [0x28, 0xf8, 0x3, 0x0, 0x2c, 0x0, 0x0, 0x2b, 0x1, 0x0, 0x0, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
>>> d.getFeedback(u3.Timer0Config(TimerMode = 1, Value = 65535))
Sent: [0x28, 0xf8, 0x3, 0x0, 0x2a, 0x2, 0x0, 0x2b, 0x1, 0xff, 0xff, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
"""
def __init__(self, TimerMode, Value = 0):
TimerConfig.__init__(self, 0, TimerMode, Value)
def __repr__(self):
return "<u3.Timer0Config( TimerMode = %s, Value = %s )>" % (self.timerMode, self.value)
class Timer1Config(TimerConfig):
"""
This IOType configures Timer1.
TimerMode = See Section 2.9 for more information about the available modes.
Value = The meaning of this parameter varies with the timer mode.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.configIO(NumberOfTimersEnabled = 2)
Sent: [0x4a, 0xf8, 0x3, 0xb, 0x43, 0x0, 0x1, 0x0, 0x42, 0x0, 0x0, 0x0]
Response: [0x58, 0xf8, 0x3, 0xb, 0x51, 0x0, 0x0, 0x0, 0x42, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 2, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 66, 'EnableCounter1': False, 'EnableCounter0': False}
>>> d.getFeedback(u3.Timer1Config(TimerMode = 6, Value = 1))
Sent: [0x30, 0xf8, 0x3, 0x0, 0x34, 0x0, 0x0, 0x2d, 0x6, 0x1, 0x0, 0x0]
Response: [0xfa, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[None]
"""
def __init__(self, TimerMode, Value = 0):
TimerConfig.__init__(self, 1, TimerMode, Value)
def __repr__(self):
return "<u3.Timer1Config( TimerMode = %s, Value = %s )>" % (self.timerMode, self.value)
class Counter(FeedbackCommand):
'''
Counter Feedback command
Reads a hardware counter, optionally resetting it
counter: 0 or 1
Reset: True ( or 1 ) = Reset, False ( or 0 ) = Don't Reset
Returns the current count from the counter if enabled. If reset,
this is the value before the reset.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.configIO(EnableCounter0 = True, FIOAnalog = 15)
Sent: [0x5f, 0xf8, 0x3, 0xb, 0x58, 0x0, 0x5, 0x0, 0x44, 0x0, 0xf, 0x0]
Response: [0x5a, 0xf8, 0x3, 0xb, 0x53, 0x0, 0x0, 0x0, 0x44, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 0, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 68, 'EnableCounter1': False, 'EnableCounter0': True}
>>> d.getFeedback(u3.Counter(counter = 0, Reset = False))
Sent: [0x31, 0xf8, 0x2, 0x0, 0x36, 0x0, 0x0, 0x36, 0x0, 0x0]
Response: [0xfc, 0xf8, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[0]
>>> # Tap a ground wire to counter 0
>>> d.getFeedback(u3.Counter(counter = 0, Reset = False))
Sent: [0x31, 0xf8, 0x2, 0x0, 0x36, 0x0, 0x0, 0x36, 0x0, 0x0]
Response: [0xe9, 0xf8, 0x4, 0x0, 0xec, 0x0, 0x0, 0x0, 0x0, 0xe8, 0x4, 0x0, 0x0, 0x0]
[1256]
'''
def __init__(self, counter, Reset = False):
self.counter = counter
self.reset = Reset
self.cmdBytes = [ 54 + (counter % 2), int(bool(Reset))]
readLen = 4
def __repr__(self):
return "<u3.Counter( counter = %s, Reset = %s )>" % (self.counter, self.reset)
def handle(self, input):
inStr = ''.join([chr(x) for x in input])
return struct.unpack('<I', inStr )[0]
class Counter0(Counter):
'''
Counter0 Feedback command
Reads hardware counter0, optionally resetting it
Reset: True ( or 1 ) = Reset, False ( or 0 ) = Don't Reset
Returns the current count from the counter if enabled. If reset,
this is the value before the reset.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.configIO(EnableCounter0 = True, FIOAnalog = 15)
Sent: [0x5f, 0xf8, 0x3, 0xb, 0x58, 0x0, 0x5, 0x0, 0x44, 0x0, 0xf, 0x0]
Response: [0x5a, 0xf8, 0x3, 0xb, 0x53, 0x0, 0x0, 0x0, 0x44, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 0, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 68, 'EnableCounter1': False, 'EnableCounter0': True}
>>> d.getFeedback(u3.Counter0( Reset = False ) )
Sent: [0x31, 0xf8, 0x2, 0x0, 0x36, 0x0, 0x0, 0x36, 0x0, 0x0]
Response: [0xfc, 0xf8, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[0]
>>> # Tap a ground wire to counter 0
>>> d.getFeedback(u3.Counter0(Reset = False))
Sent: [0x31, 0xf8, 0x2, 0x0, 0x36, 0x0, 0x0, 0x36, 0x0, 0x0]
Response: [0xe, 0xf8, 0x4, 0x0, 0x11, 0x0, 0x0, 0x0, 0x0, 0x11, 0x0, 0x0, 0x0, 0x0]
[17]
>>> # Tap a ground wire to counter 0
>>> d.getFeedback(u3.Counter0(Reset = False))
Sent: [0x31, 0xf8, 0x2, 0x0, 0x36, 0x0, 0x0, 0x36, 0x0, 0x0]
Response: [0x19, 0xf8, 0x4, 0x0, 0x1c, 0x0, 0x0, 0x0, 0x0, 0xb, 0x11, 0x0, 0x0, 0x0]
[4363]
'''
def __init__(self, Reset = False):
Counter.__init__(self, 0, Reset)
def __repr__(self):
return "<u3.Counter0( Reset = %s )>" % self.reset
class Counter1(Counter):
'''
Counter1 Feedback command
Reads hardware counter1, optionally resetting it
Reset: True ( or 1 ) = Reset, False ( or 0 ) = Don't Reset
Returns the current count from the counter if enabled. If reset,
this is the value before the reset.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.configIO(EnableCounter1 = True, FIOAnalog = 15)
Sent: [0x63, 0xf8, 0x3, 0xb, 0x5c, 0x0, 0x5, 0x0, 0x48, 0x0, 0xf, 0x0]
Response: [0x5e, 0xf8, 0x3, 0xb, 0x57, 0x0, 0x0, 0x0, 0x48, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 0, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 72, 'EnableCounter1': True, 'EnableCounter0': False}
>>> d.getFeedback(u3.Counter1(Reset = False))
Sent: [0x32, 0xf8, 0x2, 0x0, 0x37, 0x0, 0x0, 0x37, 0x0, 0x0]
Response: [0xfc, 0xf8, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[0]
>>> # Tap a ground wire to counter 1
>>> d.getFeedback(u3.Counter1(Reset = False))
Sent: [0x32, 0xf8, 0x2, 0x0, 0x37, 0x0, 0x0, 0x37, 0x0, 0x0]
Response: [0xfd, 0xf8, 0x4, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0]
[1]
>>> # Tap a ground wire to counter 1
>>> d.getFeedback(u3.Counter1(Reset = False))
Sent: [0x32, 0xf8, 0x2, 0x0, 0x37, 0x0, 0x0, 0x37, 0x0, 0x0]
Response: [0xb4, 0xf8, 0x4, 0x0, 0xb7, 0x0, 0x0, 0x0, 0x0, 0x6b, 0x2b, 0x21, 0x0, 0x0]
[2173803]
'''
def __init__(self, Reset = False):
Counter.__init__(self, 1, Reset)
def __repr__(self):
return "<u3.Counter0( Reset = %s )>" % self.reset
| 102,511 | 36.522694 | 815 | py |
SDR | SDR-master/Setup/shiftPsFreq.py | import numpy as np
import sys
oldFreqPath = '/mnt/data0/Darkness/20160718_ps/freq_FL3_a_neg.txt'
psFreqPath = '/mnt/data0/Darkness/20160718_ps/ps_FL3_a_neg.txt'
fixedPsFreqPath = '/mnt/data0/Darkness/20160718_ps/ps2_FL3_a_neg.txt'
oldFreqTable = np.loadtxt(oldFreqPath)
psFreqTable = np.loadtxt(psFreqPath)
keptIndices = []
keptFreqs = []
for iFreq,freq in enumerate(oldFreqTable[:,0]):
print iFreq,freq,
closestPsFreqIdx = np.argmin(np.abs(psFreqTable[:,0]-freq))
closestFreq = psFreqTable[closestPsFreqIdx,0]
distFromClosest = closestFreq-freq
print closestFreq,distFromClosest
if np.abs(distFromClosest) < 512e3:
keptIndices.append(iFreq)
keptFreqs.append(freq)
keptFreqs = np.array(keptFreqs)
print 'kept',len(keptIndices),'of',len(oldFreqTable[:,0])
print 'num ps freqs',len(psFreqTable[:,0])
print np.shape(oldFreqTable[keptIndices,0])
if len(keptIndices) != len(psFreqTable[:,0]):
print 'ERROR: Couldn\'t match all ps freqs with old freq'
sys.exit(1)
freqDiffs = psFreqTable[:,0] - keptFreqs
print np.shape(freqDiffs)
print 'diff',freqDiffs[0:2]
print 'old',oldFreqTable[0:2,0]
print 'clicked',psFreqTable[0:2,0]
fixedOldFreqs = np.roll(keptFreqs,2)
fixedPsFreqs = fixedOldFreqs + freqDiffs
print 'fixed',fixedPsFreqs[0:2]
fixedPsFreqTable = np.array(psFreqTable)
fixedPsFreqTable[:,0] = fixedPsFreqs
np.savetxt(fixedPsFreqPath,fixedPsFreqTable,fmt=['%.9e','%d'])
| 1,431 | 28.22449 | 69 | py |
SDR | SDR-master/Setup/PSFit_ml_diffAttens.py | '''
Author Rupert Dodkins
A script to automate the identification of resonator attenuations normally performed by PSFit.py. This is accomplished
using Google's Tensor Flow machine learning package which implements a pattern recognition algorithm on the IQ velocity
spectrum. The code implements a 2D image classification algorithm similar to the MNIST test. This code creates a 2D
image from a 1D variable by populating a matrix of zeros with ones at the y location of each datapoint
Usage: python PSFit_ml.py 20160712/ps_r115_FL1_1_20160712-225809.h5 20160720/ps_r118_FL1_b_pos_20160720-231653.h5
Inputs:
20160712/ps_r115_FL1_1.txt: list of resonator frequencies and correct attenuations
20160712/ps_r115_FL1_1_20160712-225809.h5: corresponding powersweep file
20160720/ps_r118_FL1_b_pos_20160720-231653.h5: powersweep file the user wishes to infer attenuations for
Intermediaries:
SDR/Setup/ps_peaks_train_w<x>_s<y>.pkl: images and corresponding labels used to train the algorithm
Outputs:
20160712/ps_r115_FL1_1.pkl: frequencies, IQ velocities, Is, Qs, attenuations formatted for quick use
20160720/ps_r118_FL1_b_pos_20160720-231653-ml.txt: to be used with PSFit.py (temporary)
20160720/ps_r118_FL1_b_pos.txt: final list of frequencies and attenuations
How it works:
For each resonator and attenuation the script first assesses if the IQ loop appears saturated. If the unstaurated IQ
velocity spectrum for that attenuation is compared with the pattern recognition machine. A list of attenuations for each
resonator, where the loop is not saturated and the IQ velocity peak looks the correct shape, and the attenuation value
is chosen which has the highest 2nd largest IQ velocity. This identifier was chosen because the optimum attenuation
value has a high max IQ velocity and a low ratio of max IQ velocity to 2nd max IQ velocity which is equivalent to
choosing the highest 2nd max IQ velocity.
This list of attenuation values and frequencies are either fed PSFit.py to checked manually or dumped to
ps_r118_FL1_b_pos.txt
The machine learning algorithm requires a series of images to train and test the algorithm with. If they exist the image
data will be loaded from a train pkl file
Alternatively, if the user does not have a train pkl file but does have a powersweep file and corresponding list of
resonator attenuations this should be used as the initial file and training data will be made. The 3 classes are an
overpowered peak (saturated), peak with the correct amount of power, or an underpowered peak.
These new image data will be saved as pkl files (or appened to existing pkl files) and reloaded
The machine is then trained and its ability to predict the type of image is validated
The weights used to make predictions for each class can be displayed using the plotWeights function
to do:
change training txt file freq comparison function so its able to match all frequencies
'''
import os,sys,inspect
from PSFit import *
from lib.iqsweep import *
import numpy as np
import sys, os
import matplotlib.pyplot as plt
import tensorflow as tf
import pickle
import random
import time
import math
from scipy import interpolate
#removes visible depreciation warnings from lib.iqsweep
import warnings
warnings.filterwarnings("ignore")
class PSFitting():
'''Class has been lifted from PSFit.py and modified to incorporate the machine learning algorithms from
WideAna_ml.py
'''
def __init__(self, initialFile=None):
self.initialFile = initialFile
self.resnum = 0
def loadres(self):
'''
Outputs
Freqs: the span of frequencies for a given resonator
iq_vels: the IQ velocities for all attenuations for a given resonator
Is: the I component of the frequencies for a given resonator
Qs: the Q component of the frequencies for a given resonator
attens: the span of attenuations. The same for all resonators
'''
self.Res1=IQsweep()
self.Res1.LoadPowers(self.initialFile, 'r0', self.freq[self.resnum])
self.resfreq = self.freq[self.resnum]
self.NAttens = len(self.Res1.atten1s)
self.res1_iq_vels=numpy.zeros((self.NAttens,self.Res1.fsteps-1))
self.res1_iq_amps=numpy.zeros((self.NAttens,self.Res1.fsteps))
for iAtt in range(self.NAttens):
for i in range(1,self.Res1.fsteps-1):
self.res1_iq_vels[iAtt,i]=sqrt((self.Res1.Qs[iAtt][i]-self.Res1.Qs[iAtt][i-1])**2+(self.Res1.Is[iAtt][i]-self.Res1.Is[iAtt][i-1])**2)
self.res1_iq_amps[iAtt,:]=sqrt((self.Res1.Qs[iAtt])**2+(self.Res1.Is[iAtt])**2)
#Sort the IQ velocities for each attenuation, to pick out the maximums
sorted_vels = numpy.sort(self.res1_iq_vels,axis=1)
#Last column is maximum values for each atten (row)
self.res1_max_vels = sorted_vels[:,-1]
#Second to last column has second highest value
self.res1_max2_vels = sorted_vels[:,-2]
#Also get indices for maximum of each atten, and second highest
sort_indices = numpy.argsort(self.res1_iq_vels,axis=1)
max_indices = sort_indices[:,-1]
max2_indices = sort_indices[:,-2]
max_neighbor = max_indices.copy()
#for each attenuation find the ratio of the maximum velocity to the second highest velocity
self.res1_max_ratio = self.res1_max_vels.copy()
max_neighbors = zeros(self.NAttens)
max2_neighbors = zeros(self.NAttens)
self.res1_max2_ratio = self.res1_max2_vels.copy()
for iAtt in range(self.NAttens):
if max_indices[iAtt] == 0:
max_neighbor = self.res1_iq_vels[iAtt,max_indices[iAtt]+1]
elif max_indices[iAtt] == len(self.res1_iq_vels[iAtt,:])-1:
max_neighbor = self.res1_iq_vels[iAtt,max_indices[iAtt]-1]
else:
max_neighbor = maximum(self.res1_iq_vels[iAtt,max_indices[iAtt]-1],
self.res1_iq_vels[iAtt,max_indices[iAtt]+1])
max_neighbors[iAtt]=max_neighbor
self.res1_max_ratio[iAtt] = self.res1_max_vels[iAtt]/max_neighbor
if max2_indices[iAtt] == 0:
max2_neighbor = self.res1_iq_vels[iAtt,max2_indices[iAtt]+1]
elif max2_indices[iAtt] == len(self.res1_iq_vels[iAtt,:])-1:
max2_neighbor = self.res1_iq_vels[iAtt,max2_indices[iAtt]-1]
else:
max2_neighbor = maximum(self.res1_iq_vels[iAtt,max2_indices[iAtt]-1],
self.res1_iq_vels[iAtt,max2_indices[iAtt]+1])
max2_neighbors[iAtt]=max2_neighbor
self.res1_max2_ratio[iAtt] = self.res1_max2_vels[iAtt]/max2_neighbor
#normalize the new arrays
self.res1_max_vels /= numpy.max(self.res1_max_vels)
self.res1_max_vels *= numpy.max(self.res1_max_ratio)
self.res1_max2_vels /= numpy.max(self.res1_max2_vels)
max_ratio_threshold = 2.5#1.5
rule_of_thumb_offset = 1#2
# require ROTO adjacent elements to be all below the MRT
bool_remove = np.ones(len(self.res1_max_ratio))
for ri in range(len(self.res1_max_ratio)-rule_of_thumb_offset-2):
bool_remove[ri] = bool((self.res1_max_ratio[ri:ri+rule_of_thumb_offset+1]< max_ratio_threshold).all())
guess_atten_idx = np.extract(bool_remove,np.arange(len(self.res1_max_ratio)))
# require the attenuation value to be past the initial peak in MRT
guess_atten_idx = guess_atten_idx[where(guess_atten_idx > argmax(self.res1_max_ratio) )[0]]
if size(guess_atten_idx) >= 1:
if guess_atten_idx[0]+rule_of_thumb_offset < len(self.Res1.atten1s):
guess_atten_idx[0] += rule_of_thumb_offset
guess_atten_idx = int(guess_atten_idx[0])
else:
guess_atten_idx = self.NAttens/2
return {'freq': self.Res1.freq,
'iq_vels': self.res1_iq_vels,
'Is': self.Res1.Is,
'Qs': self.Res1.Qs,
'attens':self.Res1.atten1s}
def loadps(self):
hd5file=openFile(self.initialFile,mode='r')
group = hd5file.getNode('/','r0')
self.freq=empty(0,dtype='float32')
for sweep in group._f_walkNodes('Leaf'):
k=sweep.read()
self.scale = k['scale'][0]
#print "Scale factor is ", self.scale
self.freq=append(self.freq,[k['f0'][0]])
hd5file.close()
class mlClassification():
def __init__(self, initialFile=None):
'''
Implements the machine learning pattern recognition algorithm on IQ velocity data as well as other tests to
choose the optimum attenuation for each resonator
'''
self.nClass = 3
self.xWidth = 40#np.shape(res1_freqs[1])
self.scalexWidth = 0.5
self.oAttDist = -1 # rule of thumb attenuation steps to reach the overpowered peak
#self.uAttDist = +2 # rule of thumb attenuation steps to reach the underpowed peak
self.initialFile = initialFile
self.baseFile = ('.').join(initialFile.split('.')[:-1])
self.PSFile = self.baseFile[:-16] + '.txt'#os.environ['MKID_DATA_DIR']+'20160712/ps_FL1_1.txt' # power sweep fit, .txt
self.trainFile = 'ps_peaks_train_w%i_s%.2f.pkl' % (self.xWidth, self.scalexWidth)
self.trainFrac = 0.8
self.testFrac=1 - self.trainFrac
def makeWindowImage(self, res_num, iAtten, xCenter, showFrames=False, test_if_noisy=False):
'''Using a given x coordinate a frame is created at that location of size xWidth x xWidth, and then flattened
into a 1d array. Called multiple times in each function.
inputs
xCenter: center location of frame in wavelength space
res_num: index of resonator in question
iAtten: index of attenuation in question
self.scalexWidth: typical values: 1/2, 1/4, 1/8
uses interpolation to put data from an xWidth x xWidth grid to a
(xWidth/scalexWidth) x (xWidth/scalexWidth) grid. This allows the
user to probe the spectrum using a smaller window while utilizing
the higher resolution training data
showFrames: pops up a window of the frame plotted using matplotlib.plot
test_if_noisy: test spectrum by comparing heights of the outer quadrants to the center. A similar test to what
the pattern recognition classification does
'''
xWidth= self.xWidth
start = int(xCenter - xWidth/2)
end = int(xCenter + xWidth/2)
scalexWidth = self.scalexWidth
# for spectra where the peak is close enough to the edge that some points falls across the bounadry, pad zeros
if start < 0:
start_diff = abs(start)
start = 0
iq_vels = self.iq_vels[res_num, iAtten, start:end]
iq_vels = np.lib.pad(iq_vels, (start_diff,0), 'constant', constant_values=(0))
elif end >= np.shape(self.freqs)[1]:
iq_vels = self.iq_vels[res_num, iAtten, start:end]
iq_vels = np.lib.pad(iq_vels, (0,end-np.shape(self.freqs)[1]+1), 'constant', constant_values=(0))
else:
iq_vels = self.iq_vels[res_num, iAtten, start:end]
iq_vels = np.round(iq_vels * xWidth / max(self.iq_vels[res_num, iAtten, :]) )
if showFrames:
fig = plt.figure(frameon=False)
fig.add_subplot(111)
plt.plot( iq_vels)
plt.ylim((0,xWidth))
plt.show()
plt.close()
# interpolate iq_vels onto a finer grid
if scalexWidth!=None:
x = np.arange(0, xWidth+1)
iq_vels = np.append(iq_vels, iq_vels[-1])
f = interpolate.interp1d(x, iq_vels)
xnew = np.arange(0, xWidth, scalexWidth)
iq_vels = f(xnew)/ scalexWidth
xWidth = int(xWidth/scalexWidth)
if test_if_noisy:
peak_iqv = mean(iq_vels[int(xWidth/4): int(3*xWidth/4)])
nonpeak_indicies=np.delete(np.arange(xWidth),np.arange(int(xWidth/4),int(3*xWidth/4)))
nonpeak_iqv = iq_vels[nonpeak_indicies]
nonpeak_iqv = mean(nonpeak_iqv[np.where(nonpeak_iqv!=0)]) # since it spans a larger area
noise_condition = 0.7
if (peak_iqv/nonpeak_iqv < noise_condition):
return None
# populates 2d image with ones at location of iq_vel
image = np.zeros((xWidth, xWidth))
for i in range(xWidth-1):
if iq_vels[i]>=xWidth: iq_vels[i] = xWidth-1
if iq_vels[i] < iq_vels[i+1]:
image[int(iq_vels[i]):int(iq_vels[i+1]),i]=1
else:
image[int(iq_vels[i]):int(iq_vels[i-1]),i]=1
if iq_vels[i] == iq_vels[i+1]:
image[int(iq_vels[i]),i]=1
try:
image[map(int,iq_vels), range(xWidth)]=1
except IndexError:
pass
image = image.flatten()
return image
def get_peak_idx(self,res_num,iAtten):
print 'IQVel Shape', shape(self.iq_vels)
print 'res_num, iAtten', res_num, iAtten
return argmax(self.iq_vels[res_num,iAtten,:])
def makeTrainData(self):
'''creates images of each class with associated labels and saves to pkl file
0: saturated peak, too much power
1: goldilocks, not too narrow or short
2: underpowered peak, too little power
outputs
train file.pkl. contains...
trainImages: cube of size- xWidth * xWidth * xCenters*trainFrac
trainLabels: 1d array of size- xCenters*trainFrac
testImages: cube of size- xWidth * xWidth * xCenters*testFrac
testLabels: 1d array of size- xCenters*testFrac
'''
self.freqs, self.iq_vels,self.Is,self.Qs, self.attens = get_PS_data_all_attens(h5File=initialFile, searchAllRes=True)
self.res_nums = np.shape(self.freqs)[0]
if os.path.isfile(self.PSFile):
print 'loading peak location data from %s' % self.PSFile
PSFile = np.loadtxt(self.PSFile, skiprows=0)[:self.res_nums]
print 'psfile shape', PSFile.shape
good_res = np.array(PSFile[:,0]-PSFile[0,0],dtype='int')
self.res_nums = len(good_res)
print 'goodres',good_res
print 'resnums', self.res_nums
#print 'good_res', good_res
opt_freqs = PSFile[:,1]
opt_attens = PSFile[:,2]
self.attens = self.attens[good_res,:]
#print 'Min Atten', min(opt_attens)
print 'opt_attens shape', shape(opt_attens)
print 'self.attens shape', shape(self.attens)
#print 'self.attens', self.attens
#print 'opt attens range', max(opt_attens)-min(opt_attens)
optAttenLocs = np.where(np.transpose(np.transpose(np.array(self.attens))==np.array(opt_attens))) #find optimal atten indices
#print np.array(self.attens)
#print np.array(opt_attens)
#print np.transpose(opt_attens)==self.attens
optAttenExists = optAttenLocs[0]
self.opt_iAttens = optAttenLocs[1]
attenSkips = optAttenLocs[0]-np.arange(len(optAttenLocs[0]))
attenSkips = np.where(np.diff(attenSkips))[0]+1 #indices where opt atten was not found
for resSkip in attenSkips:
print 'resSkip', resSkip
if(opt_attens[resSkip]<self.attens[resSkip,0]):
opt_attens[resSkip] = self.attens[resSkip,0]
self.opt_iAttens = np.insert(self.opt_iAttens,resSkip,0)
elif(opt_attens[resSkip]>self.attens[resSkip,-1]):
opt_attens[resSkip] = self.attens[resSkip,-1]
self.opt_iAttens = np.insert(self.opt_iAttens,resSkip,np.shape(self.attens)[1]-1)
print '129 opt_atten', opt_attens[129]
print '129 atten', self.attens[129,:]
print '129 opt_freq', opt_freqs[129]
print '129 freq', self.freqs[129]
print 'opt_iAtten shape', np.shape(self.opt_iAttens)
#self.opt_iAttens = opt_attens - min(opt_attens)
print 'attenSkipIndices', attenSkips
else:
print 'no PS.txt file found'
exit()
#good_res = np.arange(self.res_nums)
iAttens = np.zeros((self.res_nums,self.nClass))
iAttens[:,0] = self.opt_iAttens[:self.res_nums] + self.oAttDist
iAttens[:,1] = self.opt_iAttens[:self.res_nums] # goldilocks attenuation
iAttens[:,2] = np.ones((self.res_nums))*20#self.opt_iAttens[:self.res_nums] + self.uAttDist
lb_rej = np.where(iAttens[:,0]<0)[0]
print 'lb_rej', lb_rej
if len(lb_rej) != 0:
iAttens = np.delete(iAttens,lb_rej,axis=0) # when index is below zero
good_res = np.delete(good_res,lb_rej)
self.res_nums = self.res_nums-len(lb_rej)
ub_rej = np.where(iAttens[:,2]>len(self.attens))[0]
if len(ub_rej) != 0:
iAttens = np.delete(iAttens,ub_rej,axis=0)
good_res = np.delete(good_res,ub_rej)
self.res_nums = self.res_nums-len(ub_rej)
self.res_indicies = np.zeros((self.res_nums,self.nClass))
print 'goodresshape', np.shape(good_res)
for i, rn in enumerate(good_res):
self.res_indicies[i,0] = self.get_peak_idx(rn,iAttens[i,0])
self.res_indicies[i,1] = self.get_peak_idx(rn,iAttens[i,1])
self.res_indicies[i,2] = self.get_peak_idx(rn,iAttens[i,2])
self.iq_vels=self.iq_vels[good_res]
self.freqs=self.freqs[good_res]
self.Is = self.Is[good_res]
self.Qs = self.Qs[good_res]
trainImages, trainLabels, testImages, testLabels = [], [], [], []
for c in range(self.nClass):
for rn in range(int(self.trainFrac*self.res_nums) ):
image = self.makeWindowImage(res_num = rn, iAtten= iAttens[rn,c], xCenter=self.res_indicies[rn,c])
if image!=None:
trainImages.append(image)
one_hot = np.zeros(self.nClass)
one_hot[c] = 1
trainLabels.append(one_hot)
# A more simple way would be to separate the train and test data after they were read but this did not occur to me
#before most of the code was written
for c in range(self.nClass):
for rn in range(int(self.trainFrac*self.res_nums), int(self.trainFrac*self.res_nums + self.testFrac*self.res_nums)) :
image = self.makeWindowImage(res_num = rn, iAtten= iAttens[rn,c], xCenter=self.res_indicies[rn,c])
if image!=None:
testImages.append(image)
one_hot = np.zeros(self.nClass)
one_hot[c] = 1
testLabels.append(one_hot)
append = None
if os.path.isfile(self.trainFile):
append = raw_input('Do you want to append this training data to previous data [y/n]')
if (append == 'y') or (os.path.isfile(self.trainFile)== False):
print 'saving files %s & to %s' % (self.trainFile, os.path.dirname(os.path.abspath(self.trainFile)) )
with open(self.trainFile, 'ab') as tf:
pickle.dump([trainImages, trainLabels], tf)
pickle.dump([testImages, testLabels], tf)
def mlClass(self):
'''Code adapted from the tensor flow MNIST tutorial 1.
Using training images and labels the machine learning class (mlClass) "learns" how to classify IQ velocity peaks.
Using similar data the ability of mlClass to classify peaks is tested
The training and test matricies are loaded from file (those made earlier if chosen to not be appended to file
will not be used)
'''
if not os.path.isfile(self.trainFile):
self.makeTrainData()
trainImages, trainLabels, testImages, testLabels = loadPkl(self.trainFile)
print 'Number of training images:', np.shape(trainImages)[0], ' Number of test images:', np.shape(testImages)[0]
if self.scalexWidth != None:
self.xWidth = self.xWidth/self.scalexWidth
if np.shape(trainImages)[1]!=self.xWidth**2:
print 'Please make new training images of the correct size'
exit()
self.nClass = np.shape(trainLabels)[1]
self.x = tf.placeholder(tf.float32, [None, self.xWidth**2]) # correspond to the images
self.W = tf.Variable(tf.zeros([self.xWidth**2, self.nClass])) #the weights used to make predictions on classes
self.b = tf.Variable(tf.zeros([self.nClass])) # the biases also used to make class predictions
self.y = tf.nn.softmax(tf.matmul(self.x, self.W) + self.b) # class lables predictions made from x,W,b
y_ = tf.placeholder(tf.float32, [None, self.nClass]) # true class lables identified by user
cross_entropy = -tf.reduce_sum(y_*tf.log(tf.clip_by_value(self.y,1e-10,1.0)) ) # find out how right you are by finding out how wrong you are
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) # the best result is when the wrongness is minimal
init = tf.initialize_all_variables()
self.sess = tf.Session()
self.sess.run(init) # need to do this everytime you want to access a tf variable (for example the true class labels calculation or plotweights)
trainReps = 500
batches = 100
if np.shape(trainLabels)[0]< batches:
batches = np.shape(trainLabels)[0]/2
print 'Performing', trainReps, 'training repeats, using batches of', batches
for i in range(trainReps): #perform the training step using random batches of images and according labels
batch_xs, batch_ys = next_batch(trainImages, trainLabels, batches)
self.sess.run(train_step, feed_dict={self.x: batch_xs, y_: batch_ys}) #calculate train_step using feed_dict
print 'true class labels: ', self.sess.run(tf.argmax(y_,1),
feed_dict={self.x: testImages, y_: testLabels})[:25]
print 'class estimates: ', self.sess.run(tf.argmax(self.y,1),
feed_dict={self.x: testImages, y_: testLabels})[:25] #1st 25 printed
#print self.sess.run(self.y, feed_dict={self.x: testImages, y_: testLabels})[:100] # print the scores for each class
correct_prediction = tf.equal(tf.argmax(self.y,1), tf.argmax(y_,1)) #which ones did it get right?
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
score = self.sess.run(accuracy, feed_dict={self.x: testImages, y_: testLabels}) * 100
print 'Accuracy of model in testing: ', score, '%'
if score < 95: print 'Consider making more training images'
del trainImages, trainLabels, testImages, testLabels
def plotWeights(self):
'''creates a 2d map showing the positive and negative weights for each class'''
weights = self.sess.run(self.W)
weights = np.reshape(weights,(self.xWidth,self.xWidth,self.nClass))
weights = np.flipud(weights)
for nc in range(self.nClass):
plt.imshow(weights[:,:, nc])
plt.title('class %i' % nc)
plt.show()
plt.close()
def checkLoopAtten(self, res_num, iAtten, showLoop=False, min_theta = 135, max_theta = 200, max_ratio_threshold = 1.5):
'''function to check if the IQ loop at a certain attenuation is saturated. 3 checks are made.
if the angle on either side of the sides connected to the longest edge is < min_theta or > max_theta
the loop is saturated. Or if the ratio between the 1st and 2nd largest edge is > max_ratio_threshold.
A True result means that the loop is unsaturated.
Inputs:
res_num: index of resonator in question
iAtten: index of attenuation in question
showLoop: pops up a window of the frame plotted using matplotlib.plot
min/max_theta: limits outside of which the loop is considered saturated
max_ratio_threshold: maximum largest/ 2nd largest IQ velocity allowed before loop is considered saturated
Output:
Boolean. True if unsaturated
'''
vindx = (-self.iq_vels[res_num,iAtten,:]).argsort()[:3]
max_theta_vel = math.atan2(self.Qs[res_num,iAtten,vindx[0]-1] - self.Qs[res_num,iAtten,vindx[0]],
self.Is[res_num,iAtten,vindx[0]-1] - self.Is[res_num,iAtten,vindx[0]])
low_theta_vel = math.atan2(self.Qs[res_num,iAtten,vindx[0]-2] - self.Qs[res_num,iAtten,vindx[0]-1],
self.Is[res_num,iAtten,vindx[0]-2] - self.Is[res_num,iAtten,vindx[0]-1])
upp_theta_vel = math.atan2(self.Qs[res_num,iAtten,vindx[0]] - self.Qs[res_num,iAtten,vindx[0]+1],
self.Is[res_num,iAtten,vindx[0]] - self.Is[res_num,iAtten,vindx[0]+1])
theta1 = (math.pi + max_theta_vel - low_theta_vel)/math.pi * 180
theta2 = (math.pi + upp_theta_vel - max_theta_vel)/math.pi * 180
theta1 = abs(theta1)
if theta1 > 360:
theta1 = theta1-360
theta2= abs(theta2)
if theta2 > 360:
theta2 = theta2-360
max_ratio = self.iq_vels[res_num,iAtten,vindx[0]]/ self.iq_vels[res_num,iAtten,vindx[1]]
if showLoop:
plt.plot(self.Is[res_num,iAtten,:],self.Qs[res_num,iAtten,:])
plt.show()
return bool((max_theta >theta1 > min_theta) *
(max_theta > theta2 > min_theta) *
(max_ratio < max_ratio_threshold))
def findAtten(self, inferenceFile, wsFile, res_nums =20, searchAllRes=True, showFrames = True, usePSFit=True, useWSID=True):
'''The trained machine learning class (mlClass) finds the optimum attenuation for each resonator using peak shapes in IQ velocity
Inputs
inferenceFile: widesweep data file to be used
searchAllRes: if only a few resonator attenuations need to be identified set to False
res_nums: if searchAllRes is False, the number of resonators the atteunation value will be estimated for
usePSFit: if true once all the resonator attenuations have been estimated these values are fed into PSFit which opens
the window where the user can manually check all the peaks have been found and make corrections if neccessary
Outputs
Goodfile: either immediately after the peaks have been located or through WideAna if useWideAna =True
mlFile: temporary file read in to PSFit.py containing an attenuation estimate for each resonator
'''
try:
self.sess
except AttributeError:
print 'You have to train the model first'
exit()
if self.scalexWidth!= None:
self.xWidth=self.xWidth*self.scalexWidth #reset ready for get_PS_data
self.freqs, self.iq_vels, self.Is, self.Qs, self.attens = get_PS_data(h5File=inferenceFile,
searchAllRes=searchAllRes,
res_nums=res_nums)
total_res_nums = np.shape(self.freqs)[0]
print 'number of res in sweep file', total_res_nums
print 'freqs', self.freqs
print 'freqShape', np.shape(self.freqs)
if searchAllRes:
res_nums = total_res_nums
span = range(res_nums)
self.inferenceLabels = np.zeros((res_nums,len(self.attens),self.nClass))
print 'Using trained algorithm on images on each resonator'
skip = []
for i,rn in enumerate(span):
sys.stdout.write("\r%d of %i" % (i+1,res_nums) )
sys.stdout.flush()
for ia in range(len(self.attens)):
# first check the loop for saturation
nonsaturated_loop = self.checkLoopAtten(res_num=rn, iAtten= ia, showLoop=showFrames)
if nonsaturated_loop:
# each image is formatted into a single element of a list so sess.run can receive a single values dictionary
# argument and save memory
image = self.makeWindowImage(res_num = rn, iAtten= ia,
xCenter=self.get_peak_idx(rn,ia),
showFrames=showFrames)
inferenceImage=[]
inferenceImage.append(image) # inferenceImage is just reformatted image
self.inferenceLabels[rn,ia,:] = self.sess.run(self.y, feed_dict={self.x: inferenceImage} )
del inferenceImage
del image
else:
self.inferenceLabels[rn,ia,:] = [1,0,0] # would just skip these if certain
if np.all(self.inferenceLabels[rn,:,1] ==0): # if all loops appear saturated for resonator then set attenuation to highest
self.inferenceLabels[rn,-1,:] = [0,1,0] # or omit from list
#skip.append(rn)
print '\n'
max_2nd_vels = np.zeros((res_nums,len(self.attens)))
for r in range(res_nums):
for iAtten in range(len(self.attens)):
vindx = (-self.iq_vels[r,iAtten,:]).argsort()[:2]
max_2nd_vels[r,iAtten] = self.iq_vels[r,iAtten,vindx[1]]
atten_guess=numpy.zeros((res_nums))
# choose attenuation where there is the maximum in the 2nd highest IQ velocity
for r in range(res_nums):
class_guess = np.argmax(self.inferenceLabels[r,:,:], 1)
if np.any(class_guess==1):
atten_guess[r] = np.where(class_guess==1)[0][argmax(max_2nd_vels[r,:][np.where(class_guess==1)[0]] )]
else:
atten_guess[r] = argmax(self.inferenceLabels[r,:,1])
wsIds = np.loadtxt(wsFile)[:,0]
if usePSFit:
if skip != None:
atten_guess = np.delete(atten_guess,skip)
self.mlFile = ('.').join(inferenceFile.split('.')[:-1]) + '-ml.txt'
if os.path.isfile(self.mlFile):
self.mlFile = self.mlFile+time.strftime("-%Y-%m-%d-%H-%M-%S")
#shutil.copy(self.mlFile, self.mlFile+time.strftime("-%Y-%m-%d-%H-%M-%S"))
print 'wrote', self.mlFile
mlf = open(self.mlFile,'wb') #mlf machine learning file is temporary
for ag in atten_guess:
line = "%12d\n" % ag
mlf.write(line)
mlf.close()
#on ubuntu 14.04 and matplotlib-1.5.1 backend 'Qt4Agg' running matplotlib.show() prior to this causes segmentation fault
os.system("python PSFit.py 1")
#os.remove(self.mlFile)
else:
baseFile = ('.').join(inferenceFile.split('.')[:-1])
#saveFile = baseFile + '.txt'
saveFile = baseFile[:-16] + '.txt'
#saveFile = 'newAttens.txt'
sf = open(saveFile,'wb')
print 'saving file', saveFile
print 'baseFile', baseFile
#sf.write('1\t1\t1\t1 \n')
for r in np.delete(range(len(atten_guess)),skip):
line = "%4i \t %10.9e \t %4i \n" % (wsIds[r], self.freqs[r, self.get_peak_idx(r, atten_guess[r])],
self.attens[atten_guess[r]] )
sf.write(line)
print line
sf.close()
def next_batch(trainImages, trainLabels, batch_size):
'''selects a random batch of batch_size from trainImages and trainLabels'''
perm = random.sample(range(len(trainImages)), batch_size)
trainImages = np.array(trainImages)[perm,:]
trainLabels = np.array(trainLabels)[perm,:]
return trainImages, trainLabels
def loadPkl(filename):
'''load the train and test data to train and test mlClass
pkl file hirerachy is as follows:
-The file is split in two, one side for train data and one side for test data -These halfs are further divdided into image data and labels
-makeTrainData creates image data of size: xWidth * xWidth * res_nums and the label data of size: res_nums
-each time makeTrainData is run a new image cube and label array is created and appended to the old data
so the final size of the file is (xWidth * xWidth * res_nums * "no of train runs") + (res_nums * "no of train runs") + [the equivalent test data structure]
A more simple way would be to separate the train and test data after they were read but this did not occur to the
me before most of the code was written
Input
pkl filename to be read.
Outputs
image cube and label array
'''
file =[]
with open(filename, 'rb') as f:
while 1:
try:
file.append(pickle.load(f))
except EOFError:
break
trainImages = file[0][0]
trainLabels = file[0][1]
testImages = file[1][0]
testLabels = file[1][1]
if np.shape(file)[0]/2 > 1:
for i in range(1, np.shape(file)[0]/2-1):
trainImages = np.append(trainImages, file[2*i][0], axis=0)
trainLabels = np.append(trainLabels, file[2*i][1], axis=0)
testImages = np.append(testImages, file[2*i+1][0], axis=0)
testLabels = np.append(testLabels, file[2*i+1][1], axis=0)
print "loaded dataset from ", filename
return trainImages, trainLabels, testImages, testLabels
def get_PS_data(h5File=None, searchAllRes=False, res_nums=50):
'''A function to read and write all resonator information so stop having to run the PSFit function on all resonators
if running the script more than once. This is used on both the initial and inference file
Inputs:
h5File: the power sweep h5 file for the information to be extracted from. Can be initialFile or inferenceFile
'''
print 'get_PS_data H5 file', h5File
baseFile = ('.').join(h5File.split('.')[:-1])
PSPFile = baseFile[:-16] + '.pkl'
print 'resNums', res_nums
if os.path.isfile(PSPFile):
file = []
with open(PSPFile, 'rb') as f:
for v in range(5):
file.append(pickle.load(f))
if searchAllRes:
res_nums = -1
freqs = file[0][:res_nums]
print 'freqshape get_PS_data', np.shape(freqs)
iq_vels = file[1][:res_nums]
Is = file[2][:res_nums]
Qs= file[3][:res_nums]
attens = file[4]
else:
PSFit = PSFitting(initialFile=h5File)
PSFit.loadps()
tot_res_nums= len(PSFit.freq)
print 'totalResNums in getPSdata', tot_res_nums
if searchAllRes:
res_nums = tot_res_nums
res_size = np.shape(PSFit.loadres()['iq_vels'])
freqs = np.zeros((res_nums, res_size[1]+1))
iq_vels = np.zeros((res_nums, res_size[0], res_size[1]))
Is = np.zeros((res_nums, res_size[0], res_size[1]+1))
Qs = np.zeros((res_nums, res_size[0], res_size[1]+1))
attens = np.zeros((res_size[0]))
for r in range(res_nums):
sys.stdout.write("\r%d of %i" % (r+1,res_nums) )
sys.stdout.flush()
res = PSFit.loadres()
freqs[r,:] =res['freq']
iq_vels[r,:,:] = res['iq_vels']
Is[r,:,:] = res['Is']
Qs[r,:,:] = res['Qs']
attens[:] = res['attens']
PSFit.resnum += 1
with open(PSPFile, "wb") as f:
pickle.dump(freqs, f)
pickle.dump(iq_vels, f)
pickle.dump(Is, f)
pickle.dump(Qs, f)
pickle.dump(attens, f)
return freqs, iq_vels, Is, Qs, attens
def get_PS_data_all_attens(h5File=None, searchAllRes=False, res_nums=50):
'''A function to read and write all resonator information so stop having to run the PSFit function on all resonators
if running the script more than once. This is used on both the initial and inference file
Inputs:
h5File: the power sweep h5 file for the information to be extracted from. Can be initialFile or inferenceFile
'''
print 'get_PS_data_all_attens H5 file', h5File
baseFile = ('.').join(h5File.split('.')[:-1])
PSPFile = baseFile[:-16] + '.pkl'
print 'resNums', res_nums
if os.path.isfile(PSPFile):
file = []
with open(PSPFile, 'rb') as f:
for v in range(5):
file.append(pickle.load(f))
if searchAllRes:
res_nums = -1
freqs = file[0][:]
print 'freqshape get_PS_data', np.shape(freqs)
iq_vels = file[1][:]
Is = file[2][:]
Qs= file[3][:]
attens = file[4]
else:
freqs = file[0][:res_nums]
print 'freqshape get_PS_data', np.shape(freqs)
iq_vels = file[1][:res_nums]
Is = file[2][:res_nums]
Qs= file[3][:res_nums]
attens = file[4]
else:
PSFit = PSFitting(initialFile=h5File)
PSFit.loadps()
tot_res_nums= len(PSFit.freq)
print 'totalResNums in getPSdata', tot_res_nums
if searchAllRes:
res_nums = tot_res_nums
res_size = np.shape(PSFit.loadres()['iq_vels'])
freqs = np.zeros((res_nums, res_size[1]+1))
iq_vels = np.zeros((res_nums, res_size[0], res_size[1]))
Is = np.zeros((res_nums, res_size[0], res_size[1]+1))
Qs = np.zeros((res_nums, res_size[0], res_size[1]+1))
attens = np.zeros((res_nums, res_size[0]))
for r in range(res_nums):
sys.stdout.write("\r%d of %i" % (r+1,res_nums) )
sys.stdout.flush()
res = PSFit.loadres()
freqs[r,:] =res['freq']
iq_vels[r,:,:] = res['iq_vels']
Is[r,:,:] = res['Is']
Qs[r,:,:] = res['Qs']
attens[r,:] = res['attens']
PSFit.resnum += 1
with open(PSPFile, "wb") as f:
pickle.dump(freqs, f)
pickle.dump(iq_vels, f)
pickle.dump(Is, f)
pickle.dump(Qs, f)
pickle.dump(attens, f)
print 'attenshape',shape(attens)
return freqs, iq_vels, Is, Qs, attens
def main(initialFile=None, inferenceFile=None, wsFile=None, res_nums=497):
mlClass = mlClassification(initialFile=initialFile)
#mlClass.makeTrainData()
mlClass.mlClass()
mlClass.plotWeights()
mlClass.findAtten(inferenceFile=inferenceFile, wsFile=wsFile, searchAllRes=True, usePSFit=False, showFrames=False, res_nums=497)
if __name__ == "__main__":
initialFile = None
inferenceFile = None
if len(sys.argv) > 2:
initialFileName = sys.argv[1]
inferenceFileName = sys.argv[2]
wsFileName = sys.argv[3]
#mdd = os.environ['pwd']
initialFile = os.path.join('./mlTrainingData',initialFileName)
#inferenceFile = os.path.join(mdd,inferenceFileName)
#initialFile = initialFileName
inferenceFile = os.path.join('/home/neelay/DarknessData/powerSweeps', inferenceFileName)
wsFile = os.path.join('/home/neelay/DarknessData/wideSweeps', wsFileName)
else:
print "need to specify an initial and inference filename located in MKID_DATA_DIR"
exit()
main(initialFile=initialFile, inferenceFile=inferenceFile, wsFile=wsFile)
| 40,224 | 45.991822 | 159 | py |
SDR | SDR-master/Setup/PSFile.py | from tables import *
from numpy import *
from lib.iqsweep import *
class PSFile():
def __init__(self,fileName):
self.openfile = fileName
hd5File = openFile(fileName,mode='r')
group = hd5File.getNode('/','r0')
self.freq=empty(0,dtype='float32')
for sweep in group._f_walkNodes('Leaf'):
k=sweep.read()
self.scale = k['scale'][0]
#print "Scale factor is ", self.scale
self.freq=append(self.freq,[k['f0'][0]])
hd5File.close()
def loadres(self, resnum):
self.resnum = resnum
self.Res1=IQsweep()
self.Res1.LoadPowers(str(self.openfile), 'r0', self.freq[self.resnum])
#self.ui.res_num.setText(str(self.resnum))
self.resfreq = self.resnum
#self.ui.frequency.setText(str(self.resfreq))
self.NAttens = len(self.Res1.atten1s)
self.res1_iq_vels=zeros((self.NAttens,self.Res1.fsteps-1))
self.res1_iq_amps=zeros((self.NAttens,self.Res1.fsteps))
for iAtt in range(self.NAttens):
for i in range(1,self.Res1.fsteps-1):
self.res1_iq_vels[iAtt,i]=sqrt((self.Res1.Qs[iAtt][i]-self.Res1.Qs[iAtt][i-1])**2+(self.Res1.Is[iAtt][i]-self.Res1.Is[iAtt][i-1])**2)
self.res1_iq_amps[iAtt,:]=sqrt((self.Res1.Qs[iAtt])**2+(self.Res1.Is[iAtt])**2)
#Sort the IQ velocities for each attenuation, to pick out the maximums
sorted_vels = sort(self.res1_iq_vels,axis=1)
#Last column is maximum values for each atten (row)
self.res1_max_vels = sorted_vels[:,-1]
#Second to last column has second highest value
self.res1_max2_vels = sorted_vels[:,-2]
#Also get indices for maximum of each atten, and second highest
sort_indices = argsort(self.res1_iq_vels,axis=1)
max_indices = sort_indices[:,-1]
max2_indices = sort_indices[:,-2]
max_neighbor = max_indices.copy()
#for each attenuation find the ratio of the maximum velocity to the second highest velocity
self.res1_max_ratio = self.res1_max_vels.copy()
max_neighbors = zeros(self.NAttens)
max2_neighbors = zeros(self.NAttens)
self.res1_max2_ratio = self.res1_max2_vels.copy()
for iAtt in range(self.NAttens):
if max_indices[iAtt] == 0:
max_neighbor = self.res1_iq_vels[iAtt,max_indices[iAtt]+1]
elif max_indices[iAtt] == len(self.res1_iq_vels[iAtt,:])-1:
max_neighbor = self.res1_iq_vels[iAtt,max_indices[iAtt]-1]
else:
max_neighbor = maximum(self.res1_iq_vels[iAtt,max_indices[iAtt]-1],self.res1_iq_vels[iAtt,max_indices[iAtt]+1])
max_neighbors[iAtt]=max_neighbor
self.res1_max_ratio[iAtt] = self.res1_max_vels[iAtt]/max_neighbor
if max2_indices[iAtt] == 0:
max2_neighbor = self.res1_iq_vels[iAtt,max2_indices[iAtt]+1]
elif max2_indices[iAtt] == len(self.res1_iq_vels[iAtt,:])-1:
max2_neighbor = self.res1_iq_vels[iAtt,max2_indices[iAtt]-1]
else:
max2_neighbor = maximum(self.res1_iq_vels[iAtt,max2_indices[iAtt]-1],self.res1_iq_vels[iAtt,max2_indices[iAtt]+1])
max2_neighbors[iAtt]=max2_neighbor
self.res1_max2_ratio[iAtt] = self.res1_max2_vels[iAtt]/max2_neighbor
#normalize the new arrays
self.res1_max_vels /= max(self.res1_max_vels)
self.res1_max_vels *= max(self.res1_max_ratio)
self.res1_max2_vels /= max(self.res1_max2_vels)
#self.res1_relative_max_vels /= numpy.max(self.res1_relative_max_vels)
#self.ui.plot_1.canvas.ax.clear()
#self.ui.plot_1.canvas.ax.plot(self.Res1.atten1s,self.res1_max_vels,'b.-',label='Max IQ velocity')
#self.ui.plot_1.canvas.ax.plot(self.Res1.atten1s,max_neighbors,'r.-')
#self.ui.plot_1.canvas.ax.plot(self.Res1.atten1s,self.res1_max_ratio,'k.-',label='Ratio (Max Vel)/(2nd Max Vel)')
#self.ui.plot_1.canvas.ax.legend()
#self.ui.plot_1.canvas.ax.set_xlabel('attenuation')
#self.ui.plot_1.canvas.ax.plot(self.Res1.atten1s,self.res1_max2_vels-1,'b.-')
#self.ui.plot_1.canvas.ax.plot(self.Res1.atten1s,max2_neighbors-1,'b.-')
#self.ui.plot_1.canvas.ax.plot(self.Res1.atten1s,self.res1_max2_ratio-1,'g.-')
#cid=self.ui.plot_1.canvas.mpl_connect('button_press_event', self.click_plot_1)
#self.ui.plot_1.canvas.format_labels()
#self.ui.plot_1.canvas.draw()
max_ratio_threshold = 1.5
guess_atten_idx = where(self.res1_max_ratio < max_ratio_threshold)
rule_of_thumb_offset = 2
if size(guess_atten_idx) >= 1:
if guess_atten_idx[0][0]+rule_of_thumb_offset < len(self.Res1.atten1s):
guess_atten_idx[0][0] += rule_of_thumb_offset
guess_atten = self.Res1.atten1s[guess_atten_idx[0][0]]
print 'Guessing attenuation is ',guess_atten
#self.select_atten(guess_atten)
else:
print 'Defaulting guess attenuation to center'
#self.select_atten(self.Res1.atten1s[self.NAttens/2])
| 5,195 | 52.020408 | 149 | py |
SDR | SDR-master/Setup/PSFit_ml.py | '''
Author Rupert Dodkins
A script to automate the identification of resonator attenuations normally performed by PSFit.py. This is accomplished
using Google's Tensor Flow machine learning package which implements a pattern recognition algorithm on the IQ velocity
spectrum. The code implements a 2D image classification algorithm similar to the MNIST test. This code creates a 2D
image from a 1D variable by populating a matrix of zeros with ones at the y location of each datapoint
Usage: python PSFit_ml.py 20160712/ps_r115_FL1_1_20160712-225809.h5 20160720/ps_r118_FL1_b_pos_20160720-231653.h5
Inputs:
20160712/ps_r115_FL1_1.txt: list of resonator frequencies and correct attenuations
20160712/ps_r115_FL1_1_20160712-225809.h5: corresponding powersweep file
20160720/ps_r118_FL1_b_pos_20160720-231653.h5: powersweep file the user wishes to infer attenuations for
Intermediaries:
SDR/Setup/ps_peaks_train_w<x>_s<y>.pkl: images and corresponding labels used to train the algorithm
Outputs:
20160712/ps_r115_FL1_1.pkl: frequencies, IQ velocities, Is, Qs, attenuations formatted for quick use
20160720/ps_r118_FL1_b_pos_20160720-231653-ml.txt: to be used with PSFit.py (temporary)
20160720/ps_r118_FL1_b_pos.txt: final list of frequencies and attenuations
How it works:
For each resonator and attenuation the script first assesses if the IQ loop appears saturated. If the unstaurated IQ
velocity spectrum for that attenuation is compared with the pattern recognition machine. A list of attenuations for each
resonator, where the loop is not saturated and the IQ velocity peak looks the correct shape, and the attenuation value
is chosen which has the highest 2nd largest IQ velocity. This identifier was chosen because the optimum attenuation
value has a high max IQ velocity and a low ratio of max IQ velocity to 2nd max IQ velocity which is equivalent to
choosing the highest 2nd max IQ velocity.
This list of attenuation values and frequencies are either fed PSFit.py to checked manually or dumped to
ps_r118_FL1_b_pos.txt
The machine learning algorithm requires a series of images to train and test the algorithm with. If they exist the image
data will be loaded from a train pkl file
Alternatively, if the user does not have a train pkl file but does have a powersweep file and corresponding list of
resonator attenuations this should be used as the initial file and training data will be made. The 3 classes are an
overpowered peak (saturated), peak with the correct amount of power, or an underpowered peak.
These new image data will be saved as pkl files (or appened to existing pkl files) and reloaded
The machine is then trained and its ability to predict the type of image is validated
The weights used to make predictions for each class can be displayed using the plotWeights function
to do:
change training txt file freq comparison function so its able to match all frequencies
'''
import os,sys,inspect
from PSFit import *
from lib.iqsweep import *
import numpy as np
import sys, os
import matplotlib.pyplot as plt
import tensorflow as tf
import pickle
import random
import time
import math
from scipy import interpolate
#removes visible depreciation warnings from lib.iqsweep
import warnings
warnings.filterwarnings("ignore")
class PSFitting():
'''Class has been lifted from PSFit.py and modified to incorporate the machine learning algorithms from
WideAna_ml.py
'''
def __init__(self, initialFile=None):
self.initialFile = initialFile
self.resnum = 0
def loadres(self):
'''
Outputs
Freqs: the span of frequencies for a given resonator
iq_vels: the IQ velocities for all attenuations for a given resonator
Is: the I component of the frequencies for a given resonator
Qs: the Q component of the frequencies for a given resonator
attens: the span of attenuations. The same for all resonators
'''
self.Res1=IQsweep()
self.Res1.LoadPowers(self.initialFile, 'r0', self.freq[self.resnum])
self.resfreq = self.freq[self.resnum]
self.NAttens = len(self.Res1.atten1s)
self.res1_iq_vels=numpy.zeros((self.NAttens,self.Res1.fsteps-1))
self.res1_iq_amps=numpy.zeros((self.NAttens,self.Res1.fsteps))
for iAtt in range(self.NAttens):
for i in range(1,self.Res1.fsteps-1):
self.res1_iq_vels[iAtt,i]=sqrt((self.Res1.Qs[iAtt][i]-self.Res1.Qs[iAtt][i-1])**2+(self.Res1.Is[iAtt][i]-self.Res1.Is[iAtt][i-1])**2)
self.res1_iq_amps[iAtt,:]=sqrt((self.Res1.Qs[iAtt])**2+(self.Res1.Is[iAtt])**2)
#Sort the IQ velocities for each attenuation, to pick out the maximums
sorted_vels = numpy.sort(self.res1_iq_vels,axis=1)
#Last column is maximum values for each atten (row)
self.res1_max_vels = sorted_vels[:,-1]
#Second to last column has second highest value
self.res1_max2_vels = sorted_vels[:,-2]
#Also get indices for maximum of each atten, and second highest
sort_indices = numpy.argsort(self.res1_iq_vels,axis=1)
max_indices = sort_indices[:,-1]
max2_indices = sort_indices[:,-2]
max_neighbor = max_indices.copy()
#for each attenuation find the ratio of the maximum velocity to the second highest velocity
self.res1_max_ratio = self.res1_max_vels.copy()
max_neighbors = zeros(self.NAttens)
max2_neighbors = zeros(self.NAttens)
self.res1_max2_ratio = self.res1_max2_vels.copy()
for iAtt in range(self.NAttens):
if max_indices[iAtt] == 0:
max_neighbor = self.res1_iq_vels[iAtt,max_indices[iAtt]+1]
elif max_indices[iAtt] == len(self.res1_iq_vels[iAtt,:])-1:
max_neighbor = self.res1_iq_vels[iAtt,max_indices[iAtt]-1]
else:
max_neighbor = maximum(self.res1_iq_vels[iAtt,max_indices[iAtt]-1],
self.res1_iq_vels[iAtt,max_indices[iAtt]+1])
max_neighbors[iAtt]=max_neighbor
self.res1_max_ratio[iAtt] = self.res1_max_vels[iAtt]/max_neighbor
if max2_indices[iAtt] == 0:
max2_neighbor = self.res1_iq_vels[iAtt,max2_indices[iAtt]+1]
elif max2_indices[iAtt] == len(self.res1_iq_vels[iAtt,:])-1:
max2_neighbor = self.res1_iq_vels[iAtt,max2_indices[iAtt]-1]
else:
max2_neighbor = maximum(self.res1_iq_vels[iAtt,max2_indices[iAtt]-1],
self.res1_iq_vels[iAtt,max2_indices[iAtt]+1])
max2_neighbors[iAtt]=max2_neighbor
self.res1_max2_ratio[iAtt] = self.res1_max2_vels[iAtt]/max2_neighbor
#normalize the new arrays
self.res1_max_vels /= numpy.max(self.res1_max_vels)
self.res1_max_vels *= numpy.max(self.res1_max_ratio)
self.res1_max2_vels /= numpy.max(self.res1_max2_vels)
max_ratio_threshold = 2.5#1.5
rule_of_thumb_offset = 1#2
# require ROTO adjacent elements to be all below the MRT
bool_remove = np.ones(len(self.res1_max_ratio))
for ri in range(len(self.res1_max_ratio)-rule_of_thumb_offset-2):
bool_remove[ri] = bool((self.res1_max_ratio[ri:ri+rule_of_thumb_offset+1]< max_ratio_threshold).all())
guess_atten_idx = np.extract(bool_remove,np.arange(len(self.res1_max_ratio)))
# require the attenuation value to be past the initial peak in MRT
guess_atten_idx = guess_atten_idx[where(guess_atten_idx > argmax(self.res1_max_ratio) )[0]]
if size(guess_atten_idx) >= 1:
if guess_atten_idx[0]+rule_of_thumb_offset < len(self.Res1.atten1s):
guess_atten_idx[0] += rule_of_thumb_offset
guess_atten_idx = int(guess_atten_idx[0])
else:
guess_atten_idx = self.NAttens/2
return {'freq': self.Res1.freq,
'iq_vels': self.res1_iq_vels,
'Is': self.Res1.Is,
'Qs': self.Res1.Qs,
'attens':self.Res1.atten1s}
def loadps(self):
hd5file=openFile(self.initialFile,mode='r')
group = hd5file.getNode('/','r0')
self.freq=empty(0,dtype='float32')
for sweep in group._f_walkNodes('Leaf'):
k=sweep.read()
self.scale = k['scale'][0]
#print "Scale factor is ", self.scale
self.freq=append(self.freq,[k['f0'][0]])
hd5file.close()
class mlClassification():
def __init__(self, initialFile=None):
'''
Implements the machine learning pattern recognition algorithm on IQ velocity data as well as other tests to
choose the optimum attenuation for each resonator
'''
self.nClass = 3
self.xWidth = 40#np.shape(res1_freqs[1])
self.scalexWidth = 0.5
self.oAttDist = -1 # rule of thumb attenuation steps to reach the overpowered peak
#self.uAttDist = +2 # rule of thumb attenuation steps to reach the underpowed peak
self.initialFile = initialFile
self.baseFile = ('.').join(initialFile.split('.')[:-1])
self.PSFile = self.baseFile[:-16] + '.txt'#os.environ['MKID_DATA_DIR']+'20160712/ps_FL1_1.txt' # power sweep fit, .txt
self.trainFile = 'ps_peaks_train_w%i_s%.2f.pkl' % (self.xWidth, self.scalexWidth)
self.trainFrac = 0.8
self.testFrac=1 - self.trainFrac
def makeWindowImage(self, res_num, iAtten, xCenter, showFrames=False, test_if_noisy=False):
'''Using a given x coordinate a frame is created at that location of size xWidth x xWidth, and then flattened
into a 1d array. Called multiple times in each function.
inputs
xCenter: center location of frame in wavelength space
res_num: index of resonator in question
iAtten: index of attenuation in question
self.scalexWidth: typical values: 1/2, 1/4, 1/8
uses interpolation to put data from an xWidth x xWidth grid to a
(xWidth/scalexWidth) x (xWidth/scalexWidth) grid. This allows the
user to probe the spectrum using a smaller window while utilizing
the higher resolution training data
showFrames: pops up a window of the frame plotted using matplotlib.plot
test_if_noisy: test spectrum by comparing heights of the outer quadrants to the center. A similar test to what
the pattern recognition classification does
'''
xWidth= self.xWidth
start = int(xCenter - xWidth/2)
end = int(xCenter + xWidth/2)
scalexWidth = self.scalexWidth
# for spectra where the peak is close enough to the edge that some points falls across the bounadry, pad zeros
if start < 0:
start_diff = abs(start)
start = 0
iq_vels = self.iq_vels[res_num, iAtten, start:end]
iq_vels = np.lib.pad(iq_vels, (start_diff,0), 'constant', constant_values=(0))
elif end >= np.shape(self.freqs)[1]:
iq_vels = self.iq_vels[res_num, iAtten, start:end]
iq_vels = np.lib.pad(iq_vels, (0,end-np.shape(self.freqs)[1]+1), 'constant', constant_values=(0))
else:
iq_vels = self.iq_vels[res_num, iAtten, start:end]
iq_vels = np.round(iq_vels * xWidth / max(self.iq_vels[res_num, iAtten, :]) )
if showFrames:
fig = plt.figure(frameon=False)
fig.add_subplot(111)
plt.plot( iq_vels)
plt.ylim((0,xWidth))
plt.show()
plt.close()
# interpolate iq_vels onto a finer grid
if scalexWidth!=None:
x = np.arange(0, xWidth+1)
iq_vels = np.append(iq_vels, iq_vels[-1])
f = interpolate.interp1d(x, iq_vels)
xnew = np.arange(0, xWidth, scalexWidth)
iq_vels = f(xnew)/ scalexWidth
xWidth = int(xWidth/scalexWidth)
if test_if_noisy:
peak_iqv = mean(iq_vels[int(xWidth/4): int(3*xWidth/4)])
nonpeak_indicies=np.delete(np.arange(xWidth),np.arange(int(xWidth/4),int(3*xWidth/4)))
nonpeak_iqv = iq_vels[nonpeak_indicies]
nonpeak_iqv = mean(nonpeak_iqv[np.where(nonpeak_iqv!=0)]) # since it spans a larger area
noise_condition = 0.7
if (peak_iqv/nonpeak_iqv < noise_condition):
return None
# populates 2d image with ones at location of iq_vel
image = np.zeros((xWidth, xWidth))
for i in range(xWidth-1):
if iq_vels[i]>=xWidth: iq_vels[i] = xWidth-1
if iq_vels[i] < iq_vels[i+1]:
image[int(iq_vels[i]):int(iq_vels[i+1]),i]=1
else:
image[int(iq_vels[i]):int(iq_vels[i-1]),i]=1
if iq_vels[i] == iq_vels[i+1]:
image[int(iq_vels[i]),i]=1
try:
image[map(int,iq_vels), range(xWidth)]=1
except IndexError:
pass
image = image.flatten()
return image
def get_peak_idx(self,res_num,iAtten):
return argmax(self.iq_vels[res_num,iAtten,:])
def makeTrainData(self):
'''creates images of each class with associated labels and saves to pkl file
0: saturated peak, too much power
1: goldilocks, not too narrow or short
2: underpowered peak, too little power
outputs
train file.pkl. contains...
trainImages: cube of size- xWidth * xWidth * xCenters*trainFrac
trainLabels: 1d array of size- xCenters*trainFrac
testImages: cube of size- xWidth * xWidth * xCenters*testFrac
testLabels: 1d array of size- xCenters*testFrac
'''
self.freqs, self.iq_vels,self.Is,self.Qs, self.attens = get_PS_data(h5File=initialFile)
self.res_nums = np.shape(self.freqs)[0]
if os.path.isfile(self.PSFile):
print 'loading peak location data from %s' % self.PSFile
PSFile = np.loadtxt(self.PSFile, skiprows=1)[:self.res_nums]
opt_freqs = PSFile[:,0]
opt_attens = PSFile[:,3]
self.opt_iAttens = opt_attens -40
else:
print 'no PS.txt file found'
exit()
good_res = np.arange(self.res_nums)
i=0
for r in range(len(opt_freqs)):
if r+i < len(opt_freqs):
cen_freq = self.freqs[r+i,self.get_peak_idx(r+i,self.opt_iAttens[r])]
s=0
while not np.isclose(cen_freq,opt_freqs[r],rtol=1e-03):
i += 1
self.res_nums -= 1
good_res = np.delete(good_res,r)
cen_freq = self.freqs[r+i,self.get_peak_idx(r+i,self.opt_iAttens[r])]
s+= 1
if s>5:
print "couldn't match frequencies after", r, "resonators"
break
if s>5: break
iAttens = np.zeros((self.res_nums,self.nClass))
iAttens[:,0] = self.opt_iAttens[:self.res_nums] + self.oAttDist
iAttens[:,1] = self.opt_iAttens[:self.res_nums] # goldilocks attenuation
iAttens[:,2] = np.ones((self.res_nums))*20#self.opt_iAttens[:self.res_nums] + self.uAttDist
lb_rej = np.where(iAttens[:,0]<0)[0]
if len(lb_rej) != 0:
iAttens = np.delete(iAttens,lb_rej,axis=0) # when index is below zero
good_res = np.delete(good_res,lb_rej)
self.res_nums = self.res_nums-len(lb_rej)
ub_rej = np.where(iAttens[:,2]>len(self.attens))[0]
if len(ub_rej) != 0:
iAttens = np.delete(iAttens,ub_rej,axis=0)
good_res = np.delete(good_res,ub_rej)
self.res_nums = self.res_nums-len(ub_rej)
self.res_indicies = np.zeros((self.res_nums,self.nClass))
for i, rn in enumerate(good_res):
self.res_indicies[i,0] = self.get_peak_idx(rn,iAttens[i,0])
self.res_indicies[i,1] = self.get_peak_idx(rn,iAttens[i,1])
self.res_indicies[i,2] = self.get_peak_idx(rn,iAttens[i,2])
self.iq_vels=self.iq_vels[good_res]
self.freqs=self.freqs[good_res]
self.Is = self.Is[good_res]
self.Qs = self.Qs[good_res]
trainImages, trainLabels, testImages, testLabels = [], [], [], []
for c in range(self.nClass):
for rn in range(int(self.trainFrac*self.res_nums) ):
image = self.makeWindowImage(res_num = rn, iAtten= iAttens[rn,c], xCenter=self.res_indicies[rn,c])
if image!=None:
trainImages.append(image)
one_hot = np.zeros(self.nClass)
one_hot[c] = 1
trainLabels.append(one_hot)
# A more simple way would be to separate the train and test data after they were read but this did not occur to me
#before most of the code was written
for c in range(self.nClass):
for rn in range(int(self.trainFrac*self.res_nums), int(self.trainFrac*self.res_nums + self.testFrac*self.res_nums)) :
image = self.makeWindowImage(res_num = rn, iAtten= iAttens[rn,c], xCenter=self.res_indicies[rn,c])
if image!=None:
testImages.append(image)
one_hot = np.zeros(self.nClass)
one_hot[c] = 1
testLabels.append(one_hot)
append = None
if os.path.isfile(self.trainFile):
append = raw_input('Do you want to append this training data to previous data [y/n]')
if (append == 'y') or (os.path.isfile(self.trainFile)== False):
print 'saving files %s & to %s' % (self.trainFile, os.path.dirname(os.path.abspath(self.trainFile)) )
with open(self.trainFile, 'ab') as tf:
pickle.dump([trainImages, trainLabels], tf)
pickle.dump([testImages, testLabels], tf)
def mlClass(self):
'''Code adapted from the tensor flow MNIST tutorial 1.
Using training images and labels the machine learning class (mlClass) "learns" how to classify IQ velocity peaks.
Using similar data the ability of mlClass to classify peaks is tested
The training and test matricies are loaded from file (those made earlier if chosen to not be appended to file
will not be used)
'''
if not os.path.isfile(self.trainFile):
self.makeTrainData()
trainImages, trainLabels, testImages, testLabels = loadPkl(self.trainFile)
print 'Number of training images:', np.shape(trainImages)[0], ' Number of test images:', np.shape(testImages)[0]
if self.scalexWidth != None:
self.xWidth = self.xWidth/self.scalexWidth
if np.shape(trainImages)[1]!=self.xWidth**2:
print 'Please make new training images of the correct size'
exit()
self.nClass = np.shape(trainLabels)[1]
self.x = tf.placeholder(tf.float32, [None, self.xWidth**2]) # correspond to the images
self.W = tf.Variable(tf.zeros([self.xWidth**2, self.nClass])) #the weights used to make predictions on classes
self.b = tf.Variable(tf.zeros([self.nClass])) # the biases also used to make class predictions
self.y = tf.nn.softmax(tf.matmul(self.x, self.W) + self.b) # class lables predictions made from x,W,b
y_ = tf.placeholder(tf.float32, [None, self.nClass]) # true class lables identified by user
cross_entropy = -tf.reduce_sum(y_*tf.log(tf.clip_by_value(self.y,1e-10,1.0)) ) # find out how right you are by finding out how wrong you are
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) # the best result is when the wrongness is minimal
init = tf.initialize_all_variables()
self.sess = tf.Session()
self.sess.run(init) # need to do this everytime you want to access a tf variable (for example the true class labels calculation or plotweights)
trainReps = 500
batches = 100
if np.shape(trainLabels)[0]< batches:
batches = np.shape(trainLabels)[0]/2
print 'Performing', trainReps, 'training repeats, using batches of', batches
for i in range(trainReps): #perform the training step using random batches of images and according labels
batch_xs, batch_ys = next_batch(trainImages, trainLabels, batches)
self.sess.run(train_step, feed_dict={self.x: batch_xs, y_: batch_ys}) #calculate train_step using feed_dict
print 'true class labels: ', self.sess.run(tf.argmax(y_,1),
feed_dict={self.x: testImages, y_: testLabels})[:25]
print 'class estimates: ', self.sess.run(tf.argmax(self.y,1),
feed_dict={self.x: testImages, y_: testLabels})[:25] #1st 25 printed
#print self.sess.run(self.y, feed_dict={self.x: testImages, y_: testLabels})[:100] # print the scores for each class
correct_prediction = tf.equal(tf.argmax(self.y,1), tf.argmax(y_,1)) #which ones did it get right?
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
score = self.sess.run(accuracy, feed_dict={self.x: testImages, y_: testLabels}) * 100
print 'Accuracy of model in testing: ', score, '%'
if score < 95: print 'Consider making more training images'
del trainImages, trainLabels, testImages, testLabels
def plotWeights(self):
'''creates a 2d map showing the positive and negative weights for each class'''
weights = self.sess.run(self.W)
weights = np.reshape(weights,(self.xWidth,self.xWidth,self.nClass))
weights = np.flipud(weights)
for nc in range(self.nClass):
plt.imshow(weights[:,:, nc])
plt.title('class %i' % nc)
plt.show()
plt.close()
def checkLoopAtten(self, res_num, iAtten, showLoop=False, min_theta = 135, max_theta = 200, max_ratio_threshold = 1.5):
'''function to check if the IQ loop at a certain attenuation is saturated. 3 checks are made.
if the angle on either side of the sides connected to the longest edge is < min_theta or > max_theta
the loop is saturated. Or if the ratio between the 1st and 2nd largest edge is > max_ratio_threshold.
A True result means that the loop is unsaturated.
Inputs:
res_num: index of resonator in question
iAtten: index of attenuation in question
showLoop: pops up a window of the frame plotted using matplotlib.plot
min/max_theta: limits outside of which the loop is considered saturated
max_ratio_threshold: maximum largest/ 2nd largest IQ velocity allowed before loop is considered saturated
Output:
Boolean. True if unsaturated
'''
vindx = (-self.iq_vels[res_num,iAtten,:]).argsort()[:3]
max_theta_vel = math.atan2(self.Qs[res_num,iAtten,vindx[0]-1] - self.Qs[res_num,iAtten,vindx[0]],
self.Is[res_num,iAtten,vindx[0]-1] - self.Is[res_num,iAtten,vindx[0]])
low_theta_vel = math.atan2(self.Qs[res_num,iAtten,vindx[0]-2] - self.Qs[res_num,iAtten,vindx[0]-1],
self.Is[res_num,iAtten,vindx[0]-2] - self.Is[res_num,iAtten,vindx[0]-1])
upp_theta_vel = math.atan2(self.Qs[res_num,iAtten,vindx[0]] - self.Qs[res_num,iAtten,vindx[0]+1],
self.Is[res_num,iAtten,vindx[0]] - self.Is[res_num,iAtten,vindx[0]+1])
theta1 = (math.pi + max_theta_vel - low_theta_vel)/math.pi * 180
theta2 = (math.pi + upp_theta_vel - max_theta_vel)/math.pi * 180
theta1 = abs(theta1)
if theta1 > 360:
theta1 = theta1-360
theta2= abs(theta2)
if theta2 > 360:
theta2 = theta2-360
max_ratio = self.iq_vels[res_num,iAtten,vindx[0]]/ self.iq_vels[res_num,iAtten,vindx[1]]
if showLoop:
plt.plot(self.Is[res_num,iAtten,:],self.Qs[res_num,iAtten,:])
plt.show()
return bool((max_theta >theta1 > min_theta) *
(max_theta > theta2 > min_theta) *
(max_ratio < max_ratio_threshold))
def findAtten(self, inferenceFile, res_nums =20, searchAllRes=True, showFrames = True, usePSFit=True):
'''The trained machine learning class (mlClass) finds the optimum attenuation for each resonator using peak shapes in IQ velocity
Inputs
inferenceFile: widesweep data file to be used
searchAllRes: if only a few resonator attenuations need to be identified set to False
res_nums: if searchAllRes is False, the number of resonators the atteunation value will be estimated for
usePSFit: if true once all the resonator attenuations have been estimated these values are fed into PSFit which opens
the window where the user can manually check all the peaks have been found and make corrections if neccessary
Outputs
Goodfile: either immediately after the peaks have been located or through WideAna if useWideAna =True
mlFile: temporary file read in to PSFit.py containing an attenuation estimate for each resonator
'''
try:
self.sess
except AttributeError:
print 'You have to train the model first'
exit()
if self.scalexWidth!= None:
self.xWidth=self.xWidth*self.scalexWidth #reset ready for get_PS_data
self.freqs, self.iq_vels, self.Is, self.Qs, self.attens = get_PS_data(h5File=inferenceFile,
searchAllRes=searchAllRes,
res_nums=res_nums)
total_res_nums = np.shape(self.freqs)[0]
if searchAllRes:
res_nums = total_res_nums
span = range(res_nums)
self.inferenceLabels = np.zeros((res_nums,len(self.attens),self.nClass))
print 'Using trained algorithm on images on each resonator'
skip = []
for i,rn in enumerate(span):
sys.stdout.write("\r%d of %i" % (i+1,res_nums) )
sys.stdout.flush()
for ia in range(len(self.attens)):
# first check the loop for saturation
nonsaturated_loop = self.checkLoopAtten(res_num=rn, iAtten= ia, showLoop=showFrames)
if nonsaturated_loop:
# each image is formatted into a single element of a list so sess.run can receive a single values dictionary
# argument and save memory
image = self.makeWindowImage(res_num = rn, iAtten= ia,
xCenter=self.get_peak_idx(rn,ia),
showFrames=showFrames)
inferenceImage=[]
inferenceImage.append(image) # inferenceImage is just reformatted image
self.inferenceLabels[rn,ia,:] = self.sess.run(self.y, feed_dict={self.x: inferenceImage} )
del inferenceImage
del image
else:
self.inferenceLabels[rn,ia,:] = [1,0,0] # would just skip these if certain
if np.all(self.inferenceLabels[rn,:,1] ==0): # if all loops appear saturated for resonator then set attenuation to highest
self.inferenceLabels[rn,-1,:] = [0,1,0] # or omit from list
skip.append(rn)
print '\n'
max_2nd_vels = np.zeros((res_nums,len(self.attens)))
for r in range(res_nums):
for iAtten in range(len(self.attens)):
vindx = (-self.iq_vels[r,iAtten,:]).argsort()[:2]
max_2nd_vels[r,iAtten] = self.iq_vels[r,iAtten,vindx[1]]
atten_guess=numpy.zeros((res_nums))
# choose attenuation where there is the maximum in the 2nd highest IQ velocity
for r in range(res_nums):
class_guess = np.argmax(self.inferenceLabels[r,:,:], 1)
if np.any(class_guess==1):
atten_guess[r] = np.where(class_guess==1)[0][argmax(max_2nd_vels[r,:][np.where(class_guess==1)[0]] )]
else:
atten_guess[r] = argmax(self.inferenceLabels[r,:,1])
if usePSFit:
if skip != None:
atten_guess = np.delete(atten_guess,skip)
self.mlFile = ('.').join(inferenceFile.split('.')[:-1]) + '-ml.txt'
if os.path.isfile(self.mlFile):
self.mlFile = self.mlFile+time.strftime("-%Y-%m-%d-%H-%M-%S")
#shutil.copy(self.mlFile, self.mlFile+time.strftime("-%Y-%m-%d-%H-%M-%S"))
print 'wrote', self.mlFile
mlf = open(self.mlFile,'wb') #mlf machine learning file is temporary
for ag in atten_guess:
line = "%12d\n" % ag
mlf.write(line)
mlf.close()
#on ubuntu 14.04 and matplotlib-1.5.1 backend 'Qt4Agg' running matplotlib.show() prior to this causes segmentation fault
os.system("python PSFit.py 1")
#os.remove(self.mlFile)
else:
baseFile = ('.').join(inferenceFile.split('.')[:-1])
saveFile = baseFile[:-16] + '.txt'
sf = open(saveFile,'wb')
#sf.write('1\t1\t1\t1 \n')
for r in np.delete(range(len(atten_guess)),skip):
line = "%10.9e \t %4i \n" % (self.freqs[r, self.get_peak_idx(r, atten_guess[r])],
self.attens[atten_guess[r]] )
sf.write(line)
sf.close()
def next_batch(trainImages, trainLabels, batch_size):
'''selects a random batch of batch_size from trainImages and trainLabels'''
perm = random.sample(range(len(trainImages)), batch_size)
trainImages = np.array(trainImages)[perm,:]
trainLabels = np.array(trainLabels)[perm,:]
return trainImages, trainLabels
def loadPkl(filename):
'''load the train and test data to train and test mlClass
pkl file hirerachy is as follows:
-The file is split in two, one side for train data and one side for test data -These halfs are further divdided into image data and labels
-makeTrainData creates image data of size: xWidth * xWidth * res_nums and the label data of size: res_nums
-each time makeTrainData is run a new image cube and label array is created and appended to the old data
so the final size of the file is (xWidth * xWidth * res_nums * "no of train runs") + (res_nums * "no of train runs") + [the equivalent test data structure]
A more simple way would be to separate the train and test data after they were read but this did not occur to the
me before most of the code was written
Input
pkl filename to be read.
Outputs
image cube and label array
'''
file =[]
with open(filename, 'rb') as f:
while 1:
try:
file.append(pickle.load(f))
except EOFError:
break
trainImages = file[0][0]
trainLabels = file[0][1]
testImages = file[1][0]
testLabels = file[1][1]
if np.shape(file)[0]/2 > 1:
for i in range(1, np.shape(file)[0]/2-1):
trainImages = np.append(trainImages, file[2*i][0], axis=0)
trainLabels = np.append(trainLabels, file[2*i][1], axis=0)
testImages = np.append(testImages, file[2*i+1][0], axis=0)
testLabels = np.append(testLabels, file[2*i+1][1], axis=0)
print "loaded dataset from ", filename
return trainImages, trainLabels, testImages, testLabels
def get_PS_data(h5File=None, searchAllRes= False, res_nums=50):
'''A function to read and write all resonator information so stop having to run the PSFit function on all resonators
if running the script more than once. This is used on both the initial and inference file
Inputs:
h5File: the power sweep h5 file for the information to be extracted from. Can be initialFile or inferenceFile
'''
baseFile = ('.').join(h5File.split('.')[:-1])
PSPFile = baseFile[:-16] + '.pkl'
if os.path.isfile(PSPFile):
file = []
with open(PSPFile, 'rb') as f:
for v in range(5):
file.append(pickle.load(f))
if searchAllRes:
res_nums = -1
freqs = file[0][:res_nums]
iq_vels = file[1][:res_nums]
Is = file[2][:res_nums]
Qs= file[3][:res_nums]
attens = file[4]
else:
PSFit = PSFitting(initialFile=h5File)
PSFit.loadps()
tot_res_nums= len(PSFit.freq)
if searchAllRes:
res_nums = tot_res_nums
res_size = np.shape(PSFit.loadres()['iq_vels'])
freqs = np.zeros((res_nums, res_size[1]+1))
iq_vels = np.zeros((res_nums, res_size[0], res_size[1]))
Is = np.zeros((res_nums, res_size[0], res_size[1]+1))
Qs = np.zeros((res_nums, res_size[0], res_size[1]+1))
attens = np.zeros((res_size[0]))
for r in range(res_nums):
sys.stdout.write("\r%d of %i" % (r+1,res_nums) )
sys.stdout.flush()
res = PSFit.loadres()
freqs[r,:] =res['freq']
iq_vels[r,:,:] = res['iq_vels']
Is[r,:,:] = res['Is']
Qs[r,:,:] = res['Qs']
attens[:] = res['attens']
PSFit.resnum += 1
with open(PSPFile, "wb") as f:
pickle.dump(freqs, f)
pickle.dump(iq_vels, f)
pickle.dump(Is, f)
pickle.dump(Qs, f)
pickle.dump(attens, f)
return freqs, iq_vels, Is, Qs, attens
def main(initialFile=None, inferenceFile=None, res_nums=50):
mlClass = mlClassification(initialFile=initialFile)
#mlClass.makeTrainData()
mlClass.mlClass()
mlClass.plotWeights()
mlClass.findAtten(inferenceFile=inferenceFile, searchAllRes=False, usePSFit=False, showFrames=False, res_nums=50)
if __name__ == "__main__":
initialFile = None
inferenceFile = None
if len(sys.argv) > 2:
initialFileName = sys.argv[1]
inferenceFileName = sys.argv[2]
mdd = os.environ['MKID_DATA_DIR']
initialFile = os.path.join(mdd,initialFileName)
inferenceFile = os.path.join(mdd,inferenceFileName)
else:
print "need to specify an initial and inference filename located in MKID_DATA_DIR"
exit()
main(initialFile=initialFile, inferenceFile=inferenceFile)
| 35,253 | 46.512129 | 159 | py |
SDR | SDR-master/Setup/cleanUpLowAtten.py | import os
import numpy
import pylab as plt
import sys
#import matplotlib.mlab as mlab
#import matplotlib.pyplot as plt
#with open('~data/20120812adr/FL1-ps_freq0.txt', 'r') as f:
if len(sys.argv) != 2:
print 'Usage: ',sys.argv[0],' zero-based roachNum'
exit(1)
roachNum = int(sys.argv[1])
#path='/home/sean/data/sci4alpha/'
path = os.environ['MKID_DATA_DIR']
filename = 'ps_freq%d'%roachNum
outfilename = filename + '-old'
os.rename(os.path.join(path,filename+'.txt'),os.path.join(path,outfilename+'.txt'))
numBin=20
data=numpy.loadtxt(os.path.join(path,outfilename+'.txt'))
print data[1:,3]
print 'median: ', numpy.median(data[1:,3])
avg=numpy.mean(data[1:,3])
print 'average is: ', avg
print 'min is: ', min(data[1:,3])
sig=numpy.std(data[1:,3])
print 'standard deviation: ',sig
h=plt.hist(data[1:,3],bins=numBin)
plt.xlabel('Attenuations')
plt.ylabel('Number')
plt.title('title')
#plt.ion()
#plt.draw()
plt.show()
newData=data[1:,3]
minAtten=input('Input min Attenuation: ')
for i in range(len(newData)):
if newData[i] < minAtten:
#print newData[i]
newData[i]=minAtten
print newData
h2=plt.hist(newData,bins=numBin)
#plt.draw()
plt.show()
#enter=input('Press any key to continue...')
data[1:,3]=newData
#numpy.savetxt(path+outfilename+'txt',data,delimiter='/t')
outFn = os.path.join(path,filename+'.txt')
print "save final answers to outFn=",outFn
f=open(outFn,'w')
f.write('\n\n')
for i in range(len(data[1:,3])):
#f.write(str((data[i,0],'\t',data[i,1],'\t',data[i,2],'\t',data[i,3])))
f.write(str(data[i,0]))
f.write('\t')
f.write(str(int(data[i,1])))
f.write('\t')
f.write(str(int(data[i,2])))
f.write('\t')
f.write(str(int(data[i,3])))
f.write('\n')
f.close()
p=plt.show()
#numpy.savetxt('testReaddata.txt',[[4,2,3,4],[8,6,7,8],[29,23,25,27]],fmt=['%f','%d','%d','%d'],delimiter='\t')
| 1,879 | 21.117647 | 111 | py |
SDR | SDR-master/Setup/PSFit.py | #-----------------------------------
# PSFitAuto.py
#
# Given IQ sweeps at various powers of resonators, this program chooses the best resonant frequency and power
# ----------------------------------
#
# Chris S:
#
# select_atten was being called multiple times after clicking on a point in plot_1.
# inside of select_atten, the call to self.ui.atten.setValue(self.atten) triggered
# another call to select_atten since it is a slot.
#
# So, instead of calling select_atten directly, call self.ui.atten.setValue(round(attenuation)) when
# you want to call select_atten, and do not call this setValue inside select_atten.
#
# Near line 68, set the frequency instead of the index to the frequency.
#
# Implemented a v2 gui that fits in a small screen.
# Run this program with no arguments to get the "classic" look.
# Run this progam with any variable to get the "new" look. The values of arguments are ignored.
#import standard python libraries
import sys
import time
import struct
import os
from os.path import isfile
#import installed libraries
from matplotlib import pylab
from matplotlib import pyplot as plt
from numpy import *
import numpy
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from tables import *
#import my functions
#from make_image_v2 import make_image as make_image_import
from lib.iqsweep import *
class StartQt4(QMainWindow):
def __init__(self,parent=None):
QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.atten = -1
self.ui.atten.setValue(self.atten)
self.resnum = 0
self.indx=0
QObject.connect(self.ui.open_browse, SIGNAL("clicked()"), self.open_dialog)
QObject.connect(self.ui.save_browse, SIGNAL("clicked()"), self.save_dialog)
QObject.connect(self.ui.atten, SIGNAL("valueChanged(int)"), self.setnewatten)
QObject.connect(self.ui.savevalues, SIGNAL("clicked()"), self.savevalues)
QObject.connect(self.ui.jumptores, SIGNAL("clicked()"), self.jumptores)
def open_dialog(self):
self.openfile = QFileDialog.getOpenFileName(parent=None, caption=QString(str("Choose PS File")),directory = ".",filter=QString(str("H5 (*.h5)")))
self.ui.open_filename.setText(str(self.openfile))
self.loadps()
def save_dialog(self):
self.savefile = QFileDialog.getOpenFileName(parent=None, caption=QString(str("Choose Save File")),directory = ".")
self.ui.save_filename.setText(str(self.savefile))
self.f = open(str(self.savefile), 'a')
self.f.close()
def loadres(self):
self.Res1=IQsweep()
self.Res1.LoadPowers(str(self.openfile), 'r0', self.freq[self.resnum])
self.ui.res_num.setText(str(self.resnum))
self.resfreq = self.freq[self.resnum]
self.ui.frequency.setText(str(self.resfreq))
self.NAttens = len(self.Res1.atten1s)
self.res1_iq_vels=numpy.zeros((self.NAttens,self.Res1.fsteps-1))
self.res1_iq_amps=numpy.zeros((self.NAttens,self.Res1.fsteps))
for iAtt in range(self.NAttens):
for i in range(1,self.Res1.fsteps-1):
self.res1_iq_vels[iAtt,i]=sqrt((self.Res1.Qs[iAtt][i]-self.Res1.Qs[iAtt][i-1])**2+(self.Res1.Is[iAtt][i]-self.Res1.Is[iAtt][i-1])**2)
self.res1_iq_amps[iAtt,:]=sqrt((self.Res1.Qs[iAtt])**2+(self.Res1.Is[iAtt])**2)
#Sort the IQ velocities for each attenuation, to pick out the maximums
sorted_vels = numpy.sort(self.res1_iq_vels,axis=1)
#Last column is maximum values for each atten (row)
self.res1_max_vels = sorted_vels[:,-1]
#Second to last column has second highest value
self.res1_max2_vels = sorted_vels[:,-2]
#Also get indices for maximum of each atten, and second highest
sort_indices = numpy.argsort(self.res1_iq_vels,axis=1)
max_indices = sort_indices[:,-1]
max2_indices = sort_indices[:,-2]
max_neighbor = max_indices.copy()
#for each attenuation find the ratio of the maximum velocity to the second highest velocity
self.res1_max_ratio = self.res1_max_vels.copy()
max_neighbors = zeros(self.NAttens)
max2_neighbors = zeros(self.NAttens)
self.res1_max2_ratio = self.res1_max2_vels.copy()
for iAtt in range(self.NAttens):
if max_indices[iAtt] == 0:
max_neighbor = self.res1_iq_vels[iAtt,max_indices[iAtt]+1]
elif max_indices[iAtt] == len(self.res1_iq_vels[iAtt,:])-1:
max_neighbor = self.res1_iq_vels[iAtt,max_indices[iAtt]-1]
else:
max_neighbor = maximum(self.res1_iq_vels[iAtt,max_indices[iAtt]-1],self.res1_iq_vels[iAtt,max_indices[iAtt]+1])
max_neighbors[iAtt]=max_neighbor
self.res1_max_ratio[iAtt] = self.res1_max_vels[iAtt]/max_neighbor
if max2_indices[iAtt] == 0:
max2_neighbor = self.res1_iq_vels[iAtt,max2_indices[iAtt]+1]
elif max2_indices[iAtt] == len(self.res1_iq_vels[iAtt,:])-1:
max2_neighbor = self.res1_iq_vels[iAtt,max2_indices[iAtt]-1]
else:
max2_neighbor = maximum(self.res1_iq_vels[iAtt,max2_indices[iAtt]-1],self.res1_iq_vels[iAtt,max2_indices[iAtt]+1])
max2_neighbors[iAtt]=max2_neighbor
self.res1_max2_ratio[iAtt] = self.res1_max2_vels[iAtt]/max2_neighbor
#normalize the new arrays
self.res1_max_vels /= numpy.max(self.res1_max_vels)
self.res1_max_vels *= numpy.max(self.res1_max_ratio)
self.res1_max2_vels /= numpy.max(self.res1_max2_vels)
#self.res1_relative_max_vels /= numpy.max(self.res1_relative_max_vels)
self.ui.plot_1.canvas.ax.clear()
self.ui.plot_1.canvas.ax.plot(self.Res1.atten1s,self.res1_max_vels,'b.-',label='Max IQ velocity')
#self.ui.plot_1.canvas.ax.plot(self.Res1.atten1s,max_neighbors,'r.-')
self.ui.plot_1.canvas.ax.plot(self.Res1.atten1s,self.res1_max_ratio,'k.-',label='Ratio (Max Vel)/(2nd Max Vel)')
self.ui.plot_1.canvas.ax.legend()
self.ui.plot_1.canvas.ax.set_xlabel('attenuation')
#self.ui.plot_1.canvas.ax.plot(self.Res1.atten1s,self.res1_max2_vels-1,'b.-')
#self.ui.plot_1.canvas.ax.plot(self.Res1.atten1s,max2_neighbors-1,'b.-')
#self.ui.plot_1.canvas.ax.plot(self.Res1.atten1s,self.res1_max2_ratio-1,'g.-')
# Chris S: seems that button_press_event causes click_plot_1 to be called more than once sometimes.
cid=self.ui.plot_1.canvas.mpl_connect('button_press_event', self.click_plot_1)
#cid=self.ui.plot_1.canvas.mpl_connect('button_release_event', self.click_plot_1)
#self.ui.plot_1.canvas.format_labels()
self.ui.plot_1.canvas.draw()
max_ratio_threshold = 1.5
rule_of_thumb_offset = 2
mlFile = ('.').join(str(self.openfile).split('.')[:-1])+"-ml.txt"
if os.path.isfile(mlFile): # update: use machine learning peak loacations if they've been made
print 'loading attenuation predictions from', mlFile
guess_atten_idx = np.loadtxt(mlFile)[self.resnum]
#print guess_atten_idx
guess_atten = self.Res1.atten1s[guess_atten_idx]
self.select_atten(guess_atten)
self.ui.atten.setValue(round(guess_atten))
else:
# require ROTO adjacent elements to be all below the MRT
bool_remove = np.ones(len(self.res1_max_ratio))
for ri in range(len(self.res1_max_ratio)-rule_of_thumb_offset-2):
bool_remove[ri] = bool((self.res1_max_ratio[ri:ri+rule_of_thumb_offset+1]< max_ratio_threshold).all())
guess_atten_idx = np.extract(bool_remove,np.arange(len(self.res1_max_ratio)))
# require the attenuation value to be past the initial peak in MRT
guess_atten_idx = guess_atten_idx[where(guess_atten_idx > argmax(self.res1_max_ratio) )[0]]
if size(guess_atten_idx) >= 1:
if guess_atten_idx[0]+rule_of_thumb_offset < len(self.Res1.atten1s):
guess_atten_idx[0] += rule_of_thumb_offset
guess_atten = self.Res1.atten1s[guess_atten_idx[0]]
self.select_atten(guess_atten)
self.ui.atten.setValue(round(guess_atten))
else:
self.select_atten(self.Res1.atten1s[self.NAttens/2])
self.ui.atten.setValue(round(self.Res1.atten1s[self.NAttens/2]))
def guess_res_freq(self):
guess_idx = argmax(self.res1_iq_vels[self.iAtten])
print 'guess idx', guess_idx
#The longest edge is identified, choose which vertex of the edge
#is the resonant frequency by checking the neighboring edges
#len(IQ_vels[ch]) == len(f_span)-1, so guess_idx is the index
#of the lower frequency vertex of the longest edge
if guess_idx-1 < 0 or self.res1_iq_vel[guess_idx-1] < self.res1_iq_vel[guess_idx+1]:
iNewResFreq = guess_idx
else:
iNewResFreq = guess_idx-1
guess = self.Res1.freq[iNewResFreq]
print 'Guessing resonant freq at ',guess,' for self.iAtten=',self.iAtten
self.select_freq(guess)
def loadps(self):
hd5file=openFile(str(self.openfile),mode='r')
group = hd5file.getNode('/','r0')
self.freq=empty(0,dtype='float32')
for sweep in group._f_walkNodes('Leaf'):
k=sweep.read()
self.scale = k['scale'][0]
#print "Scale factor is ", self.scale
self.freq=append(self.freq,[k['f0'][0]])
#self.freqList = np.zeros(len(k['f0']))
#self.attenList = np.zeros(len(self.freqList)) - 1
self.freqList = np.zeros(2000)
self.attenList = np.zeros(len(self.freqList)) - 1
hd5file.close()
self.loadres()
def on_press(self, event):
self.select_freq(event.xdata)
def click_plot_1(self, event):
#Chris. self.select_atten(event.xdata)
self.ui.atten.setValue(round(event.xdata))
def select_freq(self,freq):
self.resfreq = freq
self.ui.frequency.setText(str(self.resfreq))
self.ui.plot_2.canvas.ax.plot(self.Res1.freq[self.indx],self.res1_iq_vel[self.indx],'bo')
self.ui.plot_3.canvas.ax.plot(self.Res1.I[self.indx],self.Res1.Q[self.indx],'bo')
self.indx= where(self.Res1.freq >= self.resfreq)[0][0]
self.ui.plot_2.canvas.ax.plot(self.Res1.freq[self.indx],self.res1_iq_vel[self.indx],'ro')
self.ui.plot_2.canvas.draw()
self.ui.plot_3.canvas.ax.plot(self.Res1.I[self.indx],self.Res1.Q[self.indx],'ro')
self.ui.plot_3.canvas.draw()
def select_atten(self,attenuation):
if self.atten != -1:
attenIndex = where(self.Res1.atten1s == self.atten)
if size(attenIndex) >= 1:
self.iAtten = attenIndex[0][0]
self.ui.plot_1.canvas.ax.plot(self.atten,self.res1_max_ratio[self.iAtten],'ko')
self.ui.plot_1.canvas.ax.plot(self.atten,self.res1_max_vels[self.iAtten],'bo')
self.atten = round(attenuation)
attenIndex = where(self.Res1.atten1s == self.atten)
if size(attenIndex) != 1:
print "Atten value is not in file"
return
self.iAtten = attenIndex[0][0]
self.res1_iq_vel = self.res1_iq_vels[self.iAtten,:]
self.Res1.I=self.Res1.Is[self.iAtten]
self.Res1.Q=self.Res1.Qs[self.iAtten]
self.Res1.Icen=self.Res1.Icens[self.iAtten]
self.Res1.Qcen=self.Res1.Qcens[self.iAtten]
self.ui.plot_1.canvas.ax.plot(self.atten,self.res1_max_ratio[self.iAtten],'ro')
self.ui.plot_1.canvas.ax.plot(self.atten,self.res1_max_vels[self.iAtten],'ro')
self.ui.plot_1.canvas.draw()
#Chris S self.ui.atten.setValue(self.atten)
self.makeplots()
self.guess_res_freq()
def makeplots(self):
try:
#Plot transmission magnitudeds as a function of frequency for this resonator
#self.ui.plot_1.canvas.ax.clear()
#self.ui.plot_1.canvas.ax.semilogy(self.Res1.freq,res1_iq_amp,'.-')
#self.ui.plot_1.canvas.format_labels()
#self.ui.plot_1.canvas.draw()
self.ui.plot_2.canvas.ax.clear()
self.ui.plot_2.canvas.ax.set_xlabel('frequency (GHz)')
self.ui.plot_2.canvas.ax.set_ylabel('IQ velocity')
self.ui.plot_2.canvas.ax.plot(self.Res1.freq[:-1],self.res1_iq_vel,'b.-')
if self.iAtten > 0:
self.ui.plot_2.canvas.ax.plot(self.Res1.freq[:-1],self.res1_iq_vels[self.iAtten-1],'g.-')
self.ui.plot_2.canvas.ax.lines[-1].set_alpha(.7)
if self.iAtten > 1:
self.ui.plot_2.canvas.ax.plot(self.Res1.freq[:-1],self.res1_iq_vels[self.iAtten-2],'g.-')
self.ui.plot_2.canvas.ax.lines[-1].set_alpha(.3)
cid=self.ui.plot_2.canvas.mpl_connect('button_press_event', self.on_press)
self.ui.plot_2.canvas.draw()
self.ui.plot_3.canvas.ax.clear()
if self.iAtten >0:
self.ui.plot_3.canvas.ax.plot(self.Res1.Is[self.iAtten-1],self.Res1.Qs[self.iAtten-1],'g.-')
#print self.Res1.Is[self.iAtten-1], np.shape(self.Res1.Is[self.iAtten-1])
self.ui.plot_3.canvas.ax.lines[0].set_alpha(.6)
if self.iAtten > 1:
self.ui.plot_3.canvas.ax.plot(self.Res1.Is[self.iAtten-2],self.Res1.Qs[self.iAtten-2],'g.-')
self.ui.plot_3.canvas.ax.lines[-1].set_alpha(.3)
self.ui.plot_3.canvas.ax.plot(self.Res1.I,self.Res1.Q,'.-')
#self.ui.plot_3.canvas.format_labels()
print 'makeplots'
self.ui.plot_3.canvas.draw()
except IndexError:
self.f.close()
print "reached end of resonator list, saving file"
print "closing GUI"
sys.exit()
def jumptores(self):
try:
self.atten = -1
self.resnum = self.ui.jumptonum.value()
self.resfreq = self.resnum
self.loadres()
except IndexError:
print "Res value out of bounds."
self.ui.plot_1.canvas.ax.clear()
self.ui.plot_2.canvas.ax.clear()
self.ui.plot_3.canvas.ax.clear()
self.ui.plot_1.canvas.draw()
self.ui.plot_2.canvas.draw()
self.ui.plot_3.canvas.draw()
def setnewatten(self):
#Chris S.: this is the only place that select_atten should be called.
self.select_atten(self.ui.atten.value())
def savevalues(self):
#if self.resnum == 0:
# self.f = open(str(self.savefile), 'a')
# self.f.write(str(self.scale)+'\t'+str(self.scale)+'\t'+str(self.scale)+'\t'+str(self.scale)+'\n')
# self.f.close()
#Icen=0
#Qcen=0
self.freqList[self.resnum] = self.resfreq
self.attenList[self.resnum] = self.atten
data = np.transpose([self.freqList[np.where(self.attenList >=0)], self.attenList[np.where(self.attenList >=0)]])
try:
dataCurrent = np.atleast_2d(np.loadtxt(str(self.savefile)))
data = np.append(dataCurrent,data,axis=0)
except:
pass
numpy.savetxt(str(self.savefile), data, "%10.9e %4i")
#self.f = open(str(self.savefile), 'a')
#self.f.write(str(self.resfreq)+'\t'+str(Icen)+'\t'+str(Qcen)+'\t'+str(self.atten)+'\n')
#self.f.write(str(self.resfreq)+'\t'+str(self.atten)+'\n')
#self.f.close()
print " ....... Saved to file: resnum=",self.resnum," resfreq=",self.resfreq," atten=",self.atten
self.resnum += 1
self.atten = -1
self.loadres()
if __name__ == "__main__":
if len(sys.argv) > 1:
from lib.PSFit_GUI_v2 import Ui_MainWindow
else:
from lib.PSFit_GUI import Ui_MainWindow
app = QApplication(sys.argv)
myapp = StartQt4()
myapp.show()
app.exec_()
| 16,195 | 46.081395 | 153 | py |
SDR | SDR-master/Setup/PSFit_ml9-3layer.py | '''
90'%' accuracy sometimes and 50'%' exact attenuation choice
4 hidden layers. 2 pools
3 classes (like the original)
To do:
Could try just overpower and normal seeing as that's all you care about and then use the 2nd max to find optimal
Have it plot missed resonators to dientify why it's missing them
Read up on CNN if you have to
Make it do loop test automatically without having to do 2012 2012 in command line
Author Rupert Dodkins
A script to automate the identification of resonator attenuations normally performed by PSFit.py. This is accomplished
using Google's Tensor Flow machine learning package which implements a pattern recognition algorithm on the IQ velocity
spectrum. The code implements a 2D image classification algorithm similar to the MNIST test. This code creates a 2D
image from a 1D variable by populating a matrix of zeros with ones at the y location of each datapoint
Usage: python PSFit_ml.py 20160712/ps_r115_FL1_1_20160712-225809.h5 20160720/ps_r118_FL1_b_pos_20160720-231653.h5
Inputs:
20160712/ps_r115_FL1_1.txt: list of resonator frequencies and correct attenuations
20160712/ps_r115_FL1_1_20160712-225809.h5: corresponding powersweep file
20160720/ps_r118_FL1_b_pos_20160720-231653.h5: powersweep file the user wishes to infer attenuations for
Intermediaries:
SDR/Setup/ps_peaks_train_w<x>_s<y>.pkl: images and corresponding labels used to train the algorithm
Outputs:
20160712/ps_r115_FL1_1.pkl: frequencies, IQ velocities, Is, Qs, attenuations formatted for quick use
20160720/ps_r118_FL1_b_pos_20160720-231653-ml.txt: to be used with PSFit.py (temporary)
20160720/ps_r118_FL1_b_pos.txt: final list of frequencies and attenuations
How it works:
For each resonator and attenuation the script first assesses if the IQ loop appears saturated. If the unstaurated IQ
velocity spectrum for that attenuation is compared with the pattern recognition machine. A list of attenuations for each
resonator, where the loop is not saturated and the IQ velocity peak looks the correct shape, and the attenuation value
is chosen which has the highest 2nd largest IQ velocity. This identifier was chosen because the optimum attenuation
value has a high max IQ velocity and a low ratio of max IQ velocity to 2nd max IQ velocity which is equivalent to
choosing the highest 2nd max IQ velocity.
This list of attenuation values and frequencies are either fed PSFit.py to checked manually or dumped to
ps_r118_FL1_b_pos.txt
The machine learning algorithm requires a series of images to train and test the algorithm with. If they exist the image
data will be loaded from a train pkl file
Alternatively, if the user does not have a train pkl file but does have a powersweep file and corresponding list of
resonator attenuations this should be used as the initial file and training data will be made. The 3 classes are an
overpowered peak (saturated), peak with the correct amount of power, or an underpowered peak.
These new image data will be saved as pkl files (or appened to existing pkl files) and reloaded
The machine is then trained and its ability to predict the type of image is validated
The weights used to make predictions for each class can be displayed using the plotWeights function
to do:
change training txt file freq comparison function so its able to match all frequencies
'''
import os,sys,inspect
from PSFit import *
from lib.iqsweep import *
import numpy as np
import sys, os
import matplotlib.pyplot as plt
import tensorflow as tf
import pickle
import random
import time
import math
from scipy import interpolate
np.set_printoptions(threshold=np.inf)
#removes visible depreciation warnings from lib.iqsweep
import warnings
warnings.filterwarnings("ignore")
class PSFitting():
'''Class has been lifted from PSFit.py and modified to incorporate the machine learning algorithms from
WideAna_ml.py
'''
def __init__(self, initialFile=None):
self.initialFile = initialFile
self.resnum = 0
def loadres(self):
'''
Outputs
Freqs: the span of frequencies for a given resonator
iq_vels: the IQ velocities for all attenuations for a given resonator
Is: the I component of the frequencies for a given resonator
Qs: the Q component of the frequencies for a given resonator
attens: the span of attenuations. The same for all resonators
'''
self.Res1=IQsweep()
self.Res1.LoadPowers(self.initialFile, 'r0', self.freq[self.resnum])
self.resfreq = self.freq[self.resnum]
self.NAttens = len(self.Res1.atten1s)
self.res1_iq_vels=numpy.zeros((self.NAttens,self.Res1.fsteps-1))
self.res1_iq_amps=numpy.zeros((self.NAttens,self.Res1.fsteps))
for iAtt in range(self.NAttens):
for i in range(1,self.Res1.fsteps-1):
self.res1_iq_vels[iAtt,i]=sqrt((self.Res1.Qs[iAtt][i]-self.Res1.Qs[iAtt][i-1])**2+(self.Res1.Is[iAtt][i]-self.Res1.Is[iAtt][i-1])**2)
self.res1_iq_amps[iAtt,:]=sqrt((self.Res1.Qs[iAtt])**2+(self.Res1.Is[iAtt])**2)
#Sort the IQ velocities for each attenuation, to pick out the maximums
sorted_vels = numpy.sort(self.res1_iq_vels,axis=1)
#Last column is maximum values for each atten (row)
self.res1_max_vels = sorted_vels[:,-1]
#Second to last column has second highest value
self.res1_max2_vels = sorted_vels[:,-2]
#Also get indices for maximum of each atten, and second highest
sort_indices = numpy.argsort(self.res1_iq_vels,axis=1)
max_indices = sort_indices[:,-1]
max2_indices = sort_indices[:,-2]
max_neighbor = max_indices.copy()
#for each attenuation find the ratio of the maximum velocity to the second highest velocity
self.res1_max_ratio = self.res1_max_vels.copy()
max_neighbors = zeros(self.NAttens)
max2_neighbors = zeros(self.NAttens)
self.res1_max2_ratio = self.res1_max2_vels.copy()
for iAtt in range(self.NAttens):
if max_indices[iAtt] == 0:
max_neighbor = self.res1_iq_vels[iAtt,max_indices[iAtt]+1]
elif max_indices[iAtt] == len(self.res1_iq_vels[iAtt,:])-1:
max_neighbor = self.res1_iq_vels[iAtt,max_indices[iAtt]-1]
else:
max_neighbor = maximum(self.res1_iq_vels[iAtt,max_indices[iAtt]-1],
self.res1_iq_vels[iAtt,max_indices[iAtt]+1])
max_neighbors[iAtt]=max_neighbor
self.res1_max_ratio[iAtt] = self.res1_max_vels[iAtt]/max_neighbor
if max2_indices[iAtt] == 0:
max2_neighbor = self.res1_iq_vels[iAtt,max2_indices[iAtt]+1]
elif max2_indices[iAtt] == len(self.res1_iq_vels[iAtt,:])-1:
max2_neighbor = self.res1_iq_vels[iAtt,max2_indices[iAtt]-1]
else:
max2_neighbor = maximum(self.res1_iq_vels[iAtt,max2_indices[iAtt]-1],
self.res1_iq_vels[iAtt,max2_indices[iAtt]+1])
max2_neighbors[iAtt]=max2_neighbor
self.res1_max2_ratio[iAtt] = self.res1_max2_vels[iAtt]/max2_neighbor
#normalize the new arrays
self.res1_max_vels /= numpy.max(self.res1_max_vels)
self.res1_max_vels *= numpy.max(self.res1_max_ratio)
self.res1_max2_vels /= numpy.max(self.res1_max2_vels)
max_ratio_threshold = 2.5#1.5
rule_of_thumb_offset = 1#2
# require ROTO adjacent elements to be all below the MRT
bool_remove = np.ones(len(self.res1_max_ratio))
for ri in range(len(self.res1_max_ratio)-rule_of_thumb_offset-2):
bool_remove[ri] = bool((self.res1_max_ratio[ri:ri+rule_of_thumb_offset+1]< max_ratio_threshold).all())
guess_atten_idx = np.extract(bool_remove,np.arange(len(self.res1_max_ratio)))
# require the attenuation value to be past the initial peak in MRT
guess_atten_idx = guess_atten_idx[where(guess_atten_idx > argmax(self.res1_max_ratio) )[0]]
if size(guess_atten_idx) >= 1:
if guess_atten_idx[0]+rule_of_thumb_offset < len(self.Res1.atten1s):
guess_atten_idx[0] += rule_of_thumb_offset
guess_atten_idx = int(guess_atten_idx[0])
else:
guess_atten_idx = self.NAttens/2
return {'freq': self.Res1.freq,
'iq_vels': self.res1_iq_vels,
'Is': self.Res1.Is,
'Qs': self.Res1.Qs,
'attens':self.Res1.atten1s}
def loadps(self):
hd5file=openFile(self.initialFile,mode='r')
group = hd5file.getNode('/','r0')
self.freq=empty(0,dtype='float32')
for sweep in group._f_walkNodes('Leaf'):
k=sweep.read()
self.scale = k['scale'][0]
#print "Scale factor is ", self.scale
self.freq=append(self.freq,[k['f0'][0]])
hd5file.close()
class mlClassification():
def __init__(self, initialFile=None):
'''
Implements the machine learning pattern recognition algorithm on IQ velocity data as well as other tests to
choose the optimum attenuation for each resonator
'''
self.nClass = 3
self.xWidth = 40#np.shape(res1_freqs[1])
self.scalexWidth = 1
self.oAttDist = -1 # rule of thumb attenuation steps to reach the overpowered peak
#self.uAttDist = +2 # rule of thumb attenuation steps to reach the underpowed peak
self.initialFile = initialFile
self.baseFile = ('.').join(initialFile.split('.')[:-1])
self.PSFile = self.baseFile[:-16] + '.txt'#os.environ['MKID_DATA_DIR']+'20160712/ps_FL1_1.txt' # power sweep fit, .txt
self.mldir = './machine_learning_metadata/'
self.trainFile = 'ps_peaks_train_iqv_mag_c%i.pkl' % (self.nClass)
print self.trainFile
self.trainFrac = 0.9
self.testFrac=1 - self.trainFrac
def makeResImage(self, res_num, iAtten, angle=0, phase_normalise=False, showFrames=False, test_if_noisy=False):
'''Creates a table with 2 rows, I and Q for makeTrainData(mag_data=True)
inputs
res_num: index of resonator in question
iAtten: index of attenuation in question
self.scalexWidth: typical values: 1/2, 1/4, 1/8
uses interpolation to put data from an xWidth x xWidth grid to a
(xWidth/scalexWidth) x (xWidth/scalexWidth) grid. This allows the
user to probe the spectrum using a smaller window while utilizing
the higher resolution training data
angle: angle of rotation about the origin (radians)
showFrames: pops up a window of the frame plotted using matplotlib.plot
'''
xWidth= self.xWidth
scalexWidth = self.scalexWidth
xCenter = self.get_peak_idx(res_num,iAtten)
start = int(xCenter - xWidth/2)
end = int(xCenter + xWidth/2)
# plt.plot(self.Is[res_num,iAtten], self.Qs[res_num,iAtten])
# plt.show()
# for spectra where the peak is close enough to the edge that some points falls across the bounadry, pad zeros
if start < 0:
start_diff = abs(start)
start = 0
iq_vels = self.iq_vels[res_num, iAtten, start:end]
iq_vels = np.lib.pad(iq_vels, (start_diff,0), 'constant', constant_values=(0))
Is = self.Is[res_num,iAtten,start:end]
Is = np.lib.pad(Is, (start_diff,0), 'constant', constant_values=(Is[0]))
Qs = self.Qs[res_num,iAtten,start:end]
Qs = np.lib.pad(Qs, (start_diff,0), 'constant', constant_values=(Qs[0]))
elif end >= np.shape(self.freqs)[1]:
iq_vels = self.iq_vels[res_num, iAtten, start:end]
iq_vels = np.lib.pad(iq_vels, (0,end-np.shape(self.freqs)[1]+1), 'constant', constant_values=(0))
Is = self.Is[res_num,iAtten,start:end]
Is = np.lib.pad(Is, (0,end-np.shape(self.freqs)[1]), 'constant', constant_values=(Is[-1]))
Qs = self.Qs[res_num,iAtten,start:end]
Qs = np.lib.pad(Qs, (0,end-np.shape(self.freqs)[1]), 'constant', constant_values=(Qs[-1]))
else:
iq_vels = self.iq_vels[res_num, iAtten, start:end]
Is = self.Is[res_num,iAtten,start:end]
Qs = self.Qs[res_num,iAtten,start:end]
#iq_vels = np.round(iq_vels * xWidth / max(self.iq_vels[res_num, iAtten, :]) )
iq_vels = iq_vels / np.amax(self.iq_vels[res_num, :, :])
# interpolate iq_vels onto a finer grid
if scalexWidth!=None:
x = np.arange(0, xWidth+1)
iq_vels = np.append(iq_vels, iq_vels[-1])
f = interpolate.interp1d(x, iq_vels)
xnew = np.arange(0, xWidth, scalexWidth)
iq_vels = f(xnew)/ scalexWidth
Is = np.append(Is, Is[-1])
f = interpolate.interp1d(x, Is)
Is = f(xnew)/ scalexWidth
Qs = np.append(Qs, Qs[-1])
f = interpolate.interp1d(x, Qs)
Qs = f(xnew)/ scalexWidth
xWidth = int(xWidth/scalexWidth)
# if test_if_noisy:
# peak_iqv = mean(iq_vels[int(xWidth/4): int(3*xWidth/4)])
# nonpeak_indicies=np.delete(np.arange(xWidth),np.arange(int(xWidth/4),int(3*xWidth/4)))
# nonpeak_iqv = iq_vels[nonpeak_indicies]
# nonpeak_iqv = mean(nonpeak_iqv[np.where(nonpeak_iqv!=0)]) # since it spans a larger area
# noise_condition = 1.5#0.7
# if (peak_iqv/nonpeak_iqv < noise_condition):
# return None
res_mag = math.sqrt(np.amax(self.Is[res_num, :, :]**2 + self.Qs[res_num, :, :]**2))
Is = Is / res_mag
Qs = Qs / res_mag
# Is = Is /np.amax(self.iq_vels[res_num, :, :])
# Qs = Qs /np.amax(self.iq_vels[res_num, :, :])
# Is = Is /np.amax(self.Is[res_num, :, :])
# Qs = Qs /np.amax(self.Qs[res_num, :, :])
# print Is[::5]
# print Qs[::5]
if phase_normalise:
#mags = Qs**2 + Is**2
#mags = map(lambda x: math.sqrt(x), mags)#map(lambda x,y:x+y, a,b)
#peak_idx = self.get_peak_idx(res_num,iAtten)
peak_idx =argmax(iq_vels)
#min_idx = argmin(mags)
phase_orig = math.atan2(Qs[peak_idx],Is[peak_idx])
#phase_orig = math.atan2(Qs[min_idx],Is[min_idx])
angle = -phase_orig
rotMatrix = numpy.array([[numpy.cos(angle), -numpy.sin(angle)],
[numpy.sin(angle), numpy.cos(angle)]])
Is,Qs = np.dot(rotMatrix,[Is,Qs])
if showFrames:
fig = plt.figure(frameon=False,figsize=(15.0, 5.0))
fig.add_subplot(131)
plt.plot(iq_vels)
plt.ylim(0,1)
fig.add_subplot(132)
plt.plot(Is)
plt.plot(Qs)
fig.add_subplot(133)
plt.plot(Is,Qs)
plt.show()
plt.close()
image = np.zeros((3,len(Is)))
image[0,:] = Is
image[1,:] = Qs
image[2,:] = iq_vels
image = image.flatten()
# image = np.append(Is,Qs,axis=0)
#print np.shape(image)
return image
def get_peak_idx(self,res_num,iAtten):
return argmax(self.iq_vels[res_num,iAtten,:])
def makeTrainData(self):
'''creates 1d arrays using makeWindowImage of each class with associated labels and saves to pkl file
0: saturated peak, too much power
1: goldilocks, not too narrow or short
2: underpowered peak, too little power
or if plotting IQ mags (mag_data==True)
outputs
train file.pkl. contains...
trainImages: table of size- xWidth * xCenters*trainFrac
trainLabels: 1d array of size- xCenters*trainFrac
testImages: table of size- xWidth * xCenters*testFrac
testLabels: 1d array of size- xCenters*testFrac
creates the training data to be passed to function mlClass. For each resonator and attenuation a 2 x num_freqs table is created
with associated labels and saves to pkl file
-3 :
-2: :
-1: slightly saturated too much power
0: goldilocks, not too narrow or short
1: underpowered peak, too little power
2: :
3: :
'''
self.freqs, self.iq_vels,self.Is,self.Qs, self.attens = get_PS_data(h5File=initialFile)
self.res_nums = np.shape(self.freqs)[0]
# if mag_data==True:
# #self.trainFile = self.trainFile.split('.')[0]+'_mag.pkl'
# print self.trainFile, 'self.trainFile'
# self.nClass =3
if os.path.isfile(self.PSFile):
print 'loading peak location data from %s' % self.PSFile
PSFile = np.loadtxt(self.PSFile, skiprows=1)[:self.res_nums]
opt_freqs = PSFile[:,0]
opt_attens = PSFile[:,3]
self.opt_iAttens = opt_attens -min(self.attens)
else:
print 'no PS.txt file found'
exit()
print len(opt_freqs)
all_freqs = np.around(self.freqs, decimals=-4)
opt_freqs = np.around(opt_freqs, decimals=-4)
good_res = np.arange(self.res_nums)
a=0 # index to remove values from all_freqs
b = 0 # backtrack on g when good freqs can't be used
# g index for the good freqs
bad_opt_res = []
for g in range(len(opt_freqs)-2):
#print r, i, opt_freqs[r], round_freqs[i,:]# map(lambda x,y:x+y, a,b)
while opt_freqs[g] not in all_freqs[a,:]:
if opt_freqs[g] not in all_freqs[a:a+5,:]: # if in the next 5 rows of all_freqs then ignore good_freqs
#print 'ignoring frequency value from optimum file'
a -= 1 # cancels the index incrementing
b -= 1 # g is used to remove from good_res but g has incremented and i is stationary
bad_opt_res.append(g)
break
good_res = np.delete(good_res,g+b) # identify this value of all_freqs as bad by removing from list
a += 1 # keep incrementing until opt_freqs matches good_freqs
#print g,a,a-g, len(good_res), b # see how well the two data match
a += 1 # as g increments so does a
# attDist = np.arange(-2,3,2)
attDist = np.arange(-2,1,2)
print attDist
bad_opt_res.append(len(opt_freqs)-2)
bad_opt_res.append(len(opt_freqs)-1)
bad_opt_res.append(len(opt_freqs))
print 'bad_opt_res', np.shape(bad_opt_res)
iAttens = np.zeros((len(good_res),self.nClass))
# for i in range(self.nClass-1):
# iAttens[:,i] = np.delete(self.opt_iAttens,bad_opt_res) + attDist[i]
# print len(self.attens)
# iAttens[:,2] = np.ones((len(good_res)))*len(self.attens)-1#self.opt_iAttens[:self.res_nums] + self.uAttDist
self.opt_iAttens = np.delete(self.opt_iAttens,bad_opt_res)
for ia in range(len(self.opt_iAttens)):
attDist = int(np.random.normal(2, 1, 1))
if attDist <1: attDist = 2
iAttens[ia,0] = self.opt_iAttens[ia] - attDist
iAttens[ia,1] = self.opt_iAttens[ia] + attDist
iAttens[:,1] = self.opt_iAttens
# print np.where(self.opt_iAttens==0)
print np.shape(iAttens)
print iAttens[:10]
self.res_nums = len(good_res)
lb_rej = np.where(iAttens[:,0]<0)[0]
if len(lb_rej) != 0:
iAttens = np.delete(iAttens,lb_rej,axis=0) # when index is below zero
print len(iAttens)
good_res = np.delete(good_res,lb_rej)
self.res_nums = self.res_nums-len(lb_rej)
ub_rej = np.where(iAttens[:,2]>len(self.attens))[0]
if len(ub_rej) != 0:
iAttens = np.delete(iAttens,ub_rej,axis=0)
print len(iAttens)
good_res = np.delete(good_res,ub_rej)
self.res_nums = self.res_nums-len(ub_rej)
# self.res_indicies = np.zeros((self.res_nums,self.nClass))
# for c in range(self.nClass):
# for i, rn in enumerate(good_res):
# self.res_indicies[i,c] = self.get_peak_idx(rn,iAttens[i,c])
self.iq_vels=self.iq_vels[good_res]
self.freqs=self.freqs[good_res]
self.Is = self.Is[good_res]
self.Qs = self.Qs[good_res]
#class_steps = 300
trainImages, trainLabels, testImages, testLabels = [], [], [], []
# num_rotations = 3
# angle = np.arange(0,2*math.pi,2*math.pi/num_rotations)
train_ind = np.array(map(int,np.linspace(0,self.res_nums-1,self.res_nums*self.trainFrac)))
print type(train_ind), len(train_ind)
test_ind=[]
np.array([test_ind.append(el) for el in range(self.res_nums) if el not in train_ind])
print type(test_ind), len(test_ind)
print train_ind[:10], test_ind[:10]
test_if_noisy = False
for c in range(self.nClass):
if c ==2:
test_if_noisy = False
for rn in train_ind:#range(int(self.trainFrac*self.res_nums)):
# for t in range(num_rotations):
# image = self.makeResImage(res_num = rn, iAtten= iAttens[rn,c], angle=angle[t],showFrames=False,
# test_if_noisy=test_if_noisy, xCenter=self.res_indicies[rn,c])
image = self.makeResImage(res_num = rn, iAtten= iAttens[rn,c], phase_normalise=True ,showFrames=False)
if image!=None:
trainImages.append(image)
one_hot = np.zeros(self.nClass)
one_hot[c] = 1
trainLabels.append(one_hot)
print self.res_nums
test_if_noisy = False
for c in range(self.nClass):
if c ==2:
test_if_noisy = False
for rn in test_ind:#range(int(self.trainFrac*self.res_nums), int(self.trainFrac*self.res_nums + self.testFrac*self.res_nums)):
image = self.makeResImage(res_num = rn, iAtten= iAttens[rn,c], phase_normalise=True)
if image!=None:
testImages.append(image)
one_hot = np.zeros(self.nClass)
one_hot[c] = 1
testLabels.append(one_hot)
append = None
if os.path.isfile(self.trainFile):
append = raw_input('Do you want to append this training data to previous data [y/n]')
if (append == 'n'):
self.trainFile = self.trainFile.split('-')[0]+time.strftime("-%Y-%m-%d-%H-%M-%S")
if (append == 'y') or (os.path.isfile(self.trainFile)== False):
print 'saving %s to %s' % (self.trainFile, os.path.dirname(os.path.abspath(self.trainFile)) )
with open(self.trainFile, 'ab') as tf:
pickle.dump([trainImages, trainLabels], tf)
pickle.dump([testImages, testLabels], tf)
def mlClass(self):
'''Code adapted from the tensor flow MNIST tutorial 1.
Using training images and labels the machine learning class (mlClass) "learns" how to classify IQ velocity peaks.
Using similar data the ability of mlClass to classify peaks is tested
The training and test matricies are loaded from file (those made earlier if chosen to not be appended to file
will not be used)
'''
print self.trainFile
if not os.path.isfile(self.trainFile):
self.makeTrainData()
trainImages, trainLabels, testImages, testLabels = loadPkl(self.trainFile)
print np.sum(trainLabels,axis=0), np.sum(testLabels,axis=0)
print np.sum(trainLabels,axis=0)[0]
print np.sum(trainLabels,axis=0), np.sum(testLabels,axis=0)
print 'Number of training images:', np.shape(trainImages), ' Number of test images:', np.shape(testImages)
print np.shape(trainLabels)
print np.sum(trainLabels,axis=0)
# print len(trainImages)
# for i in range(len(trainImages)):
# if i % 50 ==0:
# print trainLabels[i]
# print np.shape(trainImages[i][:])
# plt.plot(trainImages[i][:40])
# plt.plot(trainImages[i][40:])
# plt.show()
if self.scalexWidth != 1:
self.xWidth = int(self.xWidth/self.scalexWidth)
if np.shape(trainImages)[1]/3!=self.xWidth:
print 'Please make new training images of the correct size'
exit()
#self.nClass = np.shape(trainLabels)[1]
#self.x = tf.placeholder(tf.float32, [None, self.xWidth]) # correspond to the images
self.x = tf.placeholder(tf.float32, [None, self.xWidth*3])
#print type(self.x[0][0])
#print self.x[0][0]
#print self.xWidth
#exit()
#x_image = tf.reshape(self.x, [-1,1,self.xWidth,1])
x_image = tf.reshape(self.x, [-1,3,self.xWidth,1])
def weight_variable(shape):
#initial = tf.Variable(tf.zeros(shape))
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 3, 2, 1], strides=[1, 1, 2, 1], padding='SAME')
num_filt1 = 32
self.num_filt1 = num_filt1
W_conv1 = weight_variable([1, 3, 1, num_filt1])
b_conv1 = bias_variable([num_filt1])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
num_filt2 = 4
W_conv2 = weight_variable([1, 3, num_filt1, num_filt2])
b_conv2 = bias_variable([num_filt2])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool6 = max_pool_2x2(h_conv2)
self.fc_filters = 5**2
num_fc_filt = int(math.ceil(self.xWidth*1./8) * num_filt2*6) #18*4
W_fc1 = weight_variable([num_fc_filt, self.fc_filters])
b_fc1 = bias_variable([self.fc_filters])
h_pool6_flat = tf.reshape(h_pool6, [-1, num_fc_filt])
h_fc1 = tf.nn.relu(tf.matmul(h_pool6_flat, W_fc1) + b_fc1)
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
self.W_fc2 = weight_variable([self.fc_filters, self.nClass])
b_fc2 = bias_variable([self.nClass])
self.y=tf.nn.softmax(tf.matmul(h_fc1, self.W_fc2) + b_fc2) #h_fc1_drop
y_ = tf.placeholder(tf.float32, [None, self.nClass]) # true class lables identified by user
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(self.y+ 1e-10), reduction_indices=[1])) # find optimum solution by minimizing error
train_step = tf.train.AdamOptimizer(10**-3).minimize(cross_entropy) # the best result is when the wrongness is minimal
init = tf.initialize_all_variables()
saver = tf.train.Saver()
correct_prediction = tf.equal(tf.argmax(self.y,1), tf.argmax(y_,1)) #which ones did it get right?
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
modelName = ('.').join(self.trainFile.split('.')[:-1]) + '.ckpt'
print modelName
if os.path.isfile("%s%s" % (self.mldir,modelName)):
#with tf.Session() as sess:
self.sess = tf.Session()
self.sess.run(init) #do I need this?
# Restore variables from disk.
saver.restore(self.sess, "%s%s" % (self.mldir,modelName) )
else:
self.sess = tf.Session()
self.sess.run(init) # need to do this everytime you want to access a tf variable (for example the true class labels calculation or plotweights)
# for i in range(len(trainImages)):
# if i % 30 ==0:
# print trainLabels[i]
# print np.shape(trainImages[i][:])
# plt.plot(self.sess.run(self.x)[i][0],feed_dict={self.x: trainImages})
# plt.plot(self.sess.run(self.x)[i][1],feed_dict={self.x: trainImages})
# plt.show()
start_time = time.time()
trainReps = 10000
batches = 50
if np.shape(trainLabels)[0]< batches:
batches = np.shape(trainLabels)[0]/2
# print self.sess.run(tf.shape(W_conv1), feed_dict={self.x: testImages, y_: testLabels})
# print self.sess.run(tf.shape(h_conv1), feed_dict={self.x: testImages})
# #print self.sess.run(tf.shape(h_pool1), feed_dict={self.x: testImages})
# print '\n'
# print self.sess.run(tf.shape(W_conv2))
# print self.sess.run(tf.shape(h_conv2), feed_dict={self.x: testImages})
# print self.sess.run(tf.shape(h_pool2), feed_dict={self.x: testImages})
# print '\n'
# print self.sess.run(tf.shape(W_conv3))
# print self.sess.run(tf.shape(h_conv3), feed_dict={self.x: testImages})
# #print self.sess.run(tf.shape(h_pool3), feed_dict={self.x: testImages})
# print '\n'
# print self.sess.run(tf.shape(W_conv4))
# print self.sess.run(tf.shape(h_conv4), feed_dict={self.x: testImages})
# print self.sess.run(tf.shape(h_pool4), feed_dict={self.x: testImages})
# print '\n'
# print self.sess.run(tf.shape(W_conv5))
# print self.sess.run(tf.shape(h_conv5), feed_dict={self.x: testImages})
# #print self.sess.run(tf.shape(h_pool3), feed_dict={self.x: testImages})
# print '\n'
# print self.sess.run(tf.shape(W_conv6))
# print self.sess.run(tf.shape(h_conv6), feed_dict={self.x: testImages})
# print self.sess.run(tf.shape(h_pool6), feed_dict={self.x: testImages})
# print '\n'
# print self.sess.run(tf.shape(W_fc1))
# print self.sess.run(tf.shape(h_pool6_flat), feed_dict={self.x: testImages})
# print self.sess.run(tf.shape(h_fc1), feed_dict={self.x: testImages})
# print '\n'
# print '\n'
# print self.sess.run(tf.shape(self.W_fc2))
ce_log = []
acc_log=[]
print 'Performing', trainReps, 'training repeats, using batches of', batches
for i in range(trainReps): #perform the training step using random batches of images and according labels
batch_xs, batch_ys = next_batch(trainImages, trainLabels, batches)
#print np.shape(batch_xs), np.shape(batch_ys)
if i % 100 == 0:
#self.plotW_fc2(self.sess.run(self.W_fc2))
#self.plotActivations(self.sess.run(h_conv1, feed_dict={self.x: batch_xs}), 'h_conv1', i)
#self.plotWeights(self.sess.run(W_conv2))
#self.plotActivations(self.sess.run(h_conv2, feed_dict={self.x: testImages}), 'h_conv2', i)
#print self.sess.run(W_conv1, feed_dict={self.x: testImages, y_: testLabels})
#print "max W vales: %g %g %g %g"%(self.sess.run(tf.reduce_max(tf.abs(W_conv1))),self.sess.run(tf.reduce_max(tf.abs(W_conv2))),self.sess.run(tf.reduce_max(tf.abs(W_fc1))),self.sess.run(tf.reduce_max(tf.abs(self.W_fc2))))
#print "max b vales: %g %g %g %g"%(self.sess.run(tf.reduce_max(tf.abs(b_conv1))),self.sess.run(tf.reduce_max(tf.abs(b_conv2))),self.sess.run(tf.reduce_max(tf.abs(b_fc1))),self.sess.run(tf.reduce_max(tf.abs(b_fc2))))
ce_log.append(self.sess.run(cross_entropy, feed_dict={self.x: batch_xs, y_: batch_ys}))
# print batch_ys[10],#, feed_dict={y_: batch_ys}),
# print self.sess.run(self.y, feed_dict={self.x: batch_xs})[10]
acc_log.append(self.sess.run(accuracy, feed_dict={self.x: testImages, y_: testLabels}) * 100)
# if i % 1000 ==0:
# saver.save(self.sess, "/tmp/model.ckpt",global_step=i)#self.plotWeights(self.sess.run(W_fc2))
print i, self.sess.run(cross_entropy, feed_dict={self.x: batch_xs, y_: batch_ys}),
# print batch_ys[10],#, feed_dict={y_: batch_ys}),
# print self.sess.run(self.y, feed_dict={self.x: batch_xs})[10]
print self.sess.run(accuracy, feed_dict={self.x: testImages, y_: testLabels}) * 100
self.sess.run(train_step, feed_dict={self.x: batch_xs, y_: batch_ys, keep_prob:0.5}) #calculate train_step using feed_dict
print "--- %s seconds ---" % (time.time() - start_time)
#print ce_log, acc_log
fig = plt.figure(frameon=False,figsize=(15.0, 5.0))
fig.add_subplot(121)
plt.plot(ce_log)
fig.add_subplot(122)
plt.plot(acc_log)
plt.show()
print "%s%s" % (self.mldir,modelName)
save_path = saver.save(self.sess, "%s%s" % (self.mldir,modelName))
print 'true class labels: ', self.sess.run(tf.argmax(y_,1),
feed_dict={self.x: testImages, y_: testLabels})
print 'class estimates: ', self.sess.run(tf.argmax(self.y,1),
feed_dict={self.x: testImages, y_: testLabels}) #1st 25 printed
#print self.sess.run(self.y, feed_dict={self.x: testImages, y_: testLabels})[:100] # print the scores for each class
ys_true = self.sess.run(tf.argmax(y_,1), feed_dict={self.x: testImages, y_: testLabels})
ys_guess = self.sess.run(tf.argmax(self.y,1), feed_dict={self.x: testImages, y_: testLabels})
print np.sum(self.sess.run(self.y, feed_dict={self.x: testImages, y_: testLabels}),axis=0)
right = []
for i,y in enumerate(ys_true):
#print i, y, ys_guess[i]
if ys_guess[i] == y or ys_guess[i] == y-1 or ys_guess[i] == y+1:
#print i, 'guessed right'
right.append(i)
print len(right), len(ys_true), float(len(right))/len(ys_true)
score = self.sess.run(accuracy, feed_dict={self.x: testImages, y_: testLabels, keep_prob:1}) * 100
print 'Accuracy of model in testing: ', score, '%'
if score < 85: print 'Consider making more training images'
del trainImages, trainLabels, testImages, testLabels
def plotW_fc2(self, weights):
s = np.shape(weights)
print s
fig2 = plt.figure(figsize=(8.0, 5.0))
#for f in range(s[0]):
for nc in range(self.nClass):
fig2.add_subplot(2,2,nc+1)
plt.plot(weights[:,nc])
plt.title('class %i' % nc)
plt.show()
plt.close()
# def plotWeights(self):
# '''creates a 2d map showing the positive and negative weights for each class'''
# weights = self.sess.run(self.W)
# weights = np.reshape(weights,(self.xWidth,self.xWidth,self.nClass))
# weights = np.flipud(weights)
# for nc in range(self.nClass):
# plt.imshow(weights[:,:, nc])
# plt.title('class %i' % nc)
# plt.show()
# plt.close()
def plotActivations(self, layer, layername='lol', step=0):
'''creates a 2d map showing the positive and negative weights for each class'''
#weights = self.sess.run(self.W_fc2)
#weights = np.reshape(weights,(math.sqrt(self.fc_filters),math.sqrt(self.fc_filters),self.nClass))
#weights = np.flipud(weights)
shape = np.shape(layer)
print 'layer shape', shape
fig2 = plt.figure(figsize=(8.0, 5.0))
for nc in range(self.num_filt1):
fig2.add_subplot(4,self.num_filt1/4,nc+1)
plt.imshow(layer[:,0,:, nc]**2)#i*int(shape[0]/3)
#fig2.title('class %i' % nc)
#plt.savefig('actv_layer_%s_%i_s%i'%(layername,i,step))
plt.show()
#plt.close()
def plotWeights(self, weights):
'''creates a 2d map showing the positive and negative weights for each class'''
import math
#weights = self.sess.run(self.W_fc2)
#weights = np.reshape(weights,(math.sqrt(self.fc_filters),math.sqrt(self.fc_filters),self.nClass))
#weights = np.flipud(weights)
print np.shape(weights)
for nc in range(self.num_filt1):
plt.subplot(2,self.num_filt1/2,nc+1)
#plt.imshow(weights[:,0,:, nc])
plt.plot(weights[0,:,0, nc])
#plt.title('class %i' % nc)
plt.show()
plt.close()
def checkLoopAtten(self, res_num, iAtten, showLoop=False, min_theta = 135, max_theta = 200, max_ratio_threshold = 1.5):
'''function to check if the IQ loop at a certain attenuation is saturated. 3 checks are made.
if the angle on either side of the sides connected to the longest edge is < min_theta or > max_theta
the loop is saturated. Or if the ratio between the 1st and 2nd largest edge is > max_ratio_threshold.
A True result means that the loop is unsaturated.
Inputs:
res_num: index of resonator in question
iAtten: index of attenuation in question
showLoop: pops up a window of the frame plotted using matplotlib.plot
min/max_theta: limits outside of which the loop is considered saturated
max_ratio_threshold: maximum largest/ 2nd largest IQ velocity allowed before loop is considered saturated
Output:
Boolean. True if unsaturated
'''
vindx = (-self.iq_vels[res_num,iAtten,:]).argsort()[:3]
max_theta_vel = math.atan2(self.Qs[res_num,iAtten,vindx[0]-1] - self.Qs[res_num,iAtten,vindx[0]],
self.Is[res_num,iAtten,vindx[0]-1] - self.Is[res_num,iAtten,vindx[0]])
low_theta_vel = math.atan2(self.Qs[res_num,iAtten,vindx[0]-2] - self.Qs[res_num,iAtten,vindx[0]-1],
self.Is[res_num,iAtten,vindx[0]-2] - self.Is[res_num,iAtten,vindx[0]-1])
upp_theta_vel = math.atan2(self.Qs[res_num,iAtten,vindx[0]] - self.Qs[res_num,iAtten,vindx[0]+1],
self.Is[res_num,iAtten,vindx[0]] - self.Is[res_num,iAtten,vindx[0]+1])
theta1 = (math.pi + max_theta_vel - low_theta_vel)/math.pi * 180
theta2 = (math.pi + upp_theta_vel - max_theta_vel)/math.pi * 180
theta1 = abs(theta1)
if theta1 > 360:
theta1 = theta1-360
theta2= abs(theta2)
if theta2 > 360:
theta2 = theta2-360
max_ratio = self.iq_vels[res_num,iAtten,vindx[0]]/ self.iq_vels[res_num,iAtten,vindx[1]]
if showLoop:
plt.plot(self.Is[res_num,iAtten,:],self.Qs[res_num,iAtten,:])
plt.show()
# return True
# return bool(max_ratio < max_ratio_threshold)
# if max_ratio < max_ratio_threshold == True:
# return True
# if (max_theta >theta1 > min_theta) * (max_theta > theta2 > min_theta) == True:
# return 'noisy'
# else:
# return False
# return [(max_theta >theta1 > min_theta)*(max_theta > theta2 > min_theta) , max_ratio < max_ratio_threshold]
return bool((max_theta >theta1 > min_theta) *
(max_theta > theta2 > min_theta) *
(max_ratio < max_ratio_threshold))
# if res_num==6:
# print res_num, max_ratio, self.iq_vels[res_num,iAtten,vindx[0]], self.iq_vels[res_num,iAtten,vindx[1]]
# plt.plot(self.Is[res_num,iAtten,:],self.Qs[res_num,iAtten,:])
# plt.show()
def findAtten(self, inferenceFile, res_nums =20, searchAllRes=True, showFrames = True, usePSFit=True):
'''The trained machine learning class (mlClass) finds the optimum attenuation for each resonator using peak shapes in IQ velocity
Inputs
inferenceFile: widesweep data file to be used
searchAllRes: if only a few resonator attenuations need to be identified set to False
res_nums: if searchAllRes is False, the number of resonators the atteunation value will be estimated for
usePSFit: if true once all the resonator attenuations have been estimated these values are fed into PSFit which opens
the window where the user can manually check all the peaks have been found and make corrections if neccessary
Outputs
Goodfile: either immediately after the peaks have been located or through WideAna if useWideAna =True
mlFile: temporary file read in to PSFit.py containing an attenuation estimate for each resonator
'''
try:
self.sess
except AttributeError:
print 'You have to train the model first'
exit()
if self.scalexWidth!= 1:
self.xWidth=self.xWidth*self.scalexWidth #reset ready for get_PS_data
self.freqs, self.iq_vels, self.Is, self.Qs, self.attens = get_PS_data(h5File=inferenceFile,
searchAllRes=searchAllRes,
res_nums=res_nums)
total_res_nums = np.shape(self.freqs)[0]
if searchAllRes:
res_nums = total_res_nums
span = range(res_nums)
self.inferenceLabels = np.zeros((res_nums,len(self.attens),self.nClass))
print 'Using trained algorithm on images on each resonator'
skip = []
for i,rn in enumerate(span):
sys.stdout.write("\r%d of %i" % (i+1,res_nums) )
sys.stdout.flush()
noisy_res = 0
for ia in range(len(self.attens)):
# first check the loop for saturation
nonsaturated_loop = self.checkLoopAtten(res_num=rn, iAtten= ia)
# if nonsaturated_loop[0] == True:
# noisy_res += 1
# nonsaturated_loop= bool(nonsaturated_loop[0]*nonsaturated_loop[1])
if nonsaturated_loop:
# each image is formatted into a single element of a list so sess.run can receive a single values dictionary
image = self.makeResImage(res_num = rn, iAtten= ia, phase_normalise=True,showFrames=False)
inferenceImage=[]
inferenceImage.append(image) # inferenceImage is just reformatted image
self.inferenceLabels[rn,ia,:] = self.sess.run(self.y, feed_dict={self.x: inferenceImage} )
del inferenceImage
del image
else:
self.inferenceLabels[rn,ia,:] = [1,0,0] # would just skip these if certain
if np.all(self.inferenceLabels[rn,:,1] ==0): # if all loops appear saturated for resonator then set attenuation to highest
#best_guess = argmax(self.inferenceLabels[rn,:,1])
#print best_guess
best_guess = int(np.random.normal(len(self.attens)*2/5, 3, 1))
if best_guess > len(self.attens): best_guess = len(self.attens)
self.inferenceLabels[rn,best_guess,:] = [0,1,0] # or omit from list
# if noisy_res >= 15:#len(self.attens):
# self.inferenceLabels[rn,:] = [0,0,0]
# self.inferenceLabels[rn,5] = [0,1,0]
# skip.append(rn)
print '\n'
max_2nd_vels = np.zeros((res_nums,len(self.attens)))
for r in range(res_nums):
for iAtten in range(len(self.attens)):
vindx = (-self.iq_vels[r,iAtten,:]).argsort()[:2]
max_2nd_vels[r,iAtten] = self.iq_vels[r,iAtten,vindx[1]]
# plt.plot(self.inferenceLabels[r,:,0], label='sat')
# plt.plot(self.inferenceLabels[r,:,1], label='spot-on')
# plt.plot(self.inferenceLabels[r,:,2], label='under')
# plt.plot(max_2nd_vels[r,:]/max(max_2nd_vels[r,:]),label='2nd vel')
# plt.legend()
# plt.show()
self.atten_guess=numpy.zeros((res_nums))
# choose attenuation where there is the maximum in the 2nd highest IQ velocity
for r in range(res_nums):
class_guess = np.argmax(self.inferenceLabels[r,:,:], 1)
if np.any(class_guess==1):
#atten_guess[r] = np.where(class_guess==1)[0][argmax(max_2nd_vels[r,:][np.where(class_guess==1)[0]] )]
self.atten_guess[r] = np.where(class_guess==1)[0][argmax(max_2nd_vels[r,:][np.where(class_guess==1)[0]] * self.inferenceLabels[r,:,1][np.where(class_guess==1)[0]] )]
else:
self.atten_guess[r] = argmax(self.inferenceLabels[r,:,1])
def loopTrain(self, showFrames =True, retrain=True):
self.baseFile = ('.').join(initialFile.split('.')[:-1])
self.PSFile = self.baseFile[:-16] + '.txt'
print 'loading peak location data from %s' % self.PSFile
self.res_nums = np.shape(self.freqs)[0]
PSFile = np.loadtxt(self.PSFile, skiprows=1)#[:self.res_nums-20]
opt_freqs = PSFile[:,0]
opt_attens = PSFile[:,3]
self.opt_iAttens = opt_attens -min(self.attens)
print len(opt_freqs)
all_freqs = np.around(self.freqs, decimals=-4)
opt_freqs = np.around(opt_freqs, decimals=-4)
good_res = np.arange(self.res_nums)
a=0 # index to remove values from all_freqs
b=0 # backtrack on g when good freqs can't be used
# g index for the good freqs
bad_opt_res = []
for g in range(len(opt_freqs)-2):
#print r, i, opt_freqs[r], round_freqs[i,:]# map(lambda x,y:x+y, a,b)
while opt_freqs[g] not in all_freqs[a,:]:
if opt_freqs[g] not in all_freqs[a:a+5,:]: # if in the next 5 rows of all_freqs then ignore good_freqs
#print 'ignoring frequency value from optimum file'
a -= 1 # cancels the index incrementing
b -= 1 # g is used to remove from good_res but g has incremented and i is stationary
bad_opt_res.append(g)
print g
break
good_res = np.delete(good_res,g+b) # identify this value of all_freqs as bad by removing from list
a += 1 # keep incrementing until opt_freqs matches good_freqs
#print g,a,a-g, len(good_res), b # see how well the two data match
a += 1 # as g increments so does a
bad_opt_res.append(len(opt_freqs)-2)
bad_opt_res.append(len(opt_freqs)-1)
bad_opt_res.append(len(opt_freqs))
print bad_opt_res
self.opt_iAttens =np.delete(self.opt_iAttens,bad_opt_res)
self.inferenceLabels = self.inferenceLabels[good_res]
atten_guess = self.atten_guess[good_res]
self.freqs = self.freqs[good_res]
for i in range(40):
print i, '\t', atten_guess[i], self.opt_iAttens[i]
print len(atten_guess), len(self.opt_iAttens)
correct_guesses = []
wrong_guesses=[]
within_5=np.zeros((len(atten_guess)))
within_3=np.zeros((len(atten_guess)))
within_1=np.zeros((len(atten_guess)))
within_0=np.zeros((len(atten_guess)))
for ig, ag in enumerate(atten_guess):
if abs(atten_guess[ig]-self.opt_iAttens[ig]) <=5: within_5[ig] = 1
if abs(atten_guess[ig]-self.opt_iAttens[ig]) <=3: within_3[ig] = 1
if abs(atten_guess[ig]-self.opt_iAttens[ig]) <=1: within_1[ig] = 1
if abs(atten_guess[ig]-self.opt_iAttens[ig]) ==0:
within_0[ig] = 1
correct_guesses.append(ig)
if abs(atten_guess[ig]-self.opt_iAttens[ig]) >0:
wrong_guesses.append(ig)
print 'within 5', sum(within_5)/len(atten_guess)
print 'within 3', sum(within_3)/len(atten_guess)
print 'within 1', sum(within_1)/len(atten_guess)
print 'within 0', sum(within_0)/len(atten_guess)
#print correct_guesses
# for i,wg in enumerate(wrong_guesses[:50]):
# print wg, atten_guess[wg], self.opt_iAttens[wg]
# for i, wg in enumerate(wrong_guesses):
# print wg,good_res[wg],self.atten_guess[good_res[wg]], '\t', self.opt_iAttens[wg]
# #fig = plt.figure(frameon=False,figsize=(10.0, 5.0))
# #fig.add_subplot(121)
# plt.plot(self.Is[good_res[wg],self.atten_guess[good_res[wg]],:],self.Qs[good_res[wg],self.atten_guess[good_res[wg]],:],label='guess')
# #fig.add_subplot(122)
# plt.plot(self.Is[good_res[wg],self.opt_iAttens[wg],:],self.Qs[good_res[wg],self.opt_iAttens[wg],:],label='true')
# #self.checkLoopAtten(good_res[wg],self.opt_iAttens[wg],showLoop=True)
# plt.legend()
# plt.show()
#def checkLoopAtten(self, res_num, iAtten, showLoop=False, min_theta = 135, max_theta = 200, max_ratio_threshold = 1.5):
cs_5 = np.cumsum(within_5/len(atten_guess))
cs_3 = np.cumsum(within_3/len(atten_guess))
cs_1 = np.cumsum(within_1/len(atten_guess))
cs_0 = np.cumsum(within_0/len(atten_guess))
guesses_map = np.zeros((len(self.attens),len(self.attens)))
for ia,ao in enumerate(self.opt_iAttens):
ag = atten_guess[ia]
guesses_map[ag,ao] += 1
from matplotlib import cm
plt.imshow(guesses_map,interpolation='none',cmap=cm.coolwarm)
plt.xlabel('actual')
plt.ylabel('estimate')
plt.colorbar(cmap=cm.afmhot)
plt.show()
plt.plot(np.sum(guesses_map, axis=0))
plt.plot(np.sum(guesses_map, axis=1))
plt.show()
showFrames=True
if showFrames:
plt.plot(np.arange(len(atten_guess))/float(len(atten_guess)), 'r--', label='max')
plt.fill_between(range(len(cs_0)), cs_5, alpha=0.15, label='within 5')
plt.fill_between(range(len(cs_0)), cs_3, alpha=0.15,label='within 3')
plt.fill_between(range(len(cs_0)), cs_1, alpha=0.15,label='within 1')
plt.fill_between(range(len(cs_0)), cs_0, alpha=0.15, facecolor='blue', label='within 0')
plt.legend(loc="upper left")
plt.show()
if retrain:
attDist = np.arange(-2,1,2)
# for r,g in enumerate(wrong_guesses[:10]):
# for a,_ in enumerate(self.attens[:10]):
# print g[0], a, self.inferenceLabels[g[0],a,:], np.argmax(self.inferenceLabels[g[0],a,:], axis=0), g#doesn't work self.freqs[g[0], self.get_peak_idx(g[0], atten_guess[g[0]])]#, self.opt_iAttens[g[0]]
self.opt_iAttens = self.opt_iAttens[wrong_guesses]
self.res_nums = len(self.opt_iAttens)
iAttens = np.zeros((self.res_nums,self.nClass))
for i in range(self.nClass-1):
iAttens[:,i] = self.opt_iAttens + attDist[i]
iAttens[:,2] = np.ones((self.res_nums))*len(self.attens)-1#self.opt_iAttens[:self.res_nums] + self.uAttDist
print len(iAttens)
lb_rej = np.where(iAttens[:,0]<0)[0]
if len(lb_rej) != 0:
iAttens = np.delete(iAttens,lb_rej,axis=0) # when index is below zero
print len(iAttens)
wrong_guesses = np.delete(wrong_guesses,lb_rej)
self.res_nums = self.res_nums-len(lb_rej)
ub_rej = np.where(iAttens[:,2]>len(self.attens))[0]
if len(ub_rej) != 0:
iAttens = np.delete(iAttens,ub_rej,axis=0)
print len(iAttens)
wrong_guesses = np.delete(wrong_guesses,ub_rej)
self.res_nums = self.res_nums-len(ub_rej)
self.iq_vels=self.iq_vels[wrong_guesses]
self.freqs=self.freqs[wrong_guesses]
self.Is = self.Is[wrong_guesses]
self.Qs = self.Qs[wrong_guesses]
trainImages, trainLabels, testImages, testLabels = [], [], [], []
# num_rotations = 3
# angle = np.arange(0,2*math.pi,2*math.pi/num_rotations)
train_ind = np.array(map(int,np.linspace(0,self.res_nums-1,self.res_nums*self.trainFrac)))
print type(train_ind), len(train_ind)
test_ind=[]
np.array([test_ind.append(el) for el in range(self.res_nums) if el not in train_ind])
print type(test_ind), len(test_ind)
print train_ind[:10], test_ind[:10]
for c in range(self.nClass):
for rn in train_ind:#range(int(self.trainFrac*self.res_nums)):
image = self.makeResImage(res_num = rn, iAtten= iAttens[rn,c], phase_normalise=True, showFrames=False)
if image!=None:
trainImages.append(image)
one_hot = np.zeros(self.nClass)
one_hot[c] = 1
trainLabels.append(one_hot)
print self.res_nums
for c in range(self.nClass):
for rn in test_ind:#range(int(self.trainFrac*self.res_nums), int(self.trainFrac*self.res_nums + self.testFrac*self.res_nums)):
image = self.makeResImage(res_num = rn, iAtten= iAttens[rn,c], phase_normalise=True)
if image!=None:
testImages.append(image)
one_hot = np.zeros(self.nClass)
one_hot[c] = 1
testLabels.append(one_hot)
# self.trainFile = ('.').join(self.trainFile.split('.')[:-1]) + '-retrain.pkl'
retrainFile = ('.').join(self.trainFile.split('.')[:-1]) + '-retrain.pkl'
if os.path.exists(self.trainFile):
import shutil
shutil.copy(self.trainFile,retrainFile)
print self.trainFile
append = None
# if os.path.isfile(retrainFile):
# append = raw_input('Do you want to append this training data to previous data %s [y/n]' % retrainFile)
# if (append == 'n'):
# retrainFile = retrainFile.split('-')[0]+time.strftime("-%Y-%m-%d-%H-%M-%S")
# if (append == 'y') or (os.path.isfile(self.trainFile)== False):
print 'saving %s to %s' % (retrainFile, os.path.dirname(os.path.abspath(self.trainFile)) )
with open(retrainFile, 'ab') as rtf:
pickle.dump([trainImages, trainLabels], rtf)
pickle.dump([testImages, testLabels], rtf)
self.trainFile = retrainFile
self.mlClass()
self.findAtten(inferenceFile=inferenceFile, searchAllRes=True, usePSFit=True, showFrames=False, res_nums=50)
self.i += 1
if self.i<3:
self.loopTrain(retrain=True)
else:
self.loopTrain(retrain=False)
def save_data(self, usePSFit=False):
# exit()
atten_guess = self.atten_guess
if usePSFit:
# if skip != None:
# atten_guess = np.delete(atten_guess,skip)
self.mlFile = ('.').join(inferenceFile.split('.')[:-1]) + '-ml.txt'
if os.path.isfile(self.mlFile):
self.mlFile = self.mlFile+time.strftime("-%Y-%m-%d-%H-%M-%S")
#shutil.copy(self.mlFile, self.mlFile+time.strftime("-%Y-%m-%d-%H-%M-%S"))
print 'wrote', self.mlFile
mlf = open(self.mlFile,'wb') #mlf machine learning file is temporary
for ag in atten_guess:
line = "%12d\n" % ag
mlf.write(line)
mlf.close()
#on ubuntu 14.04 and matplotlib-1.5.1 backend 'Qt4Agg' running matplotlib.show() prior to this causes segmentation fault
#os.system("python PSFit.py 1")
#os.remove(self.mlFile)
else:
baseFile = ('.').join(inferenceFile.split('.')[:-1])
saveFile = baseFile[:-16] + '.txt'
sf = open(saveFile,'wb')
sf.write('1\t1\t1\t1 \n')
for r in range(len(atten_guess)):#np.delete(range(len(atten_guess)),skip):
line = "%10.9e\t0\t0\t%4i\n" % (self.freqs[r, self.get_peak_idx(r, atten_guess[r])],
self.attens[atten_guess[r]] )
sf.write(line)
sf.close()
def next_batch(trainImages, trainLabels, batch_size):
'''selects a random batch of batch_size from trainImages and trainLabels'''
perm = random.sample(range(len(trainImages)), batch_size)
trainImages = np.array(trainImages)[perm,:]
trainLabels = np.array(trainLabels)[perm,:]
return trainImages, trainLabels
def loadPkl(filename):
'''load the train and test data to train and test mlClass
pkl file hirerachy is as follows:
-The file is split in two, one side for train data and one side for test data -These halfs are further divdided into image data and labels
-makeTrainData creates image data of size: xWidth * xWidth * res_nums and the label data of size: res_nums
-each time makeTrainData is run a new image cube and label array is created and appended to the old data
so the final size of the file is (xWidth * xWidth * res_nums * "no of train runs") + (res_nums * "no of train runs") + [the equivalent test data structure]
A more simple way would be to separate the train and test data after they were read but this did not occur to the
me before most of the code was written
Input
pkl filename to be read.
Outputs
image cube and label array
'''
file =[]
with open(filename, 'rb') as f:
while 1:
try:
file.append(pickle.load(f))
except EOFError:
break
trainImages = file[0][0]
trainLabels = file[0][1]
testImages = file[1][0]
testLabels = file[1][1]
print np.shape(file)[0]/2 -1
if np.shape(file)[0]/2 > 1:
for i in range(1, np.shape(file)[0]/2):
trainImages = np.append(trainImages, file[2*i][0], axis=0)
trainLabels = np.append(trainLabels, file[2*i][1], axis=0)
testImages = np.append(testImages, file[2*i+1][0], axis=0)
testLabels = np.append(testLabels, file[2*i+1][1], axis=0)
print np.shape(trainLabels)
print "loaded dataset from ", filename
return trainImages, trainLabels, testImages, testLabels
def get_PS_data(h5File=None, searchAllRes= True, res_nums=250):
'''A function to read and write all resonator information so stop having to run the PSFit function on all resonators
if running the script more than once. This is used on both the initial and inference file
Inputs:
h5File: the power sweep h5 file for the information to be extracted from. Can be initialFile or inferenceFile
'''
baseFile = ('.').join(h5File.split('.')[:-1])
PSPFile = baseFile[:-16] + '.pkl'
if os.path.isfile(PSPFile):
file = []
with open(PSPFile, 'rb') as f:
for v in range(5):
file.append(pickle.load(f))
if searchAllRes:
res_nums = -1
freqs = file[0][:res_nums]
iq_vels = file[1][:res_nums]
Is = file[2][:res_nums]
Qs= file[3][:res_nums]
attens = file[4]
else:
PSFit = PSFitting(initialFile=h5File)
PSFit.loadps()
tot_res_nums= len(PSFit.freq)
if searchAllRes:
res_nums = tot_res_nums
res_size = np.shape(PSFit.loadres()['iq_vels'])
freqs = np.zeros((res_nums, res_size[1]+1))
iq_vels = np.zeros((res_nums, res_size[0], res_size[1]))
Is = np.zeros((res_nums, res_size[0], res_size[1]+1))
Qs = np.zeros((res_nums, res_size[0], res_size[1]+1))
attens = np.zeros((res_size[0]))
for r in range(res_nums):
sys.stdout.write("\r%d of %i" % (r+1,res_nums) )
sys.stdout.flush()
res = PSFit.loadres()
freqs[r,:] =res['freq']
iq_vels[r,:,:] = res['iq_vels']
Is[r,:,:] = res['Is']
Qs[r,:,:] = res['Qs']
attens[:] = res['attens']
PSFit.resnum += 1
with open(PSPFile, "wb") as f:
pickle.dump(freqs, f)
pickle.dump(iq_vels, f)
pickle.dump(Is, f)
pickle.dump(Qs, f)
pickle.dump(attens, f)
print 'len freqs', len(freqs)
return freqs, iq_vels, Is, Qs, attens
def main(initialFile=None, inferenceFile=None, res_nums=50):
mlClass = mlClassification(initialFile=initialFile)
# mlClass.makeTrainData()
mlClass.mlClass()
#mlClass.plotWeights()
mlClass.findAtten(inferenceFile=inferenceFile, searchAllRes=True, showFrames=False, res_nums=50)
# if initialFile == inferenceFile:
# mlClass.i = 0
mlClass.loopTrain()
#mlClass.save_data(usePSFit=False)
if __name__ == "__main__":
initialFile = None
inferenceFile = None
if len(sys.argv) > 2:
initialFileName = sys.argv[1]
inferenceFileName = sys.argv[2]
mdd = os.environ['MKID_DATA_DIR']
initialFile = os.path.join(mdd,initialFileName)
inferenceFile = os.path.join(mdd,inferenceFileName)
else:
print "need to specify an initial and inference filename located in MKID_DATA_DIR"
exit()
main(initialFile=initialFile, inferenceFile=inferenceFile)
| 62,688 | 44.492743 | 240 | py |
SDR | SDR-master/Setup/PSFitAuto.py | #-----------------------------------
# PSFitAuto.py
#
# Given IQ sweeps at various powers of resonators, this program chooses the best resonant frequency and power
# ----------------------------------
#import standard python libraries
import sys
import time
import struct
import os
from os.path import isfile
#import installed libraries
from matplotlib import pylab
from matplotlib import pyplot as plt
from numpy import *
import numpy
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from tables import *
#import my functions
#from make_image_v2 import make_image as make_image_import
from lib.iqsweep import *
from lib.PSFit_GUI import Ui_MainWindow
class StartQt4(QMainWindow):
def __init__(self,parent=None):
QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.atten = -1
self.ui.atten.setValue(self.atten)
self.resnum = 0
self.indx=0
QObject.connect(self.ui.open_browse, SIGNAL("clicked()"), self.open_dialog)
QObject.connect(self.ui.save_browse, SIGNAL("clicked()"), self.save_dialog)
QObject.connect(self.ui.atten, SIGNAL("valueChanged(int)"), self.setnewatten)
QObject.connect(self.ui.savevalues, SIGNAL("clicked()"), self.automate)
QObject.connect(self.ui.jumptores, SIGNAL("clicked()"), self.jumptores)
def open_dialog(self):
self.openfile = QFileDialog.getOpenFileName(parent=None, caption=QString(str("Choose PS File")),directory = ".",filter=QString(str("H5 (*.h5)")))
self.ui.open_filename.setText(str(self.openfile))
self.loadps()
def save_dialog(self):
self.savefile = QFileDialog.getOpenFileName(parent=None, caption=QString(str("Choose Save File")),directory = ".")
self.ui.save_filename.setText(str(self.savefile))
self.f = open(str(self.savefile), 'a')
self.f.close()
def loadres(self):
self.Res1=IQsweep()
self.Res1.LoadPowers(str(self.openfile), 'r0', self.freq[self.resnum])
self.ui.res_num.setText(str(self.resnum))
self.resfreq = self.resnum
self.ui.frequency.setText(str(self.resfreq))
self.NAttens = len(self.Res1.atten1s)
self.res1_iq_vels=numpy.zeros((self.NAttens,self.Res1.fsteps-1))
self.res1_iq_amps=numpy.zeros((self.NAttens,self.Res1.fsteps))
for iAtt in range(self.NAttens):
for i in range(1,self.Res1.fsteps-1):
self.res1_iq_vels[iAtt,i]=sqrt((self.Res1.Qs[iAtt][i]-self.Res1.Qs[iAtt][i-1])**2+(self.Res1.Is[iAtt][i]-self.Res1.Is[iAtt][i-1])**2)
self.res1_iq_amps[iAtt,:]=sqrt((self.Res1.Qs[iAtt])**2+(self.Res1.Is[iAtt])**2)
#Sort the IQ velocities for each attenuation, to pick out the maximums
sorted_vels = numpy.sort(self.res1_iq_vels,axis=1)
#Last column is maximum values for each atten (row)
self.res1_max_vels = sorted_vels[:,-1]
#Second to last column has second highest value
self.res1_max2_vels = sorted_vels[:,-2]
#Also get indices for maximum of each atten, and second highest
sort_indices = numpy.argsort(self.res1_iq_vels,axis=1)
max_indices = sort_indices[:,-1]
max2_indices = sort_indices[:,-2]
max_neighbor = max_indices.copy()
#for each attenuation find the ratio of the maximum velocity to the second highest velocity
self.res1_max_ratio = self.res1_max_vels.copy()
max_neighbors = zeros(self.NAttens)
max2_neighbors = zeros(self.NAttens)
self.res1_max2_ratio = self.res1_max2_vels.copy()
for iAtt in range(self.NAttens):
if max_indices[iAtt] == 0:
max_neighbor = self.res1_iq_vels[iAtt,max_indices[iAtt]+1]
elif max_indices[iAtt] == len(self.res1_iq_vels[iAtt,:])-1:
max_neighbor = self.res1_iq_vels[iAtt,max_indices[iAtt]-1]
else:
max_neighbor = maximum(self.res1_iq_vels[iAtt,max_indices[iAtt]-1],self.res1_iq_vels[iAtt,max_indices[iAtt]+1])
max_neighbors[iAtt]=max_neighbor
self.res1_max_ratio[iAtt] = self.res1_max_vels[iAtt]/max_neighbor
if max2_indices[iAtt] == 0:
max2_neighbor = self.res1_iq_vels[iAtt,max2_indices[iAtt]+1]
elif max2_indices[iAtt] == len(self.res1_iq_vels[iAtt,:])-1:
max2_neighbor = self.res1_iq_vels[iAtt,max2_indices[iAtt]-1]
else:
max2_neighbor = maximum(self.res1_iq_vels[iAtt,max2_indices[iAtt]-1],self.res1_iq_vels[iAtt,max2_indices[iAtt]+1])
max2_neighbors[iAtt]=max2_neighbor
self.res1_max2_ratio[iAtt] = self.res1_max2_vels[iAtt]/max2_neighbor
#normalize the new arrays
self.res1_max_vels /= numpy.max(self.res1_max_vels)
self.res1_max_vels *= numpy.max(self.res1_max_ratio)
self.res1_max2_vels /= numpy.max(self.res1_max2_vels)
#self.res1_relative_max_vels /= numpy.max(self.res1_relative_max_vels)
self.ui.plot_1.canvas.ax.clear()
self.ui.plot_1.canvas.ax.plot(self.Res1.atten1s,self.res1_max_vels,'b.-')
#self.ui.plot_1.canvas.ax.plot(self.Res1.atten1s,max_neighbors,'r.-')
self.ui.plot_1.canvas.ax.plot(self.Res1.atten1s,self.res1_max_ratio,'k.-')
#self.ui.plot_1.canvas.ax.plot(self.Res1.atten1s,self.res1_max2_vels-1,'b.-')
#self.ui.plot_1.canvas.ax.plot(self.Res1.atten1s,max2_neighbors-1,'b.-')
#self.ui.plot_1.canvas.ax.plot(self.Res1.atten1s,self.res1_max2_ratio-1,'g.-')
cid=self.ui.plot_1.canvas.mpl_connect('button_press_event', self.click_plot_1)
self.ui.plot_1.canvas.format_labels()
self.ui.plot_1.canvas.draw()
max_ratio_threshold = 1.5
rule_of_thumb_offset = 2
# require ROTO adjacent elements to be all below the MRT
bool_remove = np.ones(len(self.res1_max_ratio))
for ri in range(len(self.res1_max_ratio)-rule_of_thumb_offset-2):
bool_remove[ri] = bool((self.res1_max_ratio[ri:ri+rule_of_thumb_offset+1]< max_ratio_threshold).all())
guess_atten_idx = np.extract(bool_remove,np.arange(len(self.res1_max_ratio)))
# require the attenuation value to be past the initial peak in MRT
guess_atten_idx = guess_atten_idx[where(guess_atten_idx > argmax(self.res1_max_ratio) )[0]]
if size(guess_atten_idx) >= 1:
guess_atten = self.Res1.atten1s[guess_atten_idx[0]+rule_of_thumb_offset]
print 'Guessing attenuation is ',guess_atten
self.select_atten(guess_atten)
else:
print 'Defaulting guess attenuation to center'
self.select_atten(self.Res1.atten1s[self.NAttens/2])
self.guess_res_freq()
def guess_res_freq(self):
guess_idx = argmax(self.res1_iq_vels[self.iAtten])
if guess_idx >0:
guess_idx-=1
guess = self.Res1.freq[guess_idx]
print 'Guessing resonant freq at ',guess
self.select_freq(guess)
def loadps(self):
hd5file=openFile(str(self.openfile),mode='r')
group = hd5file.getNode('/','r0')
self.freq=empty(0,dtype='float32')
for sweep in group._f_walkNodes('Leaf'):
k=sweep.read()
self.scale = k['scale'][0]
#print "Scale factor is ", self.scale
self.freq=append(self.freq,[k['f0'][0]])
hd5file.close()
self.loadres()
def on_press(self, event):
self.select_freq(event.xdata)
def click_plot_1(self, event):
self.select_atten(event.xdata)
def select_freq(self,freq):
self.resfreq = freq
self.ui.frequency.setText(str(self.resfreq))
self.ui.plot_2.canvas.ax.plot(self.Res1.freq[self.indx],self.res1_iq_vel[self.indx],'bo')
self.ui.plot_3.canvas.ax.plot(self.Res1.I[self.indx],self.Res1.Q[self.indx],'bo')
self.indx=where(self.Res1.freq >= self.resfreq)[0][0]
self.ui.plot_2.canvas.ax.plot(self.Res1.freq[self.indx],self.res1_iq_vel[self.indx],'ro')
self.ui.plot_2.canvas.draw()
self.ui.plot_3.canvas.ax.plot(self.Res1.I[self.indx],self.Res1.Q[self.indx],'ro')
self.ui.plot_3.canvas.draw()
def select_atten(self,attenuation):
if self.atten != -1:
attenIndex = where(self.Res1.atten1s == self.atten)
if size(attenIndex) >= 1:
self.iAtten = attenIndex[0][0]
self.ui.plot_1.canvas.ax.plot(self.atten,self.res1_max_ratio[self.iAtten],'ko')
self.ui.plot_1.canvas.ax.plot(self.atten,self.res1_max_vels[self.iAtten],'bo')
self.atten = round(attenuation)
attenIndex = where(self.Res1.atten1s == self.atten)
if size(attenIndex) != 1:
print "Atten value is not in file"
return
self.iAtten = attenIndex[0][0]
self.res1_iq_vel = self.res1_iq_vels[self.iAtten,:]
self.Res1.I=self.Res1.Is[self.iAtten]
self.Res1.Q=self.Res1.Qs[self.iAtten]
self.Res1.Icen=self.Res1.Icens[self.iAtten]
self.Res1.Qcen=self.Res1.Qcens[self.iAtten]
self.ui.plot_1.canvas.ax.plot(self.atten,self.res1_max_ratio[self.iAtten],'ro')
self.ui.plot_1.canvas.ax.plot(self.atten,self.res1_max_vels[self.iAtten],'ro')
self.ui.plot_1.canvas.draw()
self.ui.atten.setValue(self.atten)
self.makeplots()
self.guess_res_freq()
def makeplots(self):
try:
#Plot transmission magnitudeds as a function of frequency for this resonator
#self.ui.plot_1.canvas.ax.clear()
#self.ui.plot_1.canvas.ax.semilogy(self.Res1.freq,res1_iq_amp,'.-')
#self.ui.plot_1.canvas.format_labels()
#self.ui.plot_1.canvas.draw()
self.ui.plot_2.canvas.ax.clear()
self.ui.plot_2.canvas.ax.plot(self.Res1.freq[:-1],self.res1_iq_vel,'.-')
cid=self.ui.plot_2.canvas.mpl_connect('button_press_event', self.on_press)
self.ui.plot_2.canvas.draw()
self.ui.plot_3.canvas.ax.clear()
if self.iAtten >0:
self.ui.plot_3.canvas.ax.plot(self.Res1.Is[self.iAtten-1],self.Res1.Qs[self.iAtten-1],'g.-')
self.ui.plot_3.canvas.ax.lines[0].set_alpha(.5)
if self.iAtten < self.NAttens-1:
self.ui.plot_3.canvas.ax.plot(self.Res1.Is[self.iAtten+1],self.Res1.Qs[self.iAtten+1],'k.-')
self.ui.plot_3.canvas.ax.lines[-1].set_alpha(.5)
self.ui.plot_3.canvas.ax.plot(self.Res1.I,self.Res1.Q,'.-')
#self.ui.plot_3.canvas.format_labels()
print 'makeplots'
self.ui.plot_3.canvas.draw()
except IndexError:
self.f.close()
print "reached end of resonator list, saving file"
print "closing GUI"
sys.exit()
def jumptores(self):
try:
self.atten = -1
self.resnum = self.ui.jumptonum.value()
self.resfreq = self.resnum
self.loadres()
except IndexError:
print "Res value out of bounds."
self.ui.plot_1.canvas.ax.clear()
self.ui.plot_2.canvas.ax.clear()
self.ui.plot_3.canvas.ax.clear()
self.ui.plot_1.canvas.draw()
self.ui.plot_2.canvas.draw()
self.ui.plot_3.canvas.draw()
def setnewatten(self):
self.select_atten(self.ui.atten.value())
def savevalues(self):
if self.resnum == 0:
self.f = open(str(self.savefile), 'a')
self.f.write(str(self.scale)+'\t'+str(self.scale)+'\t'+str(self.scale)+'\t'+str(self.scale)+'\n')
self.f.close()
Icen=0
Qcen=0
self.f = open(str(self.savefile), 'a')
self.f.write(str(self.resfreq)+'\t'+str(Icen)+'\t'+str(Qcen)+'\t'+str(self.atten)+'\n')
self.f.close()
self.resnum += 1
self.atten = -1
self.loadres()
def automate(self):
try:
finished = False
while finished == False:
self.savevalues()
except:
pass
if __name__ == "__main__":
app = QApplication(sys.argv)
myapp = StartQt4()
myapp.show()
app.exec_()
| 12,403 | 42.830389 | 153 | py |
SDR | SDR-master/Setup/DetectorAnalysis/histQ.py | #!/usr/bin/python
import numpy as np
from matplotlib import pyplot as plt
#Plots Histogram of f, Q, and Distance of f to nearest neighbor, Q vs f, Dist to neigh vs f and saves it to a pdf. You need to change the File and pdftitle (and possibly the text position in line 79
File= '20121116/FL1-sci4a-DF-good-fits.txt'
pdftitle='/home/sean/data/fitshist/FL1-sci4a-DF-good.pdf'
autofit=np.loadtxt('/home/sean/data/%s'%File)
freqs=autofit[:,1]
Qs=autofit[:,2]
Qs=[x/1000 for x in Qs]
ds=[]
fs=[]
freq=sorted(freqs)
for i in xrange(1,len(freqs)-1):
x=abs(freq[i]-freq[i+1])
y=abs(freq[i]-freq[i-1])
if x>=y:
ds.append(y)
else:
ds.append(x)
fs.append(freq[i])
ds=[x*1000 for x in ds]
mf=np.median(freqs)
sf=np.std(freqs)
mq=np.median(Qs)
sq=np.std(Qs)
md=np.median(ds)
sd=np.std(ds)
nres=len(freqs)
fig = plt.figure(figsize=(6,8))
plt.subplots_adjust(left = 0.1, right= 0.96, bottom= .07, top= .96, wspace=0.3, hspace=0.4)
ax=fig.add_subplot(321)
ax.hist(freqs,bins=100, color='k')
ax.set_xlabel('Frequency (GHz)\nmedian=%f, std=%f'%(mf,sf), size=8)
ax.set_ylabel('Number', size=8)
ax.set_title('Histogram of Frequency', size=9)
ax.tick_params(labelsize=8)
ax2=fig.add_subplot(323)
ax2.hist(Qs, bins=100, color='k')
ax2.set_xlabel('Q(k)\nmedian=%f, std=%f'%(mq,sq), size=8)
ax2.set_ylabel('Number', size=8)
ax2.set_title('Histogram of Q', size=9)
ax2.set_xlim(0,300)
ax2.tick_params(labelsize=8)
ax3=fig.add_subplot(325)
ax3.hist(ds, bins=100, color='k')
ax3.set_xlabel('Distance to Nearest Neighbor (MHz)\nmedian=%f, std=%f'%(md,sd), size=8)
ax3.set_ylabel('Number', size=8)
ax3.set_title('Distance of f0 to Nearest Neighbor', size=9)
ax3.set_xlim(0,6)
ax3.tick_params(labelsize=8)
ax4=fig.add_subplot(322)
ax4.plot(freqs,Qs,'r,')
ax4.set_xlabel('Resonant Frequency (GHz)', size=8)
ax4.set_ylabel('Q(k)', size=8)
ax4.set_title('Q vs f0', size=9)
ax4.tick_params(labelsize=8)
ax4.set_ylim(0,300)
ax5=fig.add_subplot(324)
ax5.plot(fs,ds,'b,')
ax5.set_xlabel('Resonant Frequency (GHz)', size=8)
ax5.set_ylabel('Distance of f to Nearest Neighbor (MHz)', size=8)
ax5.set_title('Nearest Neighbor vs f0', size=9)
ax5.tick_params(labelsize=8)
ax5.set_ylim(0,20)
ax5.text(2.8,-15,'file name=\n%s\nnumber of resonators = %d'%(File, nres), size=8.5)
fig.savefig(pdftitle)
plt.show()
plt.close()
| 2,303 | 26.428571 | 199 | py |
SDR | SDR-master/Setup/DetectorAnalysis/histQi.py | #!/usr/bin/python
import numpy as np
from matplotlib import pyplot as plt
import os
#Plots Histogram of f, Q, and Distance of f to nearest neighbor, Q vs f, Dist to neigh vs f and saves it to a pdf. You need to change the filename and pdftitle (and possibly the text position in line 79
datapath = '/home/kids/labData/20140909adr/'
filename= 'SCI6_B140818-Force_-80dBm_FL2_postFlash-right-fits.txt'
pdftitle=os.path.join(datapath,'SCI6_B140818-Force_-80dBm_FL2_postFlash-right-fits-hists.pdf')
filepath = os.path.join(datapath,filename)
autofit=np.loadtxt(filepath)
Qs=1.e-3*autofit[:,2]
badFitsMask = Qs == 5.
print np.sum(badFitsMask),' bad fits removed'
autofit = autofit[~badFitsMask]
freqs=autofit[:,1]
Qs=1.e-3*autofit[:,2]
Qc=1.e-3*autofit[:,3]
Qi=1.e-3*np.abs(autofit[:,4])
ds=[]
fs=[]
freq=sorted(freqs)
for i in xrange(1,len(freqs)-1):
x=abs(freq[i]-freq[i+1])
y=abs(freq[i]-freq[i-1])
if x>=y:
ds.append(y)
else:
ds.append(x)
fs.append(freq[i])
ds=[x*1000 for x in ds]
mf=np.median(freqs)
sf=np.std(freqs)
mq=np.median(Qs)
sq=np.std(Qs)
mqi=np.median(Qi)
sqi=np.std(Qi)
md=np.median(ds)
sd=np.std(ds)
nres=len(freqs)
fig = plt.figure(figsize=(6,8))
plt.subplots_adjust(left = 0.1, right= 0.96, bottom= .07, top= .96, wspace=0.3, hspace=0.4)
ax=fig.add_subplot(321)
ax.hist(freqs,bins=200, color='k')
ax.set_xlabel('Frequency (GHz)\nmedian=%f, std=%f'%(mf,sf), size=8)
ax.set_ylabel('Number', size=8)
ax.set_title('Histogram of Frequency', size=9)
ax.tick_params(labelsize=8)
ax2=fig.add_subplot(323)
ax2.hist(Qs, bins=25, range=(0,80),color='k')
ax2.set_xlabel('$Q (10^3)$\nmedian=%f, std=%f'%(mq,sq), size=8)
ax2.set_ylabel('Number', size=8)
ax2.set_title('Histogram of Q', size=9)
ax2.set_xlim(0,80)
ax2.tick_params(labelsize=8)
#ax3=fig.add_subplot(325)
#ax3.hist(ds, bins=100, color='k')
#ax3.set_xlabel('Distance to Nearest Neighbor (MHz)\nmedian=%f, std=%f'%(md,sd), size=8)
#ax3.set_ylabel('Number', size=8)
#ax3.set_title('Distance of f0 to Nearest Neighbor', size=9)
#ax3.set_xlim(0,6)
#ax3.tick_params(labelsize=8)
ax3=fig.add_subplot(325)
ax3.hist(Qi, bins=25, range=(0,1000), color='k')
ax3.set_xlabel('$Q_i (10^3)$\nmedian=%f, std=%f'%(mqi,sqi), size=8)
ax3.set_ylabel('Number', size=8)
ax3.set_title('Histogram of $Q_i$', size=9)
ax3.set_xlim(0,1000)
ax3.tick_params(labelsize=8)
ax4=fig.add_subplot(322)
ax4.plot(freqs,Qs,'r,')
ax4.set_xlabel('Resonant Frequency (GHz)', size=8)
ax4.set_ylabel('Q(k)', size=8)
ax4.set_title('Q vs f0', size=9)
ax4.tick_params(labelsize=8)
ax4.set_ylim(0,300)
ax5=fig.add_subplot(324)
ax5.plot(fs,ds,'b,')
ax5.set_xlabel('Resonant Frequency (GHz)', size=8)
ax5.set_ylabel('Distance of f to Nearest Neighbor (MHz)', size=8)
ax5.set_title('Nearest Neighbor vs f0', size=9)
ax5.tick_params(labelsize=8)
ax5.set_ylim(0,20)
ax5.text(2.8,-15,'file name=\n%s\nnumber of resonators = %d'%(filepath, nres), size=8.5)
fig.savefig(pdftitle)
plt.show()
plt.close()
| 2,938 | 27.533981 | 203 | py |
SDR | SDR-master/Setup/DetectorAnalysis/QPixelQuality.py | #!/usr/bin/python
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.patches as pat
import tables
import re
import collections
import scipy
import pyfits
from PixelQualityfunc import *
import os
closefcutoff=.0007 #when the program compares the approximate freq in frequency files to the accurate frequency in the fit file, it will accept a difference of the closefcutoff (GHz)
#bmaptitle='/media/disk2/sci3gamma/20120904/PositionKnownOnlybeamimage_double_refined_20120904.h5'
bmaptitle='/home/sean/data/20121106/sci4a_beammap.h5'
#for feedline 1
title1=title2='20121105adr/ps_freq'
titlefits1='20121105adr/FL1-adr-sci4a-higherTc-good-fits.txt'
#for feedline 2
#titlefits2='20121006/20121006-SCI4-ADR-FL2-fits.txt'
titlefits2='20121105adr/FL2-adr-sci4a-higherTc-all-fits.txt'
outTitle='/home/sean/data/fitshist/20121106_Q_PixelQuality.fits'
freqOutTitle='/home/sean/data/fitshist/20121106_freqMap.fits'
#--Get an accurate array with roach,pixel,f,Q in the correct position--
accuratefQ = createAccuratefQMatrix(bmaptitle, title1,titlefits1,title2,titlefits2,closefcutoff=3)
fid=tables.openFile(bmaptitle)
b=fid.root.beammap.beamimage
pixarray = [[-1 for col in range(44)] for row in range(46)]
freqarray = [[-1 for col in range(44)] for row in range(46)]
pixlist = []
for row in xrange(0,46):
for column in xrange(0,44):
string=b[row][column]
if string != '' :
a=re.findall(r'\d+',string)
roachNum=int(a[0])
pixelNum=int(a[1])
if roachNum <8:
if pixelNum<len(accuratefQ[roachNum]):
pixarray[row][column]=(accuratefQ[roachNum][pixelNum][1]/1000)
freqarray[row][column]=(accuratefQ[roachNum][pixelNum][0]/1000)
# else:
# print roachNum,pixelNum
# else:
# print roachNum,pixelNum
fid.close()
#--Plot what the detector looks like with the f,Q, and position written inside each 'pixel'--
pixarray=np.array(pixarray)
freqarray=np.array(freqarray)
print np.shape(pixarray)
scale_nstds = 3
scale_max=np.mean(pixarray[:][:])+scale_nstds*np.std(pixarray[:][:])
plt.matshow(pixarray[:][:],vmin=0,vmax=scale_max)
plt.title('Q')
plt.xlabel('Col')
plt.ylabel('Row')
plt.colorbar()
plt.show()
hdu = pyfits.PrimaryHDU(pixarray)
hdu2 = pyfits.PrimaryHDU(freqarray)
hdu.writeto(outTitle,clobber=True)
hdu2.writeto(freqOutTitle,clobber=True)
| 2,426 | 30.115385 | 184 | py |
SDR | SDR-master/Setup/DetectorAnalysis/qeperpixelh5.py | from tables import *
from PixelQualityfunc import getfQforgoodpix
from qeforpixelsfunc import qeFuncOfWvl
h5filename="SDR/Setup/DetectorAnalysis/qeforpix.h5"
nroach=8
npixel=256
wvls = range(400,1100,50)
nwvl=len(wvls)
bmaptitle='/home/sean/data/common/sorted_beamimage46x44.h5'
#for feedline 1
title1='20120812adr/FL1-ps_freq'
titlefits1='20120812adr/SCI3-40-FL1-ADR-2-fits.txt'
#for feedline 2
title2='20120812adr/FL2-ps_freq'
titlefits2='20120812adr/SCI3-40-FL2-ADR-fits.txt'
#title1/2 gives the base of the filename for the frequency files for Feedline 1/2 (Don't include '.txt').
#titlefist1/2 gives the filename of the fits file (include '.txt')
#bmaptitle gives the filename of the beammap (include '.h5')
maxqeCutOff = 0.01
#if the maximum qe in the list of qe's for that pixel is less than maxqeCutOff, it will not be saved in the h5 file
qeDataFilename='/media/disk2/20120814/obs_20120814-111433.h5'
qeObsTime= 1344968073
ini=454
peakw=14.3846153846
troughw=83.5833333333
dectv=[.033,.139,.323,.682,1.025,1.287,1.451,1.530,1.420,1.364,1.766,2.291,2.844,3.169]
#this assumes that both FL1 and FL2 are included in the qeDataFile and that the ini, peakw, and troughw values are the same for all roaches
#ini is the time when the first peak starts
#peakw: time interval over which the peak occurs (does not include the first/last 3 seconds of peak)
#troughw: time interval between peaks (includes first/last 3 s of peak)
#dectv is the N of photons seen in the comparison detector *10^-7 for each wvl/peak
#qewvl=1/(dectv[i]*10**7/NPulses[0][i]*.0007096896) is the formula used to find the quantum efficiency. Where NPulses is the average number of photons seen in the ADR detector (the average number of photons seen in the troughs btw peaks is subtracted.
fQlist = getfQforgoodpix(bmaptitle,title1,titlefits1,title2,titlefits2)
#resulting list has each element [[roachnumber,pixelnumber],[f,Q]]
fQqe=[]
for pix in xrange(0,len(fQlist)):
roach = fQlist[pix][0][0]
if roach < 4: #delete this line if qeDataFile has roaches 0...7
pixel = fQlist[pix][0][1]
qeresults = qeFuncOfWvl(qeDataFilename, qeObsTime, roach, pixel, ini, peakw, troughw, dectv, NSec=3600, nwvl=14, plotYorN='N')
if max(qeresults) > maxqeCutOff:
fQqe.append([fQlist[pix][0],fQlist[pix][1],qeresults])
#fQqe is a list where each element is [[roachnumber,pixelnumber],[f,Q],[qe(wvl1),...]]
print fQqe[10]
class QEHeader(IsDescription):
wvl = Float32Col(nwvl)
class Pixel(IsDescription):
frequency = Float64Col()
Q = Float32Col()
qe = Float32Col(nwvl)
# Open a file in "w"rite mode
h5file = openFile(h5filename, mode = "w", title= "testfile")
hdrgrp = h5file.createGroup('/','header', 'Group containing wvls')
hdrtable = h5file.createTable(hdrgrp, 'Wavelengths', QEHeader)
w = hdrtable.row
w['wvl'] = wvls
w.append()
hdrtable.flush()
roaches = []
pixels = []
for roachnum in xrange(0,nroach):
roaches.append('r%d'%roachnum)
# Create the groups
for roach in roaches:
group = h5file.createGroup('/',roach)
# Create a group for each good pixel and put in the correct values
for i in xrange(0,len(fQqe)):
roach='r%d'%fQqe[i][0][0]
pixelnum='p%d'%fQqe[i][0][1]
pixgroup=h5file.createGroup('/'+roach,pixelnum)
pixtable=h5file.createTable(pixgroup,'pixtable',Pixel)
pix = pixtable.row
pix['frequency'] = fQqe[i][1][0]
pix['Q'] = fQqe[i][1][1]
pix['qe'] = fQqe[i][2]
pix.append()
pixtable.flush()
h5file.close()
| 3,529 | 35.391753 | 251 | py |
SDR | SDR-master/Setup/DetectorAnalysis/PixelQuality.py | #!/usr/bin/python
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.patches as pat
import tables
import re
import collections
import scipy
from PixelQualityfunc import *
closefcutoff=.0007 #when the program compares the approximate freq in frequency files to the accurate frequency in the fit file, it will accept a difference of the closefcutoff (GHz)
bmaptitle='/media/disk2/sci3gamma/beamimage_sci3gamma.h5'
#for feedline 1
title1=title2='20120827/ps_freq'
titlefits1='20120823adr/20120823_FL1_100mK_gold0-fits.txt'
#for feedline 2
titlefits2='20120823adr/20120823_FL2_100mK_gold0-fits.txt'
pdftitle='/home/sean/data/fitshist/20120912PixelQuality.pdf'
dithertitle='/home/sean/data/fitshist/20120912PixelQualitydither.pdf'
sqDimOpt=30
#This is the dimension of pixel area in the center of the area that we are evaluating to find the optimal dither position
#--Get an accurate array with roach,pixel,f,Q in the correct position--
accuratefQ = createAccuratefQMatrix(bmaptitle, title1,titlefits1,title2,titlefits2,closefcutoff=3)
fid=tables.openFile(bmaptitle)
b=fid.root.beammap.beamimage
pixarray = [[None for col in range(44)] for row in range(46)]
pixlist = []
for row in xrange(0,46):
for column in xrange(0,44):
string=b[row][column]
if string != '' :
a=re.findall(r'\d+',string)
roachNum=int(a[0])
pixelNum=int(a[1])
if roachNum <8:
if pixelNum<len(accuratefQ[roachNum]):
pixarray[row][column]=([[roachNum,pixelNum],accuratefQ[roachNum][pixelNum]])
pixlist.append([[roachNum,pixelNum],accuratefQ[roachNum][pixelNum]])
# else:
# print roachNum,pixelNum
# else:
# print roachNum,pixelNum
fid.close()
#--Plot what the detector looks like with the f,Q, and position written inside each 'pixel'--
fig=plt.figure(figsize=(23,14))
plt.subplots_adjust(left = 0.04, right= 0.97, bottom= .05, top= .95)
ax=fig.add_subplot(111)
binaryPixArray = scipy.zeros((46,44))
#binaryPixArray=scipy.random.random((46,44))
#binaryPixArray=np.around(binaryPixArray)
textsize=4.5
problem=[]
for row in xrange(0,46):
for column in xrange(0,44):
pix=pixarray[row][column]
if pix==None:
color='Brown'
ax.text(.002+ 0.02275*column,0.003+ 0.0217*row, '%s\n%s\n| (%d,%d) -'%('| ','| ',row,column), bbox=dict(facecolor=color, alpha=.6), size=textsize)
elif len(pixarray[row][column])== 2:
binaryPixArray[row][column]=1
color= 'PaleGreen'
ax.text(.002+ 0.02275*column,0.003+ 0.0217*row, 'r%dp%d \n%.5f\n%.1f (%d,%d)'%(pix[0][0],pix[0][1],pix[1][0],pix[1][1]/1000,row,column), bbox=dict(facecolor=color, alpha=.6), size=textsize)
else:
problem.append([row,column])
#--Add boxes around best sections of array. The purple boxes are around the best areas that are completely filled with working pixels, the dark blue boxes are around the best sections for one higher dimension--
optimalIndTotal=[]
Allfilledin=1
dim=2
plusD=0
while Allfilledin==1:
boxsum=[]
for row in xrange(0,46+1-(plusD+dim)):
for column in xrange(0,44+1-(plusD+dim)):
boxvalues=[]
for i in xrange(0,plusD+dim):
for j in xrange(0,plusD+dim):
boxvalues.append(binaryPixArray[row+i][column+j])
boxsum.append([sum(boxvalues),row,column])
boxsum=sorted(boxsum)
if boxsum[len(boxsum)-1][0] != (plusD+dim)**2:
Allfilledin=0
else:
plusD=plusD+1
optimalIndices=[]
stillmax=1
x=len(boxsum)-1
while stillmax==1:
if boxsum[len(boxsum)-1][0]==boxsum[x][0]:
optimalIndices.append([boxsum[x][1],boxsum[x][2]])
x=x-1
else:
stillmax=0
optimalIndTotal.append(optimalIndices)
#print optimalIndTotal
dim=len(optimalIndTotal)
for ind in optimalIndTotal[dim-2]:
rect = pat.Rectangle((0.02275*ind[1],0.0217*ind[0]),width=0.02275*dim, height=0.0217*dim, color='Indigo', fill=False, lw=2)
ax.add_patch(rect)
ax.figure.canvas.draw()
dim=len(optimalIndTotal)+1
for ind in optimalIndTotal[dim-2]:
rect = pat.Rectangle((1/44.*ind[1],1/46.*ind[0]),width=1/44.*dim, height=1/46.*dim, color='MediumBlue', fill=False, lw=2)
ax.add_patch(rect)
ax.figure.canvas.draw()
#print problem
ax.text(-0.7, 1.02, 'Each box represents a pixel. Green means the pixel is working.\npixelnumber, f0(GHz), Q(k), and pixel location are inside each box.', bbox=dict(facecolor='white', alpha=1), size=10)
plt.title('Pixel Quality and Characteristics for 20120912 Detector', size=24, position=(.5,1.01))
fig.savefig(pdftitle)
plt.show()
plt.close()
#--Figure out optimal placement of 4 dithers in rect. formation by looking at the percentage of good pixels in the center sqDimOpt by sqDimOpt region--
yvariation=int((46-sqDimOpt)/2)
xvariation=int((44-sqDimOpt)/2)
binaryPixArray=np.array(binaryPixArray)
impSection=binaryPixArray[yvariation:(46-yvariation),xvariation:(44-xvariation)]
percentgood=np.sum(impSection)/(sqDimOpt**2.)
resultPercent=[]
for j in xrange(-xvariation,xvariation+1):
for i in xrange(-yvariation, yvariation+1):
ditherArray=np.array([[None for col in range(sqDimOpt)] for row in range(sqDimOpt)])
for row in xrange(0, sqDimOpt):
for column in xrange(0, sqDimOpt):
ditherArray[row,column]=binaryPixArray[row+yvariation,column+xvariation]+binaryPixArray[(row+yvariation),(column+xvariation+j)]+binaryPixArray[(row+yvariation+i),(column+xvariation)]+binaryPixArray[(row+yvariation+i),(column+xvariation+j)]
resultPercent.append([sum(sum(1 for i in row if i>0) for row in ditherArray)/(sqDimOpt**2.),i,j])
resultPercent=sorted(resultPercent)
i=resultPercent[len(resultPercent)-1][1]
j=resultPercent[len(resultPercent)-1][2]
ditherArray=np.array([[None for col in range(sqDimOpt)] for row in range(sqDimOpt)])
for row in xrange(0, sqDimOpt):
for column in xrange(0, sqDimOpt):
ditherArray[row,column]=int(binaryPixArray[row+yvariation,column+xvariation]+binaryPixArray[(row+yvariation),(column+xvariation+j)]+binaryPixArray[(row+yvariation+i),(column+xvariation)]+binaryPixArray[(row+yvariation+i),(column+xvariation+j)])
finalresultPercent=sum(sum(1 for i in row if i>0) for row in ditherArray)/(sqDimOpt**2.)
#print impSection
#print ditherArray
print 'Considering the middle %dx%d pixels'%(impSection.shape[0],impSection.shape[1])
print 'The percent of working pixels initially is %f'%percentgood
print 'The percent with 4 dithers in rect. formation is %f'%finalresultPercent
print 'best dither position: up %d rows and %d columns to the right'%(i,j)
#--Now we will make two plots comparing the center area with and without dithering--
fig2=plt.figure(figsize=(26,11))
plt.subplots_adjust(left = 0.04, right= 0.9, bottom= .05, top= .95)
ax1=fig2.add_subplot(121)
ax2=fig2.add_subplot(122)
textsize=4.5
ax1.text(0, 1.02, 'Green means the pixel is working.\nThe dither position is up %d rows and %d rows to the right'%(i,j), bbox=dict(facecolor='white', alpha=1), size=10)
problem=[]
for row in xrange(0,sqDimOpt):
for column in xrange(0,sqDimOpt):
if binaryPixArray[row+yvariation][column+xvariation]==0:
color='Brown'
ax1.text(.002+ 1./sqDimOpt*column,0.003+ 1./sqDimOpt*row, '%s\n%s\n| (%d,%d)'%('| ','| ',row+yvariation,column+xvariation), bbox=dict(facecolor=color, alpha=.6), size=textsize)
else:
color= 'PaleGreen'
ax1.text(.002+ 1./sqDimOpt*column,0.003+ 1./sqDimOpt*row, '%s\n%s\n| (%d,%d)'%('| ','| ',row+yvariation,column+xvariation), bbox=dict(facecolor=color, alpha=.6), size=textsize)
for row in xrange(0,sqDimOpt):
for column in xrange(0,sqDimOpt):
if ditherArray[row][column]==0:
color='Brown'
ax2.text(.002+ 1./sqDimOpt*column,0.003+ 1./sqDimOpt*row, '%s\n%s\n| (%d,%d)'%('| ','| ',row+yvariation,column+xvariation), bbox=dict(facecolor=color, alpha=.6), size=textsize)
else:
color= 'PaleGreen'
ax2.text(.002+ 1./sqDimOpt*column,0.003+ 1./sqDimOpt*row, '%s\n%s\n| (%d,%d)'%('| ','| ',row+yvariation,column+xvariation), bbox=dict(facecolor=color, alpha=.6), size=textsize)
optimalIndTotal=[]
Allfilledin=1
dim=2
plusD=0
while Allfilledin==1:
boxsum=[]
for row in xrange(yvariation,46-yvariation+1-(plusD+dim)):
for column in xrange(xvariation,44-xvariation+1-(plusD+dim)):
boxvalues=[]
for i in xrange(0,plusD+dim):
for j in xrange(0,plusD+dim):
boxvalues.append(binaryPixArray[row+i][column+j])
boxsum.append([sum(boxvalues),row,column])
boxsum=sorted(boxsum)
if boxsum[len(boxsum)-1][0] != (plusD+dim)**2:
Allfilledin=0
else:
plusD=plusD+1
optimalIndices=[]
stillmax=1
x=len(boxsum)-1
while stillmax==1:
if boxsum[len(boxsum)-1][0]==boxsum[x][0]:
optimalIndices.append([boxsum[x][1],boxsum[x][2]])
x=x-1
else:
stillmax=0
optimalIndTotal.append(optimalIndices)
#print optimalIndTotal
dim=len(optimalIndTotal)
for ind in optimalIndTotal[dim-2]:
rect = pat.Rectangle((1./sqDimOpt*ind[1],1./sqDimOpt*ind[0]),width=1./sqDimOpt*dim, height=1./sqDimOpt*dim, color='Indigo', fill=False, lw=2)
# ax1.add_patch(rect)
# ax1.figure.canvas.draw()
dim=len(optimalIndTotal)+1
for ind in optimalIndTotal[dim-2]:
rect = pat.Rectangle((1./sqDimOpt*ind[1],1./sqDimOpt*ind[0]),width=1./sqDimOpt*dim, height=1./sqDimOpt*dim, color='MediumBlue', fill=False, lw=2)
# ax1.add_patch(rect)
# ax1.figure.canvas.draw()
optimalIndTotal=[]
Allfilledin=1
dim=2
plusD=0
while Allfilledin==1:
boxsum=[]
for row in xrange(0,sqDimOpt+1-(plusD+dim)):
for column in xrange(0,sqDimOpt+1-(plusD+dim)):
boxvalues=[]
for i in xrange(0,plusD+dim):
for j in xrange(0,plusD+dim):
boxvalues.append(ditherArray[row+i][column+j])
boxsum.append([sum(1 for i in boxvalues if i>0),row,column])
boxsum=sorted(boxsum)
if boxsum[len(boxsum)-1][0] != (plusD+dim)**2:
Allfilledin=0
else:
plusD=plusD+1
optimalIndices=[]
stillmax=1
x=len(boxsum)-1
while stillmax==1:
if boxsum[len(boxsum)-1][0]==boxsum[x][0]:
optimalIndices.append([boxsum[x][1],boxsum[x][2]])
x=x-1
if x<0:
stillmax=0
else:
stillmax=0
optimalIndTotal.append(optimalIndices)
#print optimalIndTotal
dim=len(optimalIndTotal)
for ind in optimalIndTotal[dim-2]:
rect = pat.Rectangle((1./sqDimOpt*ind[1],1./sqDimOpt*ind[0]),width=1./sqDimOpt*dim, height=1./sqDimOpt*dim, color='Indigo', fill=False, lw=2)
# ax2.add_patch(rect)
# ax2.figure.canvas.draw()
dim=len(optimalIndTotal)+1
for ind in optimalIndTotal[dim-2]:
rect = pat.Rectangle((1./sqDimOpt*ind[1],1./sqDimOpt*ind[0]),width=1./sqDimOpt*dim, height=1./sqDimOpt*dim, color='MediumBlue', fill=False, lw=2)
# ax2.add_patch(rect)
# ax2.figure.canvas.draw()
ax1.set_title('%dx%d middle section of array'%(sqDimOpt,sqDimOpt))
ax2.set_title('%dx%d section of array with 4 dithers in rect. formation'%(sqDimOpt,sqDimOpt))
fig2.savefig(dithertitle)
plt.show()
plt.close()
| 11,539 | 38.251701 | 255 | py |
SDR | SDR-master/Setup/DetectorAnalysis/MasterQE.py | import tables
import numpy as np
import matplotlib.pyplot as plt
import math
import itertools
from qeforpixelsfunc import *
#savedValues= raw_input('Do you want to used the saved values? Y or enter : ')
automated = raw_input('Is this input from a file?')
if automated in ['y','Y']:
plt.ion()
qeDataFilename = input('Which obs file do you want?')
fid = tables.openFile(qeDataFilename,mode='r')
testbedFileName = input('Which testbed file do you want?')
testbedFile = np.loadtxt(testbedFileName)
qeObsTime = input('What are the datasets named (obs time)?')
roach= input('Which roach do you want to analyze? ')
#qeDataFilename= '/home/sean/data/20121003/obs_20121003-210815.h5'
#qeObsTime=1349298497
#testbedFileName = '/home/sean/data/QEmeas/20121003_210815_postLick_sci3gamma.txt'
#NSec=1800
#qeDataFilename= '/home/sean/data/20121003/obs_20121003-223105.h5'
#qeObsTime=1349303467
#testbedFileName = '/home/sean/data/QEmeas/20121003_223105_postLick_sci3gamma.txt'
#NSec=2000
#qeDataFilename= '/home/sean/data/20121018/obs_20121019-044657.h5'
#qeObsTime=1350622020
#testbedFileName = '/home/sean/data/QEmeas/SCI4-microlens-20121019-044657.txt'
#NSec=1800
#qeDataFilename= '/home/sean/data/20121010/obs_20121010-215637.h5'
#qeObsTime=1349906199
#testbedFileName = '/home/sean/data/QEmeas/SCI4-nomicrolens-1.txt'
#NSec=1300
#dercutoff=12000, firstpeak=109, time interval 800-810
#SCI4 alpha, no microlens
#qeDataFilename= '/home/sean/data/20121011/qe_20121011-185036.h5'
#qeObsTime=1349981438
#testbedFileName='/home/sean/data/QEmeas/SCI4-nomicrolens-2.txt'
#NSec=1800
#dercutoff=10000, pauseafterpeak 14, firstpeakafterpause=1178, firstpeak=92, time interval 850-860
#qeDataFilename= '/home/sean/data/20121019/obs_20121019-193507.h5'
#qeObsTime=1350675309
#testbedFileName='/home/sean/data/QEmeas/SCI4-microlens-20121019-3.txt'
#NSec=1900
##r0,dercutoff=14000, pauseafterpeak 14, firstpeakafterpause=1178, firstpeak=86, time interval 430-440, range 350-1400
#qeDataFilename= '/home/sean/data/20121022/obs_20121022-210829.h5'
#qeObsTime=1350940111
#testbedFileName='/home/sean/data/QEmeas/SCI4-microlens-20121022-210829.txt'
#NSec=2000
##dercutoff=9000, pauseafterpeak 14, firstpeakafterpause=1449, firstpeak=104, time interval 696-712, range 500-600
#Sci4 alpha,best aligned microlens
#qeDataFilename= '/home/sean/data/20121027/obs_20121028-032905.h5'
#qeObsTime=1351394947
#testbedFileName='/home/sean/data/QEmeas/sci4-newalignment-20121028-032905.txt'
#NSec=2000
##dercutoff=10000, pauseafterpeak 14, firstpeakafterpause=1431, firstpeak=86, time interval 1103-1118, range 500-600
#saveMedQEPlotname='/home/sean/data/qePlots/qe20121027r%d.pdf'%(roach)
#qeDataFilename= '/home/sean/data/20121120/obs_20121120-213604.h5'
#qeObsTime=1353447366
#testbedFileName='/home/sean/data/QEmeas/sci4alpha-left-2.txt'
#NSec=2000
##dercutoff=10000, pauseafterpeak 14, firstpeakafterpause=1439, firstpeak=96, time interval 1117-1123, range 500-600
#saveMedQEPlotname='/home/sean/data/qePlots/qe20121120r%d.pdf'%(roach)
#
#qeDataFilename= '/home/sean/data/20121121/obs_20121121-230002.h5'
#qeObsTime=1353538804
#testbedFileName='/home/sean/data/QEmeas/sci4alpha-left-align-1.txt'
#NSec=2000
##dercutoff=20000,15000, pauseafterpeak 14, firstpeakafterpause=1414, firstpeak=70, time interval 665-679,
#saveMedQEPlotname='/home/sean/data/qePlots/qe20121121r%d.pdf'%(roach)
##Sci4a
#qeDataFilename= '/home/sean/data/20121107/obs_20121108-015713.h5'
#qeObsTime=1352339835
#testbedFileName='/home/sean/data/QEmeas/sci4a-waferedge.txt'
#NSec=2000
## roach 0,dercutoff=9000, pauseafterpeak 14, firstpeakafterpause=1456, firstpeak=116, time interval 705-722, range 500-600
#saveMedQEPlotname='/home/sean/data/qePlots/qe20121108r%d.pdf'%(roach)
NPixels=253
magnificationLick = 1.2
magnificationPalomar = 1.46
areaARCONSwithMicrolens = 222*10**-6
areaDetector = 1*10**-2
IRAreaDetector = 3*10**-3
areaARCONSwithoutMicrolens=40*10**-6
areaARCONS = areaARCONSwithMicrolens
magnification = magnificationPalomar
#dectvManual=[0.149,.497,1.156,2.305,3.820,4.762,5.014,5.746,5.232,5.056,6.466,8.5,10.513,11.783]
#wvlManual=range(400,1100,50)
print 'Loading data...\nThis will take a couple minutes...'
#def peakfit(y1,y2,y3):
# y4=y2-0.125*((y3-y1)**2)/(y3+y1-2*y2)
# return y4
#def binToDeg_12_9(binOffset12_9):
# x = binOffset12_9/2.0**9-4.0
# return x*180.0/np.pi
#view the overall histogram of photons seen by a single roach. Record a good time interval during a strong peak and the time the peaks start
photonSec=[]
#pulseMask = int(12*'1',2)#bitmask of 12 ones
NSec = fid.root.header.header.read()[0]['exptime']
pulseh=[[] for x in xrange(NSec)]
for pix in xrange(0,NPixels):
pixelName = '/r%d/p%d/t%d'%(roach,pix,qeObsTime)
# print pixelName
dataset=fid.getNode(pixelName)
for ind, sec in enumerate(dataset):
for packet in sec:
pulseh[ind].append(1)
# packet = int(packet)
# beforePeak = binToDeg_12_9(packet>>44 & pulseMask)
# atPeak = binToDeg_12_9(packet>>32 & pulseMask)
# afterPeak = binToDeg_12_9(packet >> 20 & pulseMask)
# if beforePeak+afterPeak-2*atPeak != 0:
# peak = peakfit(beforePeak,atPeak,afterPeak)
# peak = atPeak
# pulseh[ind].append(peak)
# the peaks for all photons in each second is in its own row of pulseh
for t in pulseh:
photonSec.append(len(t))
# photonSec has the total number of photons per second,
print 'Things to record when you view the following plot: \n time interval during a strong peak\n time the first peak starts\n if there is a pause and if so,\n after what peak does the pause occur\n the time the first peak after the pause starts'
#plt.ion()
der=[]
for t in xrange(0, len(photonSec)-1):
der.append(photonSec[t+1]-photonSec[t])
status='R'
riseCutoff = 10000
fallCutoff = 10000
x=[1,NSec/2,NSec]
y1=[riseCutoff,riseCutoff,riseCutoff]
y2=[-1*fallCutoff,-1*fallCutoff,-1*fallCutoff]
fig1=plt.figure()
plt.plot(der, 'k', x,y1,'b',x,y2,'b')
plt.xlabel('Time')
plt.ylabel('Derivative of the Number of Photons')
plt.title('Derivative of # Photons vs. Time')
plt.grid(True)
plt.draw()
plt.show()
riseCutoff= int(raw_input('What value of the derivative should define a rising edge? 10000? '))
fallCutoff= int(raw_input('What value of the derivative should define a falling edge? 10000? '))
plt.close()
plt.close()
fig0=plt.figure()
plt.plot(photonSec)
plt.xlabel('Time')
plt.ylabel('Number of Photons')
plt.title('# Photons vs. Time')
plt.grid(True)
plt.draw()
plt.show()
pause= raw_input("Is there a pause in the middle of the data? Y or press enter ")
if pause in ('Y', "'Y'",'y',"'y'"):
pause= 'Y'
pausePeak= int(raw_input('After what peak does the pause occur? '))
pauseInitial= int(raw_input('What time does the %d th peak start? '%(pausePeak+1)))
else:
pause= 'N'
pausePeak=0
pauseInitial=NSec+20
indi = []
#print pauseInitial-20
risingEdge = []
fallingEdge = []
for t in xrange(0,len(der)):
if der[t] >= riseCutoff:
risingEdge.append(t)
if der[t] <= -fallCutoff:
fallingEdge.append(t)
print risingEdge
print fallingEdge
peakw = fallingEdge[0]-risingEdge[0]-10
troughw = risingEdge[1] - risingEdge[0]-10
#for g in xrange(0, len(der)):
# if abs(der[g]) >= ncutoff :
# indi.append(g)
##remove close indices that correspond to the same peak
##print indi
#for i in indi:
# x = indi.index(i)
# if x+1 != len(indi) :
# if abs(indi[x+1]-indi[x]) <= 5 :
# del indi[x+1]
#x=0
#while x!= len(indi):
# if indi[x]>(pauseInitial-20):
## print indi[x]
# del indi[x]
# else:
# x=x+1
##print indi
#if len(indi)%2 != 0:
# del indi[len(indi)-1]
#
# # +- 3 so we don't average the first or last 3 sec in each peak
#init = indi[0] + 3
#numon = len(indi)//2
#
#spw = []
#stw = []
#
#for j in xrange(0,numon):
# pw = indi[2*j+1]-indi[2*j]
# spw.append(pw)
#for k in xrange(0,numon-1):
# tw = indi[2*(k+1)]-indi[2*k+1]
# stw.append(tw)
##print spw
##print stw
#peakw = np.average(spw) - 2*3
#troughw = np.average(stw) + 2*3
print 'peakw = %f'%peakw
print 'troughw = %f'%troughw
#useCalc= raw_input("Do you want to use the calculated peakw and troughw? type N or press enter: ")
#if useCalc in ('N', "'N'", 'n', "'n'"):
# peakw = int(raw_input('What do you want to set the peakw as?\n peakw = number of seconds the peak lasts -6 : '))
# troughw = int(raw_input('What do you want to set the troughw as?\n troughw = number of seconds the between peaks +6 : '))
initial= int(raw_input('What time does the first peak start? '))
if status not in ('Q', 'q', "'Q'", "'q'"):
print 'We will see how many photons hit each individual pixel during a given time interval'
intervalStart= int(raw_input('When should the time interval start? '))
intervalStop= int(raw_input('When should the interval stop? '))
finish=[]
Final=[]
pixels=[]
for pix in xrange(0,NPixels):
temp=[]
dataset=fid.getNode('/r%d/p%d/t%d'%(roach,pix,qeObsTime))
for t in xrange(intervalStart,intervalStop):
temp.append(len(dataset[t]))
finish.append([int(np.average(temp)),pix])
Final=sorted(finish)
print '# of photons hit during time interval, pixel they hit] in ascending order'
print Final
fid.close()
#This program looks at specific pixels (picked by using FindGoodPix.py) and plots the photon histogram and qe for each.
#dectv is the values (x10^7) seen in the comparison detector (not arcons).
# HaveTestBed = raw_input("Do you have a test bed file loaded? N or press enter: ")
# if HaveTestBed in ('N', "'N'", 'n', "'n'"):
# dectv=dectvManual
# wvl=wvlManual
# else:
wvl = testbedFile[:,0]
dectv=testbedFile[:,-1]
status='R'
LowPhotonLimit=0
HighPhotonLimit=0
plt.close()
while status in ('R', "'R'", 'r', "'r'"):
LowPhotonLimit=0
HighPhotonLimit=0
PixList=Final
listOrRange= raw_input("Do you want to analyze pixels that recieved a certain level of photons or enter a list of pixel numbers?\nList = L or for Range press enter : ")
if listOrRange in ('L', "'L'", 'l', "'l'"):
pixlist= input("What pixels do you want to analyze? \nMake sure you enter a list! [ , , ] : ")
else:
LowPhotonLimit= int(raw_input('What is the smallest amount of photons allowed? '))
HighPhotonLimit= int(raw_input('What is the largest amount of photons allowed? '))
x=0
while x != len(PixList):
if PixList[x][0]>HighPhotonLimit or PixList[x][0]<LowPhotonLimit:
del PixList[x]
else:
x=x+1
for pix in xrange(0,len(PixList)):
PixList[pix]=PixList[pix][1]
pixlist = PixList
print 'The pixels selected are'
print pixlist
print 'The number of pixels selected are'
print len(pixlist)
plotYorN = raw_input("Do you want to plot photons vs. time for each pixel selected? Y or press enter: ")
if plotYorN in ('Y', "'Y'",'y',"'y'"):
plotYorN= 'Y'
else:
plotYorN= 'N'
NPulses = NumPhotonInWVLPulses(qeDataFilename, qeObsTime, roach, pixlist, initial, peakw, troughw, dectv, NSec, len(wvl), plotYorN , pause, pauseInitial, pausePeak)
print NPulses[0]
fig2=plt.figure()
qeresults=[]
medianQeResults=[]
meanQeResults=[]
print 'dectv=',dectv
print 'NPulses[0]=',NPulses[0][:]
for j in xrange(0,len(pixlist)):
qepix=[]
for i in xrange(0,len(dectv)):
# print wvl[i]
if wvl[i]>= 1100:
qewvl=(NPulses[j][i]*IRAreaDetector**2)/((dectv[i]*10**7)*(magnification*areaARCONS)**2)
else:
qewvl=(NPulses[j][i]*areaDetector**2)/((dectv[i]*10**7)*(magnification*areaARCONS)**2)
# print qewvl
qepix.append(qewvl)
plt.plot(wvl,qepix,label='r%dp%d'%(roach,pixlist[j]))
qeresults.append(qepix)
qeresults = np.array(qeresults)
print 'qeresult[0]=',qeresults[0]
for wl in xrange(0,len(qeresults[0])):
medianQeResults.append(np.median(qeresults[:,wl]))
meanQeResults.append(np.mean(qeresults[:,wl]))
print 'medianQE=',medianQeResults
#print meanQeResults
#-------Some error above. inputs right, formula right, output not right...------
plt.xlabel('Wavelength (nm)')
plt.ylabel('QE')
plt.title('QE of %s in r%d'%(qeDataFilename,roach))
plt.grid(True)
plt.legend()
plt.draw()
plt.show()
# print 'The decimal quantum efficiency of the ADR for 400-1050 wvls are:'
# print qeresults
Save= raw_input("Do you want to save this next plot of the median QE vs. wavelength? Y or enter: ")
plt.close()
fig3=plt.figure()
plt.plot(wvl,medianQeResults, label='median')
plt.plot(wvl,meanQeResults, label='mean')
plt.xlabel('Wavelength (nm)')
plt.ylabel('QE')
plt.legend()
plt.title('Median and Mean QE of %s in r%d'%(qeDataFilename,roach), size=12)
plt.grid(True)
if Save in ('Y', "'Y'",'y',"'y'"):
saveMedQEPlotname= raw_input('Enter the desired filename: ')
print saveMedQEPlotname
plt.savefig(saveMedQEPlotname)
plt.draw()
plt.show()
status = raw_input("What do you want to do? \nRepeat with different pixels= R or press enter to finish: ")
plt.close()
| 13,791 | 34.546392 | 248 | py |
SDR | SDR-master/Setup/DetectorAnalysis/QvsNN.py | #!/usr/bin/python
import numpy as np
from matplotlib import pyplot as plt
#Plots Histogram of f, Q, and Distance of f to nearest neighbor, Q vs f, Dist to neigh vs f and saves it to a pdf. You need to change the File and pdftitle (and possibly the text position in line 79
File= '20121030/FL-sci4a-all-fits.txt'
pdftitle='/home/sean/data/fitshist/20121030-SCI4a-DF-all-QvsNN.pdf'
autofit=np.loadtxt('/home/sean/data/%s'%File)
freqs=autofit[:,1]
Qs=autofit[:,2]
Qs=[x/1000 for x in Qs]
ds=[]
fs=[]
freq=sorted(freqs)
for i in xrange(len(freqs)):
if i-1 >= 0:
y=abs(freq[i]-freq[i-1])
else:
y=abs(freq[i]-freq[i+1])
if i+1 < len(freqs):
x=abs(freq[i]-freq[i+1])
else:
x=abs(freq[i]-freq[i-1])
if x>=y:
ds.append(y)
else:
ds.append(x)
fs.append(freq[i])
ds=[x*1000 for x in ds]
mf=np.median(freqs)
sf=np.std(freqs)
mq=np.median(Qs)
sq=np.std(Qs)
md=np.median(ds)
sd=np.std(ds)
nres=len(freqs)
fig = plt.figure()
ax5=fig.add_subplot(111)
ax5.plot(ds,Qs,'b,')
ax5.set_ylabel('Q(k)', size=8)
ax5.set_xlabel('Distance of f to Nearest Neighbor (MHz)', size=8)
ax5.set_title('Nearest Neighbor vs f0', size=9)
ax5.tick_params(labelsize=8)
#ax5.set_ylim(0,20)
fig.savefig(pdftitle)
plt.show()
plt.close()
| 1,282 | 21.12069 | 199 | py |
SDR | SDR-master/Setup/DetectorAnalysis/PixelQualityfunc.py | import numpy as np
from matplotlib import pyplot as plt
import tables
import re
import collections
import scipy
def createAccuratefQMatrix(bmaptitle, title1,titlefits1,title2,titlefits2,closefcutoff=3):
freqs0=np.loadtxt('/home/sean/data/%s0.txt'%title1)
f0=freqs0[:,0]
f0=f0[1:]
freqs1=np.loadtxt('/home/sean/data/%s1.txt'%title1)
f1=freqs1[:,0]
f1=f1[1:]
freqs2=np.loadtxt('/home/sean/data/%s2.txt'%title1)
f2=freqs2[:,0]
f2=f2[1:]
freqs3=np.loadtxt('/home/sean/data/%s3.txt'%title1)
f3=freqs3[:,0]
f3=f3[1:]
FL1fits=np.loadtxt('/home/sean/data/%s'%titlefits1)
approxf1=FL1fits[:,1]
QFL1=FL1fits[:,2]
QiFL1=FL1fits[:,4]
freqs4=np.loadtxt('/home/sean/data/%s4.txt'%title2)
f4=freqs4[:,0]
f4=f4[1:]
freqs5=np.loadtxt('/home/sean/data/%s5.txt'%title2)
f5=freqs5[:,0]
f5=f5[1:]
freqs6=np.loadtxt('/home/sean/data/%s6.txt'%title2)
f6=freqs6[:,0]
f6=f6[1:]
freqs7=np.loadtxt('/home/sean/data/%s7.txt'%title2)
f7=freqs7[:,0]
f7=f7[1:]
FL2fits=np.loadtxt('/home/sean/data/%s'%titlefits2)
approxf2=FL2fits[:,1]
QFL2=FL2fits[:,2]
QiFL2=FL2fits[:,4]
accuratefs=[f0,f1,f2,f3,f4,f5,f6,f7]
accuratefQ=[]
indexofpickedapproxf1=[]
indexofpickedapproxf2=[]
indexOfDelAccuratef=[]
FL1j=0
FL2j=0
for roach in xrange(0,4):
fQroach=[]
for pixf in xrange(0,len(accuratefs[roach])):
foundmatch=0
i=0
while foundmatch==0:
if FL1j+i+1< len(approxf1):
if abs(accuratefs[roach][pixf]-approxf1[FL1j+i]) < closefcutoff:
fQroach.append([accuratefs[roach][pixf],QFL1[FL1j+i],QiFL1[FL1j+i]])
indexofpickedapproxf1.append(FL1j+i)
foundmatch=1
FL1j=FL1j+i+1
else:
i=i+1
else:
foundmatch=1
indexOfDelAccuratef.append([roach,pixf])
accuratefQ.append(fQroach)
for roach in xrange(4,8):
fQroach=[]
for pixf in xrange(0,len(accuratefs[roach])):
foundmatch=0
i=0
while foundmatch==0:
if FL2j+i+1< len(approxf2):
if abs(accuratefs[roach][pixf]-approxf2[FL2j+i]) < closefcutoff:
fQroach.append([accuratefs[roach][pixf],QFL2[FL2j+i],QiFL2[FL2j+i]])
indexofpickedapproxf2.append(FL2j+i)
foundmatch=1
FL2j=FL2j+i+1
else:
i=i+1
else:
foundmatch=1
indexOfDelAccuratef.append([roach,pixf])
accuratefQ.append(fQroach)
approxfPicked2xFL1=[x for x, y in collections.Counter(indexofpickedapproxf1).items() if y > 1]
approxfPicked2xFL2=[x for x, y in collections.Counter(indexofpickedapproxf2).items() if y > 1]
#print indexOfDelAccuratef
#print len(approxf1),len(f0)+len(f1)+len(f2)+len(f3),len(accuratefQ[0])+len(accuratefQ[1])+len(accuratefQ[2])+len(accuratefQ[3])
#print len(accuratefQ[0]),len(f0),len(accuratefQ[1]),len(f1),len(accuratefQ[2]),len(f2),len(accuratefQ[3]),len(f3)
#print len(approxf2),len(f4)+len(f5)+len(f6)+len(f7),len(accuratefQ[4])+len(accuratefQ[5])+len(accuratefQ[6])+len(accuratefQ[7])
#print len(accuratefQ[4]),len(f4),len(accuratefQ[5]),len(f5),len(accuratefQ[6]),len(f6),len(accuratefQ[7]),len(f7)
return accuratefQ
#now have accuratefQ. The rows correspond to the roaches (1st row is r0) and the entries contain the f and Q for that pixel (accuratefQ[0][0]= [f,Q] for r0p0)
def getfQforgoodpix(bmaptitle, title1,titlefits1,title2,titlefits2):
#title1/2 gives the base of the filename for the frequency files for Feedline 1/2 (Don't include '.txt').
#titlefist1/2 gives the filename of the fits file (include '.txt')
#bmaptitle gives the filename of the beammap (include '.h5')
closefcutoff=.0007 #when the program compares the approximate freq in frequency files to the accurate frequency in the fit file, it will accept a difference of the closefcutoff (GHz)
accuratefQ = createAccuratefQMatrix(bmaptitle, title1,titlefits1,title2,titlefits2,closefcutoff)
#now have accuratefQ. The rows correspond to the roaches (1st row is r0) and the entries contain the f and Q for that pixel (accuratefQ[0][0]= [f,Q] for r0p0)
fid=tables.openFile(bmaptitle)
b=fid.root.beammap.beamimage
pixlist = []
for row in xrange(0,46):
for column in xrange(0,44):
string=b[row][column]
a=re.findall(r'\d+',string)
roachNum=int(a[0])
pixelNum=int(a[1])
if roachNum<8:
if pixelNum < len(accuratefQ[roachNum]):
pixlist.append([[roachNum,pixelNum],accuratefQ[roachNum][pixelNum]])
fid.close()
pixlist=sorted(pixlist)
return pixlist
| 5,169 | 37.014706 | 187 | py |
SDR | SDR-master/Setup/DetectorAnalysis/qeforpixelsfunc.py | import tables
import numpy as np
import matplotlib.pyplot as plt
import math
import itertools
def peakfit(y1,y2,y3):
y4=y2-0.125*((y3-y1)**2)/(y3+y1-2*y2)
return y4
def binToDeg_12_9(binOffset12_9):
x = binOffset12_9/2.0**9-4.0
return x*180.0/np.pi
def NumPhotonInWVLPulses(qeDataFilename, qeObsTime, roach, pixlist, initial, peakw, troughw, dectv, NSec=3600, nwvl=14, plotYorN= 'N', pause= 'N', pauseInitial=0, pausePeak=1, indicesTooCloseCutoff=3):
delayforIR=3
peaks=[]
darkflux=[0,initial-2*indicesTooCloseCutoff]
if pause=='Y':
for x in xrange(0,pausePeak):
init=initial+int((peakw+troughw)*x)
fin=init+int(peakw)
peaks.append(init)
peaks.append(fin)
for x in xrange(0,nwvl-pausePeak):
init=pauseInitial+int((peakw+troughw+delayforIR)*x)
fin=init+int(peakw)
peaks.append(init)
peaks.append(fin)
for x in xrange(0,pausePeak):
init=int(initial+peakw+2*indicesTooCloseCutoff+(peakw+troughw)*x)
fin=init+int(troughw)-3*indicesTooCloseCutoff
darkflux.append(init)
darkflux.append(fin)
for x in xrange(0,nwvl-pausePeak):
init=int(pauseInitial+peakw+2*indicesTooCloseCutoff+(peakw+troughw+delayforIR)*x)
fin=init+int(troughw+delayforIR)-3*indicesTooCloseCutoff
darkflux.append(init)
darkflux.append(fin)
else:
for x in xrange(0,nwvl):
init=initial+int((peakw+troughw)*x)
fin=init+int(peakw)
peaks.append(init)
peaks.append(fin)
for x in xrange(0,nwvl):
init=int(initial+peakw+2*indicesTooCloseCutoff+(peakw+troughw)*x)
fin=init+int(troughw)-3*indicesTooCloseCutoff
darkflux.append(init)
darkflux.append(fin)
print 'The times indicating the beginning and end of each peak are'
print peaks
#print darkflux
NPulses=[]
pulseMask = int(12*'1',2)#bitmask of 12 ones
fid = tables.openFile(qeDataFilename,mode='r')
for pix in pixlist:
photonSec=[]
temp=[]
pulseh=[[] for x in xrange(NSec)]
dataset=fid.getNode('/r%d/p%d/t%d'%(roach,pix,qeObsTime))
for ind, sec in enumerate(dataset):
for packet in sec:
pulseh[ind].append(1)
# packet = int(packet)
# beforePeak = binToDeg_12_9(packet>>44 & pulseMask)
# atPeak = binToDeg_12_9(packet>>32 & pulseMask)
# afterPeak = binToDeg_12_9(packet >> 20 & pulseMask)
# if beforePeak+afterPeak-2*atPeak != 0:
# peak = peakfit(beforePeak,atPeak,afterPeak)
# pulseh[ind].append(peak)
# the peaks for all photons in each second is in its own row of pulseh
for q in pulseh:
photonSec.append(len(q))
fin=[]
tpeak=[]
for i in xrange(0,len(peaks)/2):
pk=np.average(photonSec[peaks[2*i]:peaks[2*i+1]])
dk=np.average(photonSec[darkflux[2*i]:darkflux[2*i+1]]+photonSec[darkflux[2*i+2]:darkflux[2*i+3]])
net=pk-dk
fin.append(net)
tpeak.append(np.average([peaks[2*i],peaks[2*i+1]]))
# fin.append(pk)
NPulses.append(fin)
# photonSec has the total number of photons per second,
if plotYorN == 'Y':
# plt.plot(photonSec)
fig=plt.figure()
ax=fig.add_subplot(111)
ax.plot(peaks,[0]*len(peaks),'ro')
ax.plot(tpeak,fin,'bo')
ax.plot(photonSec)
ax.set_xlabel('Time')
ax.set_ylabel('Number of Photons')
ax.set_title('# Photons vs. Time r%dp%d'%(roach,pix))
plt.grid(True)
plt.show()
plt.close()
fid.close()
return NPulses
def qeFuncOfWvl(qeDataFilename, qeObsTime, roach, pixel, ini, peakw, troughw, dectv, NSec=3600, nwvl=14, plotYorN='N'):
pixlist= [pixel]
NPulses = NumPhotonInWVLPulses(qeDataFilename, qeObsTime, roach, pixlist, ini, peakw, troughw, dectv, NSec, nwvl, plotYorN='N', indicesTooCloseCutoff=3)
qeresults=[]
for i in xrange(0,len(dectv)):
qewvl=1/(dectv[i]*10**7/NPulses[0][i]*.0007096896)
qeresults.append(qewvl)
return qeresults
| 4,349 | 33.52381 | 202 | py |
SDR | SDR-master/Setup/WideSweep/distributeFreqsToRoaches.py | import numpy as np
import pylab as plt
import sys
import os
import argparse
"""
Read the list of frequencies (data01-good.txt by default) and write
local oscillator frequencies (FL1-lofreqs.txt) for each roach.
"""
parser = argparse.ArgumentParser(description="Distribute frequencies to roach boards")
parser.add_argument('feedline',help='one-based index of the feed line',
type=int)
parser.add_argument('-fileName',
help='file of frequencies, located in MKID_DATA_DIR',
default='data01-good.txt')
args = parser.parse_args()
fileName = args.fileName
feedline = args.feedline
print "begin with fileName=",fileName," feedline=",feedline
NRoaches = int(os.environ['MKID_NROACHES'])
roachBandwidth = float(os.environ['MKID_ROACH_BANDWIDTH'])
#resonant frequency list for the feedline
dir = os.environ['MKID_DATA_DIR']
datafilename=os.path.join(dir,fileName)
table = np.loadtxt(datafilename)
freqs = table[:,2]
#freqs = table[:,1]
freqs.sort()
fig = plt.figure()
ax=fig.add_subplot(111)
fStart=freqs.min()
fLast=freqs.max()
print ''
print len(freqs), ' total frequencies'
print 'f_min = ',freqs.min()
print 'f_max = ',freqs.max()
totalSpread=fLast-fStart
#totalBinsOverSpread=200.0
#binWidth=totalSpread/totalBinsOverSpread
#set default freq ranges for each roach or manually tweak them
#roachFreqStart = np.array([fStart]*NRoaches)
#roachLOFreq = np.array([fStart]*NRoaches)
#if feedline == 1:
# roachLOFreq[0] = fStart+roachBandwidth/2.0+.08
# roachLOFreq[1] = roachLOFreq[0]+roachBandwidth+.15
# roachLOFreq[2] = roachLOFreq[1]+roachBandwidth+.1
# roachLOFreq[3] = roachLOFreq[2]+roachBandwidth+.05
#else:
# roachLOFreq[0] = fStart+roachBandwidth/2.0
# roachLOFreq[1] = roachLOFreq[0]+roachBandwidth+.08
# roachLOFreq[2] = roachLOFreq[1]+roachBandwidth+.11
# roachLOFreq[3] = roachLOFreq[2]+roachBandwidth+.11
# Chris S. version that only does MKID_NROACHES
# what is the logic of the small offsets? I'll just use 0.1 everywhere
roachLOFreq = np.zeros(NRoaches)
roachLOFreq[0] = fStart+roachBandwidth/2.0
for iRoach in range(1,NRoaches):
roachLOFreq[iRoach] = roachLOFreq[iRoach-1] + roachBandwidh + 0.10
print "roachLOFreq=",roachLOFreq
roachFreqEnd = roachLOFreq+roachBandwidth/2.0
roachFreqStart = roachLOFreq-roachBandwidth/2.0
roachFreqList=[[]]*NRoaches
outputTable=[[]]*NRoaches
excludedFreqs = freqs
for iRoach in np.arange(0,NRoaches):
r = iRoach+4*(feedline-1)
print "begin iRoach=",iRoach,' r=',r," start=",roachFreqStart[iRoach],' end=',roachFreqEnd[iRoach]
roachFreqList[iRoach] = freqs[np.logical_and(roachFreqStart[iRoach] <= freqs,freqs < roachFreqEnd[iRoach])]
excludedFreqs = excludedFreqs[np.logical_or(excludedFreqs < roachFreqStart[iRoach],roachFreqEnd[iRoach] < excludedFreqs)]
print 'roach ',r, ' covers ',len(roachFreqList[iRoach]),' freqs'
if len(roachFreqList[iRoach]>0):
ax.hist(roachFreqList[iRoach],bins=20)
print '%d freqs excluded'%len(excludedFreqs)
if len(excludedFreqs) > 0:
ax.hist(excludedFreqs,bins=100,color='black')
plt.show()
lo_fid=open(os.path.join(dir,'FL%d-lofreqs.txt'%feedline),'w')
for iRoach in np.arange(0,NRoaches):
r = iRoach+4*(feedline-1)
roachFreqList[iRoach] = freqs[np.logical_and(roachFreqStart[iRoach] <= freqs,freqs < roachFreqEnd[iRoach])]
excludedFreqs = excludedFreqs[np.logical_or(excludedFreqs < roachFreqStart[iRoach],roachFreqEnd[iRoach] < excludedFreqs)]
print 'roach ',r, ' covers ',len(roachFreqList[iRoach]),' freqs, ',
roachFreqMin = roachFreqList[iRoach].min()
roachFreqMax = roachFreqList[iRoach].max()
print 'from %.3f to %.3f'%(roachFreqMin,roachFreqMax),
roachFreqLO=roachFreqMin+(roachFreqMax-roachFreqMin)/2.0
print ' with LO freq at %.3f'%roachLOFreq[iRoach]
lo_fid.write('%.5f\n'%roachLOFreq[iRoach])
ax.hist(roachFreqList[iRoach],bins=20)
fid = open(os.path.join(dir,'freq%d.txt'%r),'w')
fid.write('1\t1\t1\t1\n')
for freq in roachFreqList[iRoach]:
fid.write('%.7f\t0\t0\t1\n'%freq)
fid.close()
#ax.hist(excludedFreqs,bins=100,color='black')
print '%d freqs excluded'%len(excludedFreqs)
lo_fid.close()
| 4,195 | 36.132743 | 125 | py |
SDR | SDR-master/Setup/WideSweep/mpfit.py | """
Perform Levenberg-Marquardt least-squares minimization, based on MINPACK-1.
AUTHORS
The original version of this software, called LMFIT, was written in FORTRAN
as part of the MINPACK-1 package by XXX.
Craig Markwardt converted the FORTRAN code to IDL. The information for the
IDL version is:
Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
[email protected]
UPDATED VERSIONs can be found on my WEB PAGE:
http://cow.physics.wisc.edu/~craigm/idl/idl.html
Mark Rivers created this Python version from Craig's IDL version.
Mark Rivers, University of Chicago
Building 434A, Argonne National Laboratory
9700 South Cass Avenue, Argonne, IL 60439
[email protected]
Updated versions can be found at http://cars.uchicago.edu/software
Sergey Koposov converted the Mark's Python version from Numeric to numpy
Sergey Koposov, University of Cambridge, Institute of Astronomy,
Madingley road, CB3 0HA, Cambridge, UK
[email protected]
Updated versions can be found at http://code.google.com/p/astrolibpy/source/browse/trunk/
DESCRIPTION
MPFIT uses the Levenberg-Marquardt technique to solve the
least-squares problem. In its typical use, MPFIT will be used to
fit a user-supplied function (the "model") to user-supplied data
points (the "data") by adjusting a set of parameters. MPFIT is
based upon MINPACK-1 (LMDIF.F) by More' and collaborators.
For example, a researcher may think that a set of observed data
points is best modelled with a Gaussian curve. A Gaussian curve is
parameterized by its mean, standard deviation and normalization.
MPFIT will, within certain constraints, find the set of parameters
which best fits the data. The fit is "best" in the least-squares
sense; that is, the sum of the weighted squared differences between
the model and data is minimized.
The Levenberg-Marquardt technique is a particular strategy for
iteratively searching for the best fit. This particular
implementation is drawn from MINPACK-1 (see NETLIB), and is much faster
and more accurate than the version provided in the Scientific Python package
in Scientific.Functions.LeastSquares.
This version allows upper and lower bounding constraints to be placed on each
parameter, or the parameter can be held fixed.
The user-supplied Python function should return an array of weighted
deviations between model and data. In a typical scientific problem
the residuals should be weighted so that each deviate has a
gaussian sigma of 1.0. If X represents values of the independent
variable, Y represents a measurement for each value of X, and ERR
represents the error in the measurements, then the deviates could
be calculated as follows:
DEVIATES = (Y - F(X)) / ERR
where F is the analytical function representing the model. You are
recommended to use the convenience functions MPFITFUN and
MPFITEXPR, which are driver functions that calculate the deviates
for you. If ERR are the 1-sigma uncertainties in Y, then
TOTAL( DEVIATES^2 )
will be the total chi-squared value. MPFIT will minimize the
chi-square value. The values of X, Y and ERR are passed through
MPFIT to the user-supplied function via the FUNCTKW keyword.
Simple constraints can be placed on parameter values by using the
PARINFO keyword to MPFIT. See below for a description of this
keyword.
MPFIT does not perform more general optimization tasks. See TNMIN
instead. MPFIT is customized, based on MINPACK-1, to the
least-squares minimization problem.
USER FUNCTION
The user must define a function which returns the appropriate
values as specified above. The function should return the weighted
deviations between the model and the data. It should also return a status
flag and an optional partial derivative array. For applications which
use finite-difference derivatives -- the default -- the user
function should be declared in the following way:
def myfunct(p, fjac=None, x=None, y=None, err=None)
# Parameter values are passed in "p"
# If fjac==None then partial derivatives should not be
# computed. It will always be None if MPFIT is called with default
# flag.
model = F(x, p)
# Non-negative status value means MPFIT should continue, negative means
# stop the calculation.
status = 0
return([status, (y-model)/err]
See below for applications with analytical derivatives.
The keyword parameters X, Y, and ERR in the example above are
suggestive but not required. Any parameters can be passed to
MYFUNCT by using the functkw keyword to MPFIT. Use MPFITFUN and
MPFITEXPR if you need ideas on how to do that. The function *must*
accept a parameter list, P.
In general there are no restrictions on the number of dimensions in
X, Y or ERR. However the deviates *must* be returned in a
one-dimensional Numeric array of type Float.
User functions may also indicate a fatal error condition using the
status return described above. If status is set to a number between
-15 and -1 then MPFIT will stop the calculation and return to the caller.
ANALYTIC DERIVATIVES
In the search for the best-fit solution, MPFIT by default
calculates derivatives numerically via a finite difference
approximation. The user-supplied function need not calculate the
derivatives explicitly. However, if you desire to compute them
analytically, then the AUTODERIVATIVE=0 keyword must be passed to MPFIT.
As a practical matter, it is often sufficient and even faster to allow
MPFIT to calculate the derivatives numerically, and so
AUTODERIVATIVE=0 is not necessary.
If AUTODERIVATIVE=0 is used then the user function must check the parameter
FJAC, and if FJAC!=None then return the partial derivative array in the
return list.
def myfunct(p, fjac=None, x=None, y=None, err=None)
# Parameter values are passed in "p"
# If FJAC!=None then partial derivatives must be comptuer.
# FJAC contains an array of len(p), where each entry
# is 1 if that parameter is free and 0 if it is fixed.
model = F(x, p)
Non-negative status value means MPFIT should continue, negative means
# stop the calculation.
status = 0
if (dojac):
pderiv = zeros([len(x), len(p)], Float)
for j in range(len(p)):
pderiv[:,j] = FGRAD(x, p, j)
else:
pderiv = None
return([status, (y-model)/err, pderiv]
where FGRAD(x, p, i) is a user function which must compute the
derivative of the model with respect to parameter P[i] at X. When
finite differencing is used for computing derivatives (ie, when
AUTODERIVATIVE=1), or when MPFIT needs only the errors but not the
derivatives the parameter FJAC=None.
Derivatives should be returned in the PDERIV array. PDERIV should be an m x
n array, where m is the number of data points and n is the number
of parameters. dp[i,j] is the derivative at the ith point with
respect to the jth parameter.
The derivatives with respect to fixed parameters are ignored; zero
is an appropriate value to insert for those derivatives. Upon
input to the user function, FJAC is set to a vector with the same
length as P, with a value of 1 for a parameter which is free, and a
value of zero for a parameter which is fixed (and hence no
derivative needs to be calculated).
If the data is higher than one dimensional, then the *last*
dimension should be the parameter dimension. Example: fitting a
50x50 image, "dp" should be 50x50xNPAR.
CONSTRAINING PARAMETER VALUES WITH THE PARINFO KEYWORD
The behavior of MPFIT can be modified with respect to each
parameter to be fitted. A parameter value can be fixed; simple
boundary constraints can be imposed; limitations on the parameter
changes can be imposed; properties of the automatic derivative can
be modified; and parameters can be tied to one another.
These properties are governed by the PARINFO structure, which is
passed as a keyword parameter to MPFIT.
PARINFO should be a list of dictionaries, one list entry for each parameter.
Each parameter is associated with one element of the array, in
numerical order. The dictionary can have the following keys
(none are required, keys are case insensitive):
'value' - the starting parameter value (but see the START_PARAMS
parameter for more information).
'fixed' - a boolean value, whether the parameter is to be held
fixed or not. Fixed parameters are not varied by
MPFIT, but are passed on to MYFUNCT for evaluation.
'limited' - a two-element boolean array. If the first/second
element is set, then the parameter is bounded on the
lower/upper side. A parameter can be bounded on both
sides. Both LIMITED and LIMITS must be given
together.
'limits' - a two-element float array. Gives the
parameter limits on the lower and upper sides,
respectively. Zero, one or two of these values can be
set, depending on the values of LIMITED. Both LIMITED
and LIMITS must be given together.
'parname' - a string, giving the name of the parameter. The
fitting code of MPFIT does not use this tag in any
way. However, the default iterfunct will print the
parameter name if available.
'step' - the step size to be used in calculating the numerical
derivatives. If set to zero, then the step size is
computed automatically. Ignored when AUTODERIVATIVE=0.
'mpside' - the sidedness of the finite difference when computing
numerical derivatives. This field can take four
values:
0 - one-sided derivative computed automatically
1 - one-sided derivative (f(x+h) - f(x) )/h
-1 - one-sided derivative (f(x) - f(x-h))/h
2 - two-sided derivative (f(x+h) - f(x-h))/(2*h)
Where H is the STEP parameter described above. The
"automatic" one-sided derivative method will chose a
direction for the finite difference which does not
violate any constraints. The other methods do not
perform this check. The two-sided method is in
principle more precise, but requires twice as many
function evaluations. Default: 0.
'mpmaxstep' - the maximum change to be made in the parameter
value. During the fitting process, the parameter
will never be changed by more than this value in
one iteration.
A value of 0 indicates no maximum. Default: 0.
'tied' - a string expression which "ties" the parameter to other
free or fixed parameters. Any expression involving
constants and the parameter array P are permitted.
Example: if parameter 2 is always to be twice parameter
1 then use the following: parinfo(2).tied = '2 * p(1)'.
Since they are totally constrained, tied parameters are
considered to be fixed; no errors are computed for them.
[ NOTE: the PARNAME can't be used in expressions. ]
'mpprint' - if set to 1, then the default iterfunct will print the
parameter value. If set to 0, the parameter value
will not be printed. This tag can be used to
selectively print only a few parameter values out of
many. Default: 1 (all parameters printed)
Future modifications to the PARINFO structure, if any, will involve
adding dictionary tags beginning with the two letters "MP".
Therefore programmers are urged to avoid using tags starting with
the same letters; otherwise they are free to include their own
fields within the PARINFO structure, and they will be ignored.
PARINFO Example:
parinfo = [{'value':0., 'fixed':0, 'limited':[0,0], 'limits':[0.,0.]}
for i in range(5)]
parinfo[0]['fixed'] = 1
parinfo[4]['limited'][0] = 1
parinfo[4]['limits'][0] = 50.
values = [5.7, 2.2, 500., 1.5, 2000.]
for i in range(5): parinfo[i]['value']=values[i]
A total of 5 parameters, with starting values of 5.7,
2.2, 500, 1.5, and 2000 are given. The first parameter
is fixed at a value of 5.7, and the last parameter is
constrained to be above 50.
EXAMPLE
import mpfit
import numpy.oldnumeric as Numeric
x = arange(100, float)
p0 = [5.7, 2.2, 500., 1.5, 2000.]
y = ( p[0] + p[1]*[x] + p[2]*[x**2] + p[3]*sqrt(x) +
p[4]*log(x))
fa = {'x':x, 'y':y, 'err':err}
m = mpfit('myfunct', p0, functkw=fa)
print 'status = ', m.status
if (m.status <= 0): print 'error message = ', m.errmsg
print 'parameters = ', m.params
Minimizes sum of squares of MYFUNCT. MYFUNCT is called with the X,
Y, and ERR keyword parameters that are given by FUNCTKW. The
results can be obtained from the returned object m.
THEORY OF OPERATION
There are many specific strategies for function minimization. One
very popular technique is to use function gradient information to
realize the local structure of the function. Near a local minimum
the function value can be taylor expanded about x0 as follows:
f(x) = f(x0) + f'(x0) . (x-x0) + (1/2) (x-x0) . f''(x0) . (x-x0)
----- --------------- ------------------------------- (1)
Order 0th 1st 2nd
Here f'(x) is the gradient vector of f at x, and f''(x) is the
Hessian matrix of second derivatives of f at x. The vector x is
the set of function parameters, not the measured data vector. One
can find the minimum of f, f(xm) using Newton's method, and
arrives at the following linear equation:
f''(x0) . (xm-x0) = - f'(x0) (2)
If an inverse can be found for f''(x0) then one can solve for
(xm-x0), the step vector from the current position x0 to the new
projected minimum. Here the problem has been linearized (ie, the
gradient information is known to first order). f''(x0) is
symmetric n x n matrix, and should be positive definite.
The Levenberg - Marquardt technique is a variation on this theme.
It adds an additional diagonal term to the equation which may aid the
convergence properties:
(f''(x0) + nu I) . (xm-x0) = -f'(x0) (2a)
where I is the identity matrix. When nu is large, the overall
matrix is diagonally dominant, and the iterations follow steepest
descent. When nu is small, the iterations are quadratically
convergent.
In principle, if f''(x0) and f'(x0) are known then xm-x0 can be
determined. However the Hessian matrix is often difficult or
impossible to compute. The gradient f'(x0) may be easier to
compute, if even by finite difference techniques. So-called
quasi-Newton techniques attempt to successively estimate f''(x0)
by building up gradient information as the iterations proceed.
In the least squares problem there are further simplifications
which assist in solving eqn (2). The function to be minimized is
a sum of squares:
f = Sum(hi^2) (3)
where hi is the ith residual out of m residuals as described
above. This can be substituted back into eqn (2) after computing
the derivatives:
f' = 2 Sum(hi hi')
f'' = 2 Sum(hi' hj') + 2 Sum(hi hi'') (4)
If one assumes that the parameters are already close enough to a
minimum, then one typically finds that the second term in f'' is
negligible [or, in any case, is too difficult to compute]. Thus,
equation (2) can be solved, at least approximately, using only
gradient information.
In matrix notation, the combination of eqns (2) and (4) becomes:
hT' . h' . dx = - hT' . h (5)
Where h is the residual vector (length m), hT is its transpose, h'
is the Jacobian matrix (dimensions n x m), and dx is (xm-x0). The
user function supplies the residual vector h, and in some cases h'
when it is not found by finite differences (see MPFIT_FDJAC2,
which finds h and hT'). Even if dx is not the best absolute step
to take, it does provide a good estimate of the best *direction*,
so often a line minimization will occur along the dx vector
direction.
The method of solution employed by MINPACK is to form the Q . R
factorization of h', where Q is an orthogonal matrix such that QT .
Q = I, and R is upper right triangular. Using h' = Q . R and the
ortogonality of Q, eqn (5) becomes
(RT . QT) . (Q . R) . dx = - (RT . QT) . h
RT . R . dx = - RT . QT . h (6)
R . dx = - QT . h
where the last statement follows because R is upper triangular.
Here, R, QT and h are known so this is a matter of solving for dx.
The routine MPFIT_QRFAC provides the QR factorization of h, with
pivoting, and MPFIT_QRSOLV provides the solution for dx.
REFERENCES
MINPACK-1, Jorge More', available from netlib (www.netlib.org).
"Optimization Software Guide," Jorge More' and Stephen Wright,
SIAM, *Frontiers in Applied Mathematics*, Number 14.
More', Jorge J., "The Levenberg-Marquardt Algorithm:
Implementation and Theory," in *Numerical Analysis*, ed. Watson,
G. A., Lecture Notes in Mathematics 630, Springer-Verlag, 1977.
MODIFICATION HISTORY
Translated from MINPACK-1 in FORTRAN, Apr-Jul 1998, CM
Copyright (C) 1997-2002, Craig Markwardt
This software is provided as is without any warranty whatsoever.
Permission to use, copy, modify, and distribute modified or
unmodified copies is granted, provided this copyright and disclaimer
are included unchanged.
Translated from MPFIT (Craig Markwardt's IDL package) to Python,
August, 2002. Mark Rivers
Converted from Numeric to numpy (Sergey Koposov, July 2008)
"""
import numpy
import types
import scipy.lib.blas
# Original FORTRAN documentation
# **********
#
# subroutine lmdif
#
# the purpose of lmdif is to minimize the sum of the squares of
# m nonlinear functions in n variables by a modification of
# the levenberg-marquardt algorithm. the user must provide a
# subroutine which calculates the functions. the jacobian is
# then calculated by a forward-difference approximation.
#
# the subroutine statement is
#
# subroutine lmdif(fcn,m,n,x,fvec,ftol,xtol,gtol,maxfev,epsfcn,
# diag,mode,factor,nprint,info,nfev,fjac,
# ldfjac,ipvt,qtf,wa1,wa2,wa3,wa4)
#
# where
#
# fcn is the name of the user-supplied subroutine which
# calculates the functions. fcn must be declared
# in an external statement in the user calling
# program, and should be written as follows.
#
# subroutine fcn(m,n,x,fvec,iflag)
# integer m,n,iflag
# double precision x(n),fvec(m)
# ----------
# calculate the functions at x and
# return this vector in fvec.
# ----------
# return
# end
#
# the value of iflag should not be changed by fcn unless
# the user wants to terminate execution of lmdif.
# in this case set iflag to a negative integer.
#
# m is a positive integer input variable set to the number
# of functions.
#
# n is a positive integer input variable set to the number
# of variables. n must not exceed m.
#
# x is an array of length n. on input x must contain
# an initial estimate of the solution vector. on output x
# contains the final estimate of the solution vector.
#
# fvec is an output array of length m which contains
# the functions evaluated at the output x.
#
# ftol is a nonnegative input variable. termination
# occurs when both the actual and predicted relative
# reductions in the sum of squares are at most ftol.
# therefore, ftol measures the relative error desired
# in the sum of squares.
#
# xtol is a nonnegative input variable. termination
# occurs when the relative error between two consecutive
# iterates is at most xtol. therefore, xtol measures the
# relative error desired in the approximate solution.
#
# gtol is a nonnegative input variable. termination
# occurs when the cosine of the angle between fvec and
# any column of the jacobian is at most gtol in absolute
# value. therefore, gtol measures the orthogonality
# desired between the function vector and the columns
# of the jacobian.
#
# maxfev is a positive integer input variable. termination
# occurs when the number of calls to fcn is at least
# maxfev by the end of an iteration.
#
# epsfcn is an input variable used in determining a suitable
# step length for the forward-difference approximation. this
# approximation assumes that the relative errors in the
# functions are of the order of epsfcn. if epsfcn is less
# than the machine precision, it is assumed that the relative
# errors in the functions are of the order of the machine
# precision.
#
# diag is an array of length n. if mode = 1 (see
# below), diag is internally set. if mode = 2, diag
# must contain positive entries that serve as
# multiplicative scale factors for the variables.
#
# mode is an integer input variable. if mode = 1, the
# variables will be scaled internally. if mode = 2,
# the scaling is specified by the input diag. other
# values of mode are equivalent to mode = 1.
#
# factor is a positive input variable used in determining the
# initial step bound. this bound is set to the product of
# factor and the euclidean norm of diag*x if nonzero, or else
# to factor itself. in most cases factor should lie in the
# interval (.1,100.). 100. is a generally recommended value.
#
# nprint is an integer input variable that enables controlled
# printing of iterates if it is positive. in this case,
# fcn is called with iflag = 0 at the beginning of the first
# iteration and every nprint iterations thereafter and
# immediately prior to return, with x and fvec available
# for printing. if nprint is not positive, no special calls
# of fcn with iflag = 0 are made.
#
# info is an integer output variable. if the user has
# terminated execution, info is set to the (negative)
# value of iflag. see description of fcn. otherwise,
# info is set as follows.
#
# info = 0 improper input parameters.
#
# info = 1 both actual and predicted relative reductions
# in the sum of squares are at most ftol.
#
# info = 2 relative error between two consecutive iterates
# is at most xtol.
#
# info = 3 conditions for info = 1 and info = 2 both hold.
#
# info = 4 the cosine of the angle between fvec and any
# column of the jacobian is at most gtol in
# absolute value.
#
# info = 5 number of calls to fcn has reached or
# exceeded maxfev.
#
# info = 6 ftol is too small. no further reduction in
# the sum of squares is possible.
#
# info = 7 xtol is too small. no further improvement in
# the approximate solution x is possible.
#
# info = 8 gtol is too small. fvec is orthogonal to the
# columns of the jacobian to machine precision.
#
# nfev is an integer output variable set to the number of
# calls to fcn.
#
# fjac is an output m by n array. the upper n by n submatrix
# of fjac contains an upper triangular matrix r with
# diagonal elements of nonincreasing magnitude such that
#
# t t t
# p *(jac *jac)*p = r *r,
#
# where p is a permutation matrix and jac is the final
# calculated jacobian. column j of p is column ipvt(j)
# (see below) of the identity matrix. the lower trapezoidal
# part of fjac contains information generated during
# the computation of r.
#
# ldfjac is a positive integer input variable not less than m
# which specifies the leading dimension of the array fjac.
#
# ipvt is an integer output array of length n. ipvt
# defines a permutation matrix p such that jac*p = q*r,
# where jac is the final calculated jacobian, q is
# orthogonal (not stored), and r is upper triangular
# with diagonal elements of nonincreasing magnitude.
# column j of p is column ipvt(j) of the identity matrix.
#
# qtf is an output array of length n which contains
# the first n elements of the vector (q transpose)*fvec.
#
# wa1, wa2, and wa3 are work arrays of length n.
#
# wa4 is a work array of length m.
#
# subprograms called
#
# user-supplied ...... fcn
#
# minpack-supplied ... dpmpar,enorm,fdjac2,,qrfac
#
# fortran-supplied ... dabs,dmax1,dmin1,dsqrt,mod
#
# argonne national laboratory. minpack project. march 1980.
# burton s. garbow, kenneth e. hillstrom, jorge j. more
#
# **********
class mpfit:
blas_enorm32, = scipy.lib.blas.get_blas_funcs(['nrm2'],numpy.array([0],dtype=numpy.float32))
blas_enorm64, = scipy.lib.blas.get_blas_funcs(['nrm2'],numpy.array([0],dtype=numpy.float64))
def __init__(self, fcn, xall=None, functkw={}, parinfo=None,
ftol=1.e-10, xtol=1.e-10, gtol=1.e-10,
damp=0., maxiter=200, factor=100., nprint=1,
iterfunct='default', iterkw={}, nocovar=0,
rescale=0, autoderivative=1, quiet=0,
diag=None, epsfcn=None, debug=0):
"""
Inputs:
fcn:
The function to be minimized. The function should return the weighted
deviations between the model and the data, as described above.
xall:
An array of starting values for each of the parameters of the model.
The number of parameters should be fewer than the number of measurements.
This parameter is optional if the parinfo keyword is used (but see
parinfo). The parinfo keyword provides a mechanism to fix or constrain
individual parameters.
Keywords:
autoderivative:
If this is set, derivatives of the function will be computed
automatically via a finite differencing procedure. If not set, then
fcn must provide the (analytical) derivatives.
Default: set (=1)
NOTE: to supply your own analytical derivatives,
explicitly pass autoderivative=0
ftol:
A nonnegative input variable. Termination occurs when both the actual
and predicted relative reductions in the sum of squares are at most
ftol (and status is accordingly set to 1 or 3). Therefore, ftol
measures the relative error desired in the sum of squares.
Default: 1E-10
functkw:
A dictionary which contains the parameters to be passed to the
user-supplied function specified by fcn via the standard Python
keyword dictionary mechanism. This is the way you can pass additional
data to your user-supplied function without using global variables.
Consider the following example:
if functkw = {'xval':[1.,2.,3.], 'yval':[1.,4.,9.],
'errval':[1.,1.,1.] }
then the user supplied function should be declared like this:
def myfunct(p, fjac=None, xval=None, yval=None, errval=None):
Default: {} No extra parameters are passed to the user-supplied
function.
gtol:
A nonnegative input variable. Termination occurs when the cosine of
the angle between fvec and any column of the jacobian is at most gtol
in absolute value (and status is accordingly set to 4). Therefore,
gtol measures the orthogonality desired between the function vector
and the columns of the jacobian.
Default: 1e-10
iterkw:
The keyword arguments to be passed to iterfunct via the dictionary
keyword mechanism. This should be a dictionary and is similar in
operation to FUNCTKW.
Default: {} No arguments are passed.
iterfunct:
The name of a function to be called upon each NPRINT iteration of the
MPFIT routine. It should be declared in the following way:
def iterfunct(myfunct, p, iter, fnorm, functkw=None,
parinfo=None, quiet=0, dof=None, [iterkw keywords here])
# perform custom iteration update
iterfunct must accept all three keyword parameters (FUNCTKW, PARINFO
and QUIET).
myfunct: The user-supplied function to be minimized,
p: The current set of model parameters
iter: The iteration number
functkw: The arguments to be passed to myfunct.
fnorm: The chi-squared value.
quiet: Set when no textual output should be printed.
dof: The number of degrees of freedom, normally the number of points
less the number of free parameters.
See below for documentation of parinfo.
In implementation, iterfunct can perform updates to the terminal or
graphical user interface, to provide feedback while the fit proceeds.
If the fit is to be stopped for any reason, then iterfunct should return a
a status value between -15 and -1. Otherwise it should return None
(e.g. no return statement) or 0.
In principle, iterfunct should probably not modify the parameter values,
because it may interfere with the algorithm's stability. In practice it
is allowed.
Default: an internal routine is used to print the parameter values.
Set iterfunct=None if there is no user-defined routine and you don't
want the internal default routine be called.
maxiter:
The maximum number of iterations to perform. If the number is exceeded,
then the status value is set to 5 and MPFIT returns.
Default: 200 iterations
nocovar:
Set this keyword to prevent the calculation of the covariance matrix
before returning (see COVAR)
Default: clear (=0) The covariance matrix is returned
nprint:
The frequency with which iterfunct is called. A value of 1 indicates
that iterfunct is called with every iteration, while 2 indicates every
other iteration, etc. Note that several Levenberg-Marquardt attempts
can be made in a single iteration.
Default value: 1
parinfo
Provides a mechanism for more sophisticated constraints to be placed on
parameter values. When parinfo is not passed, then it is assumed that
all parameters are free and unconstrained. Values in parinfo are never
modified during a call to MPFIT.
See description above for the structure of PARINFO.
Default value: None All parameters are free and unconstrained.
quiet:
Set this keyword when no textual output should be printed by MPFIT
damp:
A scalar number, indicating the cut-off value of residuals where
"damping" will occur. Residuals with magnitudes greater than this
number will be replaced by their hyperbolic tangent. This partially
mitigates the so-called large residual problem inherent in
least-squares solvers (as for the test problem CURVI,
http://www.maxthis.com/curviex.htm).
A value of 0 indicates no damping.
Default: 0
Note: DAMP doesn't work with autoderivative=0
xtol:
A nonnegative input variable. Termination occurs when the relative error
between two consecutive iterates is at most xtol (and status is
accordingly set to 2 or 3). Therefore, xtol measures the relative error
desired in the approximate solution.
Default: 1E-10
Outputs:
Returns an object of type mpfit. The results are attributes of this class,
e.g. mpfit.status, mpfit.errmsg, mpfit.params, npfit.niter, mpfit.covar.
.status
An integer status code is returned. All values greater than zero can
represent success (however .status == 5 may indicate failure to
converge). It can have one of the following values:
-16
A parameter or function value has become infinite or an undefined
number. This is usually a consequence of numerical overflow in the
user's model function, which must be avoided.
-15 to -1
These are error codes that either MYFUNCT or iterfunct may return to
terminate the fitting process. Values from -15 to -1 are reserved
for the user functions and will not clash with MPFIT.
0 Improper input parameters.
1 Both actual and predicted relative reductions in the sum of squares
are at most ftol.
2 Relative error between two consecutive iterates is at most xtol
3 Conditions for status = 1 and status = 2 both hold.
4 The cosine of the angle between fvec and any column of the jacobian
is at most gtol in absolute value.
5 The maximum number of iterations has been reached.
6 ftol is too small. No further reduction in the sum of squares is
possible.
7 xtol is too small. No further improvement in the approximate solution
x is possible.
8 gtol is too small. fvec is orthogonal to the columns of the jacobian
to machine precision.
.fnorm
The value of the summed squared residuals for the returned parameter
values.
.covar
The covariance matrix for the set of parameters returned by MPFIT.
The matrix is NxN where N is the number of parameters. The square root
of the diagonal elements gives the formal 1-sigma statistical errors on
the parameters if errors were treated "properly" in fcn.
Parameter errors are also returned in .perror.
To compute the correlation matrix, pcor, use this example:
cov = mpfit.covar
pcor = cov * 0.
for i in range(n):
for j in range(n):
pcor[i,j] = cov[i,j]/sqrt(cov[i,i]*cov[j,j])
If nocovar is set or MPFIT terminated abnormally, then .covar is set to
a scalar with value None.
.errmsg
A string error or warning message is returned.
.nfev
The number of calls to MYFUNCT performed.
.niter
The number of iterations completed.
.perror
The formal 1-sigma errors in each parameter, computed from the
covariance matrix. If a parameter is held fixed, or if it touches a
boundary, then the error is reported as zero.
If the fit is unweighted (i.e. no errors were given, or the weights
were uniformly set to unity), then .perror will probably not represent
the true parameter uncertainties.
*If* you can assume that the true reduced chi-squared value is unity --
meaning that the fit is implicitly assumed to be of good quality --
then the estimated parameter uncertainties can be computed by scaling
.perror by the measured chi-squared value.
dof = len(x) - len(mpfit.params) # deg of freedom
# scaled uncertainties
pcerror = mpfit.perror * sqrt(mpfit.fnorm / dof)
"""
self.niter = 0
self.params = None
self.covar = None
self.perror = None
self.status = 0 # Invalid input flag set while we check inputs
self.debug = debug
self.errmsg = ''
self.nfev = 0
self.damp = damp
self.dof=0
if fcn==None:
self.errmsg = "Usage: parms = mpfit('myfunt', ... )"
return
if iterfunct == 'default':
iterfunct = self.defiter
# Parameter damping doesn't work when user is providing their own
# gradients.
if (self.damp != 0) and (autoderivative == 0):
self.errmsg = 'ERROR: keywords DAMP and AUTODERIVATIVE are mutually exclusive'
return
# Parameters can either be stored in parinfo, or x. x takes precedence if it exists
if (xall is None) and (parinfo is None):
self.errmsg = 'ERROR: must pass parameters in P or PARINFO'
return
# Be sure that PARINFO is of the right type
if parinfo is not None:
if type(parinfo) != types.ListType:
self.errmsg = 'ERROR: PARINFO must be a list of dictionaries.'
return
else:
if type(parinfo[0]) != types.DictionaryType:
self.errmsg = 'ERROR: PARINFO must be a list of dictionaries.'
return
if ((xall is not None) and (len(xall) != len(parinfo))):
self.errmsg = 'ERROR: number of elements in PARINFO and P must agree'
return
# If the parameters were not specified at the command line, then
# extract them from PARINFO
if xall is None:
xall = self.parinfo(parinfo, 'value')
if xall is None:
self.errmsg = 'ERROR: either P or PARINFO(*)["value"] must be supplied.'
return
# Make sure parameters are numpy arrays
xall = numpy.asarray(xall)
# In the case if the xall is not float or if is float but has less
# than 64 bits we do convert it into double
if xall.dtype.kind != 'f' or xall.dtype.itemsize<=4:
xall = xall.astype(numpy.float)
npar = len(xall)
self.fnorm = -1.
fnorm1 = -1.
# TIED parameters?
ptied = self.parinfo(parinfo, 'tied', default='', n=npar)
self.qanytied = 0
for i in range(npar):
ptied[i] = ptied[i].strip()
if ptied[i] != '':
self.qanytied = 1
self.ptied = ptied
# FIXED parameters ?
pfixed = self.parinfo(parinfo, 'fixed', default=0, n=npar)
pfixed = (pfixed == 1)
for i in range(npar):
pfixed[i] = pfixed[i] or (ptied[i] != '') # Tied parameters are also effectively fixed
# Finite differencing step, absolute and relative, and sidedness of deriv.
step = self.parinfo(parinfo, 'step', default=0., n=npar)
dstep = self.parinfo(parinfo, 'relstep', default=0., n=npar)
dside = self.parinfo(parinfo, 'mpside', default=0, n=npar)
# Maximum and minimum steps allowed to be taken in one iteration
maxstep = self.parinfo(parinfo, 'mpmaxstep', default=0., n=npar)
minstep = self.parinfo(parinfo, 'mpminstep', default=0., n=npar)
qmin = minstep != 0
qmin[:] = False # Remove minstep for now!!
qmax = maxstep != 0
if numpy.any(qmin & qmax & (maxstep<minstep)):
self.errmsg = 'ERROR: MPMINSTEP is greater than MPMAXSTEP'
return
wh = (numpy.nonzero((qmin!=0.) | (qmax!=0.)))[0]
qminmax = len(wh > 0)
# Finish up the free parameters
ifree = (numpy.nonzero(pfixed != 1))[0]
nfree = len(ifree)
if nfree == 0:
self.errmsg = 'ERROR: no free parameters'
return
# Compose only VARYING parameters
self.params = xall.copy() # self.params is the set of parameters to be returned
x = self.params[ifree] # x is the set of free parameters
# LIMITED parameters ?
limited = self.parinfo(parinfo, 'limited', default=[0,0], n=npar)
limits = self.parinfo(parinfo, 'limits', default=[0.,0.], n=npar)
if (limited is not None) and (limits is not None):
# Error checking on limits in parinfo
if numpy.any((limited[:,0] & (xall < limits[:,0])) |
(limited[:,1] & (xall > limits[:,1]))):
self.errmsg = 'ERROR: parameters are not within PARINFO limits'
return
if numpy.any((limited[:,0] & limited[:,1]) &
(limits[:,0] >= limits[:,1]) &
(pfixed == 0)):
self.errmsg = 'ERROR: PARINFO parameter limits are not consistent'
return
# Transfer structure values to local variables
qulim = (limited[:,1])[ifree]
ulim = (limits [:,1])[ifree]
qllim = (limited[:,0])[ifree]
llim = (limits [:,0])[ifree]
if numpy.any((qulim!=0.) | (qllim!=0.)):
qanylim = 1
else:
qanylim = 0
else:
# Fill in local variables with dummy values
qulim = numpy.zeros(nfree)
ulim = x * 0.
qllim = qulim
llim = x * 0.
qanylim = 0
n = len(x)
# Check input parameters for errors
if (n < 0) or (ftol <= 0) or (xtol <= 0) or (gtol <= 0) \
or (maxiter < 0) or (factor <= 0):
self.errmsg = 'ERROR: input keywords are inconsistent'
return
if rescale != 0:
self.errmsg = 'ERROR: DIAG parameter scales are inconsistent'
if len(diag) < n:
return
if numpy.any(diag <= 0):
return
self.errmsg = ''
[self.status, fvec] = self.call(fcn, self.params, functkw)
if self.status < 0:
self.errmsg = 'ERROR: first call to "'+str(fcn)+'" failed'
return
# If the returned fvec has more than four bits I assume that we have
# double precision
# It is important that the machar is determined by the precision of
# the returned value, not by the precision of the input array
if numpy.array([fvec]).dtype.itemsize>4:
self.machar = machar(double=1)
self.blas_enorm = mpfit.blas_enorm64
else:
self.machar = machar(double=0)
self.blas_enorm = mpfit.blas_enorm32
machep = self.machar.machep
m = len(fvec)
if m < n:
self.errmsg = 'ERROR: number of parameters must not exceed data'
return
self.dof = m-nfree
self.fnorm = self.enorm(fvec)
# Initialize Levelberg-Marquardt parameter and iteration counter
par = 0.
self.niter = 1
qtf = x * 0.
self.status = 0
# Beginning of the outer loop
while(1):
# If requested, call fcn to enable printing of iterates
self.params[ifree] = x
if self.qanytied:
self.params = self.tie(self.params, ptied)
if (nprint > 0) and (iterfunct is not None):
if ((self.niter-1) % nprint) == 0:
mperr = 0
xnew0 = self.params.copy()
dof = numpy.max([len(fvec) - len(x), 0])
status = iterfunct(fcn, self.params, self.niter, self.fnorm**2,
functkw=functkw, parinfo=parinfo, quiet=quiet,
dof=dof, **iterkw)
if status is not None:
self.status = status
# Check for user termination
if self.status < 0:
self.errmsg = 'WARNING: premature termination by ' + str(iterfunct)
return
# If parameters were changed (grrr..) then re-tie
if numpy.max(numpy.abs(xnew0-self.params)) > 0:
if self.qanytied:
self.params = self.tie(self.params, ptied)
x = self.params[ifree]
# Calculate the jacobian matrix
self.status = 2
catch_msg = 'calling MPFIT_FDJAC2'
fjac = self.fdjac2(fcn, x, fvec, step, qulim, ulim, dside,
epsfcn=epsfcn,
autoderivative=autoderivative, dstep=dstep,
functkw=functkw, ifree=ifree, xall=self.params)
if fjac is None:
self.errmsg = 'WARNING: premature termination by FDJAC2'
return
# Determine if any of the parameters are pegged at the limits
if qanylim:
catch_msg = 'zeroing derivatives of pegged parameters'
whlpeg = (numpy.nonzero(qllim & (x == llim)))[0]
nlpeg = len(whlpeg)
whupeg = (numpy.nonzero(qulim & (x == ulim)))[0]
nupeg = len(whupeg)
# See if any "pegged" values should keep their derivatives
if nlpeg > 0:
# Total derivative of sum wrt lower pegged parameters
for i in range(nlpeg):
sum0 = sum(fvec * fjac[:,whlpeg[i]])
if sum0 > 0:
fjac[:,whlpeg[i]] = 0
if nupeg > 0:
# Total derivative of sum wrt upper pegged parameters
for i in range(nupeg):
sum0 = sum(fvec * fjac[:,whupeg[i]])
if sum0 < 0:
fjac[:,whupeg[i]] = 0
# Compute the QR factorization of the jacobian
[fjac, ipvt, wa1, wa2] = self.qrfac(fjac, pivot=1)
# On the first iteration if "diag" is unspecified, scale
# according to the norms of the columns of the initial jacobian
catch_msg = 'rescaling diagonal elements'
if self.niter == 1:
if (rescale==0) or (len(diag) < n):
diag = wa2.copy()
diag[diag == 0] = 1.
# On the first iteration, calculate the norm of the scaled x
# and initialize the step bound delta
wa3 = diag * x
xnorm = self.enorm(wa3)
delta = factor*xnorm
if delta == 0.:
delta = factor
# Form (q transpose)*fvec and store the first n components in qtf
catch_msg = 'forming (q transpose)*fvec'
wa4 = fvec.copy()
for j in range(n):
lj = ipvt[j]
temp3 = fjac[j,lj]
if temp3 != 0:
fj = fjac[j:,lj]
wj = wa4[j:]
# *** optimization wa4(j:*)
wa4[j:] = wj - fj * sum(fj*wj) / temp3
fjac[j,lj] = wa1[j]
qtf[j] = wa4[j]
# From this point on, only the square matrix, consisting of the
# triangle of R, is needed.
fjac = fjac[0:n, 0:n]
fjac.shape = [n, n]
temp = fjac.copy()
for i in range(n):
temp[:,i] = fjac[:, ipvt[i]]
fjac = temp.copy()
# Check for overflow. This should be a cheap test here since FJAC
# has been reduced to a (small) square matrix, and the test is
# O(N^2).
#wh = where(finite(fjac) EQ 0, ct)
#if ct GT 0 then goto, FAIL_OVERFLOW
# Compute the norm of the scaled gradient
catch_msg = 'computing the scaled gradient'
gnorm = 0.
if self.fnorm != 0:
for j in range(n):
l = ipvt[j]
if wa2[l] != 0:
sum0 = sum(fjac[0:j+1,j]*qtf[0:j+1])/self.fnorm
gnorm = numpy.max([gnorm,numpy.abs(sum0/wa2[l])])
# Test for convergence of the gradient norm
if gnorm <= gtol:
self.status = 4
break
if maxiter == 0:
self.status = 5
break
# Rescale if necessary
if rescale == 0:
diag = numpy.choose(diag>wa2, (wa2, diag))
# Beginning of the inner loop
while(1):
# Determine the levenberg-marquardt parameter
catch_msg = 'calculating LM parameter (MPFIT_)'
[fjac, par, wa1, wa2] = self.lmpar(fjac, ipvt, diag, qtf,
delta, wa1, wa2, par=par)
# Store the direction p and x+p. Calculate the norm of p
wa1 = -wa1
if (qanylim == 0) and (qminmax == 0):
# No parameter limits, so just move to new position WA2
alpha = 1.
wa2 = x + wa1
else:
# Respect the limits. If a step were to go out of bounds, then
# we should take a step in the same direction but shorter distance.
# The step should take us right to the limit in that case.
alpha = 1.
if qanylim:
# Do not allow any steps out of bounds
catch_msg = 'checking for a step out of bounds'
if nlpeg > 0:
wa1[whlpeg] = numpy.clip( wa1[whlpeg], 0., numpy.max(wa1))
if nupeg > 0:
wa1[whupeg] = numpy.clip(wa1[whupeg], numpy.min(wa1), 0.)
dwa1 = numpy.abs(wa1) > machep
whl = (numpy.nonzero(((dwa1!=0.) & qllim) & ((x + wa1) < llim)))[0]
if len(whl) > 0:
t = ((llim[whl] - x[whl]) /
wa1[whl])
alpha = numpy.min([alpha, numpy.min(t)])
whu = (numpy.nonzero(((dwa1!=0.) & qulim) & ((x + wa1) > ulim)))[0]
if len(whu) > 0:
t = ((ulim[whu] - x[whu]) /
wa1[whu])
alpha = numpy.min([alpha, numpy.min(t)])
# Obey any max step values.
if qminmax:
nwa1 = wa1 * alpha
whmax = (numpy.nonzero((qmax != 0.) & (maxstep > 0)))[0]
if len(whmax) > 0:
mrat = numpy.max(numpy.abs(nwa1[whmax]) /
numpy.abs(maxstep[ifree[whmax]]))
if mrat > 1:
alpha = alpha / mrat
# Scale the resulting vector
wa1 = wa1 * alpha
wa2 = x + wa1
# Adjust the final output values. If the step put us exactly
# on a boundary, make sure it is exact.
sgnu = (ulim >= 0) * 2. - 1.
sgnl = (llim >= 0) * 2. - 1.
# Handles case of
# ... nonzero *LIM ... ...zero * LIM
ulim1 = ulim * (1 - sgnu * machep) - (ulim == 0) * machep
llim1 = llim * (1 + sgnl * machep) + (llim == 0) * machep
wh = (numpy.nonzero((qulim!=0) & (wa2 >= ulim1)))[0]
if len(wh) > 0:
wa2[wh] = ulim[wh]
wh = (numpy.nonzero((qllim!=0.) & (wa2 <= llim1)))[0]
if len(wh) > 0:
wa2[wh] = llim[wh]
# endelse
wa3 = diag * wa1
pnorm = self.enorm(wa3)
# On the first iteration, adjust the initial step bound
if self.niter == 1:
delta = numpy.min([delta,pnorm])
self.params[ifree] = wa2
# Evaluate the function at x+p and calculate its norm
mperr = 0
catch_msg = 'calling '+str(fcn)
[self.status, wa4] = self.call(fcn, self.params, functkw)
if self.status < 0:
self.errmsg = 'WARNING: premature termination by "'+fcn+'"'
return
fnorm1 = self.enorm(wa4)
# Compute the scaled actual reduction
catch_msg = 'computing convergence criteria'
actred = -1.
if (0.1 * fnorm1) < self.fnorm:
actred = - (fnorm1/self.fnorm)**2 + 1.
# Compute the scaled predicted reduction and the scaled directional
# derivative
for j in range(n):
wa3[j] = 0
wa3[0:j+1] = wa3[0:j+1] + fjac[0:j+1,j]*wa1[ipvt[j]]
# Remember, alpha is the fraction of the full LM step actually
# taken
temp1 = self.enorm(alpha*wa3)/self.fnorm
temp2 = (numpy.sqrt(alpha*par)*pnorm)/self.fnorm
prered = temp1*temp1 + (temp2*temp2)/0.5
dirder = -(temp1*temp1 + temp2*temp2)
# Compute the ratio of the actual to the predicted reduction.
ratio = 0.
if prered != 0:
ratio = actred/prered
# Update the step bound
if ratio <= 0.25:
if actred >= 0:
temp = .5
else:
temp = .5*dirder/(dirder + .5*actred)
if ((0.1*fnorm1) >= self.fnorm) or (temp < 0.1):
temp = 0.1
delta = temp*numpy.min([delta,pnorm/0.1])
par = par/temp
else:
if (par == 0) or (ratio >= 0.75):
delta = pnorm/.5
par = .5*par
# Test for successful iteration
if ratio >= 0.0001:
# Successful iteration. Update x, fvec, and their norms
x = wa2
wa2 = diag * x
fvec = wa4
xnorm = self.enorm(wa2)
self.fnorm = fnorm1
self.niter = self.niter + 1
# Tests for convergence
if (numpy.abs(actred) <= ftol) and (prered <= ftol) \
and (0.5 * ratio <= 1):
self.status = 1
if delta <= xtol*xnorm:
self.status = 2
if (numpy.abs(actred) <= ftol) and (prered <= ftol) \
and (0.5 * ratio <= 1) and (self.status == 2):
self.status = 3
if self.status != 0:
break
# Tests for termination and stringent tolerances
if self.niter >= maxiter:
self.status = 5
if (numpy.abs(actred) <= machep) and (prered <= machep) \
and (0.5*ratio <= 1):
self.status = 6
if delta <= machep*xnorm:
self.status = 7
if gnorm <= machep:
self.status = 8
if self.status != 0:
break
# End of inner loop. Repeat if iteration unsuccessful
if ratio >= 0.0001:
break
# Check for over/underflow
if ~numpy.all(numpy.isfinite(wa1) & numpy.isfinite(wa2) & \
numpy.isfinite(x)) or ~numpy.isfinite(ratio):
errmsg = ('''ERROR: parameter or function value(s) have become
'infinite; check model function for over- 'and underflow''')
self.status = -16
break
#wh = where(finite(wa1) EQ 0 OR finite(wa2) EQ 0 OR finite(x) EQ 0, ct)
#if ct GT 0 OR finite(ratio) EQ 0 then begin
if self.status != 0:
break;
# End of outer loop.
catch_msg = 'in the termination phase'
# Termination, either normal or user imposed.
if len(self.params) == 0:
return
if nfree == 0:
self.params = xall.copy()
else:
self.params[ifree] = x
if (nprint > 0) and (self.status > 0):
catch_msg = 'calling ' + str(fcn)
[status, fvec] = self.call(fcn, self.params, functkw)
catch_msg = 'in the termination phase'
self.fnorm = self.enorm(fvec)
if (self.fnorm is not None) and (fnorm1 is not None):
self.fnorm = numpy.max([self.fnorm, fnorm1])
self.fnorm = self.fnorm**2.
self.covar = None
self.perror = None
# (very carefully) set the covariance matrix COVAR
if (self.status > 0) and (nocovar==0) and (n is not None) \
and (fjac is not None) and (ipvt is not None):
sz = fjac.shape
if (n > 0) and (sz[0] >= n) and (sz[1] >= n) \
and (len(ipvt) >= n):
catch_msg = 'computing the covariance matrix'
cv = self.calc_covar(fjac[0:n,0:n], ipvt[0:n])
cv.shape = [n, n]
nn = len(xall)
# Fill in actual covariance matrix, accounting for fixed
# parameters.
self.covar = numpy.zeros([nn, nn], dtype=float)
for i in range(n):
self.covar[ifree,ifree[i]] = cv[:,i]
# Compute errors in parameters
catch_msg = 'computing parameter errors'
self.perror = numpy.zeros(nn, dtype=float)
d = numpy.diagonal(self.covar)
wh = (numpy.nonzero(d >= 0))[0]
if len(wh) > 0:
self.perror[wh] = numpy.sqrt(d[wh])
return
def __str__(self):
return {'params': self.params,
'niter': self.niter,
'params': self.params,
'covar': self.covar,
'perror': self.perror,
'status': self.status,
'debug': self.debug,
'errmsg': self.errmsg,
'nfev': self.nfev,
'damp': self.damp
#,'machar':self.machar
}.__str__()
# Default procedure to be called every iteration. It simply prints
# the parameter values.
def defiter(self, fcn, x, iter, fnorm=None, functkw=None,
quiet=0, iterstop=None, parinfo=None,
format=None, pformat='%.10g', dof=1):
if self.debug:
print 'Entering defiter...'
if quiet:
return
if fnorm is None:
[status, fvec] = self.call(fcn, x, functkw)
fnorm = self.enorm(fvec)**2
# Determine which parameters to print
nprint = len(x)
print "Iter ", ('%6i' % iter)," CHI-SQUARE = ",('%.10g' % fnorm)," DOF = ", ('%i' % dof)
for i in range(nprint):
if (parinfo is not None) and (parinfo[i].has_key('parname')):
p = ' ' + parinfo[i]['parname'] + ' = '
else:
p = ' P' + str(i) + ' = '
if (parinfo is not None) and (parinfo[i].has_key('mpprint')):
iprint = parinfo[i]['mpprint']
else:
iprint = 1
if iprint:
print p + (pformat % x[i]) + ' '
return 0
# DO_ITERSTOP:
# if keyword_set(iterstop) then begin
# k = get_kbrd(0)
# if k EQ string(byte(7)) then begin
# message, 'WARNING: minimization not complete', /info
# print, 'Do you want to terminate this procedure? (y/n)', $
# format='(A,$)'
# k = ''
# read, k
# if strupcase(strmid(k,0,1)) EQ 'Y' then begin
# message, 'WARNING: Procedure is terminating.', /info
# mperr = -1
# endif
# endif
# endif
# Procedure to parse the parameter values in PARINFO, which is a list of dictionaries
def parinfo(self, parinfo=None, key='a', default=None, n=0):
if self.debug:
print 'Entering parinfo...'
if (n == 0) and (parinfo is not None):
n = len(parinfo)
if n == 0:
values = default
return values
values = []
for i in range(n):
if (parinfo is not None) and (parinfo[i].has_key(key)):
values.append(parinfo[i][key])
else:
values.append(default)
# Convert to numeric arrays if possible
test = default
if type(default) == types.ListType:
test=default[0]
if isinstance(test, types.IntType):
values = numpy.asarray(values, int)
elif isinstance(test, types.FloatType):
values = numpy.asarray(values, float)
return values
# Call user function or procedure, with _EXTRA or not, with
# derivatives or not.
def call(self, fcn, x, functkw, fjac=None):
if self.debug:
print 'Entering call...'
if self.qanytied:
x = self.tie(x, self.ptied)
self.nfev = self.nfev + 1
if fjac is None:
[status, f] = fcn(x, fjac=fjac, **functkw)
if self.damp > 0:
# Apply the damping if requested. This replaces the residuals
# with their hyperbolic tangent. Thus residuals larger than
# DAMP are essentially clipped.
f = numpy.tanh(f/self.damp)
return [status, f]
else:
return fcn(x, fjac=fjac, **functkw)
def enorm(self, vec):
ans = self.blas_enorm(vec)
return ans
def fdjac2(self, fcn, x, fvec, step=None, ulimited=None, ulimit=None, dside=None,
epsfcn=None, autoderivative=1,
functkw=None, xall=None, ifree=None, dstep=None):
if self.debug:
print 'Entering fdjac2...'
machep = self.machar.machep
if epsfcn is None:
epsfcn = machep
if xall is None:
xall = x
if ifree is None:
ifree = numpy.arange(len(xall))
if step is None:
step = x * 0.
nall = len(xall)
eps = numpy.sqrt(numpy.max([epsfcn, machep]))
m = len(fvec)
n = len(x)
# Compute analytical derivative if requested
if autoderivative == 0:
mperr = 0
fjac = numpy.zeros(nall, dtype=float)
fjac[ifree] = 1.0 # Specify which parameters need derivatives
[status, fp] = self.call(fcn, xall, functkw, fjac=fjac)
if len(fjac) != m*nall:
print 'ERROR: Derivative matrix was not computed properly.'
return None
# This definition is consistent with CURVEFIT
# Sign error found (thanks Jesus Fernandez <[email protected]>)
fjac.shape = [m,nall]
fjac = -fjac
# Select only the free parameters
if len(ifree) < nall:
fjac = fjac[:,ifree]
fjac.shape = [m, n]
return fjac
fjac = numpy.zeros([m, n], dtype=float)
h = eps * numpy.abs(x)
# if STEP is given, use that
# STEP includes the fixed parameters
if step is not None:
stepi = step[ifree]
wh = (numpy.nonzero(stepi > 0))[0]
if len(wh) > 0:
h[wh] = stepi[wh]
# if relative step is given, use that
# DSTEP includes the fixed parameters
if len(dstep) > 0:
dstepi = dstep[ifree]
wh = (numpy.nonzero(dstepi > 0))[0]
if len(wh) > 0:
h[wh] = numpy.abs(dstepi[wh]*x[wh])
# In case any of the step values are zero
h[h == 0] = eps
# Reverse the sign of the step if we are up against the parameter
# limit, or if the user requested it.
# DSIDE includes the fixed parameters (ULIMITED/ULIMIT have only
# varying ones)
mask = dside[ifree] == -1
if len(ulimited) > 0 and len(ulimit) > 0:
mask = (mask | ((ulimited!=0) & (x > ulimit-h)))
wh = (numpy.nonzero(mask))[0]
if len(wh) > 0:
h[wh] = - h[wh]
# Loop through parameters, computing the derivative for each
for j in range(n):
xp = xall.copy()
xp[ifree[j]] = xp[ifree[j]] + h[j]
[status, fp] = self.call(fcn, xp, functkw)
if status < 0:
return None
if numpy.abs(dside[ifree[j]]) <= 1:
# COMPUTE THE ONE-SIDED DERIVATIVE
# Note optimization fjac(0:*,j)
fjac[0:,j] = (fp-fvec)/h[j]
else:
# COMPUTE THE TWO-SIDED DERIVATIVE
xp[ifree[j]] = xall[ifree[j]] - h[j]
mperr = 0
[status, fm] = self.call(fcn, xp, functkw)
if status < 0:
return None
# Note optimization fjac(0:*,j)
fjac[0:,j] = (fp-fm)/(2*h[j])
return fjac
# Original FORTRAN documentation
# **********
#
# subroutine qrfac
#
# this subroutine uses householder transformations with column
# pivoting (optional) to compute a qr factorization of the
# m by n matrix a. that is, qrfac determines an orthogonal
# matrix q, a permutation matrix p, and an upper trapezoidal
# matrix r with diagonal elements of nonincreasing magnitude,
# such that a*p = q*r. the householder transformation for
# column k, k = 1,2,...,min(m,n), is of the form
#
# t
# i - (1/u(k))*u*u
#
# where u has zeros in the first k-1 positions. the form of
# this transformation and the method of pivoting first
# appeared in the corresponding linpack subroutine.
#
# the subroutine statement is
#
# subroutine qrfac(m,n,a,lda,pivot,ipvt,lipvt,rdiag,acnorm,wa)
#
# where
#
# m is a positive integer input variable set to the number
# of rows of a.
#
# n is a positive integer input variable set to the number
# of columns of a.
#
# a is an m by n array. on input a contains the matrix for
# which the qr factorization is to be computed. on output
# the strict upper trapezoidal part of a contains the strict
# upper trapezoidal part of r, and the lower trapezoidal
# part of a contains a factored form of q (the non-trivial
# elements of the u vectors described above).
#
# lda is a positive integer input variable not less than m
# which specifies the leading dimension of the array a.
#
# pivot is a logical input variable. if pivot is set true,
# then column pivoting is enforced. if pivot is set false,
# then no column pivoting is done.
#
# ipvt is an integer output array of length lipvt. ipvt
# defines the permutation matrix p such that a*p = q*r.
# column j of p is column ipvt(j) of the identity matrix.
# if pivot is false, ipvt is not referenced.
#
# lipvt is a positive integer input variable. if pivot is false,
# then lipvt may be as small as 1. if pivot is true, then
# lipvt must be at least n.
#
# rdiag is an output array of length n which contains the
# diagonal elements of r.
#
# acnorm is an output array of length n which contains the
# norms of the corresponding columns of the input matrix a.
# if this information is not needed, then acnorm can coincide
# with rdiag.
#
# wa is a work array of length n. if pivot is false, then wa
# can coincide with rdiag.
#
# subprograms called
#
# minpack-supplied ... dpmpar,enorm
#
# fortran-supplied ... dmax1,dsqrt,min0
#
# argonne national laboratory. minpack project. march 1980.
# burton s. garbow, kenneth e. hillstrom, jorge j. more
#
# **********
#
# PIVOTING / PERMUTING:
#
# Upon return, A(*,*) is in standard parameter order, A(*,IPVT) is in
# permuted order.
#
# RDIAG is in permuted order.
# ACNORM is in standard parameter order.
#
#
# NOTE: in IDL the factors appear slightly differently than described
# above. The matrix A is still m x n where m >= n.
#
# The "upper" triangular matrix R is actually stored in the strict
# lower left triangle of A under the standard notation of IDL.
#
# The reflectors that generate Q are in the upper trapezoid of A upon
# output.
#
# EXAMPLE: decompose the matrix [[9.,2.,6.],[4.,8.,7.]]
# aa = [[9.,2.,6.],[4.,8.,7.]]
# mpfit_qrfac, aa, aapvt, rdiag, aanorm
# IDL> print, aa
# 1.81818* 0.181818* 0.545455*
# -8.54545+ 1.90160* 0.432573*
# IDL> print, rdiag
# -11.0000+ -7.48166+
#
# The components marked with a * are the components of the
# reflectors, and those marked with a + are components of R.
#
# To reconstruct Q and R we proceed as follows. First R.
# r = fltarr(m, n)
# for i = 0, n-1 do r(0:i,i) = aa(0:i,i) # fill in lower diag
# r(lindgen(n)*(m+1)) = rdiag
#
# Next, Q, which are composed from the reflectors. Each reflector v
# is taken from the upper trapezoid of aa, and converted to a matrix
# via (I - 2 vT . v / (v . vT)).
#
# hh = ident # identity matrix
# for i = 0, n-1 do begin
# v = aa(*,i) & if i GT 0 then v(0:i-1) = 0 # extract reflector
# hh = hh # (ident - 2*(v # v)/total(v * v)) # generate matrix
# endfor
#
# Test the result:
# IDL> print, hh # transpose(r)
# 9.00000 4.00000
# 2.00000 8.00000
# 6.00000 7.00000
#
# Note that it is usually never necessary to form the Q matrix
# explicitly, and MPFIT does not.
def qrfac(self, a, pivot=0):
if self.debug: print 'Entering qrfac...'
machep = self.machar.machep
sz = a.shape
m = sz[0]
n = sz[1]
# Compute the initial column norms and initialize arrays
acnorm = numpy.zeros(n, dtype=float)
for j in range(n):
acnorm[j] = self.enorm(a[:,j])
rdiag = acnorm.copy()
wa = rdiag.copy()
ipvt = numpy.arange(n)
# Reduce a to r with householder transformations
minmn = numpy.min([m,n])
for j in range(minmn):
if pivot != 0:
# Bring the column of largest norm into the pivot position
rmax = numpy.max(rdiag[j:])
kmax = (numpy.nonzero(rdiag[j:] == rmax))[0]
ct = len(kmax)
kmax = kmax + j
if ct > 0:
kmax = kmax[0]
# Exchange rows via the pivot only. Avoid actually exchanging
# the rows, in case there is lots of memory transfer. The
# exchange occurs later, within the body of MPFIT, after the
# extraneous columns of the matrix have been shed.
if kmax != j:
temp = ipvt[j] ; ipvt[j] = ipvt[kmax] ; ipvt[kmax] = temp
rdiag[kmax] = rdiag[j]
wa[kmax] = wa[j]
# Compute the householder transformation to reduce the jth
# column of A to a multiple of the jth unit vector
lj = ipvt[j]
ajj = a[j:,lj]
ajnorm = self.enorm(ajj)
if ajnorm == 0:
break
if a[j,lj] < 0:
ajnorm = -ajnorm
ajj = ajj / ajnorm
ajj[0] = ajj[0] + 1
# *** Note optimization a(j:*,j)
a[j:,lj] = ajj
# Apply the transformation to the remaining columns
# and update the norms
# NOTE to SELF: tried to optimize this by removing the loop,
# but it actually got slower. Reverted to "for" loop to keep
# it simple.
if j+1 < n:
for k in range(j+1, n):
lk = ipvt[k]
ajk = a[j:,lk]
# *** Note optimization a(j:*,lk)
# (corrected 20 Jul 2000)
if a[j,lj] != 0:
a[j:,lk] = ajk - ajj * sum(ajk*ajj)/a[j,lj]
if (pivot != 0) and (rdiag[k] != 0):
temp = a[j,lk]/rdiag[k]
rdiag[k] = rdiag[k] * numpy.sqrt(numpy.max([(1.-temp**2), 0.]))
temp = rdiag[k]/wa[k]
if (0.05*temp*temp) <= machep:
rdiag[k] = self.enorm(a[j+1:,lk])
wa[k] = rdiag[k]
rdiag[j] = -ajnorm
return [a, ipvt, rdiag, acnorm]
# Original FORTRAN documentation
# **********
#
# subroutine qrsolv
#
# given an m by n matrix a, an n by n diagonal matrix d,
# and an m-vector b, the problem is to determine an x which
# solves the system
#
# a*x = b , d*x = 0 ,
#
# in the least squares sense.
#
# this subroutine completes the solution of the problem
# if it is provided with the necessary information from the
# factorization, with column pivoting, of a. that is, if
# a*p = q*r, where p is a permutation matrix, q has orthogonal
# columns, and r is an upper triangular matrix with diagonal
# elements of nonincreasing magnitude, then qrsolv expects
# the full upper triangle of r, the permutation matrix p,
# and the first n components of (q transpose)*b. the system
# a*x = b, d*x = 0, is then equivalent to
#
# t t
# r*z = q *b , p *d*p*z = 0 ,
#
# where x = p*z. if this system does not have full rank,
# then a least squares solution is obtained. on output qrsolv
# also provides an upper triangular matrix s such that
#
# t t t
# p *(a *a + d*d)*p = s *s .
#
# s is computed within qrsolv and may be of separate interest.
#
# the subroutine statement is
#
# subroutine qrsolv(n,r,ldr,ipvt,diag,qtb,x,sdiag,wa)
#
# where
#
# n is a positive integer input variable set to the order of r.
#
# r is an n by n array. on input the full upper triangle
# must contain the full upper triangle of the matrix r.
# on output the full upper triangle is unaltered, and the
# strict lower triangle contains the strict upper triangle
# (transposed) of the upper triangular matrix s.
#
# ldr is a positive integer input variable not less than n
# which specifies the leading dimension of the array r.
#
# ipvt is an integer input array of length n which defines the
# permutation matrix p such that a*p = q*r. column j of p
# is column ipvt(j) of the identity matrix.
#
# diag is an input array of length n which must contain the
# diagonal elements of the matrix d.
#
# qtb is an input array of length n which must contain the first
# n elements of the vector (q transpose)*b.
#
# x is an output array of length n which contains the least
# squares solution of the system a*x = b, d*x = 0.
#
# sdiag is an output array of length n which contains the
# diagonal elements of the upper triangular matrix s.
#
# wa is a work array of length n.
#
# subprograms called
#
# fortran-supplied ... dabs,dsqrt
#
# argonne national laboratory. minpack project. march 1980.
# burton s. garbow, kenneth e. hillstrom, jorge j. more
#
def qrsolv(self, r, ipvt, diag, qtb, sdiag):
if self.debug:
print 'Entering qrsolv...'
sz = r.shape
m = sz[0]
n = sz[1]
# copy r and (q transpose)*b to preserve input and initialize s.
# in particular, save the diagonal elements of r in x.
for j in range(n):
r[j:n,j] = r[j,j:n]
x = numpy.diagonal(r).copy()
wa = qtb.copy()
# Eliminate the diagonal matrix d using a givens rotation
for j in range(n):
l = ipvt[j]
if diag[l] == 0:
break
sdiag[j:] = 0
sdiag[j] = diag[l]
# The transformations to eliminate the row of d modify only a
# single element of (q transpose)*b beyond the first n, which
# is initially zero.
qtbpj = 0.
for k in range(j,n):
if sdiag[k] == 0:
break
if numpy.abs(r[k,k]) < numpy.abs(sdiag[k]):
cotan = r[k,k]/sdiag[k]
sine = 0.5/numpy.sqrt(.25 + .25*cotan*cotan)
cosine = sine*cotan
else:
tang = sdiag[k]/r[k,k]
cosine = 0.5/numpy.sqrt(.25 + .25*tang*tang)
sine = cosine*tang
# Compute the modified diagonal element of r and the
# modified element of ((q transpose)*b,0).
r[k,k] = cosine*r[k,k] + sine*sdiag[k]
temp = cosine*wa[k] + sine*qtbpj
qtbpj = -sine*wa[k] + cosine*qtbpj
wa[k] = temp
# Accumulate the transformation in the row of s
if n > k+1:
temp = cosine*r[k+1:n,k] + sine*sdiag[k+1:n]
sdiag[k+1:n] = -sine*r[k+1:n,k] + cosine*sdiag[k+1:n]
r[k+1:n,k] = temp
sdiag[j] = r[j,j]
r[j,j] = x[j]
# Solve the triangular system for z. If the system is singular
# then obtain a least squares solution
nsing = n
wh = (numpy.nonzero(sdiag == 0))[0]
if len(wh) > 0:
nsing = wh[0]
wa[nsing:] = 0
if nsing >= 1:
wa[nsing-1] = wa[nsing-1]/sdiag[nsing-1] # Degenerate case
# *** Reverse loop ***
for j in range(nsing-2,-1,-1):
sum0 = sum(r[j+1:nsing,j]*wa[j+1:nsing])
wa[j] = (wa[j]-sum0)/sdiag[j]
# Permute the components of z back to components of x
x[ipvt] = wa
return (r, x, sdiag)
# Original FORTRAN documentation
#
# subroutine lmpar
#
# given an m by n matrix a, an n by n nonsingular diagonal
# matrix d, an m-vector b, and a positive number delta,
# the problem is to determine a value for the parameter
# par such that if x solves the system
#
# a*x = b , sqrt(par)*d*x = 0 ,
#
# in the least squares sense, and dxnorm is the euclidean
# norm of d*x, then either par is zero and
#
# (dxnorm-delta) .le. 0.1*delta ,
#
# or par is positive and
#
# abs(dxnorm-delta) .le. 0.1*delta .
#
# this subroutine completes the solution of the problem
# if it is provided with the necessary information from the
# qr factorization, with column pivoting, of a. that is, if
# a*p = q*r, where p is a permutation matrix, q has orthogonal
# columns, and r is an upper triangular matrix with diagonal
# elements of nonincreasing magnitude, then lmpar expects
# the full upper triangle of r, the permutation matrix p,
# and the first n components of (q transpose)*b. on output
# lmpar also provides an upper triangular matrix s such that
#
# t t t
# p *(a *a + par*d*d)*p = s *s .
#
# s is employed within lmpar and may be of separate interest.
#
# only a few iterations are generally needed for convergence
# of the algorithm. if, however, the limit of 10 iterations
# is reached, then the output par will contain the best
# value obtained so far.
#
# the subroutine statement is
#
# subroutine lmpar(n,r,ldr,ipvt,diag,qtb,delta,par,x,sdiag,
# wa1,wa2)
#
# where
#
# n is a positive integer input variable set to the order of r.
#
# r is an n by n array. on input the full upper triangle
# must contain the full upper triangle of the matrix r.
# on output the full upper triangle is unaltered, and the
# strict lower triangle contains the strict upper triangle
# (transposed) of the upper triangular matrix s.
#
# ldr is a positive integer input variable not less than n
# which specifies the leading dimension of the array r.
#
# ipvt is an integer input array of length n which defines the
# permutation matrix p such that a*p = q*r. column j of p
# is column ipvt(j) of the identity matrix.
#
# diag is an input array of length n which must contain the
# diagonal elements of the matrix d.
#
# qtb is an input array of length n which must contain the first
# n elements of the vector (q transpose)*b.
#
# delta is a positive input variable which specifies an upper
# bound on the euclidean norm of d*x.
#
# par is a nonnegative variable. on input par contains an
# initial estimate of the levenberg-marquardt parameter.
# on output par contains the final estimate.
#
# x is an output array of length n which contains the least
# squares solution of the system a*x = b, sqrt(par)*d*x = 0,
# for the output par.
#
# sdiag is an output array of length n which contains the
# diagonal elements of the upper triangular matrix s.
#
# wa1 and wa2 are work arrays of length n.
#
# subprograms called
#
# minpack-supplied ... dpmpar,enorm,qrsolv
#
# fortran-supplied ... dabs,dmax1,dmin1,dsqrt
#
# argonne national laboratory. minpack project. march 1980.
# burton s. garbow, kenneth e. hillstrom, jorge j. more
#
def lmpar(self, r, ipvt, diag, qtb, delta, x, sdiag, par=None):
if self.debug:
print 'Entering lmpar...'
dwarf = self.machar.minnum
machep = self.machar.machep
sz = r.shape
m = sz[0]
n = sz[1]
# Compute and store in x the gauss-newton direction. If the
# jacobian is rank-deficient, obtain a least-squares solution
nsing = n
wa1 = qtb.copy()
rthresh = numpy.max(numpy.abs(numpy.diagonal(r))) * machep
wh = (numpy.nonzero(numpy.abs(numpy.diagonal(r)) < rthresh))[0]
if len(wh) > 0:
nsing = wh[0]
wa1[wh[0]:] = 0
if nsing >= 1:
# *** Reverse loop ***
for j in range(nsing-1,-1,-1):
wa1[j] = wa1[j]/r[j,j]
if j-1 >= 0:
wa1[0:j] = wa1[0:j] - r[0:j,j]*wa1[j]
# Note: ipvt here is a permutation array
x[ipvt] = wa1
# Initialize the iteration counter. Evaluate the function at the
# origin, and test for acceptance of the gauss-newton direction
iter = 0
wa2 = diag * x
dxnorm = self.enorm(wa2)
fp = dxnorm - delta
if fp <= 0.1*delta:
return [r, 0., x, sdiag]
# If the jacobian is not rank deficient, the newton step provides a
# lower bound, parl, for the zero of the function. Otherwise set
# this bound to zero.
parl = 0.
if nsing >= n:
wa1 = diag[ipvt] * wa2[ipvt] / dxnorm
wa1[0] = wa1[0] / r[0,0] # Degenerate case
for j in range(1,n): # Note "1" here, not zero
sum0 = sum(r[0:j,j]*wa1[0:j])
wa1[j] = (wa1[j] - sum0)/r[j,j]
temp = self.enorm(wa1)
parl = ((fp/delta)/temp)/temp
# Calculate an upper bound, paru, for the zero of the function
for j in range(n):
sum0 = sum(r[0:j+1,j]*qtb[0:j+1])
wa1[j] = sum0/diag[ipvt[j]]
gnorm = self.enorm(wa1)
paru = gnorm/delta
if paru == 0:
paru = dwarf/numpy.min([delta,0.1])
# If the input par lies outside of the interval (parl,paru), set
# par to the closer endpoint
par = numpy.max([par,parl])
par = numpy.min([par,paru])
if par == 0:
par = gnorm/dxnorm
# Beginning of an interation
while(1):
iter = iter + 1
# Evaluate the function at the current value of par
if par == 0:
par = numpy.max([dwarf, paru*0.001])
temp = numpy.sqrt(par)
wa1 = temp * diag
[r, x, sdiag] = self.qrsolv(r, ipvt, wa1, qtb, sdiag)
wa2 = diag*x
dxnorm = self.enorm(wa2)
temp = fp
fp = dxnorm - delta
if (numpy.abs(fp) <= 0.1*delta) or \
((parl == 0) and (fp <= temp) and (temp < 0)) or \
(iter == 10):
break;
# Compute the newton correction
wa1 = diag[ipvt] * wa2[ipvt] / dxnorm
for j in range(n-1):
wa1[j] = wa1[j]/sdiag[j]
wa1[j+1:n] = wa1[j+1:n] - r[j+1:n,j]*wa1[j]
wa1[n-1] = wa1[n-1]/sdiag[n-1] # Degenerate case
temp = self.enorm(wa1)
parc = ((fp/delta)/temp)/temp
# Depending on the sign of the function, update parl or paru
if fp > 0:
parl = numpy.max([parl,par])
if fp < 0:
paru = numpy.min([paru,par])
# Compute an improved estimate for par
par = numpy.max([parl, par+parc])
# End of an iteration
# Termination
return [r, par, x, sdiag]
# Procedure to tie one parameter to another.
def tie(self, p, ptied=None):
if self.debug:
print 'Entering tie...'
if ptied is None:
return
for i in range(len(ptied)):
if ptied[i] == '':
continue
cmd = 'p[' + str(i) + '] = ' + ptied[i]
exec(cmd)
return p
# Original FORTRAN documentation
# **********
#
# subroutine covar
#
# given an m by n matrix a, the problem is to determine
# the covariance matrix corresponding to a, defined as
#
# t
# inverse(a *a) .
#
# this subroutine completes the solution of the problem
# if it is provided with the necessary information from the
# qr factorization, with column pivoting, of a. that is, if
# a*p = q*r, where p is a permutation matrix, q has orthogonal
# columns, and r is an upper triangular matrix with diagonal
# elements of nonincreasing magnitude, then covar expects
# the full upper triangle of r and the permutation matrix p.
# the covariance matrix is then computed as
#
# t t
# p*inverse(r *r)*p .
#
# if a is nearly rank deficient, it may be desirable to compute
# the covariance matrix corresponding to the linearly independent
# columns of a. to define the numerical rank of a, covar uses
# the tolerance tol. if l is the largest integer such that
#
# abs(r(l,l)) .gt. tol*abs(r(1,1)) ,
#
# then covar computes the covariance matrix corresponding to
# the first l columns of r. for k greater than l, column
# and row ipvt(k) of the covariance matrix are set to zero.
#
# the subroutine statement is
#
# subroutine covar(n,r,ldr,ipvt,tol,wa)
#
# where
#
# n is a positive integer input variable set to the order of r.
#
# r is an n by n array. on input the full upper triangle must
# contain the full upper triangle of the matrix r. on output
# r contains the square symmetric covariance matrix.
#
# ldr is a positive integer input variable not less than n
# which specifies the leading dimension of the array r.
#
# ipvt is an integer input array of length n which defines the
# permutation matrix p such that a*p = q*r. column j of p
# is column ipvt(j) of the identity matrix.
#
# tol is a nonnegative input variable used to define the
# numerical rank of a in the manner described above.
#
# wa is a work array of length n.
#
# subprograms called
#
# fortran-supplied ... dabs
#
# argonne national laboratory. minpack project. august 1980.
# burton s. garbow, kenneth e. hillstrom, jorge j. more
#
# **********
def calc_covar(self, rr, ipvt=None, tol=1.e-14):
if self.debug:
print 'Entering calc_covar...'
if numpy.rank(rr) != 2:
print 'ERROR: r must be a two-dimensional matrix'
return -1
s = rr.shape
n = s[0]
if s[0] != s[1]:
print 'ERROR: r must be a square matrix'
return -1
if ipvt is None:
ipvt = numpy.arange(n)
r = rr.copy()
r.shape = [n,n]
# For the inverse of r in the full upper triangle of r
l = -1
tolr = tol * numpy.abs(r[0,0])
for k in range(n):
if numpy.abs(r[k,k]) <= tolr:
break
r[k,k] = 1./r[k,k]
for j in range(k):
temp = r[k,k] * r[j,k]
r[j,k] = 0.
r[0:j+1,k] = r[0:j+1,k] - temp*r[0:j+1,j]
l = k
# Form the full upper triangle of the inverse of (r transpose)*r
# in the full upper triangle of r
if l >= 0:
for k in range(l+1):
for j in range(k):
temp = r[j,k]
r[0:j+1,j] = r[0:j+1,j] + temp*r[0:j+1,k]
temp = r[k,k]
r[0:k+1,k] = temp * r[0:k+1,k]
# For the full lower triangle of the covariance matrix
# in the strict lower triangle or and in wa
wa = numpy.repeat([r[0,0]], n)
for j in range(n):
jj = ipvt[j]
sing = j > l
for i in range(j+1):
if sing:
r[i,j] = 0.
ii = ipvt[i]
if ii > jj:
r[ii,jj] = r[i,j]
if ii < jj:
r[jj,ii] = r[i,j]
wa[jj] = r[j,j]
# Symmetrize the covariance matrix in r
for j in range(n):
r[0:j+1,j] = r[j,0:j+1]
r[j,j] = wa[j]
return r
class machar:
def __init__(self, double=1):
if double == 0:
info = numpy.finfo(numpy.float32)
else:
info = numpy.finfo(numpy.float64)
self.machep = info.eps
self.maxnum = info.max
self.minnum = info.tiny
self.maxlog = numpy.log(self.maxnum)
self.minlog = numpy.log(self.minnum)
self.rdwarf = numpy.sqrt(self.minnum*1.5) * 10
self.rgiant = numpy.sqrt(self.maxnum) * 0.1
| 78,409 | 32.479932 | 93 | py |
SDR | SDR-master/Setup/WideSweep/Peaks.py | import numpy as np
def peaks(y,nsig, m=2, returnDict=False):
"""
Find the peaks in a vector (spectrum) which lie nsig above the
standard deviation of all peaks in the spectrum.
y -- vector in which to locate peaks
nsig -- number of sigma above the standard deviation of all peaks to search
return -- vector holding indices of peak locations in y
Intended to duplicate logic of peaks.pro
nsig is NOT the number of sigma above the noise in the spectrum.
It's instead a measure of the significance of a peak. First, all
peaks are located. Then the standard deviation of the peaks is
calculated using ROBUST_SIGMA (see Goddard routines online). Then
peaks which are NSIG above the sigma of all peaks are selected.
"""
print "begin Peaks.peaks with nsig,m=",nsig,m
d0 = y - np.roll(y,-1)
d1 = y - np.roll(y,1)
pk = np.arange(y.size)[np.logical_and(d0>0, d1>0)]
npk = pk.size
yp = y[pk]
# reject outliers more than m=2 sigma from median
delta = np.abs(yp - np.median(yp))
mdev = np.median(delta)
s = delta/mdev if mdev else 0
ypGood = y[np.where(s<m)] # using a subset of y
mn = ypGood.mean()
sig = ypGood.std()
big = pk[yp > mn + nsig*sig]
#to remove multiple identifications of the same peak (not collisions)
minPeakDist = 60
cluster = []
clusters=[]
for pks in range(len(big)-1):
dist = abs(big[pks]-big[pks+1])
cluster.append(pks)
if dist > minPeakDist:
clusters.append(cluster)
cluster=[]
indrem=[]
for c in range(len(clusters)):
try:
trueind = np.argmax( y[big[clusters[c]]] )
falseind = np.where(big[clusters[c]] != big[clusters[c]][trueind])[0]
indrem = np.concatenate((indrem, np.array(clusters[c])[falseind]))
except ValueError:
pass
big = np.delete(big,indrem)
if returnDict:
return {"big":big, "pk":pk, "yp":yp, "m":m}
else:
return big
| 2,033 | 31.806452 | 81 | py |
SDR | SDR-master/Setup/WideSweep/WideSweepFile.py | import numpy as np
from scipy.interpolate import UnivariateSpline
from scipy import signal
import Peaks
#from interval import interval, inf, imath
import math
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
class WideSweepFile():
"""
Handle data written by the program SegmentedSweep.vi
The first seven lines are header information.
Each remaining line is frequency, I, sigma_I, Q, sigma_Q
"""
def __init__(self,fileName):
file = open(fileName,'r')
#(self.fr1,self.fspan1,self.fsteps1,self.atten1) = \
# file.readline().split()
#(self.fr2,self.fspan2,self.fsteps2,self.atten2) = \
# file.readline().split()
#(self.ts,self.te) = file.readline().split()
#(self.Iz1,self.Izsd1) = [float(x) for x in file.readline().split()]
#(self.Qz1,self.Qzsd1) = [float(x) for x in file.readline().split()]
#(self.Iz2,self.Izsd2) = [float(x) for x in file.readline().split()]
#(self.Qz2,self.Qzsd2) = [float(x) for x in file.readline().split()]
(self.ts,self.te) = 0.100, 0.100
(self.Iz1,self.Izsd1) = 0.000, 0.000
(self.Qz1,self.Qzsd1) = 0.000, 0.000
(self.Iz2,self.Izsd2) = 0.000, 0.000
(self.Qz2,self.Qzsd2) = 0.000, 0.000
file.close()
self.data1 = np.loadtxt(fileName, skiprows=3)
self.loadedFileName=fileName
self.x = self.data1[:,0]
self.n = len(self.x)
ind = np.arange(self.n)
Iz = np.where(ind<self.n/2, self.Iz1, self.Iz2)
self.I = self.data1[:,1]
self.I = self.I - Iz
self.Ierr = 0.001000000 #self.data1[:,2]
Qz = np.where(ind<self.n/2, self.Qz1, self.Qz2)
self.Q = self.data1[:,2] - Qz
self.Qerr = 0.001000000#self.data1[:,4]
self.mag = np.sqrt(np.power(self.I,2) + np.power(self.Q,2))
def fitSpline(self, splineS=1, splineK=3):
x = self.data1[:,0]
y = self.mag
self.splineS = splineS
self.splineK = splineK
spline = UnivariateSpline(x,y,s=self.splineS, k=self.splineK)
self.baseline = spline(x)
def findPeaks(self, m=2, useDifference=True):
if useDifference:
diff = self.baseline - self.mag
else:
diff = -self.mag
self.peaksDict = Peaks.peaks(diff,m,returnDict=True)
self.peaks = self.peaksDict['big']
self.pk = self.peaksDict['pk']
def findPeaksThreshold(self,threshSigma):
self.fptThreshSigma = threshSigma
values = self.mag-self.baseline
self.fptHg = np.histogram(values,bins=100)
self.fptCenters = 0.5*(self.fptHg[1][:-1] + self.fptHg[1][1:])
self.fptAverage = np.average(self.fptCenters,weights=self.fptHg[0])
self.fptStd = np.sqrt(np.average((self.fptCenters-self.fptAverage)**2,
weights=self.fptHg[0]))
thresh = self.fptAverage - threshSigma*self.fptStd
ind = np.arange(len(values))[values < thresh]
self.threshIntervals = interval()
for i in ind-1:
self.threshIntervals = threshIntervals | interval[i-0.6,i+0.6]
self.peaks = np.zeros(len(threshIntervals))
iPeak = 0
for threshInterval in self.threshIntervals:
i0 = int(math.ceil(self.threshInterval[0]))
i1 = int(math.ceil(self.threshInterval[1]))
peak = np.average(self.x[i0:i1],weights=np.abs(values[i0:i1]))
self.peaks[iPeak] = peak
x0 = self.x[i0]
x1 = self.x[i1]
iPeak += 1
def filter(self, order=4, rs=40, wn=0.1):
b,a = signal.cheby2(order, rs, wn, btype="high", analog=False)
self.filtered = signal.filtfilt(b,a,self.mag)
def fitFilter(self, order=4, rs=40, wn=0.5):
self.filter(order=order, rs=rs, wn=wn)
self.baseline = self.mag-self.filtered
def createPdf(self, pdfFile, deltaF=0.15, plotsPerPage=5):
nx = int(deltaF*len(self.x)/(self.x.max()-self.x.min()))
pdf_pages = PdfPages(pdfFile)
db = 20*np.log10(self.mag/self.mag.max())
startNewPage = True
for i0 in range(0,len(self.x),nx):
if startNewPage:
fig = plt.figure(figsize=(8.5,11), dpi=100)
iPlot = 0
startNewPage = False
iPlot += 1
ax = fig.add_subplot(plotsPerPage, 1, iPlot)
ax.plot(self.x[i0:i0+nx],db[i0:i0+nx])
ax.set_xlabel("Frequency (GHz)")
ax.set_ylabel("S21(db)")
if iPlot == plotsPerPage:
startNewPage = True
pdf_pages.savefig(fig)
if not startNewPage:
pdf_pages.savefig(fig)
pdf_pages.close()
def resFit(self,ind0,ind1):
"""
Logic copied from MasterResonatorAnalysis/resfit.pro
"""
if ind0 < len(self.x)/2:
iZero = self.Iz1
qZero = self.Qz1
else:
iZero = self.Iz2
qZero = self.Qz2
| 5,079 | 37.484848 | 79 | py |
SDR | SDR-master/Setup/WideSweep/peakdetect.py | import numpy as np
from math import pi, log
import pylab
from scipy import fft, ifft
from scipy.optimize import curve_fit
i = 10000
x = np.linspace(0, 3.5 * pi, i)
y = (0.3*np.sin(x) + np.sin(1.3 * x) + 0.9 * np.sin(4.2 * x) + 0.06 *
np.random.randn(i))
def _datacheck_peakdetect(x_axis, y_axis):
if x_axis is None:
x_axis = range(len(y_axis))
if len(y_axis) != len(x_axis):
raise (ValueError,
'Input vectors y_axis and x_axis must have same length')
#needs to be a numpy array
y_axis = np.array(y_axis)
x_axis = np.array(x_axis)
return x_axis, y_axis
def _peakdetect_parabole_fitter(raw_peaks, x_axis, y_axis, points):
"""
Performs the actual parabole fitting for the peakdetect_parabole function.
keyword arguments:
raw_peaks -- A list of either the maximium or the minimum peaks, as given
by the peakdetect_zero_crossing function, with index used as x-axis
x_axis -- A numpy list of all the x values
y_axis -- A numpy list of all the y values
points -- How many points around the peak should be used during curve
fitting, must be odd.
return -- A list giving all the peaks and the fitted waveform, format:
[[x, y, [fitted_x, fitted_y]]]
"""
func = lambda x, k, tau, m: k * ((x - tau) ** 2) + m
fitted_peaks = []
for peak in raw_peaks:
index = peak[0]
x_data = x_axis[index - points // 2: index + points // 2 + 1]
y_data = y_axis[index - points // 2: index + points // 2 + 1]
# get a first approximation of tau (peak position in time)
tau = x_axis[index]
# get a first approximation of peak amplitude
m = peak[1]
# build list of approximations
# k = -m as first approximation?
p0 = (-m, tau, m)
popt, pcov = curve_fit(func, x_data, y_data, p0)
# retrieve tau and m i.e x and y value of peak
x, y = popt[1:3]
# create a high resolution data set for the fitted waveform
x2 = np.linspace(x_data[0], x_data[-1], points * 10)
y2 = func(x2, *popt)
fitted_peaks.append([x, y, [x2, y2]])
return fitted_peaks
def peakdetect(y_axis, x_axis = None, lookahead = 300, delta=0):
"""
Converted from/based on a MATLAB script at:
http://billauer.co.il/peakdet.html
function for detecting local maximas and minmias in a signal.
Discovers peaks by searching for values which are surrounded by lower
or larger values for maximas and minimas respectively
keyword arguments:
y_axis -- A list containg the signal over which to find peaks
x_axis -- (optional) A x-axis whose values correspond to the y_axis list
and is used in the return to specify the postion of the peaks. If
omitted an index of the y_axis is used. (default: None)
lookahead -- (optional) distance to look ahead from a peak candidate to
determine if it is the actual peak (default: 200)
'(sample / period) / f' where '4 >= f >= 1.25' might be a good value
delta -- (optional) this specifies a minimum difference between a peak and
the following points, before a peak may be considered a peak. Useful
to hinder the function from picking up false peaks towards to end of
the signal. To work well delta should be set to delta >= RMSnoise * 5.
(default: 0)
delta function causes a 20% decrease in speed, when omitted
Correctly used it can double the speed of the function
return -- two lists [max_peaks, min_peaks] containing the positive and
negative peaks respectively. Each cell of the lists contains a tupple
of: (position, peak_value)
to get the average peak value do: np.mean(max_peaks, 0)[1] on the
results to unpack one of the lists into x, y coordinates do:
x, y = zip(*tab)
"""
max_peaks = []
min_peaks = []
dump = [] #Used to pop the first hit which almost always is false
# check input data
x_axis, y_axis = _datacheck_peakdetect(x_axis, y_axis)
# store data length for later use
length = len(y_axis)
#perform some checks
if lookahead < 1:
raise ValueError, "Lookahead must be '1' or above in value"
if not (np.isscalar(delta) and delta >= 0):
raise ValueError, "delta must be a positive number"
#maxima and minima candidates are temporarily stored in
#mx and mn respectively
mn, mx = np.Inf, -np.Inf
#Only detect peak if there is 'lookahead' amount of points after it
for index, (x, y) in enumerate(zip(x_axis[:-lookahead],
y_axis[:-lookahead])):
if y > mx:
mx = y
mxpos = x
if y < mn:
mn = y
mnpos = x
####look for max####
if y < mx-delta and mx != np.Inf:
#Maxima peak candidate found
#look ahead in signal to ensure that this is a peak and not jitter
if y_axis[index:index+lookahead].max() < mx:
max_peaks.append([mxpos, mx])
dump.append(True)
#set algorithm to only find minima now
mx = np.Inf
mn = np.Inf
if index+lookahead >= length:
#end is within lookahead no more peaks can be found
break
continue
#else: #slows shit down this does
# mx = ahead
# mxpos = x_axis[np.where(y_axis[index:index+lookahead]==mx)]
####look for min####
if y > mn+delta and mn != -np.Inf:
#Minima peak candidate found
#look ahead in signal to ensure that this is a peak and not jitter
if y_axis[index:index+lookahead].min() > mn:
min_peaks.append([mnpos, mn])
dump.append(False)
#set algorithm to only find maxima now
mn = -np.Inf
mx = -np.Inf
if index+lookahead >= length:
#end is within lookahead no more peaks can be found
break
#else: #slows shit down this does
# mn = ahead
# mnpos = x_axis[np.where(y_axis[index:index+lookahead]==mn)]
#Remove the false hit on the first value of the y_axis
try:
if dump[0]:
max_peaks.pop(0)
else:
min_peaks.pop(0)
del dump
except IndexError:
#no peaks were found, should the function return empty lists?
pass
return [max_peaks, min_peaks]
def peakdetect_fft(y_axis, x_axis, pad_len = 5):
"""
Performs a FFT calculation on the data and zero-pads the results to
increase the time domain resolution after performing the inverse fft and
send the data to the 'peakdetect' function for peak
detection.
Omitting the x_axis is forbidden as it would make the resulting x_axis
value silly if it was returned as the index 50.234 or similar.
Will find at least 1 less peak then the 'peakdetect_zero_crossing'
function, but should result in a more precise value of the peak as
resolution has been increased. Some peaks are lost in an attempt to
minimize spectral leakage by calculating the fft between two zero
crossings for n amount of signal periods.
The biggest time eater in this function is the ifft and thereafter it's
the 'peakdetect' function which takes only half the time of the ifft.
Speed improvementd could include to check if 2**n points could be used for
fft and ifft or change the 'peakdetect' to the 'peakdetect_zero_crossing',
which is maybe 10 times faster than 'peakdetct'. The pro of 'peakdetect'
is that it resutls in one less lost peak. It should also be noted that the
time used by the ifft function can change greatly depending on the input.
keyword arguments:
y_axis -- A list containg the signal over which to find peaks
x_axis -- A x-axis whose values correspond to the y_axis list and is used
in the return to specify the postion of the peaks.
pad_len -- (optional) By how many times the time resolution should be
increased by, e.g. 1 doubles the resolution. The amount is rounded up
to the nearest 2 ** n amount (default: 5)
return -- two lists [max_peaks, min_peaks] containing the positive and
negative peaks respectively. Each cell of the lists contains a tupple
of: (position, peak_value)
to get the average peak value do: np.mean(max_peaks, 0)[1] on the
results to unpack one of the lists into x, y coordinates do:
x, y = zip(*tab)
"""
# check input data
x_axis, y_axis = _datacheck_peakdetect(x_axis, y_axis)
zero_indices = zero_crossings(y_axis, window = 11)
#select a n amount of periods
last_indice = - 1 - (1 - len(zero_indices) & 1)
# Calculate the fft between the first and last zero crossing
# this method could be ignored if the begining and the end of the signal
# are discardable as any errors induced from not using whole periods
# should mainly manifest in the beginning and the end of the signal, but
# not in the rest of the signal
fft_data = fft(y_axis[zero_indices[0]:zero_indices[last_indice]])
padd = lambda x, c: x[:len(x) // 2] + [0] * c + x[len(x) // 2:]
n = lambda x: int(log(x)/log(2)) + 1
# padds to 2**n amount of samples
fft_padded = padd(list(fft_data), 2 **
n(len(fft_data) * pad_len) - len(fft_data))
# There is amplitude decrease directly proportional to the sample increase
sf = len(fft_padded) / float(len(fft_data))
# There might be a leakage giving the result an imaginary component
# Return only the real component
y_axis_ifft = ifft(fft_padded).real * sf #(pad_len + 1)
x_axis_ifft = np.linspace(
x_axis[zero_indices[0]], x_axis[zero_indices[last_indice]],
len(y_axis_ifft))
# get the peaks to the interpolated waveform
max_peaks, min_peaks = peakdetect(y_axis_ifft, x_axis_ifft, 500,
delta = abs(np.diff(y_axis).max() * 2))
#max_peaks, min_peaks = peakdetect_zero_crossing(y_axis_ifft, x_axis_ifft)
# store one 20th of a period as waveform data
data_len = int(np.diff(zero_indices).mean()) / 10
data_len += 1 - data_len & 1
fitted_wave = []
for peaks in [max_peaks, min_peaks]:
peak_fit_tmp = []
index = 0
for peak in peaks:
index = np.where(x_axis_ifft[index:]==peak[0])[0][0] + index
x_fit_lim = x_axis_ifft[index - data_len // 2:
index + data_len // 2 + 1]
y_fit_lim = y_axis_ifft[index - data_len // 2:
index + data_len // 2 + 1]
peak_fit_tmp.append([x_fit_lim, y_fit_lim])
fitted_wave.append(peak_fit_tmp)
#pylab.plot(range(len(fft_data)), fft_data)
#pylab.show()
pylab.plot(x_axis, y_axis)
pylab.hold(True)
pylab.plot(x_axis_ifft, y_axis_ifft)
#for max_p in max_peaks:
# pylab.plot(max_p[0], max_p[1], 'xr')
pylab.show()
return [max_peaks, min_peaks]
def peakdetect_parabole(y_axis, x_axis, points = 9):
"""
Function for detecting local maximas and minmias in a signal.
Discovers peaks by fitting the model function: y = k (x - tau) ** 2 + m
to the peaks. The amount of points used in the fitting is set by the
points argument.
Omitting the x_axis is forbidden as it would make the resulting x_axis
value silly if it was returned as index 50.234 or similar.
will find the same amount of peaks as the 'peakdetect_zero_crossing'
function, but might result in a more precise value of the peak.
keyword arguments:
y_axis -- A list containg the signal over which to find peaks
x_axis -- A x-axis whose values correspond to the y_axis list and is used
in the return to specify the postion of the peaks.
points -- (optional) How many points around the peak should be used during
curve fitting, must be odd (default: 9)
return -- two lists [max_peaks, min_peaks] containing the positive and
negative peaks respectively. Each cell of the lists contains a list
of: (position, peak_value)
to get the average peak value do: np.mean(max_peaks, 0)[1] on the
results to unpack one of the lists into x, y coordinates do:
x, y = zip(*max_peaks)
"""
# check input data
x_axis, y_axis = _datacheck_peakdetect(x_axis, y_axis)
# make the points argument odd
points += 1 - points % 2
#points += 1 - int(points) & 1 slower when int conversion needed
# get raw peaks
max_raw, min_raw = peakdetect_zero_crossing(y_axis)
# define output variable
max_peaks = []
min_peaks = []
max_ = _peakdetect_parabole_fitter(max_raw, x_axis, y_axis, points)
min_ = _peakdetect_parabole_fitter(min_raw, x_axis, y_axis, points)
max_peaks = map(lambda x: [x[0], x[1]], max_)
max_fitted = map(lambda x: x[-1], max_)
min_peaks = map(lambda x: [x[0], x[1]], min_)
min_fitted = map(lambda x: x[-1], min_)
#pylab.plot(x_axis, y_axis)
#pylab.hold(True)
#for max_p, max_f in zip(max_peaks, max_fitted):
# pylab.plot(max_p[0], max_p[1], 'x')
# pylab.plot(max_f[0], max_f[1], 'o', markersize = 2)
#for min_p, min_f in zip(min_peaks, min_fitted):
# pylab.plot(min_p[0], min_p[1], 'x')
# pylab.plot(min_f[0], min_f[1], 'o', markersize = 2)
#pylab.show()
return [max_peaks, min_peaks]
def peakdetect_sine(y_axis, x_axis, points = 9, lock_frequency = False):
"""
Function for detecting local maximas and minmias in a signal.
Discovers peaks by fitting the model function:
y = A * sin(2 * pi * f * x - tau) to the peaks. The amount of points used
in the fitting is set by the points argument.
Omitting the x_axis is forbidden as it would make the resulting x_axis
value silly if it was returned as index 50.234 or similar.
will find the same amount of peaks as the 'peakdetect_zero_crossing'
function, but might result in a more precise value of the peak.
The function might have some problems if the sine wave has a
non-negligible total angle i.e. a k*x component, as this messes with the
internal offset calculation of the peaks, might be fixed by fitting a
k * x + m function to the peaks for offset calculation.
keyword arguments:
y_axis -- A list containg the signal over which to find peaks
x_axis -- A x-axis whose values correspond to the y_axis list and is used
in the return to specify the postion of the peaks.
points -- (optional) How many points around the peak should be used during
curve fitting, must be odd (default: 9)
lock_frequency -- (optional) Specifies if the frequency argument of the
model function should be locked to the value calculated from the raw
peaks or if optimization process may tinker with it. (default: False)
return -- two lists [max_peaks, min_peaks] containing the positive and
negative peaks respectively. Each cell of the lists contains a tupple
of: (position, peak_value)
to get the average peak value do: np.mean(max_peaks, 0)[1] on the
results to unpack one of the lists into x, y coordinates do:
x, y = zip(*tab)
"""
# check input data
x_axis, y_axis = _datacheck_peakdetect(x_axis, y_axis)
# make the points argument odd
points += 1 - points % 2
#points += 1 - int(points) & 1 slower when int conversion needed
# get raw peaks
max_raw, min_raw = peakdetect_zero_crossing(y_axis)
# define output variable
max_peaks = []
min_peaks = []
# get global offset
offset = np.mean([np.mean(max_raw, 0)[1], np.mean(min_raw, 0)[1]])
# fitting a k * x + m function to the peaks might be better
#offset_func = lambda x, k, m: k * x + m
# calculate an approximate frequenzy of the signal
Hz = []
for raw in [max_raw, min_raw]:
if len(raw) > 1:
peak_pos = [x_axis[index] for index in zip(*raw)[0]]
Hz.append(np.mean(np.diff(peak_pos)))
Hz = 1 / np.mean(Hz)
# model function
# if cosine is used then tau could equal the x position of the peak
# if sine were to be used then tau would be the first zero crossing
if lock_frequency:
func = lambda x, A, tau: A * np.sin(2 * pi * Hz * (x - tau) + pi / 2)
else:
func = lambda x, A, Hz, tau: A * np.sin(2 * pi * Hz * (x - tau) +
pi / 2)
#func = lambda x, A, Hz, tau: A * np.cos(2 * pi * Hz * (x - tau))
#get peaks
fitted_peaks = []
for raw_peaks in [max_raw, min_raw]:
peak_data = []
for peak in raw_peaks:
index = peak[0]
x_data = x_axis[index - points // 2: index + points // 2 + 1]
y_data = y_axis[index - points // 2: index + points // 2 + 1]
# get a first approximation of tau (peak position in time)
tau = x_axis[index]
# get a first approximation of peak amplitude
A = peak[1]
# build list of approximations
if lock_frequency:
p0 = (A, tau)
else:
p0 = (A, Hz, tau)
# subtract offset from waveshape
y_data -= offset
popt, pcov = curve_fit(func, x_data, y_data, p0)
# retrieve tau and A i.e x and y value of peak
x = popt[-1]
y = popt[0]
# create a high resolution data set for the fitted waveform
x2 = np.linspace(x_data[0], x_data[-1], points * 10)
y2 = func(x2, *popt)
# add the offset to the results
y += offset
y2 += offset
y_data += offset
peak_data.append([x, y, [x2, y2]])
fitted_peaks.append(peak_data)
# structure date for output
max_peaks = map(lambda x: [x[0], x[1]], fitted_peaks[0])
max_fitted = map(lambda x: x[-1], fitted_peaks[0])
min_peaks = map(lambda x: [x[0], x[1]], fitted_peaks[1])
min_fitted = map(lambda x: x[-1], fitted_peaks[1])
#pylab.plot(x_axis, y_axis)
#pylab.hold(True)
#for max_p, max_f in zip(max_peaks, max_fitted):
# pylab.plot(max_p[0], max_p[1], 'x')
# pylab.plot(max_f[0], max_f[1], 'o', markersize = 2)
#for min_p, min_f in zip(min_peaks, min_fitted):
# pylab.plot(min_p[0], min_p[1], 'x')
# pylab.plot(min_f[0], min_f[1], 'o', markersize = 2)
#pylab.show()
return [max_peaks, min_peaks]
def peakdetect_sine_locked(y_axis, x_axis, points = 9):
"""
Convinience function for calling the 'peakdetect_sine' function with
the lock_frequency argument as True.
keyword arguments:
y_axis -- A list containg the signal over which to find peaks
x_axis -- A x-axis whose values correspond to the y_axis list and is used
in the return to specify the postion of the peaks.
points -- (optional) How many points around the peak should be used during
curve fitting, must be odd (default: 9)
return -- see 'peakdetect_sine'
"""
return peakdetect_sine(y_axis, x_axis, points, True)
def peakdetect_zero_crossing(y_axis, x_axis = None, window = 11):
"""
Function for detecting local maximas and minmias in a signal.
Discovers peaks by dividing the signal into bins and retrieving the
maximum and minimum value of each the even and odd bins respectively.
Division into bins is performed by smoothing the curve and finding the
zero crossings.
Suitable for repeatable signals, where some noise is tolerated. Excecutes
faster than 'peakdetect', although this function will break if the offset
of the signal is too large. It should also be noted that the first and
last peak will probably not be found, as this function only can find peaks
between the first and last zero crossing.
keyword arguments:
y_axis -- A list containg the signal over which to find peaks
x_axis -- (optional) A x-axis whose values correspond to the y_axis list
and is used in the return to specify the postion of the peaks. If
omitted an index of the y_axis is used. (default: None)
window -- the dimension of the smoothing window; should be an odd integer
(default: 11)
return -- two lists [max_peaks, min_peaks] containing the positive and
negative peaks respectively. Each cell of the lists contains a tupple
of: (position, peak_value)
to get the average peak value do: np.mean(max_peaks, 0)[1] on the
results to unpack one of the lists into x, y coordinates do:
x, y = zip(*tab)
"""
# check input data
x_axis, y_axis = _datacheck_peakdetect(x_axis, y_axis)
zero_indices = zero_crossings(y_axis, window = window)
period_lengths = np.diff(zero_indices)
bins_y = [y_axis[index:index + diff] for index, diff in
zip(zero_indices, period_lengths)]
bins_x = [x_axis[index:index + diff] for index, diff in
zip(zero_indices, period_lengths)]
even_bins_y = bins_y[::2]
odd_bins_y = bins_y[1::2]
even_bins_x = bins_x[::2]
odd_bins_x = bins_x[1::2]
hi_peaks_x = []
lo_peaks_x = []
#check if even bin contains maxima
if abs(even_bins_y[0].max()) > abs(even_bins_y[0].min()):
hi_peaks = [bin.max() for bin in even_bins_y]
lo_peaks = [bin.min() for bin in odd_bins_y]
# get x values for peak
for bin_x, bin_y, peak in zip(even_bins_x, even_bins_y, hi_peaks):
hi_peaks_x.append(bin_x[np.where(bin_y==peak)[0][0]])
for bin_x, bin_y, peak in zip(odd_bins_x, odd_bins_y, lo_peaks):
lo_peaks_x.append(bin_x[np.where(bin_y==peak)[0][0]])
else:
hi_peaks = [bin.max() for bin in odd_bins_y]
lo_peaks = [bin.min() for bin in even_bins_y]
# get x values for peak
for bin_x, bin_y, peak in zip(odd_bins_x, odd_bins_y, hi_peaks):
hi_peaks_x.append(bin_x[np.where(bin_y==peak)[0][0]])
for bin_x, bin_y, peak in zip(even_bins_x, even_bins_y, lo_peaks):
lo_peaks_x.append(bin_x[np.where(bin_y==peak)[0][0]])
max_peaks = [[x, y] for x,y in zip(hi_peaks_x, hi_peaks)]
min_peaks = [[x, y] for x,y in zip(lo_peaks_x, lo_peaks)]
return [max_peaks, min_peaks]
def _smooth(x, window_len=11, window='hanning'):
"""
smooth the data using a window of the requested size.
This method is based on the convolution of a scaled window on the signal.
The signal is prepared by introducing reflected copies of the signal
(with the window size) in both ends so that transient parts are minimized
in the begining and end part of the output signal.
input:
x: the input signal
window_len: the dimension of the smoothing window; should be an odd
integer
window: the type of window from 'flat', 'hanning', 'hamming',
'bartlett', 'blackman'
flat window will produce a moving average smoothing.
output:
the smoothed signal
example:
t = linspace(-2,2,0.1)
x = sin(t)+randn(len(t))*0.1
y = _smooth(x)
see also:
numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman,
numpy.convolve, scipy.signal.lfilter
TODO: the window parameter could be the window itself if a list instead of
a string
"""
if x.ndim != 1:
raise ValueError, "smooth only accepts 1 dimension arrays."
if x.size < window_len:
raise ValueError, "Input vector needs to be bigger than window size."
if window_len<3:
return x
if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']:
raise(ValueError,
"Window is not one of '{0}', '{1}', '{2}', '{3}', '{4}'".format(
*('flat', 'hanning', 'hamming', 'bartlett', 'blackman')))
s = np.r_[x[window_len-1:0:-1], x, x[-1:-window_len:-1]]
#print(len(s))
if window == 'flat': #moving average
w = np.ones(window_len,'d')
else:
w = eval('np.' + window + '(window_len)')
y = np.convolve(w / w.sum(), s, mode = 'valid')
return y
def zero_crossings(y_axis, window = 11):
"""
Algorithm to find zero crossings. Smoothens the curve and finds the
zero-crossings by looking for a sign change.
keyword arguments:
y_axis -- A list containg the signal over which to find zero-crossings
window -- the dimension of the smoothing window; should be an odd integer
(default: 11)
return -- the index for each zero-crossing
"""
# smooth the curve
length = len(y_axis)
x_axis = np.asarray(range(length), int)
# discard tail of smoothed signal
y_axis = _smooth(y_axis, window)[:length]
zero_crossings = np.where(np.diff(np.sign(y_axis)))[0]
indices = [x_axis[index] for index in zero_crossings]
# check if zero-crossings are valid
diff = np.diff(indices)
if diff.std() / diff.mean() > 0.2:
print diff.std() / diff.mean()
print np.diff(indices)
raise(ValueError,
"False zero-crossings found, indicates problem {0} or {1}".format(
"with smoothing window", "problem with offset"))
# check if any zero crossings were found
if len(zero_crossings) < 1:
raise(ValueError, "No zero crossings found")
return indices
# used this to test the fft function's sensitivity to spectral leakage
#return indices + np.asarray(30 * np.random.randn(len(indices)), int)
############################Frequency calculation#############################
# diff = np.diff(indices)
# time_p_period = diff.mean()
#
# if diff.std() / time_p_period > 0.1:
# raise ValueError,
# "smoothing window too small, false zero-crossing found"
#
# #return frequency
# return 1.0 / time_p_period
##############################################################################
def _test_zero():
_max, _min = peakdetect_zero_crossing(y,x)
def _test():
_max, _min = peakdetect(y,x, delta=0.30)
def _test_graph():
i = 10000
x = np.linspace(0,3.7*pi,i)
y = (0.3*np.sin(x) + np.sin(1.3 * x) + 0.9 * np.sin(4.2 * x) + 0.06 *
np.random.randn(i))
y *= -1
x = range(i)
_max, _min = peakdetect(y,x,750, 0.30)
xm = [p[0] for p in _max]
ym = [p[1] for p in _max]
xn = [p[0] for p in _min]
yn = [p[1] for p in _min]
plot = pylab.plot(x,y)
pylab.hold(True)
pylab.plot(xm, ym, 'r+')
pylab.plot(xn, yn, 'g+')
_max, _min = peak_det_bad.peakdetect(y, 0.7, x)
xm = [p[0] for p in _max]
ym = [p[1] for p in _max]
xn = [p[0] for p in _min]
yn = [p[1] for p in _min]
pylab.plot(xm, ym, 'y*')
pylab.plot(xn, yn, 'k*')
pylab.show()
if __name__ == "__main__":
from math import pi
import pylab
i = 10000
x = np.linspace(0,3.7*pi,i)
y = (0.3*np.sin(x) + np.sin(1.3 * x) + 0.9 * np.sin(4.2 * x) + 0.06 *
np.random.randn(i))
y *= -1
_max, _min = peakdetect(y, x, 750, 0.30)
xm = [p[0] for p in _max]
ym = [p[1] for p in _max]
xn = [p[0] for p in _min]
yn = [p[1] for p in _min]
plot = pylab.plot(x, y)
pylab.hold(True)
pylab.plot(xm, ym, 'r+')
pylab.plot(xn, yn, 'g+')
pylab.show()
| 28,254 | 37.547067 | 78 | py |
SDR | SDR-master/Setup/WideSweep/WideSweepFile_old_wsf_format.py | import numpy as np
from scipy.interpolate import UnivariateSpline
from scipy import signal
import Peaks
#from interval import interval, inf, imath
import math
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
class WideSweepFile():
"""
Handle data written by the program SegmentedSweep.vi
The first seven lines are header information.
Each remaining line is frequency, I, sigma_I, Q, sigma_Q
"""
def __init__(self,fileName):
file = open(fileName,'r')
(self.fr1,self.fspan1,self.fsteps1,self.atten1) = \
file.readline().split()
(self.fr2,self.fspan2,self.fsteps2,self.atten2) = \
file.readline().split()
(self.ts,self.te) = file.readline().split()
(self.Iz1,self.Izsd1) = [float(x) for x in file.readline().split()]
(self.Qz1,self.Qzsd1) = [float(x) for x in file.readline().split()]
(self.Iz2,self.Izsd2) = [float(x) for x in file.readline().split()]
(self.Qz2,self.Qzsd2) = [float(x) for x in file.readline().split()]
file.close()
self.data1 = np.loadtxt(fileName, skiprows=7)
self.loadedFileName=fileName
self.x = self.data1[:,0]
self.n = len(self.x)
ind = np.arange(self.n)
Iz = np.where(ind<self.n/2, self.Iz1, self.Iz2)
self.I = self.data1[:,1]
self.I = self.I - Iz
self.Ierr = self.data1[:,2]
Qz = np.where(ind<self.n/2, self.Qz1, self.Qz2)
self.Q = self.data1[:,2] - Qz
self.Qerr = self.data1[:,4]
self.mag = np.sqrt(np.power(self.I,2) + np.power(self.Q,2))
def fitSpline(self, splineS=1, splineK=3):
x = self.data1[:,0]
y = self.mag
self.splineS = splineS
self.splineK = splineK
spline = UnivariateSpline(x,y,s=self.splineS, k=self.splineK)
self.baseline = spline(x)
def findPeaks(self, m=2, useDifference=True):
if useDifference:
diff = self.baseline - self.mag
else:
diff = -self.mag
self.peaksDict = Peaks.peaks(diff,m,returnDict=True)
self.peaks = self.peaksDict['big']
self.pk = self.peaksDict['pk']
def findPeaksThreshold(self,threshSigma):
self.fptThreshSigma = threshSigma
values = self.mag-self.baseline
self.fptHg = np.histogram(values,bins=100)
self.fptCenters = 0.5*(self.fptHg[1][:-1] + self.fptHg[1][1:])
self.fptAverage = np.average(self.fptCenters,weights=self.fptHg[0])
self.fptStd = np.sqrt(np.average((self.fptCenters-self.fptAverage)**2,
weights=self.fptHg[0]))
thresh = self.fptAverage - threshSigma*self.fptStd
ind = np.arange(len(values))[values < thresh]
self.threshIntervals = interval()
for i in ind-1:
self.threshIntervals = threshIntervals | interval[i-0.6,i+0.6]
self.peaks = np.zeros(len(threshIntervals))
iPeak = 0
for threshInterval in self.threshIntervals:
i0 = int(math.ceil(self.threshInterval[0]))
i1 = int(math.ceil(self.threshInterval[1]))
peak = np.average(self.x[i0:i1],weights=np.abs(values[i0:i1]))
self.peaks[iPeak] = peak
x0 = self.x[i0]
x1 = self.x[i1]
iPeak += 1
def filter(self, order=4, rs=40, wn=0.1):
b,a = signal.cheby2(order, rs, wn, btype="high", analog=False)
self.filtered = signal.filtfilt(b,a,self.mag)
def fitFilter(self, order=4, rs=40, wn=0.5):
self.filter(order=order, rs=rs, wn=wn)
self.baseline = self.mag-self.filtered
def createPdf(self, pdfFile, deltaF=0.15, plotsPerPage=5):
nx = int(deltaF*len(self.x)/(self.x.max()-self.x.min()))
pdf_pages = PdfPages(pdfFile)
db = 20*np.log10(self.mag/self.mag.max())
startNewPage = True
for i0 in range(0,len(self.x),nx):
if startNewPage:
fig = plt.figure(figsize=(8.5,11), dpi=100)
iPlot = 0
startNewPage = False
iPlot += 1
ax = fig.add_subplot(plotsPerPage, 1, iPlot)
ax.plot(self.x[i0:i0+nx],db[i0:i0+nx])
ax.set_xlabel("Frequency (GHz)")
ax.set_ylabel("S21(db)")
if iPlot == plotsPerPage:
startNewPage = True
pdf_pages.savefig(fig)
if not startNewPage:
pdf_pages.savefig(fig)
pdf_pages.close()
def resFit(self,ind0,ind1):
"""
Logic copied from MasterResonatorAnalysis/resfit.pro
"""
if ind0 < len(self.x)/2:
iZero = self.Iz1
qZero = self.Qz1
else:
iZero = self.Iz2
qZero = self.Qz2
| 4,824 | 36.992126 | 79 | py |
SDR | SDR-master/Setup/WideSweep/WideAna.py | """
A replacement for WideAna.pro for those who prefer python to idl.
Usage: python WideAna.py test/ucsb_100mK_24db_1.txt
Read the input file.
Interactively add and remove resonance locations.
Create file that plot dB vs frequency, in panels that are 0.15 GHz
wide if it does not exist. This file is the base input file name with
-good.ps appended.
Create file of resonance positions.
This file is the base input file name with -good.txt appended.
This file contains one line for each resonance, with the columns:
-- id number (sequential from 0)
-- index of the wavelength in the input file
-- frequency in GHz
If this file already exists when the program starts, it is moved to
the same file name with at date and time string appended, and a new
copy is made with all found resonances. The file is updated each time
a line is added or subtracted.
The view window is controlled by:
- self.segment: value from the segment; slider , varies from 0 to 1000
- self.zoomFactor
- from this calculate fMiddle, the frequency at the middle of the plot,
ranges from self.wsf.x[0] to self.wsf[-1], xMin and xMax
Matt Strader
Chris Stoughton
Rupert Dodkins
"""
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4 import QtGui
import matplotlib.pyplot as plt
import numpy as np
import sys, os, time, shutil
from multiprocessing import Process
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import matplotlib
from functools import partial
from scipy import signal
from scipy.signal import filter_design as fd
from scipy.interpolate import UnivariateSpline
#import Peaks as Peaks
from WideSweepFile import WideSweepFile
class WideAna(QMainWindow):
def __init__(self, parent=None,plotFunc=None,title='',separateProcess=False, image=None,showMe=True, initialFile=None):
self.parent = parent
if self.parent == None:
self.app = QApplication([])
super(WideAna,self).__init__(parent)
self.fitParams = { "filter":{"order":4,"rs":40,"wn":0.1},
'spline':{"splineS":1,"splineK":3}}
self.initialFile = initialFile
self.baseFile = ('.').join(initialFile.split('.')[:-1])
self.goodFile = self.baseFile+"-good.txt"
if os.path.exists(self.goodFile):
self.goodFile = self.goodFile+time.strftime("-%Y-%m-%d-%H-%M-%S")
#shutil.copy(self.goodFile,self.goodFile+time.strftime("-%Y-%m-%d-%H-%M-%S"))
self.pdfFile = self.baseFile+"-good.pdf"
self.fitLineEdits = {}
self.fitLabels = {}
self.splineS = 1
self.splineK = 3
self.setWindowTitle(title)
self.plotFunc = plotFunc
self.create_main_frame(title)
if plotFunc != None:
plotFunc(fig=self.fig,axes=self.axes)
if showMe == True:
self.show()
self.load_file(initialFile)
# make the PDF file
if not os.path.exists(self.pdfFile):
print "Create overview PDF file:",self.pdfFile
self.wsf.createPdf(self.pdfFile)
else:
print "Overview PDF file already on disk:",self.pdfFile
# plot the first segment
self.deltaXDisplay = 0.100 # display width in GHz
self.zoomFactor = 1.0
self.segment = 0
self.calcXminXmax()
self.plotSegment()
print "Ready to add and delete peaks."
def draw(self):
self.fig.canvas.draw()
def on_key_press(self,event):
#print "WideAna.on_key_press: event.key=",event.key
if event.key == "right" or event.key == 'r':
self.segmentIncrement(None,0.1)
return
elif event.key == "left" or event.key == 'l':
self.segmentDecrement(None,0.1)
return
elif event.key == "up" or event.key == '+':
self.zoom(1.25)
return
elif event.key == "down" or event.key == '-':
self.zoom(0.8)
return
self.on_key_or_button(event, event.key)
def on_button_press(self,event):
self.on_key_or_button(event,event.button)
def on_key_or_button(self, event, pressed):
xdata = getattr(event, 'xdata', None)
if xdata is not None:
ind = np.searchsorted(self.wsf.x, xdata)
xFound = self.wsf.x[ind]
indPk = np.searchsorted(self.wsf.pk, ind)
xPkFound0 = self.wsf.x[self.wsf.pk[indPk-1]]
xPkFound1 = self.wsf.x[self.wsf.pk[indPk]]
if abs(xPkFound0-xdata) < abs(xPkFound1-xdata):
bestIndex = indPk-1
else:
bestIndex = indPk
bestWsfIndex = self.wsf.pk[bestIndex]
bestX = self.wsf.x[bestWsfIndex]
if pressed == "d":
#if self.peakMask[bestWsfIndex]:
#self.peakMask[bestWsfIndex] = False
self.peakMask[bestWsfIndex-7:bestWsfIndex+7] = False # larger area of indicies to pinpoint false resonator location
self.setCountLabel()
self.replot()
self.writeToGoodFile()
if pressed == "a":
if not self.peakMask[bestWsfIndex]:
self.peakMask[bestWsfIndex] = True
self.setCountLabel()
self.replot()
self.writeToGoodFile()
def replot(self):
xlim = self.axes.set_xlim()
self.xMin=xlim[0]
self.xMax=xlim[1]
self.plotSegment()
def create_main_frame(self,title):
self.main_frame = QWidget()
# Create the mpl Figure and FigCanvas objects.
self.dpi = 100
self.fig = Figure((7, 5), dpi=self.dpi)
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self.main_frame)
self.canvas.setFocusPolicy(Qt.StrongFocus)
self.canvas.setFocus()
self.axes = self.fig.add_subplot(111)
self.fig.canvas.mpl_connect('key_press_event',self.on_key_press)
self.fig.canvas.mpl_connect('button_press_event',self.on_button_press)
# Create the segment slider
self.segmentSlider = QtGui.QSlider(Qt.Horizontal, self)
self.segmentSlider.setToolTip("Slide to change segment")
self.segmentMax = 100000.0
self.segmentSlider.setRange(0,int(self.segmentMax))
self.segmentSlider.setFocusPolicy(Qt.NoFocus)
self.segmentSlider.setGeometry(30,40,100,30)
self.segmentSlider.valueChanged[int].connect(self.changeSegmentValue)
# Create the left and right buttons
segmentDecrement = QtGui.QPushButton('<',self)
segmentDecrement.setToolTip("Back to previous segment")
segmentDecrement.clicked[bool].connect(self.segmentDecrement)
segmentIncrement = QtGui.QPushButton('>',self)
segmentIncrement.setToolTip("Forward to next segment")
segmentIncrement.clicked[bool].connect(self.segmentIncrement)
# create display mode button
self.yDisplay = QtGui.QPushButton("raw")
self.yDisplay.setToolTip("Toggle y axis: raw data or difference=raw-baseline")
self.yDisplay.setCheckable(True)
self.yDisplay.clicked[bool].connect(self.yDisplayClicked)
# create information boxes
self.instructionsLabel = QtGui.QLabel()
self.instructionsLabel.setText("ADD peak: a; REMOVE peak: d ZOOM: +/- SCAN l/r ")
self.countLabel = QtGui.QLabel()
self.countLabel.setText("count label")
self.inputLabel = QtGui.QLabel()
self.inputLabel.setText("Input File:%s"%self.initialFile)
self.goodLabel = QtGui.QLabel()
self.goodLabel.setText("Good File:%s"%self.goodFile)
# create controls for baseline fitting
#self.baseline = QtGui.QPushButton("filter")
#self.baseline.setCheckable(True)
#self.baseline.clicked[bool].connect(self.baselineClicked)
# Create the navigation toolbar, tied to the canvas
self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)
# Do the layout
# segment box
segmentBox = QHBoxLayout()
segmentBox.addWidget(segmentDecrement)
segmentBox.addWidget(self.segmentSlider)
segmentBox.addWidget(segmentIncrement)
segmentBox.addWidget(self.yDisplay)
# baseline box
#self.baselineBox = QHBoxLayout()
#self.updateBaselineBox()
# info box
self.infoBox = QVBoxLayout()
self.infoBox.addWidget(self.inputLabel)
self.infoBox.addWidget(self.goodLabel)
self.infoBox.addWidget(self.countLabel)
self.infoBox.addWidget(self.instructionsLabel)
# entire box
vbox = QVBoxLayout()
vbox.addLayout(self.infoBox)
vbox.addLayout(segmentBox)
#vbox.addLayout(self.baselineBox)
vbox.addWidget(self.canvas)
vbox.addWidget(self.mpl_toolbar)
self.main_frame.setLayout(vbox)
self.setCentralWidget(self.main_frame)
def updateBaselineBox(self):
for i in range(self.baselineBox.count()):
item = self.baselineBox.itemAt(i)
self.baselineBox.removeItem(item)
mode = str(self.baseline.text())
self.baseline.setFixedSize(70,40)
self.baselineBox.addWidget(self.baseline)
keys = self.fitParams[mode]
def load_file(self, fileName):
self.wsf = WideSweepFile(fileName)
#self.wsf.fitSpline(splineS=1.0, splineK=1)
self.wsf.fitFilter(wn=0.01)
self.wsf.findPeaks(m=2)
self.peakMask = np.zeros(len(self.wsf.x),dtype=np.bool)
self.collMask = np.zeros(len(self.wsf.x),dtype=np.bool)
if os.path.isfile(self.baseFile+"-ml.txt"): # update: use machine learning peak loacations if they've been made
print 'loading peak location predictions from', self.baseFile+"-ml.txt"
peaks = np.loadtxt(self.baseFile+"-ml.txt")
peaks = map(int,peaks)
else:
peaks = self.wsf.peaks
#coll_thresh = self.wsf.x[0]
dist = abs(np.roll(peaks, -1) - peaks)
#colls = np.delete(peaks,np.where(dist>=9))
colls=[]
diff, coll_thresh = 0, 0
while diff <= 5e-4:
diff = self.wsf.x[coll_thresh]-self.wsf.x[0]
coll_thresh += 1
print coll_thresh
for i in range(len(peaks)):
if dist[i]<coll_thresh:
if self.wsf.mag[peaks[i+1]] - self.wsf.mag[peaks[i]] > 1.5:
colls.append(peaks[i+1])
#print 'for ', self.wsf.x[peaks[i]], 'chosing the one before'
else:
colls.append(peaks[i])
#print 'for ', self.wsf.x[peaks[i]], 'chosing the this one'
print colls
if colls != []:
#colls=np.array(map(int,colls))
self.collMask[colls] = True # update: so unidentified peaks can be identified as unusable
peaks = np.delete(peaks,colls) #remove collisions (peaks < 0.5MHz apart = < 9 steps apart)
#peaks = np.delete(peaks,np.where(dist<9)) #remove collisions (peaks < 0.5MHz apart = < 9 steps apart)
self.peakMask[peaks] = True
self.setCountLabel()
self.writeToGoodFile()
def setCountLabel(self):
self.countLabel.setText("Number of peaks = %d"%self.peakMask.sum())
def writeToGoodFile(self):
gf = open(self.goodFile,'wb')
id = 0
for index in range(len(self.peakMask)):
if self.peakMask[index]:
line = "%8d %12d %16.7f\n"%(id,index,self.wsf.x[index])
gf.write(line)
id += 1
gf.close()
# deal with zooming and plotting one segment
def zoom(self,zoom):
self.zoomFactor *= zoom
self.calcXminXmax()
self.plotSegment()
def changeSegmentValue(self,value):
self.segment = value
self.calcXminXmax()
self.plotSegment()
def segmentDecrement(self, value, amount=0.9):
wsfDx = self.wsf.x[-1]-self.wsf.x[0]
plotDx = self.xMax-self.xMin
dsdx = self.segmentMax / wsfDx
ds = amount * dsdx * plotDx
self.segment = max(0,self.segment-ds)
self.segmentSlider.setSliderPosition(self.segment)
def segmentIncrement(self, value, amount=0.9):
wsfDx = self.wsf.x[-1]-self.wsf.x[0]
plotDx = self.xMax-self.xMin
dsdx = self.segmentMax / wsfDx
ds = amount * dsdx * plotDx
self.segment = min(self.segmentMax,self.segment+ds)
self.segmentSlider.setSliderPosition(self.segment)
def calcXminXmax(self):
xMiddle = self.wsf.x[0] + \
(self.segment/self.segmentMax)*(self.wsf.x[-1]-self.wsf.x[0])
dx = self.deltaXDisplay/self.zoomFactor
self.xMin = xMiddle-dx/2.0
self.xMax = xMiddle+dx/2.0
def plotSegment(self):
ydText = self.yDisplay.text()
if self.wsf != None:
if ydText == "raw":
yPlot = self.wsf.mag
yName = "magnitude"
else:
yPlot = self.wsf.mag-self.wsf.baseline
yName = "mag-baseline"
stride = self.wsf.data1.shape[0]/self.segmentMax
# plot all values and then set xmin and xmax to show this segment
self.axes.clear()
self.axes.plot(self.wsf.x, yPlot, label=yName)
for x in self.wsf.x[self.peakMask]:
if x > self.xMin and x < self.xMax:
self.axes.axvline(x=x,color='r')
for c in self.wsf.x[self.collMask]:
if c > self.xMin and c < self.xMax:
self.axes.axvline(x=c,color='g')
self.axes.set_xlim((self.xMin,self.xMax))
self.axes.set_title("segment=%.1f/%.1f"%(self.segment,self.segmentMax))
self.axes.legend().get_frame().set_alpha(0.5)
self.draw()
def yDisplayClicked(self, value):
if value:
self.yDisplay.setText("diff")
else:
self.yDisplay.setText("raw")
self.replot()
def baselineClicked(self,value):
if value:
self.baseline.setText("spline")
else:
self.baseline.setText("filter")
self.updateBaselineBox()
def show(self):
super(WideAna,self).show()
if self.parent == None:
self.app.exec_()
def main(initialFile=None):
form = WideAna(showMe=False,title='WideSweep',initialFile=initialFile)
form.show()
if __name__ == "__main__":
initialFile = None
if len(sys.argv) > 1:
initialFileName = sys.argv[1]
mdd = os.environ['MKID_DATA_DIR']
initialFile = os.path.join(mdd,initialFileName)
else:
print "need to specify a filename located in MKID_DATA_DIR"
exit()
main(initialFile=initialFile) | 15,084 | 36.339109 | 131 | py |
SDR | SDR-master/Setup/WideSweep/Resonator.py | import numpy as np
import scipy.ndimage.filters
from mpfit import mpfit
import math
import random
import matplotlib.pyplot as plt
import matplotlib
class Resonator:
def __init__(self, freq, I, Ierr, Q, Qerr):
self.freq = freq
self.I = I
self.Ierr = Ierr
self.Q = Q
self.Qerr = Qerr
self.mag = np.sqrt(np.power(self.I,2) + np.power(self.Q,2))
self.phase = np.arctan2(self.Q,self.I)
self.dist1 = np.sqrt(np.power(self.I[1:]-self.I[0:-1],2) +
np.power(self.Q[1:]-self.Q[0:-1],2))
self.dist1[:11] = 0.0
self.dist1[-11:] = 0.0
self.dist1 = Resonator.smooth(self.dist1)
self.residx = np.argmax(self.dist1)+1
width = len(self.dist1)/5
temp = self.I[self.residx-width:self.residx+width]
self.xrc1 = (temp.min()+temp.max())/2.0
temp = self.Q[self.residx-width:self.residx+width]
self.yrc1 = (temp.min()+temp.max())/2.0
@staticmethod
def smooth(a, width=15):
"""
ape how smooth works in idl, as used in resfit.pro
"""
r = np.zeros(len(a))
for i in range(len(r)):
if i < (width-1)/2 or i > len(r)-(width+1)/2:
r[i] = a[i]
else:
r[i] = a[i-width/2:1+i+width/2].sum()/width
return r
@staticmethod
def magModel(x, p):
"""
Value of the model at x
Copied from resfit.pro function MAGDIFF, but in the .pro file the
difference is calculated in MAGDIFF, but in this .py file
the difference is calculated in magDiffLin.
"""
Q = p[0] # Q
f0 = p[1] # resonance frequency
carrier = p[2] # value of carrier
depth = p[3] # depth of dip
slope = p[4] # slope of background
curve = p[5] # curve of background
dx3Weight = p[6]
dx = (x - f0) / f0
#s21 = (complex(0,2.0*Q*dx)) / (complex(1,0) + complex(0,2.0*Q*dx))
s21 = (1j*2.0*Q*dx) / (np.ones(len(dx)) + 1j*2.0*Q*dx)
s21a = depth*(
abs(s21) + carrier + slope*dx + curve*dx*dx + dx3Weight*dx*dx*dx)
return s21a
@staticmethod
def magDiffLin(p, fjac=None, x=None, y=None, err=None):
# Parameter values are passed in "p"
# If fjac==None then partial derivatives should not be
# computed. It will always be None if MPFIT is called with default
# flag.
model = Resonator.magModel(x, p)
# Non-negative status value means MPFIT should continue,
# negative means stop the calculation.
status = 0
return [status, (y-model)/err]
def quickFitPrep(self):
x = self.freq
y = self.mag/self.mag.max()
n = len(self.freq)
middle = int(n/2) - 1
err = 0.001*np.ones(n)
# p0 is a numpy array of the initial guesses
Q = 20000.0 # quality factor
f0 = x[middle] # peak position
carrier = 0.3
depth = y.max()-y.min()
slope = -10.0
curve = 0.0
dx3Weight = 0.0
p0 = np.array([Q,f0,carrier,depth,slope,curve,dx3Weight],
dtype='float64')
parinfo = []
parinfo.append({'value':Q, 'fixed':0, 'limited':[0,0],
'limits':[5000.0, 200000.0]})
parinfo.append({'value':f0, 'fixed':0, 'limited':[0,0],
'limits':[x[middle-n/10],x[middle+n/10]]})
parinfo.append({'value':carrier, 'fixed':0, 'limited':[0,0],
'limits':[1e-3,1e2]})
parinfo.append({'value':depth, 'fixed':0, 'limited':[0,0],
'limits':[depth/2.0, depth*2.0]})
parinfo.append({'value':slope, 'fixed':0, 'limited':[0,0],
'limits':[-1e4,1e4]})
parinfo.append({'value':curve, 'fixed':0, 'limited':[0,0],
'limits':[-1e7,1e7]})
parinfo.append({'value':dx3Weight, 'fixed':0, 'limited':[0,0],
'limits':[-1e12,1e12]})
functkw = {'x':x,'y':y,'err':err}
# This is how mpfit will use these
#self.mQuickFit = mpfit(
# Resonator.magDiffLin, p0, parinfo=parinfo,functkw=fa)
return {"p0":p0, "parinfo":parinfo,"functkw":functkw}
def quickFit(self,quiet=1):
qfp = self.quickFitPrep()
m = mpfit(Resonator.magDiffLin, qfp['p0'],
parinfo=qfp['parinfo'],
functkw=qfp['functkw'],
quiet=quiet)
return m
def resFitPrep(self):
self.quickFitPrep()
mQuick = self.quickFit()
qGuess = mQuick.params[0]
fGuess = mQuick.params[1]
dc = math.sqrt(self.xrc1**2 + self.yrc1**2)
ang1 = math.atan2(-self.yrc1 + self.Q[self.residx],
-self.xrc1 + self.I[self.residx])
width = len(self.dist1)/5
x = self.freq[self.residx-width:self.residx+width+1]*1e9
I = self.I[self.residx-width:self.residx+width+1]
Q = self.Q[self.residx-width:self.residx+width+1]
y = I + 1j*Q
yerr = self.Ierr[self.residx-width:self.residx+width+1] + \
1j*self.Qerr[self.residx-width:self.residx+width+1]
deltaAng = math.atan2(self.Q[self.residx+5]-self.yrc1,
self.I[self.residx+5]-self.xrc1)
ang = ang1 + deltaAng # perhaps this is a minus in resfit.pro
# Starting values and limits
parinfo = []
# 0 quality factor
parinfo.append({'value':qGuess, 'fixed':0, 'limited':[0,0],
'limits':[5000.0,1000001.0]})
deltaF = x[len(x)/5]-x[0]
f0 = fGuess*1e9 # 1 peak position in Hz
parinfo.append({'value':f0, 'fixed':0, 'limited':[0,0],
'limits':[f0-deltaF,f0+deltaF]})
aleak = 1.0 # 2
parinfo.append({'value':aleak, 'fixed':0, 'limited':[0,0],
'limits':[1e-4,100.0]})
phi1 = 800.0 # 3
parinfo.append({'value':phi1, 'fixed':0, 'limited':[0,0],
'limits':[1.0, 4e4]})
da = 500.0 # 4
parinfo.append({'value':da, 'fixed':0, 'limited':[0,0],
'limits':[-5000.0,5000.0]})
ang1 = ang # 5
parinfo.append({'value':ang1, 'fixed':0, 'limited':[0,0],
'limits':[-4*math.pi,4*math.pi]})
Igain = I.max()-I.min() # 6
parinfo.append({'value':Igain, 'fixed':0, 'limited':[0,0],
'limits':[0.2*Igain, 3.0*Igain]})
Qgain = Q.max()-Q.min() # 7
parinfo.append({'value':Qgain, 'fixed':0, 'limited':[0,0],
'limits':[0.2*Qgain, 3.0*Qgain]})
Ioff = float(self.xrc1) # 8
parinfo.append({'value':Qgain, 'fixed':0, 'limited':[0,0],
'limits':[self.xrc1-5000.0, self.xrc1+5000.0]})
Qoff = float(self.yrc1) # 9
parinfo.append({'value':Igain, 'fixed':0, 'limited':[0,0],
'limits':[self.yrc1-5000.0, self.yrc1+5000.0]})
db = 0.0 # 10
parinfo.append({'value':db, 'fixed':0, 'limited':[0,0],
'limits':[-100000000.0,10000000.0]})
p0 = np.array([qGuess,f0,aleak,phi1,da,ang1,Igain,Qgain,Ioff,Qoff,db],
dtype='float64')
functkw = {'x':x,'y':y,'err':yerr}
return {"p0":p0, "parinfo":parinfo,"functkw":functkw}
@staticmethod
def resModel(x, p):
"""
Value of the model at x
Copied from resfit.pro function RESDIFF, but in the .pro file the
difference is calculated in RESDIFF, but in this .py file
the difference is calculated in resDiffLin.
"""
Q = p[0] # Q
f0 = p[1] # resonance frequency
aleak = p[2] # amplitude of leakage
ph1 = p[3] # phase shift of leakage
da = p[4] # variation of carrier amplitude
ang1 = p[5] # Rotation angle of data
Igain = p[6] # Gain of I channel
Qgain = p[7] # Gain of Q channel
Ioff = p[8] # Offset of I channel
Qoff = p[9] # Offset of Q channel
db = p[10] #
dx = (x - f0) / f0
# resonance dip function
s21a = ((1j*2.0*Q*dx) / (1 + 1j*2.0*Q*dx)) - 0.5
s21b = (da*dx + db*dx*dx) + s21a + \
aleak*(1.0-np.cos(dx*ph1) - 1j*np.sin(dx*ph1))
# scale, rotate, and offset
Ix1 = Igain*s21b.real
Qx1 = Qgain*s21b.imag
nI1 = Ix1*math.cos(ang1) + Qx1*math.sin(ang1) + Ioff
nQ1 = -Ix1*math.sin(ang1) + Qx1*math.cos(ang1) + Qoff
s21 = nI1 + 1j*nQ1
return s21
@staticmethod
def resDiffLin(p, fjac=None, x=None, y=None, err=None):
# Parameter values are passed in "p"
# If fjac==None then partial derivatives should not be
# computed. It will always be None if MPFIT is called with default
# flag.
model = Resonator.resModel(x, p)
# Non-negative status value means MPFIT should continue,
# negative means stop the calculation.
status = 0
return [status, np.abs((y-model)/err)]
def resfit(self):
"""
implements logic of resfit.pro for this resonator
"""
rfp = self.resFitPrep()
x = rfp['functkw']['x']
y = rfp['functkw']['y']
err = rfp['functkw']['err']
p = rfp['p0']
parinfo = rfp['parinfo']
functkw = rfp['functkw']
m = mpfit(Resonator.resDiffLin, p, parinfo=parinfo,
functkw=functkw, quiet=1)
rdlFit = Resonator.resDiffLin(m.params,
fjac=None, x=x, y=y, err=err)
bestChi2 = np.power(rdlFit[1],2).sum()
bestIter = 0
parold = p.copy()
random.seed(y.sum())
bestPar = p.copy()
bestM = m
for k in range(1,12):
parnew = parold.copy()
parnew[0] = 20000 + 30000.0*random.random()
parnew[1] = parold[1] + 5000*random.gauss(0.0, 1.0)
parnew[2] = parold[2] + 0.2*parold[2]*random.gauss(0.0,1.0)
parnew[3] = parold[3] + 0.2*parold[3]*random.gauss(0.0,1.0)
parnew[4] = parold[4] + 5.0*parold[4]*random.gauss(0.0,1.0)
parnew[5] = parold[5] + 0.2*parold[5]*random.gauss(0.0,1.0)
parnew[6] = parold[6] + 0.5*parold[6]*random.gauss(0.0,1.0)
parnew[7] = parold[7] + 0.5*parold[7]*random.gauss(0.0,1.0)
parnew[8] = parold[8] + 0.5*parold[8]*random.gauss(0.0,1.0)
parnew[9] = parold[9] + 0.5*parold[9]*random.gauss(0.0,1.0)
m = mpfit(Resonator.resDiffLin, parnew, parinfo=parinfo,
functkw=functkw, quiet=1)
rdlFit = Resonator.resDiffLin(m.params,
fjac=None, x=x, y=y, err=err)
thisChi2 = np.power(rdlFit[1],2).sum()
if m.status > 0 and thisChi2 < bestChi2:
bestIter = k
bestChi2 = thisChi2
bestM = m
p = bestM.params
yFit = Resonator.resModel(x, bestM.params)
ndf = len(x) - len(bestM.params)
# size of loop from fit
radius = (p[6]+p[7])/4.0
# normalized diamter of the loop (off resonance = 1)
diam = (2.0*radius)/(math.sqrt(p[8]**2+p[9]**2) + radius)
Qc = p[0]/diam
Qi = p[0]/(1.0-diam)
dip = 1.0 - diam
try:
dipdb = 20.0*math.log10(dip)
except ValueError:
dipdb = -99
chi2Mazin = math.sqrt(bestChi2/ndf)
return {"m":bestM,"x":x,"y":y,"yFit":yFit,"chi2":bestChi2, "ndf":ndf,
"Q":p[0],"f0":p[1]/1e9, "Qc":Qc, "Qi":Qi, "dipdb":dipdb,
"chi2Mazin":chi2Mazin, "dip":dip}
def plot(self,rf,pdfPages):
plt.clf()
#plt.figure(figsize=(8,10.5))
fig,(ax1,ax2) = plt.subplots(2,1,figsize=(8,10.5))
y = rf['y']
ax1.plot(y.real,y.imag,"o", mfc="none")
#yFit = Resonator.resModel(rf['x'], rf['m'].params)
yFit = rf['yFit']
ax1.plot(yFit.real,yFit.imag)
ax1.axvline(linewidth=1,color='b',x=self.xrc1,linestyle=":")
ax1.axhline(linewidth=1,color='b',y=self.yrc1,linestyle=":")
xFormatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
ax2.xaxis.set_major_formatter(xFormatter)
mag = abs(y)
mag /= max(mag)
mag = 20*np.log10(mag)
magFit = abs(yFit)
magFit /= max(magFit)
magFit = 20 * np.log10(magFit)
freq = rf['x']/1e9
ax2.plot(freq,mag,'o',mfc='none')
ax2.plot(freq,magFit)
ax2.set_ylabel("S21 (db)")
ax2.set_xlabel("f(GHz)")
p = rf['m'].params
textstr = "Q=%.1f \n "%rf['Q']
textstr += "Qc=%.1f \n "%rf['Qc']
textstr += "Qi=%.1f \n "%rf['Qi']
textstr += "f0=%.6f GHz\n "%rf['f0']
textstr += "S21=%.1f db \n "%rf['dipdb']
textstr += "chi2mazin=%.1f "%rf['chi2Mazin']
props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)
ax2.text(0.95, 0.05, textstr, transform=ax2.transAxes, fontsize=14,
verticalalignment='bottom',
horizontalalignment='right',
bbox=props)
pdfPages.savefig()
plt.close()
| 13,694 | 39.04386 | 79 | py |
SDR | SDR-master/Setup/WideSweep/autofit.py | import numpy as np
from WideSweepFile import WideSweepFile
from Resonator import Resonator
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
import datetime
import argparse
import os
class autofit():
def __init__(self, wideSweepFileName, reslocFileName, logFileName):
self.logFile = open(logFileName,'wb')
self.wsf = WideSweepFile(wideSweepFileName)
self.res = np.loadtxt(reslocFileName)
self.n = self.res.shape[0]
def run(self,nToDo='all', width=50, plotFileName=None):
if plotFileName:
pdf = PdfPages(plotFileName)
else:
pdf = None
if nToDo == 'all': nToDo = self.n
for iToDo in range(nToDo):
ind = self.res[iToDo,1]
print "begin iToDo=",iToDo,' nToDo',nToDo,' centered at ind=',ind,' x=',self.wsf.x[ind]
indStart = max(0,self.res[iToDo,1]-width)
indEnd = min(len(self.wsf.x), self.res[iToDo,1]+width+1-10)
f = self.wsf.x[indStart:indEnd]
I = self.wsf.I[indStart:indEnd]
Ierr = self.wsf.Ierr[indStart:indEnd]
Q = self.wsf.Q[indStart:indEnd]
Qerr = self.wsf.Qerr[indStart:indEnd]
res = Resonator(f,I,Ierr,Q,Qerr)
rf = res.resfit()
line = "%4i %17.6f %17.2f %17.2f %17.2f %17.2f\n"%(iToDo,rf['f0'],rf['Q'],rf['Qi'],rf['Qc'],rf['chi2Mazin'])
self.logFile.write(line)
self.logFile.flush()
print line
res.plot(rf,pdf)
if pdf:
pdf.close()
self.logFile.close()
if __name__ == '__main__':
parser = \
argparse.ArgumentParser(description=
"Autofit peaks chosen in WideAna.py or WideAna.pro. Writes results to wideSweepFileName-autofit.pdf and .log",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('wideSweepFile',
help='file generated by SegmentedSweep.vi')
parser.add_argument('--reslocFile', default=None,
help='file generated by WideAna.py, defaults to wideSweepFile with "good" appended to the name')
if os.environ.has_key('MKID_DATA_DIR'):
dataDirDefault = os.environ['MKID_DATA_DIR']
else:
dataDirDefault = '.'
parser.add_argument('--dataDir', dest='dataDir', default=dataDirDefault,
help='location of data files')
parser.add_argument('--nToDo', dest='nToDo', default='all',
help='number of resonators to fit')
parser.add_argument('--width', dest='width', default=50,
help='number of data points around peak to use')
args = parser.parse_args()
print "args=",args
dataDir = args.dataDir
wideSweepFileName = os.path.join(args.dataDir,args.wideSweepFile)
print "wsfn=",wideSweepFileName
if args.reslocFile:
reslocFileName = os.path.join(args.dataDir,args.reslocFile)
else:
s = os.path.splitext(args.wideSweepFile)
reslocFileName = os.path.join(args.dataDir,s[0]+"-good"+s[1])
print "rlfn=",reslocFileName
plotFileName = os.path.splitext(wideSweepFileName)[0]+"-autofit.pdf"
logFileName = os.path.splitext(wideSweepFileName)[0]+"-autofit.log"
af = autofit(wideSweepFileName, reslocFileName, logFileName)
af.run(nToDo=args.nToDo, width=int(args.width), plotFileName=plotFileName)
| 3,468 | 44.051948 | 143 | py |
SDR | SDR-master/Setup/WideSweep/WideAna_ml.py | '''
Author Rupert Dodkins
A script to automate resonator locating normally performed by WideAna.py.
This is accomplished using Google's Tensor Flow machine learning package which
implements a pattern recognition algorithm on the spectrum. The code implements
a 2D image classification algorithm similar to the MNIST test. This code creates
a 2D image from a 1D variable by populating a matrix of zeros with ones at the
y location of each datapoint.
Usage: python WideAna_ml.py 20160418/Asteria_FL1_100mK_ws.txt
Inputs:
20160418/Asteria_FL1_100mK_ws.txt: transmission sweep across intire feedline
Intermediaries:
SDR/Setup/WideSweep/train_w<x>_c<y>.pkl: images and corresponding labels used
to train the algorithm
Outputs:
Asteria_FL1_100mK_ws-ml.txt: to be used with WideAna.py (temporary)
Asteria_FL1_100mK_ws-good.txt: to be used with autofit.py (made by WideAna.py)
How it works:
The script requires a series of images to train and test the algorithm with. If
they exist the image data will be loaded from a train pkl file
Alternatively, if the peak location data exist for the inference file the
training data will be made. The classes are no peak (just noise), peak in center
or peak off to the side. If the spectra has collisions then there is a fifth class
where the rightmost peak should be central and the colliding peak is left of center
These new image data will be saved as pkl files (or appened to existing pkl
files) and reloaded
The machine is then trained and its ability to predict the type of image is
validated
The weights used to make predictions for each class can be displayed using
the plotWeights function
A window the size of the training images scans across the inference
spectrum and the locations of peaks and collisions are identified and printed to
file. This can either be in the format read by autofit if the user believes all
the peaks have been found or loaded into WideAna.py and the remianing peaks can be
identified by hand
'''
from WideSweepFile import WideSweepFile
import WideAna as WideAna
import numpy as np
import sys, os, time, shutil
import matplotlib.pyplot as plt
import tensorflow as tf
import pickle
import random
from scipy import interpolate
np.set_printoptions(threshold=np.inf)
class mlClassification():
def __init__(self, inferenceFile=None, nClass = 5, xWidth=40):
'''
inputs
inferenceFile: the spectrum the user wishes to locate resonators in. If no
training pkl files exist this file is used to create training data
nClass: Can be either 4 or 5 depending on whether the window width is large
enough. If the window width is small, enough examples of collisions
are hard to come by in the training data and there wont be enough
of this class to match other classes
xWidth: The window size to make training data and scan on the inference
spectrum. ScalexWidth is an option later which allows the training data
with large widths to analyse small windows on the inference spectrum
'''
self.baseFile = ('.').join(inferenceFile.split('.')[:-1])
self.goodFile = self.baseFile + '-good.txt'
self.mlFile = self.baseFile + '-ml.txt'
self.wsf = WideSweepFile(inferenceFile) # use WideSweepFile to get access to the data in inferenceFile
self.wsf.fitFilter(wn=0.01)
self.wsf.findPeaks()
self.nClass = nClass # can be 4 (no collisions class)
self.xWidth = xWidth # the width of each frame in number of samples
self.trans = self.wsf.mag # transmission
self.trainFile = 'train_w%i_c%i.pkl' % (self.xWidth, self.nClass) # a collection of images of xWidth and associated class labels
rescaling_factor = 2 # rule of thumb adjustment to amplitudes of each frame so peaks take up more of the frame
self.yLims=[min(self.trans), max(self.trans)]
self.trainFrac = 0.8
self.testFrac=1 - self.trainFrac
self.trans_adjusted= self.trans-min(self.trans) # stretches, normalises and scales the amplitudes to fit on a 0-40 grid
self.trans_adjusted = np.round(self.trans_adjusted*rescaling_factor*self.xWidth/max(self.trans_adjusted) )
def makeWindowImage(self, xCenter=25, markers=True, scalexWidth=None, showFrames=False):
'''Using a given x coordinate a frame is created at that location of size xWidth x xWidth, and then flattened into a 1d array.
Called multiple times in each function.
inputs
xCenter: center location of frame in wavelength space
markers: lines to guide the eye when the frame is shown
scalexWidth: typical values: 1/2, 1/4, 1/8
uses interpolation to put data from an xWidth x xWidth grid to a
(xWidth/scalexWidth) x (xWidth/scalexWidth) grid. This allows the
user to probe the spectrum using a smaller window while utilizing
the higher resolution training data
showFrames: pops up a window of the frame plotted using matplotlib.plot (used with training)
'''
xWidth= self.xWidth # to save pulling from global memory all the time
if scalexWidth==None:
start = int(xCenter - xWidth/2)
end = int(xCenter + xWidth/2)
else:
start = int(xCenter - xWidth*scalexWidth/2) #can use a smaller window for finer detail and then scale the image later to fit training data
end = int(xCenter + xWidth*scalexWidth/2)
if end-start != xWidth*scalexWidth:
end=end+1
trans = self.trans_adjusted[start:end]
trans = map(int, np.array(trans) + (xWidth*4.5/5)-np.median(trans) ) # adjusts the height of the trans data to the median
if scalexWidth!=None:
x = np.arange(0, xWidth*scalexWidth+1)
trans = np.append(trans, trans[-1])
f = interpolate.interp1d(x, trans)
xnew = np.arange(0, xWidth*scalexWidth, scalexWidth)
trans = f(xnew)
image = np.zeros((xWidth, xWidth))
#creates an image of the spectrum
for i in range(xWidth-1):
if trans[i]>=xWidth: trans[i] = xWidth-1
if trans[i]<0: trans[i] = 0
if trans[i] < trans[i+1]:
image[int(trans[i]):int(trans[i+1]),i]=1
else:
image[int(trans[i]):int(trans[i-1]),i]=1
if trans[i] == trans[i+1]:
image[int(trans[i]),i]=1
try:
image[map(int,trans), range(xWidth)]=1
except IndexError:
pass
if showFrames:
fig = plt.figure(frameon=False)
fig.add_subplot(111)
plt.plot(self.wsf.x[start:end], self.trans[start:end])
if markers:
plt.axvline(self.wsf.x[(end-start)/4 + start], ls='dashed')
plt.axvline(self.wsf.x[end - (end-start)/4], ls='dashed')
self.yLims=[min(self.trans), max(self.trans)]
plt.ylim((self.yLims[0],self.yLims[1]))
plt.xlim((self.wsf.x[start],self.wsf.x[end]))
#plt.axis('off')
plt.show()
plt.close()
image = image.flatten()
return image
def makeTrainData(self, trainSteps=500):
'''creates images of each class with associated labels and saves to pkl file
0: no peak, just flat
1: the center of the peak is 1/3 of the way to the left of center
2: the center of the peak is center of the frame
3: like 1 but to the right
4: the center of the middle peak is in the middle of the frame and there is another peak somewhere to the left of that one
s: this image does not belong in the training dataset
inputs
trainSteps: how many total image does the user want to validate. testFrac adjusts what percentage are for testing
outputs
trainImages: cube of size- xWidth * xWidth * xCenters*trainFrac
trainLabels: 1d array of size- xCenters*trainFrac
testImages: cube of size- xWidth * xWidth * xCenters*testFrac
testLabels: 1d array of size- xCenters*testFrac
'''
self.yLims=[min(self.trans), max(self.trans)]
trainImages, trainLabels, testImages, testLabels = [], [], [], []
print self.goodFile
if os.path.isfile(self.goodFile):
print 'loading peak location data from %s' % self.goodFile
peaks = np.loadtxt(self.goodFile)[:,1]
else:
print 'using WideSweepFile.py to predict where the peaks are'
peaks = self.wsf.peaksDict['big']
peakDist = abs(np.roll(peaks, 1) - peaks)
colls_thresh = self.xWidth/2 # two peaks in one frame
colls = peaks[np.where( peakDist < colls_thresh)[0]]#9
random.shuffle(colls)
# to stop multiple peaks appearing in training data of classes 1-4
peaks = peaks[np.where( peakDist >= self.xWidth)[0]]
peakDist = abs(np.roll(peaks, 1) - peaks)
class_steps = trainSteps/self.nClass
if len(colls) < class_steps or self.nClass == 4:
print 'no 5th class or not enough collisions detected within the frame width to create one'
#colls_class = raw_input('Do you want to create one? [y/n]')
#if colls_class=='n':
colls=[]
self.nClass=4
self.trainFile = 'train_w%i_c%i.pkl' % (self.xWidth, self.nClass)
#colls = peaks # same criteria as centrals
noise = range(len(self.wsf.x)) # noise locations are randomly selected across array. Hopefully peaks
# can be located this way (and labeled as other classes) to remove any
# biases from widesweepfile peaks
lefts = peaks+self.xWidth/3
centrals = peaks
rights = peaks-self.xWidth/3
if os.path.isfile(self.goodFile):
noise= peaks[np.where( peakDist > self.xWidth*2)[0]]-self.xWidth # no need for random searches
xCenters = np.zeros((class_steps,self.nClass))
xCenters[:,0]=random.sample(noise, class_steps)
xCenters[:,1]=random.sample(lefts, class_steps)
xCenters[:,2]=random.sample(centrals, class_steps)
xCenters[:,3]=random.sample(rights, class_steps)
if self.nClass==5:
xCenters[:,4]=random.sample(noise, class_steps)
for i in range(self.nClass):
for j in range(int(self.trainFrac*class_steps) ):
image = self.makeWindowImage(xCenter=xCenters[j,i], showFrames=False)
trainImages.append(image)
one_hot = np.zeros(self.nClass)
one_hot[i] = 1
trainLabels.append(one_hot)
# A more simple way would be to separate the train and test data after they were read but this did not occur to me
#before most of the code was written
for i in range(self.nClass):
for j in range(int(self.trainFrac*class_steps), int(self.trainFrac*class_steps + self.testFrac*class_steps)) :
image = self.makeWindowImage(xCenter=xCenters[j,i], showFrames=False)
testImages.append(image)
one_hot = np.zeros(self.nClass)
one_hot[i] = 1
testLabels.append(one_hot)
else:
print 'No resonator location file found for this spectrum'
append = None
if os.path.isfile(self.trainFile):
append = raw_input('Do you want to append this training data to previous data [y/n]')
if (append == 'y') or (os.path.isfile(self.trainFile)== False):
print 'saving files %s & to %s' % (self.trainFile, os.path.dirname(os.path.abspath(self.trainFile)) )
with open(self.trainFile, 'ab') as tf:
pickle.dump([trainImages, trainLabels], tf)
pickle.dump([testImages, testLabels], tf)
return trainImages, trainLabels, testImages, testLabels
def mlClass(self):
'''
Code adapted from the tensor flow MNIST tutorial 1.
Using training images and labels the machine learning class (mlClass) "learns" how to identify peaks. Using similar data the ability
of mlClass to identify peaks is tested
The training and test matricies are loaded from file (those made earlier if chosen to not be appended to file will not be used)
'''
if os.path.isfile(self.trainFile):
trainImages, trainLabels, testImages, testLabels = loadPkl(self.trainFile)
else:
trainImages, trainLabels, testImages, testLabels = self.makeTrainData()
print 'Number of training images:', np.shape(trainImages)[0], ' Number of test images:', np.shape(testImages)[0]
if np.shape(trainImages)[1]!=self.xWidth**2:
print 'Please make new training images of the correct size'
exit()
self.nClass = np.shape(trainLabels)[1]
self.x = tf.placeholder(tf.float32, [None, self.xWidth**2]) # correspond to the images
self.W = tf.Variable(tf.zeros([self.xWidth**2, self.nClass])) #the weights used to make predictions on classes
self.b = tf.Variable(tf.zeros([self.nClass])) # the biases also used to make class predictions
self.y = tf.nn.softmax(tf.matmul(self.x, self.W) + self.b) # class lables predictions made from x,W,b
y_ = tf.placeholder(tf.float32, [None, self.nClass]) # true class lables identified by user
cross_entropy = -tf.reduce_sum(y_*tf.log(tf.clip_by_value(self.y,1e-10,1.0)) ) # find out how right you are by finding out how wrong you are
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) # the best result is when the wrongness is minimal
init = tf.initialize_all_variables()
self.sess = tf.Session()
self.sess.run(init) # need to do this everytime you want to access a tf variable (for example the true class labels calculation or plotweights)
trainReps = 500
batches = 100
if np.shape(trainLabels)[0]< batches:
batches = np.shape(trainLabels)[0]/2
print 'Performing', trainReps, 'training repeats, using batches of', batches
for i in range(trainReps): #perform the training step using random batches of images and according labels
batch_xs, batch_ys = next_batch(trainImages, trainLabels, batches)
self.sess.run(train_step, feed_dict={self.x: batch_xs, y_: batch_ys}) #calculate train_step using feed_dict
print 'true class labels: ', self.sess.run(tf.argmax(y_,1), feed_dict={self.x: testImages, y_: testLabels})[:25] #argmax finds the index with the max label value
print 'class estimates: ', self.sess.run(tf.argmax(self.y,1), feed_dict={self.x: testImages, y_: testLabels})[:25] #1st 25 printed
#print self.sess.run(self.y, feed_dict={self.x: testImages, y_: testLabels})[:100] # print the scores for each class
correct_prediction = tf.equal(tf.argmax(self.y,1), tf.argmax(y_,1)) #which ones did it get right?
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
score = self.sess.run(accuracy, feed_dict={self.x: testImages, y_: testLabels}) * 100
print 'Accuracy of model in testing: ', score, '%'
if score < 95: print 'Consider making more training images'
del trainImages, trainLabels, testImages, testLabels
def plotWeights(self):
'''creates a 2d map showing the positive and negative weights for each class'''
weights = self.sess.run(self.W)
weights = np.reshape(weights,(self.xWidth,self.xWidth,self.nClass))
weights = np.flipud(weights)
for nc in range(self.nClass):
plt.imshow(weights[:,:, nc])
plt.title('class %i' % nc)
plt.show()
plt.close()
def findPeaks(self, inferenceFile, scalexWidth=None, steps =50, start=0, searchWholeSpec=False, useWideAna=True, multi_widths=False):
'''The trained machine learning class (mlClass) finds peaks in the inferenceFile spectrum
inputs
inferenceFile: widesweep data file to be used
scalexWidth: allows a smaller/finer window to search spectrum without loss of resolution that comes with smaller window sizes
this variable, if set to a number, will act as a multiplication factor for self.xWidth e.g: 0.5 or 0.25
adds to computation time (maybe 4x longer for 0.25)
searchWholeSpec: if only a few peaks need to be identified set to False
steps: if searchWhileSpec is False, the number of frames (numer of center values in centers)
start: if searchWhileSpec is False, the starting point of the frames (first center value in centers)
useWideAna: if true once all the peaks have been located these values are fed into WideAna which opens
the window where the user can manually check all the peaks have been found and make corrections if neccessary
outputs
Goodfile: either immediately after the peaks have been located or through WideAna if useWideAna =True
mlFile: temporary file read in to WideAna.py containing peak indicies
*had some issues running WideAna at the end of this script on ubuntu 14.04 and matplotlib-1.5.1 backend 'Qt4Agg'
after running matplotlib.show(). Sometimes I received a segmentation fault
'''
try:
self.sess
except AttributeError:
print 'You have to train the model first'
exit()
self.inferenceFile = inferenceFile
self.wsf = WideSweepFile(inferenceFile)
self.wsf.fitFilter(wn=0.01)
self.wsf.findPeaks()
#the center of each frame. xWidth wide, translated xWidth/20 from the previous
if scalexWidth != None:
xMove = float(self.xWidth*scalexWidth)/40 #1
centers = np.arange(self.xWidth*scalexWidth/2,len(self.wsf.x)-self.xWidth*scalexWidth/2, xMove )
else:
xMove = float(self.xWidth)/40 #1
centers = np.arange(self.xWidth/2,len(self.wsf.x)-self.xWidth/2, xMove )
centers = [int(c) for c in centers]
print len(self.wsf.x)
if searchWholeSpec:
steps = len(centers)
start=0
span = range(start, steps+start)
self.inferenceLabels = np.ones((steps,self.nClass))
print 'Using trained algorithm on images across the inference spectrum'
for i,c in enumerate(span):
inferenceImage=[]
# print how many frames remain to be studied inline
sys.stdout.write("\r%d of %i" % (i+1,steps) )
sys.stdout.flush()
# each image is formatted into a single element of a list so sess.run can receive a single values dictionary argument
# and save memory
image = self.makeWindowImage(xCenter=centers[c], scalexWidth=scalexWidth, showFrames=False)
# inferenceImage is just reformatted image
inferenceImage.append(image)
self.inferenceLabels[i,:] = self.sess.run(self.y, feed_dict={self.x: inferenceImage} )
del inferenceImage
del image
print '\n'
stdLabels = np.argmax(self.inferenceLabels, 1)
scores = np.zeros((len(stdLabels)))
# peaks is an array of positive peak identification locations
peaks = np.where(np.logical_or(stdLabels ==2, stdLabels ==4) )
# turn peaks into a list of lists of adjacent peak locations
peaks = np.split(peaks[0], np.where(np.diff(peaks[0]) >= 5)[0]+1)
#peakLocations takes the middle value of adjacent positive peak identifications in peaks
peakLocations=[]
if len(peaks[0]) == 0:
print 'No peaks found in search range'
peakLocations = None
else:
for p in peaks:
if len(p)>3:
p = np.array(p)
centers = np.array(centers)
min_location = np.argmin(self.wsf.mag[centers[p]])
middle = (p[0]+p[len(p)-1]) /2
peakLocations.append(p[min_location])
centers = np.array(centers)
peak_dist = abs(np.roll(centers[peakLocations], -1) - centers[peakLocations])
diff, coll_thresh = 0, 0
while diff <= 5e-4:
diff = self.wsf.x[coll_thresh]-self.wsf.x[0]
coll_thresh += 1
#remove collisions (peaks < 0.5MHz apart). This is also done in WideAna.py
if useWideAna:
collisions = np.delete(peakLocations,np.where(peak_dist>=coll_thresh))
else:
#peakLocations = np.delete(peakLocations,np.where(dist<50))
collisions = []
for i in range(len(peakLocations)):
if peak_dist[i]<coll_thresh:
if self.wsf.mag[centers[peakLocations[i+1]]] - self.wsf.mag[centers[peakLocations[i]]] > 1.5:
collisions.append(centers[peakLocations[i+1]])
else:
collisions.append(centers[peakLocations[i]])
peakLocations = np.delete(peakLocations,collisions)
if not multi_widths:
plt.plot(centers[start:start+steps], self.wsf.mag[centers[start:start+steps]])#- self.wsf.baseline[centers[start:start+steps]]) self.wsf.x[centers...]
if peakLocations != []:
for pl in peakLocations:
plt.axvline(centers[pl+start], color='r')
for c in collisions:
plt.axvline(centers[c+start], color='g')
plt.show()
plt.close()
print 'Number of resonators located:', len(peakLocations)
print 'Number of collisions', len(collisions)
# append the peak locations from each window width to this global variable
if multi_widths:
global mw_peakLocations
mw_peakLocations= np.concatenate((mw_peakLocations,centers[map(lambda x: x+start, peakLocations)]))
#remove collisions during each successive run to avoid a build up identifications at near collisions
mw_peakLocations = np.sort(mw_peakLocations)
mw_peakLocations = map(int,mw_peakLocations)
peak_dist = abs(np.roll(mw_peakLocations, -1) - mw_peakLocations)
collisions = []
for i in range(len(mw_peakLocations)-1):
if peak_dist[i]<=3:
if self.wsf.mag[mw_peakLocations[i]] <= self.wsf.mag[mw_peakLocations[i+1]]:
collisions.append(i)
else:
collisions.append(i+1)
#mw_peakLocations = np.delete(mw_peakLocations,np.where(peak_dist<3))
mw_peakLocations = np.delete(mw_peakLocations,collisions)
if useWideAna:
# if file exists rename it with the current time
if os.path.isfile(self.mlFile):
self.mlFile = self.mlFile+time.strftime("-%Y-%m-%d-%H-%M-%S")
#shutil.copy(self.mlFile, self.mlFile+time.strftime("-%Y-%m-%d-%H-%M-%S"))
mlf = open(self.mlFile,'wb') #mlf machine learning file is temporary
if peakLocations != []:
if multi_widths:
peakLocations =mw_peakLocations
peakLocations = np.sort(peakLocations)
for pl in peakLocations:
line = "%12d\n" % pl# just peak locations
mlf.write(line)
else:
for pl in peakLocations:
line = "%12d\n" % centers[pl+start] # just peak locations
mlf.write(line)
mlf.close()
#on ubuntu 14.04 and matplotlib-1.5.1 backend 'Qt4Agg' running matplotlib.show() prior to this causes segmentation fault
WideAna.main(initialFile=self.inferenceFile)
os.remove(self.mlFile)
else:
gf = open(self.goodFile,'wb')
id = 0
if peakLocations != []:
for pl in peakLocations:
line = "%8d %12d %16.7f\n"%(id,centers[pl]+start,self.wsf.x[centers[pl]])
gf.write(line)
id += 1
gf.close()
def next_batch(trainImages, trainLabels, batch_size):
'''selects a random batch of batch_size from trainImages and trainLabels'''
perm = random.sample(range(len(trainImages)), batch_size)
trainImages = np.array(trainImages)[perm,:]
trainLabels = np.array(trainLabels)[perm,:]
return trainImages, trainLabels
def loadPkl(filename):
'''load the train and test data to train and test mlClass
pkl file hirerachy is as follows:
-The file is split in two, one side for train data and one side for test data
-These halfs are further divdided into image data and labels
-makeTrainData creates image data of size: xWidth * xWidth * xCenters and the label data of size: xCenters
-each time makeTrainData is run a new image cube and label array is created and appended to the old data
so the final size of the file is (xWidth * xWidth * res_nums * "no of train runs") + (res_nums * "no of train runs") +
[the equivalent test data structure]
A more simple way would be to separate the train and test data after they were read but this did not occur to the
author before most of the code was written
input
pkl filename to be read. Can be either train or test data
outputs
image cube and label array
'''
file =[]
with open(filename, 'rb') as f:
while 1:
try:
file.append(pickle.load(f))
except EOFError:
break
trainImages = file[0][0]
trainLabels = file[0][1]
testImages = file[1][0]
testLabels = file[1][1]
if np.shape(file)[0]/2 > 1:
for i in range(1, np.shape(file)[0]/2-1):
trainImages = np.append(trainImages, file[2*i][0], axis=0)
trainLabels = np.append(trainLabels, file[2*i][1], axis=0)
testImages = np.append(testImages, file[2*i+1][0], axis=0)
testLabels = np.append(testLabels, file[2*i+1][1], axis=0)
print "loaded dataset from ", filename
return trainImages, trainLabels, testImages, testLabels
def main(inferenceFile=None, xWidth=80, nClass=4, scalexWidth=1./2, useWideAna =True, multi_widths=False):
mlClass = mlClassification(inferenceFile=inferenceFile, xWidth=xWidth, nClass=nClass)
#mlClass.makeTrainData(trainSteps =100)
mlClass.mlClass()
#mlClass.plotWeights()
mlClass.findPeaks(inferenceFile, scalexWidth=scalexWidth, searchWholeSpec=True, useWideAna=useWideAna, multi_widths=multi_widths)# 35200
def multi_widths(xWidths = [80,80,80], nClasses=[4,4,4], scalexWidths = [None,1./2,1./4]):
'''Runs the main functions multiple times with different window sizes to catch peaks of various
Q factors. This is especially useful if there is a large variation in Q throughout spectrum'''
global mw_peakLocations
mw_peakLocations= np.array([])
for mw in range(len(xWidths)):
print 'Searching for peaks using a model with xWidth=%s, xWidth interpolation scaling=%s, and %s peak classes' % (xWidths[mw],scalexWidths[mw],nClasses[mw])
if mw == len(xWidths)-1:
useWideAna = True
else:
useWideAna = False
main(inferenceFile=inferenceFile, xWidth = xWidths[mw], nClass = nClasses[mw], scalexWidth=scalexWidths[mw], useWideAna= useWideAna, multi_widths=True)
if __name__ == "__main__":
inferenceFile= None
if len(sys.argv) > 1:
mdd = os.environ['MKID_DATA_DIR']
inferenceFile = os.path.join(mdd,sys.argv[1])
else:
print "need to specify a filename located in MKID_DATA_DIR"
exit()
#main(inferenceFile=inferenceFile)
multi_widths() | 28,724 | 45.631494 | 169 | py |
SDR | SDR-master/Setup/WideSweep/makeRoachConfig.py | import os
import numpy as np
"""
write the roachConfig.txt file
"""
datadir = os.environ['MKID_DATA_DIR']
# here is a list of the number of roaches per feed line
rpfList = np.array(os.environ['MKID_NROACHES'].split(),dtype=np.int)
outfile = os.path.join(datadir,'roachConfig.txt')
print "Now create ",outfile
roachConfigFile=open(outfile,'w') # start a fresh file each time (not append)
for iFeedLine in range(len(rpfList)):
fn = "FL%d-lofreqs.txt"%(iFeedLine+1)
print "iFeedLine=",iFeedLine," fn=",fn
# np.loadtxt does not return a list if the file has only one line
#fl=np.loadtxt(os.path.join(datadir,fn))
file = open(os.path.join(datadir,fn))
fl = file.readlines()
for i,lo in enumerate(fl):
roachConfigFile.write('%f\t 10\n'%float(lo))
roachConfigFile.close()
| 806 | 30.038462 | 77 | py |
SDR | SDR-master/Setup/WideSweep/test/TestMpfit.py | from numpy.testing import *
import numpy as N
import copy
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from mpfit import mpfit
def Flin(x,p):
y = p[0] -p[1]*x
return y
def myfunctlin(p, fjac=None, x=None, y=None, err=None):
# Parameter values are passed in "p"
# If fjac==None then partial derivatives should not be
# computed. It will always be None if MPFIT is called with default
# flag.
model = Flin(x, p)
# Non-negative status value means MPFIT should continue, negative means
# stop the calculation.
status = 0
return [status, (y-model)/err]
def test_linfit():
x=N.array([-1.7237128E+00,1.8712276E+00,-9.6608055E-01,
-2.8394297E-01,1.3416969E+00,1.3757038E+00,
-1.3703436E+00,4.2581975E-02,-1.4970151E-01,
8.2065094E-01])
y=N.array([1.9000429E-01,6.5807428E+00,1.4582725E+00,
2.7270851E+00,5.5969253E+00,5.6249280E+00,
0.787615,3.2599759E+00,2.9771762E+00,
4.5936475E+00])
ey=0.07*N.ones(y.shape,dtype='float64')
p0=N.array([1.0,1.0],dtype='float64') #initial conditions
pactual=N.array([3.2,1.78]) #actual values used to make data
parbase={'value':0., 'fixed':0, 'limited':[0,0], 'limits':[0.,0.]}
parinfo=[]
for i in range(len(pactual)):
parinfo.append(copy.deepcopy(parbase))
for i in range(len(pactual)):
parinfo[i]['value']=p0[i]
fa = {'x':x, 'y':y, 'err':ey}
m = mpfit(myfunctlin, p0, parinfo=parinfo,functkw=fa)
if (m.status <= 0):
print 'error message = ', m.errmsg
assert N.allclose(m.params,N.array([ 3.20996572, -1.7709542 ],dtype='float64'))
assert N.allclose(m.perror,N.array([ 0.02221018, 0.01893756],dtype='float64'))
chisq=(myfunctlin(m.params, x=x, y=y, err=ey)[1]**2).sum()
assert N.allclose(N.array([chisq],dtype='float64'),N.array([2.756284983],dtype='float64'))
assert m.dof==8
return
def myfunctrosenbrock(p, fjac=None):
# rosenbrock function
res = N.array([1-p[0],-(1-p[0]),10*(p[1]-p[0]**2),-10*(p[1]-p[0]**2)])
status = 0
return [status, res]
def test_rosenbrock():
p0=N.array([-1,1.],dtype='float64') #initial conditions
pactual=N.array([1.,1.]) #actual minimum of the rosenbrock function
m = mpfit(myfunctrosenbrock, p0)
if (m.status <= 0):
print 'error message = ', m.errmsg
assert m.status > 0
assert N.allclose(m.params,pactual)
assert N.allclose(m.fnorm,0)
return
if __name__ == "__main__":
run_module_suite()
| 2,520 | 30.911392 | 94 | py |
SDR | SDR-master/Setup/WideSweep/test/TestResonator.py | import sys,os
import unittest
import numpy as np
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from Resonator import Resonator
from mpfit import mpfit
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
class TestResonator(unittest.TestCase):
"""
Test data copied from IDL session running autfit-pro with input
file FL2-right.txt, for the first resonator found
"""
def testQuickFit(self):
f = np.loadtxt("resonatorTestQIMA.txt", usecols=(1,))
I = np.loadtxt("resonatorTestQIMA.txt", usecols=(2,))
Ierr = 0.001*np.ones(len(I))
Q = np.loadtxt("resonatorTestQIMA.txt", usecols=(3,))
Qerr = 0.001*np.ones(len(Q))
res = Resonator(f,I,Ierr, Q, Qerr)
mag = np.loadtxt("resonatorTestQIMA.txt", usecols=(4,))
phase = np.loadtxt("resonatorTestQIMA.txt", usecols=(5,))
for j in range(len(I)):
self.assertAlmostEqual(I[j],res.I[j])
self.assertAlmostEqual(Q[j],res.Q[j])
self.assertAlmostEqual(mag[j],res.mag[j],places=5)
self.assertAlmostEqual(phase[j],res.phase[j],places=6)
dist1 = np.loadtxt("resonatorTestDist1.txt", usecols=(1,))
for j in range(len(res.dist1)):
self.assertAlmostEqual(res.dist1[j],dist1[j], places=6)
self.assertEquals(len(res.dist1),len(dist1))
self.assertEquals(50, res.residx)
self.assertAlmostEquals(-0.35312287, res.xrc1)
self.assertAlmostEquals(5.9134903, res.yrc1, places=6)
m = res.quickFit()
print m.params
# The values from the idl version are similar, but not too close
idl = [34093.219, 2.8350927, 0.11120927, 0.76291197,
3993.5131, 0.0000000, 0.0000000]
self.assertAlmostEqual(m.params[0]/idl[0],0.7965, places=4)
self.assertAlmostEqual(m.params[1]/idl[1],1, places=5)
self.assertAlmostEqual(m.params[2]/idl[2],1.239136, places=5)
self.assertAlmostEqual(m.params[3]/idl[3],1.035355, places=5)
self.assertAlmostEqual(m.params[4]/idl[4],0.202167, places=5)
def testMagModel(self):
f = np.loadtxt("resonatorTestQIMA.txt", usecols=(1,))
I = np.loadtxt("resonatorTestQIMA.txt", usecols=(2,))
Ierr = 0.001*np.ones(len(I))
Q = np.loadtxt("resonatorTestQIMA.txt", usecols=(3,))
Qerr = 0.001*np.ones(len(Q))
res = Resonator(f,I,Ierr,Q,Qerr)
qfp = res.quickFitPrep()
x = qfp['functkw']['x']
p = qfp['p0']
yModel = Resonator.magModel(x,p)
yData = qfp['functkw']['y']
err = qfp['functkw']['err']
mdl = Resonator.magDiffLin(p, fjac=None, x=x, y=yData, err=err)
chi2 = np.power(mdl[1],2).sum()
print "chi2=",chi2
parinfo = qfp['parinfo']
functkw = qfp['functkw']
m = mpfit(Resonator.magDiffLin, p, parinfo=parinfo, functkw=functkw, quiet=1)
print "m=",m
pFit = m.params
yFit = Resonator.magModel(x,pFit)
plt.clf()
plt.plot(x,yData,label="data")
plt.plot(x,yModel,label="first guess model")
plt.plot(x,yFit,label="fit model")
plt.legend(loc='lower right')
title="Q=%.1f f0=%.5f carrier=%.3f depth=%.2f \n slope=%.1f curve=%.1f w=%.1f"%tuple(pFit.tolist())
plt.title(title)
plt.savefig("testMagModel.png")
def testResModel(self):
f = np.loadtxt("resonatorTestQIMA.txt", usecols=(1,))
I = np.loadtxt("resonatorTestQIMA.txt", usecols=(2,))
Ierr = 0.001*np.ones(len(I))
Q = np.loadtxt("resonatorTestQIMA.txt", usecols=(3,))
Qerr = 0.001*np.ones(len(Q))
res = Resonator(f,I,Ierr,Q,Qerr)
rfp = res.resFitPrep()
x = rfp['functkw']['x']
p = rfp['p0']
yModel = Resonator.resModel(x,p)
yData = rfp['functkw']['y']
err = rfp['functkw']['err']
rdl = Resonator.resDiffLin(p, fjac=None, x=x, y=yData, err=err)
chi2 = np.power(rdl[1],2).sum()
print "chi2=",chi2
parinfo = rfp['parinfo']
functkw = rfp['functkw']
m = mpfit(Resonator.resDiffLin, p, parinfo=parinfo, functkw=functkw, quiet=1)
pFit = m.params
rdlFit = Resonator.resDiffLin(pFit, fjac=None, x=x, y=yData, err=err)
chi2Fit = np.power(rdlFit[1],2).sum()
print "chi2Fit=",chi2Fit
yFit = Resonator.resModel(x,pFit)
plt.clf()
print "xrc1,yrc1=",res.xrc1,res.yrc1
plt.plot(yData.real,yData.imag,"o",mfc='none',label="data")
#plt.plot(yData.real[0],yData.imag[0],"+",label="first data")
#plt.plot(yModel.real,yModel.imag,label="model")
#plt.plot(yModel.real[0],yModel.imag[0],"o",label="first model")
plt.plot(yFit.real,yFit.imag,label="fit")
#plt.plot(yFit.real[0],yFit.imag[0],"o",label="first fit")
#plt.legend(loc='center')
#title="Q=%.1f f0=%.5f carrier=%.3f depth=%.2f \n slope=%.1f curve=%.1f w=%.1f"%tuple(pFit.tolist())
#plt.title(title)
plt.axvline(linewidth=1,color='b',x=res.xrc1,linestyle=":")
plt.axhline(linewidth=1,color='b',y=res.yrc1,linestyle=":")
plt.axes().set_aspect('equal')
plt.savefig("testResModel.png")
def testResfit(self):
pdfPages = PdfPages("testResfit.pdf")
f = np.loadtxt("resonatorTestQIMA.txt", usecols=(1,))
I = np.loadtxt("resonatorTestQIMA.txt", usecols=(2,))
Ierr = 0.001*np.ones(len(I))
Q = np.loadtxt("resonatorTestQIMA.txt", usecols=(3,))
Qerr = 0.001*np.ones(len(Q))
res = Resonator(f,I,Ierr,Q,Qerr)
rf = res.resfit()
res.plot(rf,pdfPages)
pdfPages.close()
if __name__ == '__main__':
unittest.main()
| 5,807 | 40.191489 | 108 | py |
SDR | SDR-master/Setup/WideSweep/test/TestPeaks.py | import unittest
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import Peaks as Peaks
import numpy as np
class TestPeaks(unittest.TestCase):
def testPeaks(self):
peaks = [10,56]
n = np.random.normal(100.0, 1.0,100)
for peak in peaks:
n[peak] = 500
p = Peaks.peaks(n,2)
print "p=",p
if __name__ == '__main__':
unittest.main()
| 419 | 20 | 62 | py |
SDR | SDR-master/Setup/WideSweep/test/TestWideSweepFile.py | import unittest
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from WideSweepFile import WideSweepFile
import matplotlib.pyplot as plt
class TestWideSweepFile(unittest.TestCase):
def testWsf(self):
fileName = 'ucsb_100mK_24db_1.txt'
wsf = WideSweepFile(fileName)
wsf.fitSpline()
wsf.findPeaks()
fig,ax = plt.subplots(2)
ax[0].plot(wsf.x,wsf.mag,label='mag')
ax[0].set_xlabel("frequency")
ax[0].set_ylabel("magnitude")
ax[0].legend()
ax[1].plot(wsf.x,wsf.mag,label='mag')
ax[1].set_xlabel("frequency")
ax[1].set_ylabel("magnitude")
ax[1].legend().get_frame().set_alpha(0.5)
xmin = 5.0
xmax = 5.012
ax[1].set_xlim(xmin, xmax)
for peak in wsf.peaks:
x = wsf.x[peak]
if x > xmin and x < xmax:
ax[1].axvline(x=x,color='r')
plt.savefig("testWsf.png")
def testWsf2(self):
fileName = 'ucsb_100mK_24db_1.txt'
wsf = WideSweepFile(fileName)
var = wsf.mag.var()
m = len(wsf.mag)
#splineS = m*var/20.0
#print "var,m,splineS=",var,m,splineS
#splineK = 5
#wsf.fitSpline(splineS=splineS,splineK=splineK)
wn = 0.01
wsf.fitFilter(wn=wn)
m = 2
wsf.findPeaks(m=m)
fig,ax = plt.subplots(2)
ax[0].plot(wsf.x,wsf.mag,label='mag')
ax[0].plot(wsf.x,wsf.baseline,label='baseline')
ax[0].set_xlabel("frequency")
ax[0].set_ylabel("magnitude")
ax[0].legend()
xmin = 3.25
xmax = 3.27
ax[0].set_xlim(xmin, xmax)
for peak in wsf.peaks:
x = wsf.x[peak]
if x > xmin and x < xmax:
ax[0].axvline(x=x,color='r')
ax[0].set_title("filter wn=%f findPeaks m=%f"%(wn,m))
ax[1].plot(wsf.x,wsf.mag,label='mag')
ax[1].plot(wsf.x,wsf.baseline,label='baseline')
ax[1].set_xlabel("frequency")
ax[1].set_ylabel("magnitude")
ax[1].legend().get_frame().set_alpha(0.5)
xmin = 5.0
xmax = 5.012
ax[1].set_xlim(xmin, xmax)
for peak in wsf.peaks:
x = wsf.x[peak]
if x > xmin and x < xmax:
ax[1].axvline(x=x,color='r')
plt.savefig("testWsf2.png")
def testFilter(self):
fileName = 'ucsb_100mK_24db_1.txt'
wsf = WideSweepFile(fileName)
wsf.filter()
fig,ax = plt.subplots()
ax.plot(wsf.x,wsf.mag,label='mag')
ax.plot(wsf.x,wsf.filtered,label='filtered')
xmin = 3.2
xmax = 3.4
ax.set_xlim(xmin,xmax)
ax.legend().get_frame().set_alpha(0.5)
plt.savefig("testFilter.png")
def testFilter2(self):
fileName = 'ucsb_100mK_24db_1.txt'
wsf = WideSweepFile(fileName)
fig,ax = plt.subplots()
ax.plot(wsf.x,wsf.mag,label='mag')
wsf.fitFilter(wn=0.1)
ax.plot(wsf.x,wsf.baseline,label='filtered baseline wn=0.1')
wsf.fitFilter(wn=0.5)
ax.plot(wsf.x,wsf.baseline,label='filtered baseline wn=0.5')
wsf.fitSpline()
ax.plot(wsf.x,wsf.baseline,label='spline baseline')
xmin = 3.293
xmax = 3.294
ax.set_xlim(xmin,xmax)
ax.legend().get_frame().set_alpha(0.5)
plt.savefig("testFilter2.png")
def testFits(self):
fileName = 'ucsb_100mK_24db_1.txt'
wsf = WideSweepFile(fileName)
fig,ax = plt.subplots()
ax.plot(wsf.x,wsf.mag,label='mag')
for wn in [0.001, 0.01, 0.1]:
wsf.fitFilter(wn=wn)
ax.plot(wsf.x,wsf.baseline,label='filtered baseline wn=%0.3f'%wn)
wsf.fitSpline()
ax.plot(wsf.x,wsf.baseline,label='spline baseline')
#xmin = 3.356
#xmax = 3.357
xmin = 3.25
xmax = 3.27
ax.set_xlim(xmin,xmax)
ax.legend().get_frame().set_alpha(0.5)
plt.savefig("testFits.png")
def testFindPeaksThreshold(self):
fileName = 'ucsb_100mK_24db_1.txt'
threshSigma = 5
wsf = WideSweepFile(fileName)
wn = 0.010
wsf.fitFilter(wn=0.5)
values = wsf.mag-wsf.baseline
plt.plot(wsf.x,values,label="filtered with wn=%0.3f"%wn)
xmin = 3.25
xmax = 3.27
plt.xlim(xmin,xmax)
plt.legend().get_frame().set_alpha(0.5)
plt.savefig("testFindPeaksThreshold.png")
#wsf.findPeaksThreshold(threshSigma=threshSigma)
#plt.figure()
#plt.plot(wsf.fptCenters, wsf.fptHg[0])
#plt.yscale("symlog", linthreshy=0.1)
#plt.axvline(wsf.fptAverage, c="red", ls=":")
#plt.axvline(wsf.fptAverage-threshSigma*wsf.fptStd, c="green", ls="--")
#plt.savefig("testFpt-hg.png")
def testFitSpline(self):
fileName = 'ucsb_100mK_24db_1.txt'
wsf = WideSweepFile(fileName)
plt.plot(wsf.x,wsf.mag,label='mag')
for splineS in [1,0.9,0.5,0.3]:
wsf.fitSpline(splineS=splineS)
plt.plot(wsf.x,wsf.baseline,label='s=%f'%splineS)
xmin = 3.25
xmax = 3.27
plt.xlim(xmin,xmax)
plt.legend().get_frame().set_alpha(0.5)
plt.savefig("testFitSpline.png")
def testCreatePdf(self):
fileName = 'ucsb_100mK_24db_1.txt'
wsf = WideSweepFile(fileName)
wsf.createPdf('ucsb_100mK_24db_1-good.pdf')
if __name__ == '__main__':
unittest.main()
| 5,514 | 28.972826 | 79 | py |
SDR | SDR-master/Setup/WideSweep/test/TestAutofit.py | import unittest
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from autofit import autofit
import matplotlib.pyplot as plt
class TestAutofit(unittest.TestCase):
def testAutofit(self):
# This is the wide sweep file, generated by the labview program
# SegmentedSweep
wsfn = '20131016adr/FL2.txt'
# This is the approximate resonance location file, generated by
# WideAna.pro or WideAna.py
rlfn = '20131016adr/FL2-right.txt'
af = autofit(wsfn,rlfn)
af.run(1,plotFileName="testAutofit.pdf")
if __name__ == '__main__':
unittest.main()
| 637 | 26.73913 | 71 | py |
SDR | SDR-master/Setup/WideSweep/libs/PSFit_GUI.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'PSFit_GUI.ui'
#
# Created: Sun Jul 24 13:04:12 2011
# by: PyQt4 UI code generator 4.8.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(915, 1010)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.plot_1 = MPL_Widget(self.centralwidget)
self.plot_1.setGeometry(QtCore.QRect(20, 10, 891, 311))
self.plot_1.setObjectName(_fromUtf8("plot_1"))
self.plot_2 = MPL_Widget(self.centralwidget)
self.plot_2.setGeometry(QtCore.QRect(20, 330, 891, 331))
self.plot_2.setObjectName(_fromUtf8("plot_2"))
self.plot_3 = MPL_Widget(self.centralwidget)
self.plot_3.setGeometry(QtCore.QRect(290, 660, 391, 301))
self.plot_3.setObjectName(_fromUtf8("plot_3"))
self.frequency = QtGui.QLabel(self.centralwidget)
self.frequency.setGeometry(QtCore.QRect(790, 760, 62, 17))
self.frequency.setObjectName(_fromUtf8("frequency"))
self.atten = QtGui.QSpinBox(self.centralwidget)
self.atten.setGeometry(QtCore.QRect(770, 790, 61, 31))
self.atten.setObjectName(_fromUtf8("atten"))
self.label = QtGui.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(710, 760, 71, 17))
self.label.setObjectName(_fromUtf8("label"))
self.savevalues = QtGui.QPushButton(self.centralwidget)
self.savevalues.setGeometry(QtCore.QRect(730, 870, 131, 41))
self.savevalues.setObjectName(_fromUtf8("savevalues"))
self.label_2 = QtGui.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(710, 730, 91, 17))
self.label_2.setObjectName(_fromUtf8("label_2"))
self.res_num = QtGui.QLabel(self.centralwidget)
self.res_num.setGeometry(QtCore.QRect(810, 730, 62, 17))
self.res_num.setObjectName(_fromUtf8("res_num"))
self.open_browse = QtGui.QPushButton(self.centralwidget)
self.open_browse.setGeometry(QtCore.QRect(20, 700, 114, 32))
self.open_browse.setObjectName(_fromUtf8("open_browse"))
self.open_filename = QtGui.QLineEdit(self.centralwidget)
self.open_filename.setGeometry(QtCore.QRect(20, 740, 261, 22))
self.open_filename.setObjectName(_fromUtf8("open_filename"))
self.save_browse = QtGui.QPushButton(self.centralwidget)
self.save_browse.setGeometry(QtCore.QRect(20, 780, 114, 32))
self.save_browse.setObjectName(_fromUtf8("save_browse"))
self.save_filename = QtGui.QLineEdit(self.centralwidget)
self.save_filename.setGeometry(QtCore.QRect(20, 820, 261, 22))
self.save_filename.setObjectName(_fromUtf8("save_filename"))
self.label_3 = QtGui.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(710, 800, 62, 17))
self.label_3.setObjectName(_fromUtf8("label_3"))
self.jumptores = QtGui.QPushButton(self.centralwidget)
self.jumptores.setGeometry(QtCore.QRect(690, 686, 111, 41))
self.jumptores.setObjectName(_fromUtf8("jumptores"))
self.jumptonum = QtGui.QSpinBox(self.centralwidget)
self.jumptonum.setGeometry(QtCore.QRect(810, 690, 57, 31))
self.jumptonum.setMaximum(9999)
self.jumptonum.setObjectName(_fromUtf8("jumptonum"))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 915, 22))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
self.frequency.setText(QtGui.QApplication.translate("MainWindow", "TextLabel", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("MainWindow", "Frequency:", None, QtGui.QApplication.UnicodeUTF8))
self.savevalues.setText(QtGui.QApplication.translate("MainWindow", "Save Values", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setText(QtGui.QApplication.translate("MainWindow", "Res number:", None, QtGui.QApplication.UnicodeUTF8))
self.res_num.setText(QtGui.QApplication.translate("MainWindow", "TextLabel", None, QtGui.QApplication.UnicodeUTF8))
self.open_browse.setText(QtGui.QApplication.translate("MainWindow", "Open", None, QtGui.QApplication.UnicodeUTF8))
self.save_browse.setText(QtGui.QApplication.translate("MainWindow", "Save to:", None, QtGui.QApplication.UnicodeUTF8))
self.label_3.setText(QtGui.QApplication.translate("MainWindow", "Atten:", None, QtGui.QApplication.UnicodeUTF8))
self.jumptores.setText(QtGui.QApplication.translate("MainWindow", "Jump to Res", None, QtGui.QApplication.UnicodeUTF8))
from mpl_pyqt4_widget import MPL_Widget
| 5,518 | 55.896907 | 129 | py |
SDR | SDR-master/Setup/WideSweep/libs/mpl_pyqt4_widget.py | #!/usr/bin/env python
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4 import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import numpy as N
class MyMplCanvas(FigureCanvas):
def __init__(self, parent=None, width = 10, height = 12, dpi = 100, sharex = None, sharey = None):
self.fig = Figure(figsize = (width, height), dpi=dpi, facecolor = '#FFFFFF')
self.ax = self.fig.add_subplot(111, sharex = sharex, sharey = sharey)
self.fig.subplots_adjust(left=0.12, bottom=0.15, right=0.97, top=0.97)
self.xtitle="Wavelength"
self.ytitle="Counts"
#self.PlotTitle = "Some Plot"
self.grid_status = True
self.xaxis_style = 'linear'
self.yaxis_style = 'linear'
self.format_labels()
self.ax.hold(True)
FigureCanvas.__init__(self, self.fig)
#self.fc = FigureCanvas(self.fig)
FigureCanvas.setSizePolicy(self,
QSizePolicy.Expanding,
QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
def format_labels(self):
#self.ax.set_title(self.PlotTitle)
self.ax.title.set_fontsize(7)
self.ax.set_xlabel(self.xtitle, fontsize = 7)
self.ax.set_ylabel(self.ytitle, fontsize = 7)
labels_x = self.ax.get_xticklabels()
labels_y = self.ax.get_yticklabels()
for xlabel in labels_x:
xlabel.set_fontsize(7)
for ylabel in labels_y:
ylabel.set_fontsize(7)
ylabel.set_color('b')
def sizeHint(self):
w, h = self.get_width_height()
return QSize(w, h)
def minimumSizeHint(self):
return QSize(10, 10)
def sizeHint(self):
w, h = self.get_width_height()
return QSize(w, h)
def minimumSizeHint(self):
return QSize(10, 10)
class MPL_Widget(QWidget):
def __init__(self, parent = None):
QWidget.__init__(self, parent)
self.canvas = MyMplCanvas()
#self.toolbar = NavigationToolbar(self.canvas, self.canvas)
self.vbox = QVBoxLayout()
self.vbox.addWidget(self.canvas)
#self.vbox.addWidget(self.toolbar)
self.setLayout(self.vbox)
| 2,089 | 28.43662 | 99 | py |
SDR | SDR-master/Setup/WideSweep/libs/__init__.py | 0 | 0 | 0 | py |
|
SDR | SDR-master/Setup/WideSweep/libs/iqsweep.py | #!/usr/bin/env python
# encoding: utf-8
"""
iqsweep.py
Created by Ben Mazin on 2011-03-24.
Copyright (c) 2011 . All rights reserved.
"""
from tables import *
import numpy as np
import os
import sys
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import time
import pdb
#import powspec_rebin
class IQsweeptables(IsDescription):
"""The pytables derived class that hold IQ sweep data on the disk
"""
# recorded data
f0 = Float32Col()
span = Float32Col()
fsteps = Int32Col()
atten1 = Int32Col()
atten2 = Int32Col()
scale = Float32Col()
PreadoutdB = Float32Col()
Tstart = Float32Col()
Tend = Float32Col()
I0 = Float32Col()
Q0 = Float32Col()
resnum = Int32Col()
freq = Float32Col(2000)
I = Float32Col(2000)
Q = Float32Col(2000)
Isd = Float32Col(2000)
Qsd = Float32Col(2000)
time = Float64Col()
# data products from loop fit
vmaxidx = Int32Col()
Iceng = Float32Col()
Qceng = Float32Col()
Icen = Float32Col()
Qcen = Float32Col()
Qm = Float32Col()
Qc = Float32Col()
Qi = Float32Col()
fm = Float32Col()
dipdb = Float32Col()
popt = Float32Col(10)
fpoints = Float32Col()
fI = Float32Col(2000)
fQ = Float32Col(2000)
ff = Float32Col(2000)
# data products from mag fit
mag = Float32Col(2000)
magfreq = Float32Col(2000)
magfit = Float32Col(2000)
mopt = Float32Col(6)
# data products from noise analysis
savenoise = Int32Col()
samprate = Float32Col()
pn = Float32Col(2552)
pnidx = Float32Col(2552)
an = Float32Col(2552)
anidx = Float32Col(2552)
fn1k = Float32Col()
class optimalpow(IsDescription):
"""The pytables derived class that stored the optimal readout power and f0 for the resonator
"""
Pmax = Float32Col()
f0 = Float32Col()
class IQsweep:
"""A class for IQ sweep data designed to be compatible with pytables.
Holds the IQ response of a single resonator and functions that process it.
LoadSWP(filename,resnum) method to load the standard .swp files from the analog readout into an object.
FitLoopMP() method fits the sweep data with Ben's loop fit code
FitMagMP() method fits the sweep data with Ben's simple magnitue fit code
AnalyzeNoise() method crunches the noise data
Save(filename,gstring,mode) method saves the class in h5 file filename in group gstring ('r0','r1',etc) with write mode mode ('w','a')
Load(filename,gstring,f0,atten1) method loads sweep data from h5 file filename with center freq f0 and input atten setting atten1
Pdf(filename) plots the IQ sweep (and fit if present) to a pdf file
"""
def __init__(self):
pass
def LoadSWP(self,filename,resnum): # Load sweep data from .swp format text files
self.resnum = resnum
#read header
f = open(filename, 'r')
h1,h2,h3,self.atten1 = np.fromstring(f.readline()[:-1],dtype=np.float32,sep='\t')
h4,h5,h6,self.atten2 = np.fromstring(f.readline()[:-1],dtype=np.float32,sep='\t')
self.Tstart,self.Tend = np.fromstring(f.readline()[:-1],dtype=np.float32,sep='\t')
Iz1,Iz1sd = np.fromstring(f.readline()[:-1],dtype=np.float32,sep='\t')
Qz1,Qz1sd = np.fromstring(f.readline()[:-1],dtype=np.float32,sep='\t')
Iz2,Iz2sd = np.fromstring(f.readline()[:-1],dtype=np.float32,sep='\t')
Qz2,Qz2sd = np.fromstring(f.readline()[:-1],dtype=np.float32,sep='\t')
f.close()
#read table
data = np.loadtxt(filename, skiprows=7)
self.time = time.time()
self.savenoise = 0
if self.resnum == 0:
self.f0 = h1
self.span = h2
self.fsteps = int(h3)
self.I0 = Iz1
self.Q0 = Qz1
self.freq = data[:self.fsteps,0]
self.I = data[:self.fsteps,1]
self.Q = data[:self.fsteps,3]
self.Isd = data[:self.fsteps,2]
self.Qsd = data[:self.fsteps,4]
else:
self.f0 = h4
self.span = h5
self.fsteps = int(h6)
self.I0 = Iz2
self.Q0 = Qz2
self.freq = data[h3:h3+self.fsteps,0]
self.I = data[h3:h3+self.fsteps,1]
self.Q = data[h3:h3+self.fsteps,3]
self.Isd = data[h3:h3+self.fsteps,2]
self.Qsd = data[h3:h3+self.fsteps,4]
def FitLoopMP(self): # Fit the sweep using the full IQ data with MPFIT!
import mpfit
# find center from IQ max
vel = np.sqrt((self.I[0:self.fsteps-2]-self.I[1:self.fsteps-1])**2 + (self.Q[0:self.fsteps-2]-self.Q[1:self.fsteps-1])**2)
svel = smooth(vel)
cidx = (np.where(svel==max(svel)))[0]
self.vmaxidx = cidx[0]
# Try to pass fsteps/2 points but work even if closer to the edge than that
low = cidx - self.fsteps/4
if low < 0:
low = 0
high = cidx + self.fsteps/4
if cidx > self.fsteps :
high = self.fsteps
#print cidx,low,high
idx = self.freq[low:high]*1e9
I = self.I[low:high]-self.I0
Q = self.Q[low:high]-self.Q0
#print len(I)
s21 = np.zeros(len(I)*2)
s21[:len(I)] = I
s21[len(I):] = Q
sigma = np.zeros(len(I)*2)
sigma[:len(I)] = self.Isd[low:high]
sigma[len(I):] = self.Qsd[low:high]
# take a guess at center
self.Iceng = (max(I)-min(I))/2.0 + min(I)
self.Qceng = (max(Q)-min(Q))/2.0 + min(Q)
ang = np.arctan2( Q[self.fsteps/4] - self.Qceng, I[self.fsteps/4] - self.Iceng )
#print ang
if ang >= 0 and ang <= np.pi:
ang -= np.pi/2
if ang >= -np.pi and ang < 0:
ang += np.pi/2
#print Q[self.fsteps/4]-self.Qceng, I[self.fsteps/4]-self.Iceng
#print ang
#parinfo = [{'value':0., 'fixed':0, 'limited':[1,1], 'limits':[0.,0.]}]*10
parinfo=[ {'value':0., 'fixed':0, 'limited':[1,1], 'limits':[0.,0.]} for i in range(10) ]
parinfo[0]['value'] = 50000.0
parinfo[0]['limits'] = [5000.0,1e6]
parinfo[1]['value'] = np.mean(idx)
parinfo[1]['limits'] = [ np.min(idx),np.max(idx)]
parinfo[2]['value'] = 1.0
parinfo[2]['limits'] = [1e-4,1e2]
parinfo[3]['value'] = 800.0
parinfo[3]['limits'] = [1.0,4e4]
parinfo[4]['value'] = 500.0
parinfo[4]['limits'] = [-5000.0,5000.0]
parinfo[5]['value'] = ang
parinfo[5]['limits'] = [-np.pi*1.1,np.pi*1.1]
parinfo[6]['value'] = np.max(I[low:high]) - np.min(I[low:high])
parinfo[6]['limits'] = [parinfo[6]['value'] - 0.5*parinfo[6]['value'] , parinfo[6]['value'] + 0.5*parinfo[6]['value'] ]
parinfo[7]['value'] = np.max(Q[low:high]) - np.min(Q[low:high])
parinfo[7]['limits'] = [parinfo[7]['value'] - 0.5*parinfo[7]['value'] , parinfo[7]['value'] + 0.5*parinfo[6]['value'] ]
parinfo[8]['value'] = self.Iceng
parinfo[8]['limits'] = [parinfo[8]['value'] - np.abs(0.5*parinfo[8]['value']) , parinfo[8]['value'] + np.abs(0.5*parinfo[8]['value']) ]
parinfo[9]['value'] = self.Qceng
parinfo[9]['limits'] = [parinfo[9]['value'] - np.abs(0.5*parinfo[9]['value']) , parinfo[9]['value'] + np.abs(0.5*parinfo[9]['value']) ]
fa = {'x':idx, 'y':s21, 'err':sigma}
#pdb.set_trace()
# use magfit Q if available
try:
Qguess = np.repeat(self.mopt[0],10)
except:
Qguess = np.repeat(range(10)*10000)
chisq=1e50
for x in range(10):
# Fit
Qtry = Qguess[x] + 20000.0*np.random.normal()
if Qtry < 5000.0:
Qtry = 5000.0
parinfo[0]['value'] = Qtry
parinfo[2]['value'] = 1.1e-4 + np.random.uniform()*90.0
parinfo[3]['value'] = 1.0 + np.random.uniform()*3e4
parinfo[4]['value'] = np.random.uniform()*9000.0 - 4500.0
if x > 5:
parinfo[5]['value'] = np.random.uniform(-1,1)*np.pi
# fit!
m = mpfit.mpfit(RESDIFFMP,functkw=fa,parinfo=parinfo,quiet=1)
popt = m.params
newchisq = m.fnorm
if newchisq < chisq:
chisq = newchisq
bestpopt = m.params
try:
popt = bestpopt
except:
popt = m.params
self.popt = popt
self.Icen = popt[8]
self.Qcen = popt[9]
fit = RESDIFF(idx,popt[0],popt[1],popt[2],popt[3],popt[4],popt[5],popt[6],popt[7],popt[8],popt[9])
#pdb.set_trace()
# compute dipdb,Qc,Qi
radius = abs((popt[6]+popt[7]))/4.0
diam = (2.0*radius) / (np.sqrt(popt[8]**2 + popt[9]**2) + radius)
Qc = popt[0]/diam
Qi = popt[0]/(1.0-diam)
dip = 1.0 - 2.0*radius/(np.sqrt(popt[8]**2 + popt[9]**2) + radius)
dipdb = 20.0*np.log10(dip)
# internal power
power = 10.0**((-self.atten1-35.0)/10.0)
Pint = 10.0*np.log10((2.0 * self.popt[0]**2/(np.pi * Qc))*power)
#print popt
#print radius,diam,Qc,Qi,dip,dipdb
self.Qm = popt[0]
self.fm = popt[1]
self.Qc = Qc
self.Qi = Qi
self.dipdb = dipdb
self.Pint = Pint
self.fpoints = len(I)
self.fI = fit[:len(I)]
self.fQ = fit[len(I):]
self.ff = self.freq[low:high]
def FitMagMP(self): # Fit the sweep using just the magnitude data
import mpfit
# find center from IQ max
vel = np.sqrt((self.I[0:self.fsteps-2]-self.I[1:self.fsteps-1])**2 + (self.Q[0:self.fsteps-2]-self.Q[1:self.fsteps-1])**2)
svel = smooth(vel)
cidx = (np.where(svel==max(svel)))[0]
self.vmaxidx = cidx[0]
idx = self.freq*1e9
mag = np.sqrt((self.I-self.I0)**2 + (self.Q-self.Q0)**2)
norm = np.max(mag)
mag = mag / norm
#Q,f0,carrier,depth,slope,curve
parinfo=[ {'value':0., 'fixed':0, 'limited':[1,1], 'limits':[0.,0.]} for i in range(6) ]
parinfo[0]['value'] = 50000.0
parinfo[0]['limits'] = [5000.0,1e6]
parinfo[1]['value'] = np.mean(idx)
parinfo[1]['limits'] = [ np.min(idx),np.max(idx)]
parinfo[2]['value'] = 1.0
parinfo[2]['limits'] = [1e-4,1e2]
parinfo[3]['value'] = 0.7
parinfo[3]['limits'] = [0.01,10.0]
parinfo[4]['value'] = 0.1
parinfo[4]['limits'] = [-5000.0,5000.0]
parinfo[5]['value'] = -10.0
parinfo[5]['limits'] = [-1e8,1e8]
sigma = np.repeat(0.00001,len(mag))
fa = {'x':idx, 'y':mag, 'err':sigma}
#pdb.set_trace()
chisq=1e50
for x in range(10):
# Fit
Qtry = x*10000.0 + 5000.0*np.random.normal()
if Qtry < 5000.0:
Qtry = 5000.0
parinfo[0]['value'] = Qtry
# fit!
m = mpfit.mpfit(MAGDIFFMP,functkw=fa,parinfo=parinfo,quiet=1)
popt = m.params
newchisq = m.fnorm
#print newchisq
if newchisq < chisq:
chisq = newchisq
bestpopt = m.params
popt = bestpopt
#print popt
fit = MAGDIFF(idx,popt[0],popt[1],popt[2],popt[3],popt[4],popt[5])
self.mag = np.sqrt((self.I-self.I0)**2 + (self.Q-self.Q0)**2)/norm
self.magfreq = self.freq
self.magfit = fit
self.mopt = popt
def PlotIQ(self): # Plot the sweep
fig = plt.figure( figsize=(8, 6), dpi=100)
ax = fig.add_subplot(111)
ax.plot(self.I[:self.fsteps]-self.I0,self.Q[:self.fsteps]-self.Q0,'bo')
ax.plot(self.Iceng,self.Qceng,'gx')
ax.plot(self.I[self.vmaxidx]-self.I0,self.Q[self.vmaxidx]-self.Q0,'go')
ax.plot(self.Icen,self.Qcen,'rx')
ax.plot(self.fI,self.fQ,'r')
#leg = ax.legend(['Q = ' + '{0:.2f}'.format(self.popt[0]), 'f$_0$ = ' + '{0:.6f}'.format(self.popt[1]/1e9), 'Q$_c$ = ' + '{0:.2f}'.format(self.Qc),'Q$_i$ = ' + '{0:.2f}'.format(self.Qi),'|S$_{21}$|$_{min}$ = ' + '{0:.2f}'.format(self.dipdb)],loc=4, shadow=True,numpoints=1)
#print 'Q = ' + '{0:.2f}'.format(self.popt[0]) + '\nf$_0$ = ' + '{0:.6f}'.format(self.popt[1]/1e9) + '\nQ$_c$ = ' + '{0:.2f}'.format(self.Qc) + '\nQ$_i$ = ' + '{0:.2f}'.format(self.Qi) + '\n|S$_{21}$|$_{min}$ = ' + '{0:.2f}'.format(self.dipdb)
#leg = ax.text(.5,.5,'Q = ' + '{0:.2f}'.format(self.popt[0]) + '\nf$_0$ = ' + '{0:.6f}'.format(self.popt[1]/1e9) + '\nQ$_c$ = ' + '{0:.2f}'.format(self.Qc) + '\nQ$_i$ = ' + '{0:.2f}'.format(self.Qi) + '\n|S$_{21}$|$_{min}$ = ' + '{0:.2f}'.format(self.dipdb),transform=ax.transAxes)
ax.grid(False)
ax.set_xlabel('I')
ax.set_ylabel('Q')
# the matplotlib.patches.Rectangle instance surrounding the legend
#frame = leg.get_frame()
#frame.set_facecolor('0.80') # set the frame face color to light gray
# matplotlib.text.Text instances
#for t in leg.get_texts():
# t.set_fontsize('small') # the legend text fontsize
# matplotlib.lines.Line2D instances
#for l in leg.get_lines():
# l.set_linewidth(1.5) # the legend line width
plt.show()
def PlotMag(self): # Plot the sweep
fig = plt.figure( figsize=(8, 6), dpi=100)
ax = fig.add_subplot(111)
ax.plot(self.freq,20.0*np.log10(self.mag),'bo')
ax.plot(self.magfreq,20.0*np.log10(self.magfit),'r')
ax.grid(False)
ax.set_xlabel('Frequency (GHz)')
ax.set_ylabel('|S$_{21}$| (dB)')
plt.show()
def Save(self,filename,roach,wmode): # Save IQ sweep data into a HDF5 file
h5file = openFile(filename, mode = wmode, title = "IQ sweep file created " + time.asctime() )
# if there is no existing roach group, create one
try:
#group = h5file.root.r0
group = h5file.getNode('/',roach )
except:
group = h5file.createGroup("/",roach, 'ROACH Identifier' )
# if there is no existing sweep group, create one
#if group.__contains__('sweeps'):
# group = group.sweeps
#else:
# group = h5file.createGroup(group,'sweeps', 'IQ sweep data' )
# make a group for each resonator
try:
group = h5file.getNode(group,'f'+str(int(np.float32(self.f0)*10000.0)) )
except:
group = h5file.createGroup(group,'f'+str(int(np.float32(self.f0)*10000.0)), 'Group Created ' + time.ctime(self.time) )
# store sweeps with various Tstart and atten settings in the same table
try:
table = group.iqsweep
swp = group.iqsweep.row
except:
filt = Filters(complevel=5, complib='zlib', fletcher32=True)
table = h5file.createTable(group,'iqsweep', IQsweeptables, "IQ Sweep Data",filters=filt)
swp = table.row
try:
swp['f0'] = np.float32(self.f0)
swp['span'] = self.span
swp['fsteps'] = self.fsteps
swp['atten1'] = self.atten1
swp['atten2'] = self.atten2
swp['scale'] = self.scale
swp['PreadoutdB'] = self.PreadoutdB
swp['Tstart'] = self.Tstart
swp['Tend'] = self.Tend
swp['I0'] = self.I0
swp['Q0'] = self.Q0
swp['resnum'] = self.resnum
swp['freq'] = np.concatenate( (self.freq,np.zeros(2000-self.fsteps)),axis=0 )
swp['I'] = np.concatenate( (self.I,np.zeros(2000-self.fsteps)),axis=0 )
swp['Q'] = np.concatenate( (self.Q,np.zeros(2000-self.fsteps)),axis=0 )
swp['Isd'] = np.concatenate( (self.Isd,np.zeros(2000-self.fsteps)),axis=0 )
swp['Qsd'] = np.concatenate( (self.Qsd,np.zeros(2000-self.fsteps)),axis=0 )
swp['time'] = self.time
except:
pass
try:
swp['vmaxidx'] = self.vmaxidx
swp['Iceng'] = self.Iceng
swp['Qceng'] = self.Qceng
swp['Icen'] = self.Icen
swp['Qcen'] = self.Qcen
swp['Qm'] = self.Qm
swp['fm'] = self.fm
swp['Qc'] = self.Qc
swp['Qi'] = self.Qi
swp['dipdb'] = self.dipdb
swp['popt'] = self.popt
swp['fpoints'] = self.fpoints
swp['fI'] = np.concatenate( (self.fI,np.zeros(2000-self.fI.__len__())),axis=0 )
swp['fQ'] = np.concatenate( (self.fQ,np.zeros(2000-self.fQ.__len__())),axis=0 )
swp['ff'] = np.concatenate( (self.ff,np.zeros(2000-self.ff.__len__())),axis=0 )
except:
pass
# data products from mag fit
try:
swp['mag'] = np.concatenate( (self.mag,np.zeros(2000-self.fsteps)),axis=0 )
swp['magfreq'] = np.concatenate( (self.magfreq,np.zeros(2000-len(self.magfreq))),axis=0 )
swp['magfit'] = np.concatenate( (self.magfit,np.zeros(2000-len(self.magfit))),axis=0 )
swp['mopt'] = self.mopt
except:
pass
# data products from noise analysis
try:
swp['pn'] = self.pn
swp['pnidx'] = self.pnidx
swp['an'] = self.an
swp['anidx'] = self.anidx
swp['fn1k'] = self.fn1k
except:
pass
# now save noise data if present and save flag is set
if self.savenoise > 0:
try:
swp['samprate'] = self.samprate
swp['savenoise'] = self.savenoise
try:
noise = group.iqnoise
except:
noise = h5file.createVLArray(group, 'iqnoise', Int16Atom(shape=()), "Noise data stored in ragged array of ints. [0] = I, [1] = Q")
noise.append(self.Ix1)
noise.append(self.Qx1)
except:
print "Unexpected error saving noise data: ", sys.exc_info()[0]
swp.append()
table.flush()
h5file.close()
def Load(self,filename,roach,f0,atten): # Load the desired IQ sweep data from a HDF5 file
#load the sweep with center frequency closest to f0 and input atten=atten1
h5file = openFile(filename, mode = "r")
# find the table with the sweep data in it.
try:
group = h5file.getNode('/',roach )
group = h5file.getNode(group,'f'+str(int(f0*10000.0)) )
table = group.iqsweep
k = table.readWhere('atten1 == atten')
except:
print 'Did not find sweep in file!'
h5file.close()
return
try:
self.f0 = k['f0'][0]
self.span = k['span'][0]
self.fsteps = k['fsteps'][0]
self.atten1 = k['atten1'][0]
self.atten2 = k['atten2'][0]
self.scale = k['scale'][0]
self.PreadoutdB = k['PreadoutdB'][0]
self.Tstart = k['Tstart'][0]
self.Tend = k['Tend'][0]
self.I0 = k['I0'][0]
self.Q0 = k['Q0'][0]
self.resnum = k['resnum'][0]
self.time = k['time'][0]
except:
pass
try:
self.freq = k['freq'][0,0:self.fsteps]
self.I = k['I'][0,0:self.fsteps]
self.Q = k['Q'][0,0:self.fsteps]
self.Isd = k['Isd'][0,0:self.fsteps]
self.Qsd = k['Qsd'][0,0:self.fsteps]
self.vmaxidx = k['vmaxidx'][0]
self.Iceng = k['Iceng'][0]
self.Qceng = k['Qceng'][0]
self.Icen = k['Icen'][0]
self.Qcen= k['Qcen'][0]
self.Qm= k['Qm'][0]
self.fm= k['fm'][0]
self.Qc= k['Qc'][0]
self.Qi= k['Qi'][0]
self.dipdb= k['dipdb'][0]
self.popt = k['popt'][0]
self.fpoints = k['fpoints'][0]
self.fI = k['fI'][0,0:self.fpoints]
self.fQ = k['fQ'][0,0:self.fpoints]
self.ff = k['ff'][0,0:self.fpoints]
except:
pass
try:
self.mag = k['mag'][0,0:self.fpoints]
self.magfreq = k['magfreq'][0]
self.magfit = k['magfit'][0]
self.mopt = k['mopt'][0]
except:
pass
try:
self.savenoise = k['savenoise'][0]
self.samprate = k['samprate'][0]
self.pn = k['pn'][0]
self.pnidx = k['pnidx'][0]
self.an = k['an'][0]
self.anidx = k['anidx'][0]
self.kn1k = k['fn1k'][0]
except:
pass
h5file.close()
def LoadLeaf(self,table,row): # Load up sweep table data from a hdf5 table
# speed things up by loading the whole table at once
k = table.read()
try:
self.f0 = k['f0'][row]
self.span = k['span'][row]
self.fsteps = k['fsteps'][row]
self.atten1 = k['atten1'][row]
self.atten2 = k['atten2'][row]
self.scale = k['scale'][row]
self.PreadoutdB = k['PreadoutdB'][row]
self.Tstart = k['Tstart'][row]
self.Tend = k['Tend'][row]
self.I0 = k['I0'][row]
self.Q0 = k['Q0'][row]
self.resnum = k['resnum'][row]
self.time = k['time'][row]
except:
pass
try:
self.freq = k['freq'][row,0:self.fsteps]
self.I = k['I'][row,0:self.fsteps]
self.Q = k['Q'][row,0:self.fsteps]
self.Isd = k['Isd'][row,0:self.fsteps]
self.Qsd = k['Qsd'][row,0:self.fsteps]
self.vmaxidx = k['vmaxidx'][row]
self.Iceng = k['Iceng'][row]
self.Qceng = k['Qceng'][row]
self.Icen = k['Icen'][row]
self.Qcen= k['Qcen'][row]
self.Qm= k['Qm'][row]
self.fm= k['fm'][row]
self.Qc= k['Qc'][row]
self.Qi= k['Qi'][row]
self.dipdb= k['dipdb'][row]
self.popt = k['popt'][row]
self.fpoints = k['fpoints'][row]
self.fI = k['fI'][row,0:self.fpoints]
self.fQ = k['fQ'][row,0:self.fpoints]
self.ff = k['ff'][row,0:self.fpoints]
except:
pass
try:
self.mag = k['mag'][row,0:self.fpoints]
self.magfreq = k['magfreq'][row]
self.magfit = k['magfit'][row]
self.mopt = k['mopt'][row]
except:
pass
try:
self.savenoise = k['savenoise'][row]
self.samprate = k['samprate'][row]
self.pn = k['pn'][row]
self.pnidx = k['pnidx'][row]
self.an = k['an'][row]
self.anidx = k['anidx'][row]
self.kn1k = k['fn1k'][row]
except:
pass
def Pdf(self,filename):
pp = PdfPages(filename)
matplotlib.rcParams['font.size']=8
fig = plt.figure( figsize=(7.5, 9), dpi=100)
try:
ax = fig.add_subplot(221)
ax.plot(self.I[:self.fsteps]-self.I0,self.Q[:self.fsteps]-self.Q0,'bo',markersize=4)
ax.plot(self.Iceng,self.Qceng,'gx')
ax.plot(self.I[self.vmaxidx]-self.I0,self.Q[self.vmaxidx]-self.Q0,'go',markersize=4)
ax.plot(self.Icen,self.Qcen,'rx')
ax.plot(self.fI,self.fQ,'r')
ax.set_xlabel('I')
ax.set_ylabel('Q')
except:
pass
# overplot some noise data
try:
ax.plot(self.Ix1[0:5000]*0.2/32767.0-self.I0,self.Qx1[0:5000]*0.2/32767.0-self.Q0,'c.',markersize=1)
except:
pass
try:
ax2 = fig.add_subplot(222)
ax2.plot(self.freq,20.0*np.log10(self.mag),'bo',markersize=4)
ax2.plot(self.magfreq,20.0*np.log10(self.magfit),'r')
ax2.grid(False)
ax2.set_xlabel('Frequency (GHz)')
ax2.set_ylabel('|S$_{21}$| (dB)')
except:
pass
try:
ax3 = fig.add_subplot(212)
ax3.plot(self.pnidx[1:],10.0*np.log10(self.pn[1:]),'r',self.anidx[1:],10.0*np.log10(self.an[1:]),'k')
ax3.set_title('P$_{int}$ = ' + '{0:.2f}'.format(self.Pint) + ' dBm, Frequency Noise at 1 kHz = ' + '{0:.2e}'.format(self.fn1k) + ' Hz$^2$/Hz' )
ax3.set_xscale('log')
ax3.set_autoscale_on(False)
ax3.set_xlim([1,1e5])
ax3.set_ylim([-100,-50])
ax3.set_xlabel('Frequency (Hz)')
ax3.set_ylabel('Phase (Red) and Amplitude (Black) Noise (dBc/Hz)')
ax3.grid(True)
text = 'Q = ' + '{0:.2f}'.format(self.Qm) + '\nf$_0$ = ' + '{0:.6f}'.format(self.fm/1e9) + '\nQ$_c$ = ' + '{0:.2f}'.format(self.Qc) + '\nQ$_i$ = ' + '{0:.2f}'.format(self.Qi) + '\n|S$_{21}$|$_{min}$ = ' + '{0:.2f}'.format(self.dipdb)
bbox_args = dict(boxstyle="round", fc="0.8")
ax3.annotate(text,
xy=(0.75, 0.9), xycoords='axes fraction',
xytext=(0.75, 0.9), textcoords='axes fraction',
ha="left", va="top",
bbox=bbox_args)
except:
pass
try:
ax4 = ax3.twinx()
ax4.set_ylim([np.log10((10**(-100.0/10.0))/(16.0*self.popt[0]**2)),np.log10((10**(-50.0/10.0))/(16.0*self.popt[0]**2))])
ax4.set_ylabel('Frequency Noise log$_{10}$(Hz$^2$/Hz)', color='r')
for tl in ax4.get_yticklabels():
tl.set_color('r')
except:
pass
pp.savefig()
pp.close()
def LoadNoise(self,filename,resnum):
# Load up noise data
self.noisename = filename
f = open(filename, 'rb')
fsize = os.fstat(f.fileno())[6]
if fsize < 10:
print 'No Noise File!'
return
hdr = np.fromfile(f, dtype=np.float64,count=12)
self.samprate = 200000.0
self.Ix1 = np.zeros(2000000,dtype=np.int16)
self.Qx1 = np.zeros(2000000,dtype=np.int16)
for x in range(10):
if resnum == 0:
self.Ix1[x*200000:(x+1)*200000] = np.fromfile(f, dtype=np.int16,count=200000)
self.Qx1[x*200000:(x+1)*200000] = np.fromfile(f, dtype=np.int16,count=200000)
dummy = np.fromfile(f, dtype=np.int16,count=200000)
dummy = np.fromfile(f, dtype=np.int16,count=200000)
else:
dummy = np.fromfile(f, dtype=np.int16,count=200000)
dummy = np.fromfile(f, dtype=np.int16,count=200000)
self.Ix1[x*200000:(x+1)*200000] = np.fromfile(f, dtype=np.int16,count=200000)
self.Qx1[x*200000:(x+1)*200000] = np.fromfile(f, dtype=np.int16,count=200000)
self.savenoise = len(self.Ix1)
dummy = 0
f.close()
def AnalyzeNoise(self):
import matplotlib.mlab
# Analyze noise data
# subtract off zero point and move center of resonance to (0,0)
Ix1a = self.Ix1*0.2/32767.0 - self.I0 - self.Icen
Qx1a = self.Qx1*0.2/32767.0 - self.Q0 - self.Qcen
#convert to mag and phase
resang = np.arctan2(np.mean(Qx1a), np.mean(Ix1a) )
nI = (Ix1a*np.cos(resang) + Qx1a*np.sin(resang))
nQ = (-Ix1a*np.sin(resang) + Qx1a*np.cos(resang))
rad = np.mean(nI)
nI = nI/rad
nQ = nQ/rad
phase = np.arctan2(nQ,nI)
amp = np.sqrt(nI**2 + nQ**2)
# low frequency FFTs
pnlow, pnlowidx = matplotlib.mlab.psd(phase,NFFT=262144,Fs=self.samprate,noverlap=131072)
anlow, anlowidx = matplotlib.mlab.psd(amp,NFFT=262144,Fs=self.samprate,noverlap=131072)
#pdb.set_trace()
#self.pnidx,self.pn,dummy = powspec_rebin.rebin(pnlowidx[1:],pnslow[1:],binsize=0.002,sampling=1)
#self.anidx,self.an,dummy = powspec_rebin.rebin(anlowidx[1:],anlow[1:],binsize=0.002,sampling=1)
# high frequency FFTs
pnhigh, pnhighidx = matplotlib.mlab.psd(phase,NFFT=4096,Fs=self.samprate,noverlap=2048)
anhigh, anhighidx = matplotlib.mlab.psd(amp,NFFT=4096,Fs=self.samprate,noverlap=2048)
self.pn = np.zeros(2552)
self.pn[0:512] = pnlow[0:512]
self.pn[512:2552] = pnhigh[8:2048]
self.pnidx = np.zeros(2552)
self.pnidx[0:512] = pnlowidx[0:512]
self.pnidx[512:2552] = pnhighidx[8:2048]
self.an = np.zeros(2552)
self.an[0:512] = anlow[0:512]
self.an[512:2552] = anhigh[8:2048]
self.anidx = np.zeros(2552)
self.anidx[0:512] = anlowidx[0:512]
self.anidx[512:2552] = anhighidx[8:2048]
# calculate frequency noise at 1 kHz
coeff = np.polyfit(self.pnidx[521:526],self.pn[521:526],1)
pf = np.poly1d(coeff)
self.fn1k = pf(1000)/(16.0*self.popt[0]**2)
def RESDIFF(x,Q,f0,aleak,ph1,da,ang1,Igain,Qgain,Ioff,Qoff):
# Q = p[0] ; Q
# f0 = p[1] ; resonance frequency
# aleak = p[2] ; amplitude of leakage
# ph1 = p[3] ; phase shift of leakage
# da = p[4] ; variation of carrier amplitude
# ang1 = p[5] ; Rotation angle of data
# Igain = p[6] ; Gain of I channel
# Qgain = p[7] ; Gain of Q channel
# Ioff = p[8] ; Offset of I channel
# Qoff = p[9] ; Offset of Q channel
l = len(x)
dx = (x - f0) / f0
# resonance dip function
s21a = (np.vectorize(complex)(0,2.0*Q*dx)) / (complex(1,0) + np.vectorize(complex)(0,2.0*Q*dx))
s21a = s21a - complex(.5,0)
s21b = np.vectorize(complex)(da*dx,0) + s21a + aleak*np.vectorize(complex)(1.0-np.cos(dx*ph1),-np.sin(dx*ph1))
# scale and rotate
Ix1 = s21b.real*Igain
Qx1 = s21b.imag*Qgain
nI1 = Ix1*np.cos(ang1) + Qx1*np.sin(ang1)
nQ1 = -Ix1*np.sin(ang1) + Qx1*np.cos(ang1)
#scale and offset
nI1 = nI1 + Ioff
nQ1 = nQ1 + Qoff
s21 = np.zeros(l*2)
s21[:l] = nI1
s21[l:] = nQ1
return s21
def RESDIFFMP(p, fjac=None, x=None, y=None, err=None):
Q = p[0] # Q
f0 = p[1] # resonance frequency
aleak = p[2] # amplitude of leakage
ph1 = p[3] # phase shift of leakage
da = p[4] # variation of carrier amplitude
ang1 = p[5] # Rotation angle of data
Igain = p[6] # Gain of I channel
Qgain = p[7] # Gain of Q channel
Ioff = p[8] # Offset of I channel
Qoff = p[9] # Offset of Q channel
l = len(x)
dx = (x - f0) / f0
# resonance dip function
s21a = (np.vectorize(complex)(0,2.0*Q*dx)) / (complex(1,0) + np.vectorize(complex)(0,2.0*Q*dx))
s21a = s21a - complex(.5,0)
s21b = np.vectorize(complex)(da*dx,0) + s21a + aleak*np.vectorize(complex)(1.0-np.cos(dx*ph1),-np.sin(dx*ph1))
# scale and rotate
Ix1 = s21b.real*Igain
Qx1 = s21b.imag*Qgain
nI1 = Ix1*np.cos(ang1) + Qx1*np.sin(ang1)
nQ1 = -Ix1*np.sin(ang1) + Qx1*np.cos(ang1)
#scale and offset
nI1 = nI1 + Ioff
nQ1 = nQ1 + Qoff
s21 = np.zeros(l*2)
s21[:l] = nI1
s21[l:] = nQ1
status=0
return [status, (y-s21)/err]
def MAGDIFFMP(p, fjac=None, x=None, y=None, err=None):
Q = p[0]
f0 = p[1]
carrier = p[2]
depth = p[3]
slope = p[4]
curve = p[5]
dx = (x - f0) / f0
s21 = (np.vectorize(complex)(0,2.0*Q*dx)) / (complex(1,0) + np.vectorize(complex)(0,2.0*Q*dx))
mag1 = (np.abs(s21)-1.0)*depth + carrier + slope*dx + curve*dx*dx
status=0
return [status, (y-mag1)/err]
def MAGDIFF(x,Q,f0,carrier,depth,slope,curve):
dx = (x - f0) / f0
s21 = (np.vectorize(complex)(0,2.0*Q*dx)) / (complex(1,0) + np.vectorize(complex)(0,2.0*Q*dx))
mag1 = (np.abs(s21)-1.0)*depth + carrier + slope*dx + curve*dx*dx
return mag1
def smooth(x, window_len=10, window='hanning'):
"""smooth the data using a window with requested size.
This method is based on the convolution of a scaled window with the signal.
The signal is prepared by introducing reflected copies of the signal
(with the window size) in both ends so that transient parts are minimized
in the begining and end part of the output signal.
input:
x: the input signal
window_len: the dimension of the smoothing window
window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'
flat window will produce a moving average smoothing.
output:
the smoothed signal
example:
import numpy as np
t = np.linspace(-2,2,0.1)
x = np.sin(t)+np.random.randn(len(t))*0.1
y = smooth(x)
see also:
numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve
scipy.signal.lfilter
TODO: the window parameter could be the window itself if an array instead of a string
"""
if x.ndim != 1:
raise ValueError, "smooth only accepts 1 dimension arrays."
if x.size < window_len:
raise ValueError, "Input vector needs to be bigger than window size."
if window_len < 3:
return x
if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']:
raise ValueError, "Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'"
s=np.r_[2*x[0]-x[window_len:1:-1], x, 2*x[-1]-x[-1:-window_len:-1]]
#print(len(s))
if window == 'flat': #moving average
w = np.ones(window_len,'d')
else:
w = getattr(np, window)(window_len)
y = np.convolve(w/w.sum(), s, mode='same')
return y[window_len-1:-window_len+1]
| 34,999 | 35.458333 | 289 | py |
SDR | SDR-master/Setup/test/TestPSFile.py | import unittest,sys,os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from PSFile import PSFile
class TestPSFile(unittest.TestCase):
def testInit(self):
fn = 'ps_r0_20140815-121539.h5'
psf = PSFile(fn)
print "fn=",psf.openfile
for i,freq in enumerate(psf.freq):
print "i=",i," freq=",freq
if __name__ == '__main__':
unittest.main()
| 400 | 29.846154 | 62 | py |
SDR | SDR-master/Setup/Beammapping/BeamMap.py | import numpy as np
from tables import *
import time
import matplotlib.pyplot as plt
import sys
from matplotlib.backends.backend_pdf import PdfPages
import scipy.signal as signal
from scipy import optimize
import scipy.stats as stats
# Define the various classes and functions needed for the beam mapping
# Define BeamMapper class - this allows you to change the location of a peak if there is a mistake
class BeamMapper():
# Initialize variables needed within the class
def __init__(self,xtime,ytime,xfilelength,yfilelength):
self.crx_median = np.zeros((2024,xtime))
self.cry_median = np.zeros((2024,ytime))
self.crx = np.zeros(((xfilelength,2024,xtime)))
self.cry = np.zeros(((yfilelength,2024,ytime)))
self.flag = np.zeros(2024)
self.peakpos = np.zeros((2,2024))
# Try to find a peak position by manually selecting an approximate peak location
def on_click(self,event):
# If x sweep plot (top plot) is clicked
if(event.y > 250):
self.xvals=np.arange(len(self.crxmedian[pixelno][:]))
self.xpeakguess=event.xdata
self.xfitstart=max([self.xpeakguess-20,0])
self.xfitend=min([self.xpeakguess+20,len(self.xvals)])
params = fitgaussian(self.crxmedian[pixelno][self.xfitstart:self.xfitend],self.xvals[self.xfitstart:self.xfitend])
self.xfit = gaussian(params,self.xvals)
self.peakpos[0,self.pixelno]=params[0]
# If y sweep plot (bottom plot) is clicked
else:
self.yvals=np.arange(len(self.cry_median[pixelno][:]))
self.ypeakguess=event.xdata
self.yfitstart=max([self.ypeakguess-20,0])
self.yfitend=min([self.ypeakguess+20,len(self.yvals)])
params = fitgaussian(self.cry_median[pixelno][self.yfitstart:self.yfitend],self.yvals[self.yfitstart:self.yfitend])
self.yfit = gaussian(params,self.yvals)
self.peakpos[1,self.pixelno]=params[0]
# Connect to plot
def connect(self):
self.cid = self.fig.canvas.mpl_connect('button_press_event', self.on_click)
# Define a standard Gaussian distribution function
def gaussian(pars, x):
center, width, height, back = pars
width = float(width)
return back + height*np.exp(-(((center-x)/width)**2)/2)
# Define an error function between data and a Gaussian
def errorfunction(params, data, x):
errorfunction = data - gaussian(params,x)
return errorfunction
# Find an optimal Guassian fit for the data, return parameters of that Gaussian
def fitgaussian(data,x):
params=(x.mean(),2.*(x[1]-x[0]),data.max(), 0.)
p, success = optimize.leastsq(errorfunction, params, args=(data, x))
return p
def file_len(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
# Specify input/output directory and files
path = '/Users/kids/desktop/Beammapping/'
xsweep = []
xsweep.append('obs_20121010-031709.h5')
xsweep.append('obs_20121010-035925.h5')
ysweep = []
ysweep.append('obs_20121010-041802.h5')
ysweep.append('obs_20121010-025118.h5')
number_of_roaches = 8
roach_pixel_count = np.zeros(number_of_roaches)
for roachno in xrange(0,number_of_roaches):
roach_pixel_count[roachno] = file_len(path + 'ps_freq%i.txt' %roachno)-1
# Load the input files
# X sweep data
h5file_x = []
ts_x = []
exptime_x = []
for i in range(len(xsweep)):
h5file_x.append(openFile(path + xsweep[i], mode = 'r'))
ts_x.append(int(h5file_x[i].root.header.header.col('unixtime')[0]))
exptime_x.append(int(h5file_x[i].root.header.header.col('exptime')[0]))
# Y sweep data
h5file_y = []
ts_y = []
exptime_y = []
for i in range(len(ysweep)):
h5file_y.append(openFile(path + ysweep[i], mode = 'r'))
ts_y.append(int(h5file_y[i].root.header.header.col('unixtime')[0]))
exptime_y.append(int(h5file_y[i].root.header.header.col('exptime')[0]))
# Print start and sweep durations, also pixel selection commands
for i in range(len(xsweep)):
print 'Start Time %i = ' %i,ts_x[i], ts_y[i]
for i in range(len(xsweep)):
print 'exptime_x %i =' %i,exptime_x[i],'and exptime_y %i =' %i, exptime_y[i]
print '"A" = Accept, "D" = Delete, "Q" = Quit, "X" = X Only, "Y" = Y Only'
# Create a BeamMapper instance
# Go through each of the pixels (originally (0,2024))
for roachno in xrange(0,number_of_roaches):
map = BeamMapper(exptime_x[0],exptime_y[0],len(xsweep),len(ysweep))
f=open(path + 'r%i.pos' %roachno,'w')
for pixelno in xrange(0,int(roach_pixel_count[roachno])):
map.pixelno=pixelno
map.flag[pixelno] = pixelno
# Store the x data into crx
pn = []
data = np.empty(((len(xsweep),exptime_x[0])), dtype = object)
for i in range(len(xsweep)):
pn.append('/r%d/p%d/t%d' % ( roachno ,pixelno, ts_x[i]))
try:
for i in range(len(xsweep)):
data[i][:] = h5file_x[i].root._f_getChild(pn[i]).read()
for j in xrange(0,exptime_x[0]):
median_array = []
for i in range(len(xsweep)):
median_array.append(len(data[i][j]))
map.crx_median[pixelno][j] = np.median(median_array)
for i in range(len(xsweep)):
map.crx[i][pixelno][j] = len(data[i][j])
except:
pass
# Store the y data into cry
pn = []
data = np.empty(((len(ysweep),exptime_y[0])), dtype = object)
for i in range(len(ysweep)):
pn.append('/r%d/p%d/t%d' % ( roachno ,pixelno, ts_y[i]))
try:
for i in range(len(ysweep)):
data[i][:] = h5file_y[i].root._f_getChild(pn[i]).read()
for j in xrange(exptime_y[0]):
median_array = []
for i in range(len(ysweep)):
median_array.append(len(data[i][j]))
map.cry_median[pixelno][j] = np.median(median_array)
for i in range(len(ysweep)):
map.cry[i][pixelno][j] = len(data[i][j])
except:
pass
print 'roach %d, pixel %d' % (roachno, pixelno)
map.fig = plt.figure()
# do fit of x-position
map.ax = map.fig.add_subplot(211)
map.xvals=np.arange(len(map.crx_median[pixelno][:]))
plt.title(str(pixelno))
plt.plot(map.xvals,map.crx_median[pixelno][:])
map.xpeakguess=np.where(map.crx_median[pixelno][:] == map.crx_median[pixelno][:].max())[0][0]
map.xfitstart=max([map.xpeakguess-20,0])
map.xfitend=min([map.xpeakguess+20,len(map.xvals)])
params_x = fitgaussian(map.crx_median[pixelno][map.xfitstart:map.xfitend],map.xvals[map.xfitstart:map.xfitend])
print 'x: [center, width, height, back] =', params_x
map.xfit = gaussian(params_x,map.xvals)
plt.plot(map.xvals, map.xfit)
for i in range(len(xsweep)):
plt.plot(map.xvals,map.crx[i][pixelno][:],alpha = .2)
map.ax.set_ylim(params_x[3]-30,params_x[2]+75)
map.peakpos[0,pixelno]=params_x[0]
# do fit of y-position
map.ax = map.fig.add_subplot(212)
map.yvals=np.arange(len(map.cry_median[pixelno][:]))
plt.title(str(pixelno+1))
plt.plot(map.yvals,map.cry_median[pixelno][:])
map.ypeakguess=np.where(map.cry_median[pixelno][:] == map.cry_median[pixelno][:].max())[0][0]
map.yfitstart=max([map.ypeakguess-20,0])
map.yfitend=min([map.ypeakguess+20,len(map.yvals)])
params_y = fitgaussian(map.cry_median[pixelno][map.yfitstart:map.yfitend],map.yvals[map.yfitstart:map.yfitend])
print 'y: [center, width, height, back] =', params_y
map.yfit = gaussian(params_y,map.yvals)
plt.plot(map.yvals, map.yfit)
for i in range(len(ysweep)):
plt.plot(map.yvals,map.cry[i][pixelno][:],alpha = .2)
map.ax.set_ylim(params_y[3]-30,params_y[2]+75)
map.peakpos[1,pixelno]=params_y[0]
# AUTOMATICALLY DELETE OBVIOUSLY BAD PIXELS
# if((params_x[0] == 9.5 and params_y[0] == 9.5) or (params_x[1] >= 100 and params_y[1] >= 100)):
# map.peakpos[0,pixelno]=0
# map.peakpos[1,pixelno]=0
# map.flag[pixelno] = -1*pixelno
# plt.close()
# f=open(path+'Sweep_1/r%i.pos' %roachno,'a')
# f.write(str(map.peakpos[0,pixelno])+'\t'+str(map.peakpos[1,pixelno])+'\t'+str(int(map.flag[pixelno]))+'\n')
# f.close()
# else:
map.connect()
while True:
# Accept pixel with 'a'
response=raw_input('>')
if(response == 'a'):
print 'Response: ', response
plt.close()
f=open(path+'r%i.pos' %roachno,'a')
f.write(str(map.peakpos[0,pixelno])+'\t'+str(map.peakpos[1,pixelno])+'\t'+str(int(map.flag[pixelno]))+'\n')
f.close()
break
# Delete pixel with 'd'
elif(response == 'd'):
print 'Response: ', response
map.peakpos[0,pixelno]=0
map.peakpos[1,pixelno]=0
map.flag[pixelno] = -1*pixelno
plt.close()
f=open(path+'r%i.pos' %roachno,'a')
f.write(str(map.peakpos[0,pixelno])+'\t'+str(map.peakpos[1,pixelno])+'\t'+str(int(map.flag[pixelno]))+'\n')
f.close()
break
# Control whether only the x or y pixel is selected
# x is okay
elif(response == 'x'):
print 'Response: ', response
map.peakpos[1,pixelno]=0
map.flag[pixelno] = -1*pixelno
plt.close()
f=open(path+'r%i.pos' %roachno,'a')
f.write(str(map.peakpos[0,pixelno])+'\t'+str(map.peakpos[1,pixelno])+'\t'+str(int(map.flag[pixelno]))+'\n')
f.close()
break
# y is okay
elif(response == 'y'):
print 'Response: ', response
map.peakpos[0,pixelno]=0
map.flag[pixelno] = -1*pixelno
plt.close()
f=open(path+'r%i.pos' %roachno,'a')
f.write(str(map.peakpos[0,pixelno])+'\t'+str(map.peakpos[1,pixelno])+'\t'+str(int(map.flag[pixelno]))+'\n')
f.close()
break
# Quit program with 'q'
elif(response == 'q'):
sys.exit(0)
plt.show()
h5file_x.close()
h5file_y.close()
f.close()
| 10,642 | 40.251938 | 127 | py |
SDR | SDR-master/Setup/Beammapping/MakeSortedBeammap.py | #!/usr/bin/env python
# encoding: utf-8
import numpy as np
from tables import *
import os
import ast
nRoachRows=int(os.environ['MKID_NROW'])
nRoachCols=int(os.environ['MKID_NCOL'])
roachMatrix = ast.literal_eval(os.environ['MKID_ROACH_MATRIX'])
#nRoachRows = 23
#nRoachCols = 11
#roachMatrix = np.array([[2,0,5,6],[3,1,4,7]])
path = os.environ['MKID_BEAMMAP_PATH']
print'beamimage at ',path
if os.path.exists(path):
print "that file already exists so I quit"
exit(1)
#outfile = path + 'sorted_beamimage%dx%d.h5'%(NROWS,NCOLS)
#numpy.fromfile(txtfile,dtype='float32',count=-1,sep=' ')
# make beamap group
h5file = openFile(path, mode = "w")
if h5file < 0:
print "ERROR creating file at ",path
exit(-1)
bgroup = h5file.createGroup('/','beammap','Beam Map of Array')
# make beammap array - this is a 2d array (top left is 0,0. first index is column, second is row) containing a string with the name of the group holding the photon data
filt1 = Filters(complevel=1, complib='zlib', fletcher32=False) # without minimal compression the files sizes are ridiculous...
ca = h5file.createCArray(bgroup, 'beamimage', StringAtom(itemsize=40), (nRoachRows,nRoachCols), filters=filt1)
# load of the text file with resonator data in it and use it to make the beamimage
beamRows = int(os.environ['MKID_BEAM_ROWS'])
beamCols = int(os.environ['MKID_BEAM_COLS'])
#NCHANNELS_PER_ROACH=253
NCHANNELS_PER_ROACH=beamRows*beamCols
logFile = open(path+'.log','wb')
index = 0
for iRoachRow,roachRow in enumerate(roachMatrix):
for iRoachCol,roachCol in enumerate(roachRow):
roach = roachCol
for pixRow in range(nRoachRows):
for pixCol in range(nRoachCols):
x = iRoachCol*nRoachCols+pixCol
y = iRoachRow*nRoachRows+pixRow
pixel = (pixRow*nRoachCols+pixCol)%NCHANNELS_PER_ROACH
name = '/r%d/p%d/' % (roach,pixel)
ca[y,x]=name
logFile.write("%5d %4d %4d %4d %4d %s\n"%(index,pixRow,pixCol,y,x,name))
index += 1
logFile.close()
h5file.flush()
np.set_printoptions(threshold=np.nan)
print ca.read()
h5file.close()
print 'Success: done writing',path
| 2,195 | 33.857143 | 169 | py |
SDR | SDR-master/Setup/Beammapping/pixels_movingscan.py | import numpy as np
import matplotlib.pyplot as plt
path = '/Users/kids/desktop/Beammapping/'
# Alter pscale, xstart, ystart, and angle to match the grid
# Set up a scale factor for pixel locations
#pscale=13.7;
pscale=8.9;
# Pick x position offset
#xstart=pscale*5.5;
xstart=pscale*5;
# Pick y position offset
#ystart=pscale*10.8;
ystart=pscale*11.3;
# Angle of setup
angle=4.2;
# Find the sine and cosine of angle to use for rotations
s=np.sin(np.pi*angle/180.)
c=np.cos(np.pi*angle/180.)
# Size of grid
xsize=44;
ysize=46;
# Not sure about this
numfound=0
numfound2=0
# Initialize variables
xvals=np.empty(0,dtype='float32')
yvals=np.empty(0,dtype='float32')
xfile=np.empty(0,dtype='float32')
yfile=np.empty(0,dtype='float32')
freqvals=np.empty(0,dtype='float32')
attenvals=np.empty(0,dtype='float32')
# Create a list of position files from beam mapping
infile=[]
infile.append(path + 'r0.pos')
infile.append(path + 'r1.pos')
infile.append(path + 'r2.pos')
infile.append(path + 'r3.pos')
infile.append(path + 'r4.pos')
infile.append(path + 'r5.pos')
infile.append(path + 'r6.pos')
infile.append(path + 'r7.pos')
psfile=[]
psfile.append(path + 'ps_freq0.txt')
psfile.append(path + 'ps_freq1.txt')
psfile.append(path + 'ps_freq2.txt')
psfile.append(path + 'ps_freq3.txt')
psfile.append(path + 'ps_freq4.txt')
psfile.append(path + 'ps_freq5.txt')
psfile.append(path + 'ps_freq6.txt')
psfile.append(path + 'ps_freq7.txt')
# Create origin and scale factor
origin=[[xstart,ystart]]*len(infile)
scale=[pscale]*len(infile)
print origin;
# If files need different origins
origin[0][0] -= 0;
origin[0][1] += 0;
# Extract x position, y position, and flag from input files
for j in range(len(infile)):
print infile[j]
xpos, ypos, flag=np.loadtxt(infile[j],unpack='True')
freq, xcenpos, ycenpos, atten=np.loadtxt(psfile[j],unpack='True',skiprows=1)
# Mark the good pixels, all deleted flags will have negative values (except 0?)
goodpix=[]
addpix=np.where(flag > 0)[0]
if flag[0] == 0 and xpos[0] != 0 and ypos[0] != 0:
goodpix = np.append(0,addpix)
else:
goodpix = addpix
#Shift to account for true origin and divide by the scale factor
xpos -= origin[j][0]
xpos /= scale[j]
ypos -= origin[j][1]
ypos /= scale[j]
# if j==0:
# xpos += 0
# ypos -= 1.2
# if j==4:
# xpos -= 0.5
# ypos += 1.2
# if j==5:
# xpos += 0.1
# ypos -= 1.1
# if j==6:
# xpos += 0.1
# ypos += 1
# if j==7:
# xpos -= 0.3
# ypos -= 1
print len(xpos[goodpix]), 'Good Pixels'
#Create a list of good pixel locations
xvals=np.append(xvals,xpos[goodpix])
yvals=np.append(yvals,ypos[goodpix])
freqvals=np.append(freqvals,freq[goodpix])
attenvals=np.append(attenvals,atten[goodpix])
xfile=np.append(xfile,xpos)
yfile=np.append(yfile,ypos)
'''
mask2=(np.linspace(0,len(xpos)-1,len(xpos))).astype('int')
xfile=((xpos[mask2])*c + (ypos[mask2])*s)
yfile=(-1.*(xpos[mask2])*s + (ypos[mask2])*c)
xfile=xfile.astype('int')
yfile=yfile.astype('int')
f= open('xyint%i.txt' %j,'w')
for i in range(len(xfile)):
f= open('xyint%i.txt' %j,'a')
f.write(str(xfile[i]) + '\t' + str(yfile[i]) + '\n')
f.close()
'''
print len(xvals), 'Total Good Pixels'
print 'xmin, xmax =', np.min(xvals), np.max(xvals)
print 'ymin, ymax =', np.min(yvals), np.max(yvals)
# xstart = [0,1,2,...,32]
xstart=xsize*np.linspace(0,1,xsize+1)
# ystart = [0,0,0,...,0]
ystart=np.zeros(xsize+1)
# xstop = [0,1,2,...,32]
xstop=xstart
# ystop = [32,32,32,...,32]
ystop=ystart+ysize
# Transform with 2x2 rotation matrix
xstart2=xstart*c - ystart*s
xstop2=xstop*c - ystop*s
ystart2=xstart*s + ystart*c
ystop2=xstop*s + ystop*c
# plot square grid with 32x32 boxes, rotated counter-clockwise by angle, vertical lines
for i in range(xsize+1):
plt.plot([xstart2[i],xstop2[i]],[ystart2[i],ystop2[i]],'g')
ystart=ysize*np.linspace(0,1,ysize+1)
xstart=np.zeros(ysize+1)
ystop=ystart
xstop=xstart+xsize
xstart2=xstart*c - ystart*s
xstop2=xstop*c - ystop*s
ystart2=xstart*s + ystart*c
ystop2=xstop*s + ystop*c
# Horizontal lines
for i in range(ysize+1):
plt.plot([xstart2[i],xstop2[i]],[ystart2[i],ystop2[i]],'g')
# mask = [0,1,2,...,len(xvals)-1]
mask=(np.linspace(0,len(xvals)-1,len(xvals))).astype('int')
# find the pixel positions
# Clockwise rotation by angle
xpix=((xvals[mask])*c + (yvals[mask])*s)
ypix=(-1.*(xvals[mask])*s + (yvals[mask])*c)
# Plot the locations of the good pixels
plt.plot(xvals[mask],yvals[mask],'b+')
#xpix=xpix.astype('int')
#ypix=ypix.astype('int')
# Count the number of pixels inside the entire grid
numfound += len(np.where((xpix < xsize)&(xpix>-1)&(ypix > -1)&(ypix<ysize))[0])
print numfound, 'pixels in grid'
plt.show()
# look for regions with fewest gaps
# how are these values determined? Originally 5,5
xsize=5
ysize=5
goodgrid=np.zeros((xsize,ysize))
idx=freqvals.argsort()
print len(xpix), len(freqvals)
f= open('freq_atten_x_y.txt','w')
for i in range(len(xpix)):
# print freqvals[idx[i]], xpix[idx[i]], ypix[idx[i]]
f= open('freq_atten_x_y.txt','a')
f.write(str(freqvals[idx[i]]) + '\t' + str(attenvals[idx[i]]) +'\t' + str(xpix[idx[i]]) + '\t' + str(ypix[idx[i]]) +'\n')
f.close()
xmin=np.max([0,xpix[i]-xsize])
xmax=np.min([xsize,xpix[i]+xsize])
ymin=np.max([0,ypix[i]-xsize])
ymax=np.min([ysize,ypix[i]+xsize])
goodgrid[xmin:xmax,ymin:ymax] += 1
print goodgrid, np.max(goodgrid)
plt.imshow(goodgrid)
#plt.show()
| 5,595 | 25.77512 | 125 | py |
SDR | SDR-master/Setup/Beammapping/TxtToBeamImg.py | #!/usr/bin/env python
# encoding: utf-8
"""
TxtToBeamImg.py
Converts a text file to a beamimage h5 file
"""
import numpy as np
import random
from tables import *
import os
#path = '/home/sean/data/20121202/'
path='/home/sean/SDR/Projects/BestBeammap/'
outfile = path + 'sci4_beammap_palomar.h5'
placeUnbeammappedPixels = 0
# make beamap group
h5file = openFile(outfile, mode = "w")
bgroup = h5file.createGroup('/','beammap','Beam Map of Array')
nRow = 46
nCol = 44
# make beammap array - this is a 2d array (top left is 0,0. first index is column, second is row) containing a string with the name of the group holding the photon data
filt1 = Filters(complevel=0, complib='zlib', fletcher32=False) # without minimal compression the files sizes are ridiculous...
ca = h5file.createCArray(bgroup, 'beamimage', StringAtom(itemsize=40), (nRow,nCol), filters=filt1)
resfreq = h5file.createCArray(bgroup, 'resfreq', Float32Atom(), (nRow,nCol), filters=filt1)
atten = h5file.createCArray(bgroup, 'atten', Float32Atom(), (nRow,nCol), filters=filt1)
# load of the text file with resonator data in it and use it to make the beamimage
noloc = []
overlaps = 0
nRoach = 8
nPixel = 253
nPixelsPerRoach = 253
posList = np.recfromtxt(path+'freq_atten_x_y_swap-Sorted.txt')
posListRefined = np.loadtxt(path+'freq_atten_x_y-PalSwap.txt')
#posList = posList[np.logical_or(np.array([name[2] for name in pixelNames])=='0', np.array([name[2] for name in pixelNames])=='1')]#pick out positions for roach 4
#posFreqList = posList['f0']
#posAttenList = posList['f1']
#xList = np.round(posList['f2'])
#yList = np.round(posList['f3'])
posFreqList = posListRefined[:,0]
posAttenList = posListRefined[:,1]
xList = posListRefined[:,2]
yList = posListRefined[:,3]
pixelNames = posList['f4']
completePixelList = ['/r%d/p%d/'%(iRoach,iPixel) for iRoach in range(nRoach) for iPixel in range(nPixel)]
noloc = [pixel for pixel in completePixelList if not pixel in pixelNames]
for iPos,pixelName in enumerate(pixelNames):
x = xList[iPos]
y = yList[iPos]
freq = posFreqList[iPos]
attenval = posAttenList[iPos]
print x,y,pixelName
if x >= 0 and y >= 0 and x < nCol and y <nRow:
if ca[y,x] != '':
print 'overlapping pixel!'
overlaps += 1
noloc.append(pixelName)
else:
ca[y,x] = pixelName
atten[y,x] = attenval
resfreq[y,x] = freq
h5file.flush()
else:
print 'Pixel location out of bounds'
noloc.append(pixelName)
ca.flush()
#fill the rest in randomly
print len(pixelNames),'good pixels'
for iEmptyPix,pixelName in enumerate(noloc):
row = random.randint(0,45)
col = random.randint(0,43)
while (ca[row,col] != ''):
row = random.randint(0,45)
col = random.randint(0,43)
if placeUnbeammappedPixels == 0:
pixelName = '/r0/p250/'
ca[row,col] = pixelName
h5file.flush()
h5file.close()
print len(noloc),'Unplaced pixels'
print overlaps, 'Overlapping pixels'
#iEmptyPix = 0
#for row in xrange(nRow):
# for col in xrange(nCol):
# if ca[row,col] == '':
# ca[row,col] = noloc[iEmptyPix]
# iEmptyPix += 1
#smartfill = False
#if smartfill == True:
# xOnlyPosList = np.recfromtxt(path+'good_x_right.txt')
# xOnlyFreqList = xOnlyPosList['f0']
# xOnlyAttenList = xOnlyPosList['f1']
# xOnlyXList = xOnlyPosList['f2']
# xOnlyPixelNames = xOnlyPosList['f4']
#
# yOnlyPosList = np.recfromtxt(path+'good_y_right.txt')
# yOnlyFreqList = yOnlyPosList['f0']
# yOnlyAttenList = yOnlyPosList['f1']
# yOnlyYList = yOnlyPosList['f3']
# yOnlyPixelNames = yOnlyPosList['f4']
#
#print ''
#print 'now x only pixels'
#for iPos,pixelName in enumerate(xOnlyPixelNames):
# x = xOnlyXList[iPos]
# freq = xOnlyFreqList[iPos]
# attenval = xOnlyFreqList[iPos]
# print x,pixelName,
# if x >=0 and x < nCol:
# possibleY = np.where(ca[:,x] == '')[0]
# if len(possibleY) > 0:
# y = possibleY[0]
# ca[y,x] = pixelName
# atten[y,x] = attenval
# resfreq[y,x] = freq
# h5file.flush()
# print 'placed at ',y
# else:
# print ''
# print 'Nowhere at x to place it'
# overlaps += 1
# noloc.append(pixelName)
# else:
# print ''
# print 'Pixel location out of bounds'
# noloc.append(pixelName)
#
#
#print 'now y only pixels'
#for iPos,pixelName in enumerate(yOnlyPixelNames):
# y = yOnlyYList[iPos]
# freq = yOnlyFreqList[iPos]
# attenval = yOnlyFreqList[iPos]
# print y,pixelName,
# if y >=0 and y < nRow:
# possibleX = np.where(ca[y,:] == '')[0]
# if len(possibleX) > 0:
# x = possibleX[0]
# ca[y,x] = pixelName
# atten[y,x] = attenval
# resfreq[y,x] = freq
# h5file.flush()
# print 'placed at ',x
# else:
# print ''
# print 'Nowhere at y to place it'
# overlaps += 1
# noloc.append(pixelName)
# else:
# print ''
# print 'Pixel location out of bounds'
# noloc.append(pixelName)
##fill the rest in randomly
#for iEmptyPix,pixelName in enumerate(noloc):
# row = random.randint(0,45)
# col = random.randint(0,43)
# while (ca[row,col] != ''):
# row = random.randint(0,45)
# col = random.randint(0,43)
# if placeUnbeammappedPixels == 0:
# pixelName = '/r0/p250/'
# ca[row,col] = pixelName
#
#h5file.flush()
#h5file.close()
#print len(pixelNames),'good pixels'
#print len(xOnlyPixelNames),'x only pixels'
#print len(yOnlyPixelNames),'y only pixels'
#print len(noloc),'Unbeammpped pixels'
#print overlaps, 'Overlapping pixels'
| 5,798 | 30.516304 | 169 | py |
SDR | SDR-master/Setup/lib/PSFit_GUI_v2.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'PSFit_GUI_v2.ui'
#
# Created: Sat Aug 23 17:37:02 2014
# by: PyQt4 UI code generator 4.9.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(1100, 750)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.open_filename = QtGui.QLineEdit(self.centralwidget)
self.open_filename.setGeometry(QtCore.QRect(10, 210, 431, 21))
self.open_filename.setObjectName(_fromUtf8("open_filename"))
self.save_filename = QtGui.QLineEdit(self.centralwidget)
self.save_filename.setGeometry(QtCore.QRect(10, 240, 431, 21))
self.save_filename.setObjectName(_fromUtf8("save_filename"))
self.plot_1 = MPL_Widget(self.centralwidget)
self.plot_1.setGeometry(QtCore.QRect(10, 290, 541, 401))
self.plot_1.setObjectName(_fromUtf8("plot_1"))
self.plot_2 = MPL_Widget(self.centralwidget)
self.plot_2.setGeometry(QtCore.QRect(560, 290, 541, 401))
self.plot_2.setObjectName(_fromUtf8("plot_2"))
self.plot_3 = MPL_Widget(self.centralwidget)
self.plot_3.setGeometry(QtCore.QRect(450, 10, 651, 281))
self.plot_3.setObjectName(_fromUtf8("plot_3"))
self.widget = QtGui.QWidget(self.centralwidget)
self.widget.setGeometry(QtCore.QRect(10, 10, 431, 181))
self.widget.setObjectName(_fromUtf8("widget"))
self.gridLayout = QtGui.QGridLayout(self.widget)
self.gridLayout.setMargin(0)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.open_browse = QtGui.QPushButton(self.widget)
self.open_browse.setObjectName(_fromUtf8("open_browse"))
self.gridLayout.addWidget(self.open_browse, 0, 0, 1, 1)
self.jumptonum = QtGui.QSpinBox(self.widget)
self.jumptonum.setGeometry(QtCore.QRect(810, 690, 57, 31))
self.jumptonum.setMaximum(9999)
self.jumptonum.setObjectName(_fromUtf8("jumptonum"))
self.gridLayout.addWidget(self.jumptonum, 1, 1, 1, 1)
self.frequency = QtGui.QLabel(self.widget)
self.frequency.setObjectName(_fromUtf8("frequency"))
self.gridLayout.addWidget(self.frequency, 3, 6, 1, 1)
self.save_browse = QtGui.QPushButton(self.widget)
self.save_browse.setObjectName(_fromUtf8("save_browse"))
self.gridLayout.addWidget(self.save_browse, 0, 1, 1, 1)
self.atten = QtGui.QSpinBox(self.widget)
self.atten.setMaximumSize(QtCore.QSize(776, 16777215))
self.atten.setObjectName(_fromUtf8("atten"))
self.gridLayout.addWidget(self.atten, 3, 1, 1, 1)
self.jumptores = QtGui.QPushButton(self.widget)
self.jumptores.setObjectName(_fromUtf8("jumptores"))
self.gridLayout.addWidget(self.jumptores, 1, 0, 1, 1)
self.label = QtGui.QLabel(self.widget)
self.label.setObjectName(_fromUtf8("label"))
self.gridLayout.addWidget(self.label, 3, 0, 1, 1)
self.res_num = QtGui.QLabel(self.widget)
self.res_num.setStatusTip(_fromUtf8(""))
self.res_num.setObjectName(_fromUtf8("res_num"))
self.gridLayout.addWidget(self.res_num, 1, 6, 1, 1)
self.savevalues = QtGui.QPushButton(self.widget)
self.savevalues.setObjectName(_fromUtf8("savevalues"))
self.gridLayout.addWidget(self.savevalues, 4, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1100, 22))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.actionOpen = QtGui.QAction(MainWindow)
self.actionOpen.setObjectName(_fromUtf8("actionOpen"))
self.s = QtGui.QAction(MainWindow)
self.s.setObjectName(_fromUtf8("s"))
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
self.open_browse.setText(QtGui.QApplication.translate("MainWindow", "Open", None, QtGui.QApplication.UnicodeUTF8))
self.jumptonum.setToolTip(QtGui.QApplication.translate("MainWindow", "Resonator Number", None, QtGui.QApplication.UnicodeUTF8))
self.frequency.setToolTip(QtGui.QApplication.translate("MainWindow", "Frequency (GHz)", None, QtGui.QApplication.UnicodeUTF8))
self.frequency.setText(QtGui.QApplication.translate("MainWindow", "-1", None, QtGui.QApplication.UnicodeUTF8))
self.save_browse.setText(QtGui.QApplication.translate("MainWindow", "Save", None, QtGui.QApplication.UnicodeUTF8))
self.atten.setToolTip(QtGui.QApplication.translate("MainWindow", "Attenuation", None, QtGui.QApplication.UnicodeUTF8))
self.jumptores.setText(QtGui.QApplication.translate("MainWindow", "Jump To Res", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("MainWindow", "atten", None, QtGui.QApplication.UnicodeUTF8))
self.res_num.setToolTip(QtGui.QApplication.translate("MainWindow", "Resonator Number", None, QtGui.QApplication.UnicodeUTF8))
self.res_num.setText(QtGui.QApplication.translate("MainWindow", "-1", None, QtGui.QApplication.UnicodeUTF8))
self.savevalues.setToolTip(QtGui.QApplication.translate("MainWindow", "Save this resonator and move to next one", None, QtGui.QApplication.UnicodeUTF8))
self.savevalues.setText(QtGui.QApplication.translate("MainWindow", "Save Values", None, QtGui.QApplication.UnicodeUTF8))
self.actionOpen.setText(QtGui.QApplication.translate("MainWindow", "Open", None, QtGui.QApplication.UnicodeUTF8))
self.s.setText(QtGui.QApplication.translate("MainWindow", "Save", None, QtGui.QApplication.UnicodeUTF8))
from lib.mpl_pyqt4_widget import MPL_Widget
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
| 6,653 | 54.915966 | 160 | py |
SDR | SDR-master/Setup/lib/PSFit_GUI.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'PSFit_GUI.ui'
#
# Created: Sun Jul 24 13:04:12 2011
# by: PyQt4 UI code generator 4.8.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(915, 1010)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.plot_1 = MPL_Widget(self.centralwidget)
self.plot_1.setGeometry(QtCore.QRect(20, 10, 891, 311))
self.plot_1.setObjectName(_fromUtf8("plot_1"))
self.plot_2 = MPL_Widget(self.centralwidget)
self.plot_2.setGeometry(QtCore.QRect(20, 330, 891, 331))
self.plot_2.setObjectName(_fromUtf8("plot_2"))
self.plot_3 = MPL_Widget(self.centralwidget)
self.plot_3.setGeometry(QtCore.QRect(290, 660, 391, 301))
self.plot_3.setObjectName(_fromUtf8("plot_3"))
self.frequency = QtGui.QLabel(self.centralwidget)
self.frequency.setGeometry(QtCore.QRect(790, 760, 62, 17))
self.frequency.setObjectName(_fromUtf8("frequency"))
self.atten = QtGui.QSpinBox(self.centralwidget)
self.atten.setGeometry(QtCore.QRect(770, 790, 61, 31))
self.atten.setObjectName(_fromUtf8("atten"))
self.label = QtGui.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(710, 760, 71, 17))
self.label.setObjectName(_fromUtf8("label"))
self.savevalues = QtGui.QPushButton(self.centralwidget)
self.savevalues.setGeometry(QtCore.QRect(730, 870, 131, 41))
self.savevalues.setObjectName(_fromUtf8("savevalues"))
self.label_2 = QtGui.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(710, 730, 91, 17))
self.label_2.setObjectName(_fromUtf8("label_2"))
self.res_num = QtGui.QLabel(self.centralwidget)
self.res_num.setGeometry(QtCore.QRect(810, 730, 62, 17))
self.res_num.setObjectName(_fromUtf8("res_num"))
self.open_browse = QtGui.QPushButton(self.centralwidget)
self.open_browse.setGeometry(QtCore.QRect(20, 700, 114, 32))
self.open_browse.setObjectName(_fromUtf8("open_browse"))
self.open_filename = QtGui.QLineEdit(self.centralwidget)
self.open_filename.setGeometry(QtCore.QRect(20, 740, 261, 22))
self.open_filename.setObjectName(_fromUtf8("open_filename"))
self.save_browse = QtGui.QPushButton(self.centralwidget)
self.save_browse.setGeometry(QtCore.QRect(20, 780, 114, 32))
self.save_browse.setObjectName(_fromUtf8("save_browse"))
self.save_filename = QtGui.QLineEdit(self.centralwidget)
self.save_filename.setGeometry(QtCore.QRect(20, 820, 261, 22))
self.save_filename.setObjectName(_fromUtf8("save_filename"))
self.label_3 = QtGui.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(710, 800, 62, 17))
self.label_3.setObjectName(_fromUtf8("label_3"))
self.jumptores = QtGui.QPushButton(self.centralwidget)
self.jumptores.setGeometry(QtCore.QRect(690, 686, 111, 41))
self.jumptores.setObjectName(_fromUtf8("jumptores"))
self.jumptonum = QtGui.QSpinBox(self.centralwidget)
self.jumptonum.setGeometry(QtCore.QRect(810, 690, 57, 31))
self.jumptonum.setMaximum(9999)
self.jumptonum.setObjectName(_fromUtf8("jumptonum"))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 915, 22))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
self.frequency.setText(QtGui.QApplication.translate("MainWindow", "TextLabel", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("MainWindow", "Frequency:", None, QtGui.QApplication.UnicodeUTF8))
self.savevalues.setText(QtGui.QApplication.translate("MainWindow", "Save Values", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setText(QtGui.QApplication.translate("MainWindow", "Res number:", None, QtGui.QApplication.UnicodeUTF8))
self.res_num.setText(QtGui.QApplication.translate("MainWindow", "TextLabel", None, QtGui.QApplication.UnicodeUTF8))
self.open_browse.setText(QtGui.QApplication.translate("MainWindow", "Open", None, QtGui.QApplication.UnicodeUTF8))
self.save_browse.setText(QtGui.QApplication.translate("MainWindow", "Save to:", None, QtGui.QApplication.UnicodeUTF8))
self.label_3.setText(QtGui.QApplication.translate("MainWindow", "Atten:", None, QtGui.QApplication.UnicodeUTF8))
self.jumptores.setText(QtGui.QApplication.translate("MainWindow", "Jump to Res", None, QtGui.QApplication.UnicodeUTF8))
from mpl_pyqt4_widget import MPL_Widget
| 5,518 | 55.896907 | 129 | py |
SDR | SDR-master/Setup/lib/mpl_pyqt4_widget.py | #!/usr/bin/env python
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4 import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import numpy as N
class MyMplCanvas(FigureCanvas):
def __init__(self, parent=None, width = 10, height = 12, dpi = 100, sharex = None, sharey = None):
self.fig = Figure(figsize = (width, height), dpi=dpi, facecolor = '#FFFFFF')
self.ax = self.fig.add_subplot(111, sharex = sharex, sharey = sharey)
self.fig.subplots_adjust(left=0.12, bottom=0.15, right=0.97, top=0.97)
self.xtitle="Wavelength"
self.ytitle="Counts"
#self.PlotTitle = "Some Plot"
self.grid_status = True
self.xaxis_style = 'linear'
self.yaxis_style = 'linear'
self.format_labels()
self.ax.hold(True)
FigureCanvas.__init__(self, self.fig)
#self.fc = FigureCanvas(self.fig)
FigureCanvas.setSizePolicy(self,
QSizePolicy.Expanding,
QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
def format_labels(self):
#self.ax.set_title(self.PlotTitle)
self.ax.title.set_fontsize(7)
self.ax.set_xlabel(self.xtitle, fontsize = 7)
self.ax.set_ylabel(self.ytitle, fontsize = 7)
labels_x = self.ax.get_xticklabels()
labels_y = self.ax.get_yticklabels()
for xlabel in labels_x:
xlabel.set_fontsize(7)
for ylabel in labels_y:
ylabel.set_fontsize(7)
ylabel.set_color('b')
def sizeHint(self):
w, h = self.get_width_height()
return QSize(w, h)
def minimumSizeHint(self):
return QSize(10, 10)
def sizeHint(self):
w, h = self.get_width_height()
return QSize(w, h)
def minimumSizeHint(self):
return QSize(10, 10)
class MPL_Widget(QWidget):
def __init__(self, parent = None):
QWidget.__init__(self, parent)
self.canvas = MyMplCanvas()
#self.toolbar = NavigationToolbar(self.canvas, self.canvas)
self.vbox = QVBoxLayout()
self.vbox.addWidget(self.canvas)
#self.vbox.addWidget(self.toolbar)
self.setLayout(self.vbox)
| 2,089 | 28.43662 | 99 | py |
SDR | SDR-master/Setup/lib/__init__.py | 0 | 0 | 0 | py |
|
SDR | SDR-master/Setup/lib/iqsweep.py | #!/usr/bin/env python
# encoding: utf-8
"""
iqsweep.py
Created by Ben Mazin on 2011-03-24.
Copyright (c) 2011 . All rights reserved.
"""
from tables import *
import numpy as np
import os
import sys
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import time
import pdb
#import powspec_rebin
class IQsweeptables(IsDescription):
"""The pytables derived class that hold IQ sweep data on the disk
"""
# recorded data
f0 = Float32Col()
span = Float32Col()
fsteps = Int32Col()
atten1 = Int32Col()
atten2 = Int32Col()
scale = Float32Col()
PreadoutdB = Float32Col()
Tstart = Float32Col()
Tend = Float32Col()
I0 = Float32Col()
Q0 = Float32Col()
resnum = Int32Col()
freq = Float32Col(2000)
I = Float32Col(2000)
Q = Float32Col(2000)
Isd = Float32Col(2000)
Qsd = Float32Col(2000)
time = Float64Col()
# data products from loop fit
vmaxidx = Int32Col()
Iceng = Float32Col()
Qceng = Float32Col()
Icen = Float32Col()
Qcen = Float32Col()
Qm = Float32Col()
Qc = Float32Col()
Qi = Float32Col()
fm = Float32Col()
dipdb = Float32Col()
popt = Float32Col(10)
fpoints = Float32Col()
fI = Float32Col(2000)
fQ = Float32Col(2000)
ff = Float32Col(2000)
# data products from mag fit
mag = Float32Col(2000)
magfreq = Float32Col(2000)
magfit = Float32Col(2000)
mopt = Float32Col(6)
# data products from noise analysis
savenoise = Int32Col()
samprate = Float32Col()
pn = Float32Col(2552)
pnidx = Float32Col(2552)
an = Float32Col(2552)
anidx = Float32Col(2552)
fn1k = Float32Col()
class optimalpow(IsDescription):
"""The pytables derived class that stored the optimal readout power and f0 for the resonator
"""
Pmax = Float32Col()
f0 = Float32Col()
class IQsweep:
"""A class for IQ sweep data designed to be compatible with pytables.
Holds the IQ response of a single resonator and functions that process it.
LoadSWP(filename,resnum) method to load the standard .swp files from the analog readout into an object.
FitLoopMP() method fits the sweep data with Ben's loop fit code
FitMagMP() method fits the sweep data with Ben's simple magnitue fit code
AnalyzeNoise() method crunches the noise data
Save(filename,gstring,mode) method saves the class in h5 file filename in group gstring ('r0','r1',etc) with write mode mode ('w','a')
Load(filename,gstring,f0,atten1) method loads sweep data from h5 file filename with center freq f0 and input atten setting atten1
Pdf(filename) plots the IQ sweep (and fit if present) to a pdf file
"""
def __init__(self):
pass
def LoadSWP(self,filename,resnum): # Load sweep data from .swp format text files
self.resnum = resnum
#read header
f = open(filename, 'r')
h1,h2,h3,self.atten1 = np.fromstring(f.readline()[:-1],dtype=np.float32,sep='\t')
h4,h5,h6,self.atten2 = np.fromstring(f.readline()[:-1],dtype=np.float32,sep='\t')
self.Tstart,self.Tend = np.fromstring(f.readline()[:-1],dtype=np.float32,sep='\t')
Iz1,Iz1sd = np.fromstring(f.readline()[:-1],dtype=np.float32,sep='\t')
Qz1,Qz1sd = np.fromstring(f.readline()[:-1],dtype=np.float32,sep='\t')
Iz2,Iz2sd = np.fromstring(f.readline()[:-1],dtype=np.float32,sep='\t')
Qz2,Qz2sd = np.fromstring(f.readline()[:-1],dtype=np.float32,sep='\t')
f.close()
#read table
data = np.loadtxt(filename, skiprows=7)
self.time = time.time()
self.savenoise = 0
if self.resnum == 0:
self.f0 = h1
self.span = h2
self.fsteps = int(h3)
self.I0 = Iz1
self.Q0 = Qz1
self.freq = data[:self.fsteps,0]
self.I = data[:self.fsteps,1]
self.Q = data[:self.fsteps,3]
self.Isd = data[:self.fsteps,2]
self.Qsd = data[:self.fsteps,4]
else:
self.f0 = h4
self.span = h5
self.fsteps = int(h6)
self.I0 = Iz2
self.Q0 = Qz2
self.freq = data[h3:h3+self.fsteps,0]
self.I = data[h3:h3+self.fsteps,1]
self.Q = data[h3:h3+self.fsteps,3]
self.Isd = data[h3:h3+self.fsteps,2]
self.Qsd = data[h3:h3+self.fsteps,4]
def FitLoopMP(self): # Fit the sweep using the full IQ data with MPFIT!
import mpfit
# find center from IQ max
vel = np.sqrt((self.I[0:self.fsteps-2]-self.I[1:self.fsteps-1])**2 + (self.Q[0:self.fsteps-2]-self.Q[1:self.fsteps-1])**2)
svel = smooth(vel)
cidx = (np.where(svel==max(svel)))[0]
self.vmaxidx = cidx[0]
# Try to pass fsteps/2 points but work even if closer to the edge than that
low = cidx - self.fsteps/4
if low < 0:
low = 0
high = cidx + self.fsteps/4
if cidx > self.fsteps :
high = self.fsteps
#print cidx,low,high
idx = self.freq[low:high]*1e9
I = self.I[low:high]-self.I0
Q = self.Q[low:high]-self.Q0
#print len(I)
s21 = np.zeros(len(I)*2)
s21[:len(I)] = I
s21[len(I):] = Q
sigma = np.zeros(len(I)*2)
sigma[:len(I)] = self.Isd[low:high]
sigma[len(I):] = self.Qsd[low:high]
# take a guess at center
self.Iceng = (max(I)-min(I))/2.0 + min(I)
self.Qceng = (max(Q)-min(Q))/2.0 + min(Q)
ang = np.arctan2( Q[self.fsteps/4] - self.Qceng, I[self.fsteps/4] - self.Iceng )
#print ang
if ang >= 0 and ang <= np.pi:
ang -= np.pi/2
if ang >= -np.pi and ang < 0:
ang += np.pi/2
#print Q[self.fsteps/4]-self.Qceng, I[self.fsteps/4]-self.Iceng
#print ang
#parinfo = [{'value':0., 'fixed':0, 'limited':[1,1], 'limits':[0.,0.]}]*10
parinfo=[ {'value':0., 'fixed':0, 'limited':[1,1], 'limits':[0.,0.]} for i in range(10) ]
parinfo[0]['value'] = 50000.0
parinfo[0]['limits'] = [5000.0,1e6]
parinfo[1]['value'] = np.mean(idx)
parinfo[1]['limits'] = [ np.min(idx),np.max(idx)]
parinfo[2]['value'] = 1.0
parinfo[2]['limits'] = [1e-4,1e2]
parinfo[3]['value'] = 800.0
parinfo[3]['limits'] = [1.0,4e4]
parinfo[4]['value'] = 500.0
parinfo[4]['limits'] = [-5000.0,5000.0]
parinfo[5]['value'] = ang
parinfo[5]['limits'] = [-np.pi*1.1,np.pi*1.1]
parinfo[6]['value'] = np.max(I[low:high]) - np.min(I[low:high])
parinfo[6]['limits'] = [parinfo[6]['value'] - 0.5*parinfo[6]['value'] , parinfo[6]['value'] + 0.5*parinfo[6]['value'] ]
parinfo[7]['value'] = np.max(Q[low:high]) - np.min(Q[low:high])
parinfo[7]['limits'] = [parinfo[7]['value'] - 0.5*parinfo[7]['value'] , parinfo[7]['value'] + 0.5*parinfo[6]['value'] ]
parinfo[8]['value'] = self.Iceng
parinfo[8]['limits'] = [parinfo[8]['value'] - np.abs(0.5*parinfo[8]['value']) , parinfo[8]['value'] + np.abs(0.5*parinfo[8]['value']) ]
parinfo[9]['value'] = self.Qceng
parinfo[9]['limits'] = [parinfo[9]['value'] - np.abs(0.5*parinfo[9]['value']) , parinfo[9]['value'] + np.abs(0.5*parinfo[9]['value']) ]
fa = {'x':idx, 'y':s21, 'err':sigma}
#pdb.set_trace()
# use magfit Q if available
try:
Qguess = np.repeat(self.mopt[0],10)
except:
Qguess = np.repeat(range(10)*10000)
chisq=1e50
for x in range(10):
# Fit
Qtry = Qguess[x] + 20000.0*np.random.normal()
if Qtry < 5000.0:
Qtry = 5000.0
parinfo[0]['value'] = Qtry
parinfo[2]['value'] = 1.1e-4 + np.random.uniform()*90.0
parinfo[3]['value'] = 1.0 + np.random.uniform()*3e4
parinfo[4]['value'] = np.random.uniform()*9000.0 - 4500.0
if x > 5:
parinfo[5]['value'] = np.random.uniform(-1,1)*np.pi
# fit!
m = mpfit.mpfit(RESDIFFMP,functkw=fa,parinfo=parinfo,quiet=1)
popt = m.params
newchisq = m.fnorm
if newchisq < chisq:
chisq = newchisq
bestpopt = m.params
try:
popt = bestpopt
except:
popt = m.params
self.popt = popt
self.Icen = popt[8]
self.Qcen = popt[9]
fit = RESDIFF(idx,popt[0],popt[1],popt[2],popt[3],popt[4],popt[5],popt[6],popt[7],popt[8],popt[9])
#pdb.set_trace()
# compute dipdb,Qc,Qi
radius = abs((popt[6]+popt[7]))/4.0
diam = (2.0*radius) / (np.sqrt(popt[8]**2 + popt[9]**2) + radius)
Qc = popt[0]/diam
Qi = popt[0]/(1.0-diam)
dip = 1.0 - 2.0*radius/(np.sqrt(popt[8]**2 + popt[9]**2) + radius)
dipdb = 20.0*np.log10(dip)
# internal power
power = 10.0**((-self.atten1-35.0)/10.0)
Pint = 10.0*np.log10((2.0 * self.popt[0]**2/(np.pi * Qc))*power)
#print popt
#print radius,diam,Qc,Qi,dip,dipdb
self.Qm = popt[0]
self.fm = popt[1]
self.Qc = Qc
self.Qi = Qi
self.dipdb = dipdb
self.Pint = Pint
self.fpoints = len(I)
self.fI = fit[:len(I)]
self.fQ = fit[len(I):]
self.ff = self.freq[low:high]
def FitMagMP(self): # Fit the sweep using just the magnitude data
import mpfit
# find center from IQ max
vel = np.sqrt((self.I[0:self.fsteps-2]-self.I[1:self.fsteps-1])**2 + (self.Q[0:self.fsteps-2]-self.Q[1:self.fsteps-1])**2)
svel = smooth(vel)
cidx = (np.where(svel==max(svel)))[0]
self.vmaxidx = cidx[0]
idx = self.freq*1e9
mag = np.sqrt((self.I-self.I0)**2 + (self.Q-self.Q0)**2)
norm = np.max(mag)
mag = mag / norm
#Q,f0,carrier,depth,slope,curve
parinfo=[ {'value':0., 'fixed':0, 'limited':[1,1], 'limits':[0.,0.]} for i in range(6) ]
parinfo[0]['value'] = 50000.0
parinfo[0]['limits'] = [5000.0,1e6]
parinfo[1]['value'] = np.mean(idx)
parinfo[1]['limits'] = [ np.min(idx),np.max(idx)]
parinfo[2]['value'] = 1.0
parinfo[2]['limits'] = [1e-4,1e2]
parinfo[3]['value'] = 0.7
parinfo[3]['limits'] = [0.01,10.0]
parinfo[4]['value'] = 0.1
parinfo[4]['limits'] = [-5000.0,5000.0]
parinfo[5]['value'] = -10.0
parinfo[5]['limits'] = [-1e8,1e8]
sigma = np.repeat(0.00001,len(mag))
fa = {'x':idx, 'y':mag, 'err':sigma}
#pdb.set_trace()
chisq=1e50
for x in range(10):
# Fit
Qtry = x*10000.0 + 5000.0*np.random.normal()
if Qtry < 5000.0:
Qtry = 5000.0
parinfo[0]['value'] = Qtry
# fit!
m = mpfit.mpfit(MAGDIFFMP,functkw=fa,parinfo=parinfo,quiet=1)
popt = m.params
newchisq = m.fnorm
#print newchisq
if newchisq < chisq:
chisq = newchisq
bestpopt = m.params
popt = bestpopt
#print popt
fit = MAGDIFF(idx,popt[0],popt[1],popt[2],popt[3],popt[4],popt[5])
self.mag = np.sqrt((self.I-self.I0)**2 + (self.Q-self.Q0)**2)/norm
self.magfreq = self.freq
self.magfit = fit
self.mopt = popt
def PlotIQ(self): # Plot the sweep
fig = plt.figure( figsize=(8, 6), dpi=100)
ax = fig.add_subplot(111)
ax.plot(self.I[:self.fsteps]-self.I0,self.Q[:self.fsteps]-self.Q0,'bo')
ax.plot(self.Iceng,self.Qceng,'gx')
ax.plot(self.I[self.vmaxidx]-self.I0,self.Q[self.vmaxidx]-self.Q0,'go')
ax.plot(self.Icen,self.Qcen,'rx')
ax.plot(self.fI,self.fQ,'r')
#leg = ax.legend(['Q = ' + '{0:.2f}'.format(self.popt[0]), 'f$_0$ = ' + '{0:.6f}'.format(self.popt[1]/1e9), 'Q$_c$ = ' + '{0:.2f}'.format(self.Qc),'Q$_i$ = ' + '{0:.2f}'.format(self.Qi),'|S$_{21}$|$_{min}$ = ' + '{0:.2f}'.format(self.dipdb)],loc=4, shadow=True,numpoints=1)
#print 'Q = ' + '{0:.2f}'.format(self.popt[0]) + '\nf$_0$ = ' + '{0:.6f}'.format(self.popt[1]/1e9) + '\nQ$_c$ = ' + '{0:.2f}'.format(self.Qc) + '\nQ$_i$ = ' + '{0:.2f}'.format(self.Qi) + '\n|S$_{21}$|$_{min}$ = ' + '{0:.2f}'.format(self.dipdb)
#leg = ax.text(.5,.5,'Q = ' + '{0:.2f}'.format(self.popt[0]) + '\nf$_0$ = ' + '{0:.6f}'.format(self.popt[1]/1e9) + '\nQ$_c$ = ' + '{0:.2f}'.format(self.Qc) + '\nQ$_i$ = ' + '{0:.2f}'.format(self.Qi) + '\n|S$_{21}$|$_{min}$ = ' + '{0:.2f}'.format(self.dipdb),transform=ax.transAxes)
ax.grid(False)
ax.set_xlabel('I')
ax.set_ylabel('Q')
# the matplotlib.patches.Rectangle instance surrounding the legend
#frame = leg.get_frame()
#frame.set_facecolor('0.80') # set the frame face color to light gray
# matplotlib.text.Text instances
#for t in leg.get_texts():
# t.set_fontsize('small') # the legend text fontsize
# matplotlib.lines.Line2D instances
#for l in leg.get_lines():
# l.set_linewidth(1.5) # the legend line width
plt.show()
def PlotMag(self): # Plot the sweep
fig = plt.figure( figsize=(8, 6), dpi=100)
ax = fig.add_subplot(111)
ax.plot(self.freq,20.0*np.log10(self.mag),'bo')
ax.plot(self.magfreq,20.0*np.log10(self.magfit),'r')
ax.grid(False)
ax.set_xlabel('Frequency (GHz)')
ax.set_ylabel('|S$_{21}$| (dB)')
plt.show()
def Save(self,filename,roach,wmode): # Save IQ sweep data into a HDF5 file
h5file = openFile(filename, mode = wmode, title = "IQ sweep file created " + time.asctime() )
# if there is no existing roach group, create one
try:
#group = h5file.root.r0
group = h5file.getNode('/',roach )
except:
group = h5file.createGroup("/",roach, 'ROACH Identifier' )
# if there is no existing sweep group, create one
#if group.__contains__('sweeps'):
# group = group.sweeps
#else:
# group = h5file.createGroup(group,'sweeps', 'IQ sweep data' )
# make a group for each resonator
try:
group = h5file.getNode(group,'f'+str(int(np.float32(self.f0)*10000.0)) )
except:
group = h5file.createGroup(group,'f'+str(int(np.float32(self.f0)*10000.0)), 'Group Created ' + time.ctime(self.time) )
# store sweeps with various Tstart and atten settings in the same table
try:
table = group.iqsweep
swp = group.iqsweep.row
except:
filt = Filters(complevel=5, complib='zlib', fletcher32=True)
table = h5file.createTable(group,'iqsweep', IQsweeptables, "IQ Sweep Data",filters=filt)
swp = table.row
try:
swp['f0'] = np.float32(self.f0)
swp['span'] = self.span
swp['fsteps'] = self.fsteps
swp['atten1'] = self.atten1
swp['atten2'] = self.atten2
swp['scale'] = self.scale
swp['PreadoutdB'] = self.PreadoutdB
swp['Tstart'] = self.Tstart
swp['Tend'] = self.Tend
swp['I0'] = self.I0
swp['Q0'] = self.Q0
swp['resnum'] = self.resnum
swp['freq'] = np.concatenate( (self.freq,np.zeros(2000-self.fsteps)),axis=0 )
swp['I'] = np.concatenate( (self.I,np.zeros(2000-self.fsteps)),axis=0 )
swp['Q'] = np.concatenate( (self.Q,np.zeros(2000-self.fsteps)),axis=0 )
swp['Isd'] = np.concatenate( (self.Isd,np.zeros(2000-self.fsteps)),axis=0 )
swp['Qsd'] = np.concatenate( (self.Qsd,np.zeros(2000-self.fsteps)),axis=0 )
swp['time'] = self.time
except:
pass
try:
swp['vmaxidx'] = self.vmaxidx
swp['Iceng'] = self.Iceng
swp['Qceng'] = self.Qceng
swp['Icen'] = self.Icen
swp['Qcen'] = self.Qcen
swp['Qm'] = self.Qm
swp['fm'] = self.fm
swp['Qc'] = self.Qc
swp['Qi'] = self.Qi
swp['dipdb'] = self.dipdb
swp['popt'] = self.popt
swp['fpoints'] = self.fpoints
swp['fI'] = np.concatenate( (self.fI,np.zeros(2000-self.fI.__len__())),axis=0 )
swp['fQ'] = np.concatenate( (self.fQ,np.zeros(2000-self.fQ.__len__())),axis=0 )
swp['ff'] = np.concatenate( (self.ff,np.zeros(2000-self.ff.__len__())),axis=0 )
except:
pass
# data products from mag fit
try:
swp['mag'] = np.concatenate( (self.mag,np.zeros(2000-self.fsteps)),axis=0 )
swp['magfreq'] = np.concatenate( (self.magfreq,np.zeros(2000-len(self.magfreq))),axis=0 )
swp['magfit'] = np.concatenate( (self.magfit,np.zeros(2000-len(self.magfit))),axis=0 )
swp['mopt'] = self.mopt
except:
pass
# data products from noise analysis
try:
swp['pn'] = self.pn
swp['pnidx'] = self.pnidx
swp['an'] = self.an
swp['anidx'] = self.anidx
swp['fn1k'] = self.fn1k
except:
pass
# now save noise data if present and save flag is set
if self.savenoise > 0:
try:
swp['samprate'] = self.samprate
swp['savenoise'] = self.savenoise
try:
noise = group.iqnoise
except:
noise = h5file.createVLArray(group, 'iqnoise', Int16Atom(shape=()), "Noise data stored in ragged array of ints. [0] = I, [1] = Q")
noise.append(self.Ix1)
noise.append(self.Qx1)
except:
print "Unexpected error saving noise data: ", sys.exc_info()[0]
swp.append()
table.flush()
h5file.close()
def Load(self,filename,roach,f0,atten): # Load the desired IQ sweep data from a HDF5 file
#load the sweep with center frequency closest to f0 and input atten=atten1
h5file = openFile(filename, mode = "r")
# find the table with the sweep data in it.
try:
group = h5file.getNode('/',roach )
group = h5file.getNode(group,'f'+str(int(f0*10000.0)) )
table = group.iqsweep
k = table.readWhere('atten1 == atten')
except:
print 'Did not find sweep in file!'
h5file.close()
return
try:
self.f0 = k['f0'][0]
self.span = k['span'][0]
self.fsteps = k['fsteps'][0]
self.atten1 = k['atten1'][0]
self.atten2 = k['atten2'][0]
self.scale = k['scale'][0]
self.PreadoutdB = k['PreadoutdB'][0]
self.Tstart = k['Tstart'][0]
self.Tend = k['Tend'][0]
self.I0 = k['I0'][0]
self.Q0 = k['Q0'][0]
self.resnum = k['resnum'][0]
self.time = k['time'][0]
except:
pass
try:
self.freq = k['freq'][0,0:self.fsteps]
self.I = k['I'][0,0:self.fsteps]
self.Q = k['Q'][0,0:self.fsteps]
self.Isd = k['Isd'][0,0:self.fsteps]
self.Qsd = k['Qsd'][0,0:self.fsteps]
self.vmaxidx = k['vmaxidx'][0]
self.Iceng = k['Iceng'][0]
self.Qceng = k['Qceng'][0]
self.Icen = k['Icen'][0]
self.Qcen= k['Qcen'][0]
self.Qm= k['Qm'][0]
self.fm= k['fm'][0]
self.Qc= k['Qc'][0]
self.Qi= k['Qi'][0]
self.dipdb= k['dipdb'][0]
self.popt = k['popt'][0]
self.fpoints = k['fpoints'][0]
self.fI = k['fI'][0,0:self.fpoints]
self.fQ = k['fQ'][0,0:self.fpoints]
self.ff = k['ff'][0,0:self.fpoints]
except:
pass
try:
self.mag = k['mag'][0,0:self.fpoints]
self.magfreq = k['magfreq'][0]
self.magfit = k['magfit'][0]
self.mopt = k['mopt'][0]
except:
pass
try:
self.savenoise = k['savenoise'][0]
self.samprate = k['samprate'][0]
self.pn = k['pn'][0]
self.pnidx = k['pnidx'][0]
self.an = k['an'][0]
self.anidx = k['anidx'][0]
self.kn1k = k['fn1k'][0]
except:
pass
h5file.close()
def LoadPowers(self,filename,roach,f0): # Load the desired IQ sweep data from a HDF5 file
#load the sweep with center frequency closest to f0 and input atten=atten1
h5file = openFile(filename, mode = "r")
# find the table with the sweep data in it.
try:
group = h5file.getNode('/',roach )
group = h5file.getNode(group,'f'+str(int(f0*10000.0)) )
table = group.iqsweep
k = table.read()
except:
print 'Did not find sweep in file!'
h5file.close()
return
try:
self.f0 = k['f0'][0]
self.span = k['span'][0]
self.fsteps = k['fsteps'][0]
self.atten1s = k['atten1']
self.atten2s = k['atten2']
self.scale = k['scale'][0]
self.PreadoutdB = k['PreadoutdB'][0]
self.Tstart = k['Tstart'][0]
self.Tend = k['Tend'][0]
self.I0 = k['I0'][0]
self.Q0 = k['Q0'][0]
self.resnum = k['resnum'][0]
self.time = k['time'][0]
except:
pass
try:
self.freq = k['freq'][0,0:self.fsteps]
self.Is = k['I'][:,0:self.fsteps]
self.Qs = k['Q'][:,0:self.fsteps]
self.Isd = k['Isd'][0,0:self.fsteps]
self.Qsd = k['Qsd'][0,0:self.fsteps]
self.vmaxidx = k['vmaxidx'][0]
self.Icengs = k['Iceng'][0]
self.Qcengs = k['Qceng'][0]
self.Icens = k['Icen']
self.Qcens = k['Qcen']
self.Qm= k['Qm'][0]
self.fm= k['fm'][0]
self.Qc= k['Qc'][0]
self.Qi= k['Qi'][0]
self.dipdb= k['dipdb'][0]
self.popt = k['popt'][0]
self.fpoints = k['fpoints'][0]
self.fI = k['fI'][0,0:self.fpoints]
self.fQ = k['fQ'][0,0:self.fpoints]
self.ff = k['ff'][0,0:self.fpoints]
except:
pass
try:
self.mag = k['mag'][0,0:self.fpoints]
self.magfreq = k['magfreq'][0]
self.magfit = k['magfit'][0]
self.mopt = k['mopt'][0]
except:
pass
try:
self.savenoise = k['savenoise'][0]
self.samprate = k['samprate'][0]
self.pn = k['pn'][0]
self.pnidx = k['pnidx'][0]
self.an = k['an'][0]
self.anidx = k['anidx'][0]
self.kn1k = k['fn1k'][0]
except:
pass
h5file.close()
def LoadLeaf(self,table,row): # Load up sweep table data from a hdf5 table
# speed things up by loading the whole table at once
k = table.read()
try:
self.f0 = k['f0'][row]
self.span = k['span'][row]
self.fsteps = k['fsteps'][row]
self.atten1 = k['atten1'][row]
self.atten2 = k['atten2'][row]
self.scale = k['scale'][row]
self.PreadoutdB = k['PreadoutdB'][row]
self.Tstart = k['Tstart'][row]
self.Tend = k['Tend'][row]
self.I0 = k['I0'][row]
self.Q0 = k['Q0'][row]
self.resnum = k['resnum'][row]
self.time = k['time'][row]
except:
pass
try:
self.freq = k['freq'][row,0:self.fsteps]
self.I = k['I'][row,0:self.fsteps]
self.Q = k['Q'][row,0:self.fsteps]
self.Isd = k['Isd'][row,0:self.fsteps]
self.Qsd = k['Qsd'][row,0:self.fsteps]
self.vmaxidx = k['vmaxidx'][row]
self.Iceng = k['Iceng'][row]
self.Qceng = k['Qceng'][row]
self.Icen = k['Icen'][row]
self.Qcen= k['Qcen'][row]
self.Qm= k['Qm'][row]
self.fm= k['fm'][row]
self.Qc= k['Qc'][row]
self.Qi= k['Qi'][row]
self.dipdb= k['dipdb'][row]
self.popt = k['popt'][row]
self.fpoints = k['fpoints'][row]
self.fI = k['fI'][row,0:self.fpoints]
self.fQ = k['fQ'][row,0:self.fpoints]
self.ff = k['ff'][row,0:self.fpoints]
except:
pass
try:
self.mag = k['mag'][row,0:self.fpoints]
self.magfreq = k['magfreq'][row]
self.magfit = k['magfit'][row]
self.mopt = k['mopt'][row]
except:
pass
try:
self.savenoise = k['savenoise'][row]
self.samprate = k['samprate'][row]
self.pn = k['pn'][row]
self.pnidx = k['pnidx'][row]
self.an = k['an'][row]
self.anidx = k['anidx'][row]
self.kn1k = k['fn1k'][row]
except:
pass
def Pdf(self,filename):
pp = PdfPages(filename)
matplotlib.rcParams['font.size']=8
fig = plt.figure( figsize=(7.5, 9), dpi=100)
try:
ax = fig.add_subplot(221)
ax.plot(self.I[:self.fsteps]-self.I0,self.Q[:self.fsteps]-self.Q0,'bo',markersize=4)
ax.plot(self.Iceng,self.Qceng,'gx')
ax.plot(self.I[self.vmaxidx]-self.I0,self.Q[self.vmaxidx]-self.Q0,'go',markersize=4)
ax.plot(self.Icen,self.Qcen,'rx')
ax.plot(self.fI,self.fQ,'r')
ax.set_xlabel('I')
ax.set_ylabel('Q')
except:
pass
# overplot some noise data
try:
ax.plot(self.Ix1[0:5000]*0.2/32767.0-self.I0,self.Qx1[0:5000]*0.2/32767.0-self.Q0,'c.',markersize=1)
except:
pass
try:
ax2 = fig.add_subplot(222)
ax2.plot(self.freq,20.0*np.log10(self.mag),'bo',markersize=4)
ax2.plot(self.magfreq,20.0*np.log10(self.magfit),'r')
ax2.grid(False)
ax2.set_xlabel('Frequency (GHz)')
ax2.set_ylabel('|S$_{21}$| (dB)')
except:
pass
try:
ax3 = fig.add_subplot(212)
ax3.plot(self.pnidx[1:],10.0*np.log10(self.pn[1:]),'r',self.anidx[1:],10.0*np.log10(self.an[1:]),'k')
ax3.set_title('P$_{int}$ = ' + '{0:.2f}'.format(self.Pint) + ' dBm, Frequency Noise at 1 kHz = ' + '{0:.2e}'.format(self.fn1k) + ' Hz$^2$/Hz' )
ax3.set_xscale('log')
ax3.set_autoscale_on(False)
ax3.set_xlim([1,1e5])
ax3.set_ylim([-100,-50])
ax3.set_xlabel('Frequency (Hz)')
ax3.set_ylabel('Phase (Red) and Amplitude (Black) Noise (dBc/Hz)')
ax3.grid(True)
text = 'Q = ' + '{0:.2f}'.format(self.Qm) + '\nf$_0$ = ' + '{0:.6f}'.format(self.fm/1e9) + '\nQ$_c$ = ' + '{0:.2f}'.format(self.Qc) + '\nQ$_i$ = ' + '{0:.2f}'.format(self.Qi) + '\n|S$_{21}$|$_{min}$ = ' + '{0:.2f}'.format(self.dipdb)
bbox_args = dict(boxstyle="round", fc="0.8")
ax3.annotate(text,
xy=(0.75, 0.9), xycoords='axes fraction',
xytext=(0.75, 0.9), textcoords='axes fraction',
ha="left", va="top",
bbox=bbox_args)
except:
pass
try:
ax4 = ax3.twinx()
ax4.set_ylim([np.log10((10**(-100.0/10.0))/(16.0*self.popt[0]**2)),np.log10((10**(-50.0/10.0))/(16.0*self.popt[0]**2))])
ax4.set_ylabel('Frequency Noise log$_{10}$(Hz$^2$/Hz)', color='r')
for tl in ax4.get_yticklabels():
tl.set_color('r')
except:
pass
pp.savefig()
pp.close()
def LoadNoise(self,filename,resnum):
# Load up noise data
self.noisename = filename
f = open(filename, 'rb')
fsize = os.fstat(f.fileno())[6]
if fsize < 10:
print 'No Noise File!'
return
hdr = np.fromfile(f, dtype=np.float64,count=12)
self.samprate = 200000.0
self.Ix1 = np.zeros(2000000,dtype=np.int16)
self.Qx1 = np.zeros(2000000,dtype=np.int16)
for x in range(10):
if resnum == 0:
self.Ix1[x*200000:(x+1)*200000] = np.fromfile(f, dtype=np.int16,count=200000)
self.Qx1[x*200000:(x+1)*200000] = np.fromfile(f, dtype=np.int16,count=200000)
dummy = np.fromfile(f, dtype=np.int16,count=200000)
dummy = np.fromfile(f, dtype=np.int16,count=200000)
else:
dummy = np.fromfile(f, dtype=np.int16,count=200000)
dummy = np.fromfile(f, dtype=np.int16,count=200000)
self.Ix1[x*200000:(x+1)*200000] = np.fromfile(f, dtype=np.int16,count=200000)
self.Qx1[x*200000:(x+1)*200000] = np.fromfile(f, dtype=np.int16,count=200000)
self.savenoise = len(self.Ix1)
dummy = 0
f.close()
def AnalyzeNoise(self):
import matplotlib.mlab
# Analyze noise data
# subtract off zero point and move center of resonance to (0,0)
Ix1a = self.Ix1*0.2/32767.0 - self.I0 - self.Icen
Qx1a = self.Qx1*0.2/32767.0 - self.Q0 - self.Qcen
#convert to mag and phase
resang = np.arctan2(np.mean(Qx1a), np.mean(Ix1a) )
nI = (Ix1a*np.cos(resang) + Qx1a*np.sin(resang))
nQ = (-Ix1a*np.sin(resang) + Qx1a*np.cos(resang))
rad = np.mean(nI)
nI = nI/rad
nQ = nQ/rad
phase = np.arctan2(nQ,nI)
amp = np.sqrt(nI**2 + nQ**2)
# low frequency FFTs
pnlow, pnlowidx = matplotlib.mlab.psd(phase,NFFT=262144,Fs=self.samprate,noverlap=131072)
anlow, anlowidx = matplotlib.mlab.psd(amp,NFFT=262144,Fs=self.samprate,noverlap=131072)
#pdb.set_trace()
#self.pnidx,self.pn,dummy = powspec_rebin.rebin(pnlowidx[1:],pnslow[1:],binsize=0.002,sampling=1)
#self.anidx,self.an,dummy = powspec_rebin.rebin(anlowidx[1:],anlow[1:],binsize=0.002,sampling=1)
# high frequency FFTs
pnhigh, pnhighidx = matplotlib.mlab.psd(phase,NFFT=4096,Fs=self.samprate,noverlap=2048)
anhigh, anhighidx = matplotlib.mlab.psd(amp,NFFT=4096,Fs=self.samprate,noverlap=2048)
self.pn = np.zeros(2552)
self.pn[0:512] = pnlow[0:512]
self.pn[512:2552] = pnhigh[8:2048]
self.pnidx = np.zeros(2552)
self.pnidx[0:512] = pnlowidx[0:512]
self.pnidx[512:2552] = pnhighidx[8:2048]
self.an = np.zeros(2552)
self.an[0:512] = anlow[0:512]
self.an[512:2552] = anhigh[8:2048]
self.anidx = np.zeros(2552)
self.anidx[0:512] = anlowidx[0:512]
self.anidx[512:2552] = anhighidx[8:2048]
# calculate frequency noise at 1 kHz
coeff = np.polyfit(self.pnidx[521:526],self.pn[521:526],1)
pf = np.poly1d(coeff)
self.fn1k = pf(1000)/(16.0*self.popt[0]**2)
def RESDIFF(x,Q,f0,aleak,ph1,da,ang1,Igain,Qgain,Ioff,Qoff):
# Q = p[0] ; Q
# f0 = p[1] ; resonance frequency
# aleak = p[2] ; amplitude of leakage
# ph1 = p[3] ; phase shift of leakage
# da = p[4] ; variation of carrier amplitude
# ang1 = p[5] ; Rotation angle of data
# Igain = p[6] ; Gain of I channel
# Qgain = p[7] ; Gain of Q channel
# Ioff = p[8] ; Offset of I channel
# Qoff = p[9] ; Offset of Q channel
l = len(x)
dx = (x - f0) / f0
# resonance dip function
s21a = (np.vectorize(complex)(0,2.0*Q*dx)) / (complex(1,0) + np.vectorize(complex)(0,2.0*Q*dx))
s21a = s21a - complex(.5,0)
s21b = np.vectorize(complex)(da*dx,0) + s21a + aleak*np.vectorize(complex)(1.0-np.cos(dx*ph1),-np.sin(dx*ph1))
# scale and rotate
Ix1 = s21b.real*Igain
Qx1 = s21b.imag*Qgain
nI1 = Ix1*np.cos(ang1) + Qx1*np.sin(ang1)
nQ1 = -Ix1*np.sin(ang1) + Qx1*np.cos(ang1)
#scale and offset
nI1 = nI1 + Ioff
nQ1 = nQ1 + Qoff
s21 = np.zeros(l*2)
s21[:l] = nI1
s21[l:] = nQ1
return s21
def RESDIFFMP(p, fjac=None, x=None, y=None, err=None):
Q = p[0] # Q
f0 = p[1] # resonance frequency
aleak = p[2] # amplitude of leakage
ph1 = p[3] # phase shift of leakage
da = p[4] # variation of carrier amplitude
ang1 = p[5] # Rotation angle of data
Igain = p[6] # Gain of I channel
Qgain = p[7] # Gain of Q channel
Ioff = p[8] # Offset of I channel
Qoff = p[9] # Offset of Q channel
l = len(x)
dx = (x - f0) / f0
# resonance dip function
s21a = (np.vectorize(complex)(0,2.0*Q*dx)) / (complex(1,0) + np.vectorize(complex)(0,2.0*Q*dx))
s21a = s21a - complex(.5,0)
s21b = np.vectorize(complex)(da*dx,0) + s21a + aleak*np.vectorize(complex)(1.0-np.cos(dx*ph1),-np.sin(dx*ph1))
# scale and rotate
Ix1 = s21b.real*Igain
Qx1 = s21b.imag*Qgain
nI1 = Ix1*np.cos(ang1) + Qx1*np.sin(ang1)
nQ1 = -Ix1*np.sin(ang1) + Qx1*np.cos(ang1)
#scale and offset
nI1 = nI1 + Ioff
nQ1 = nQ1 + Qoff
s21 = np.zeros(l*2)
s21[:l] = nI1
s21[l:] = nQ1
status=0
return [status, (y-s21)/err]
def MAGDIFFMP(p, fjac=None, x=None, y=None, err=None):
Q = p[0]
f0 = p[1]
carrier = p[2]
depth = p[3]
slope = p[4]
curve = p[5]
dx = (x - f0) / f0
s21 = (np.vectorize(complex)(0,2.0*Q*dx)) / (complex(1,0) + np.vectorize(complex)(0,2.0*Q*dx))
mag1 = (np.abs(s21)-1.0)*depth + carrier + slope*dx + curve*dx*dx
status=0
return [status, (y-mag1)/err]
def MAGDIFF(x,Q,f0,carrier,depth,slope,curve):
dx = (x - f0) / f0
s21 = (np.vectorize(complex)(0,2.0*Q*dx)) / (complex(1,0) + np.vectorize(complex)(0,2.0*Q*dx))
mag1 = (np.abs(s21)-1.0)*depth + carrier + slope*dx + curve*dx*dx
return mag1
def smooth(x, window_len=10, window='hanning'):
"""smooth the data using a window with requested size.
This method is based on the convolution of a scaled window with the signal.
The signal is prepared by introducing reflected copies of the signal
(with the window size) in both ends so that transient parts are minimized
in the begining and end part of the output signal.
input:
x: the input signal
window_len: the dimension of the smoothing window
window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'
flat window will produce a moving average smoothing.
output:
the smoothed signal
example:
import numpy as np
t = np.linspace(-2,2,0.1)
x = np.sin(t)+np.random.randn(len(t))*0.1
y = smooth(x)
see also:
numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve
scipy.signal.lfilter
TODO: the window parameter could be the window itself if an array instead of a string
"""
if x.ndim != 1:
raise ValueError, "smooth only accepts 1 dimension arrays."
if x.size < window_len:
raise ValueError, "Input vector needs to be bigger than window size."
if window_len < 3:
return x
if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']:
raise ValueError, "Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'"
s=np.r_[2*x[0]-x[window_len:1:-1], x, 2*x[-1]-x[-1:-window_len:-1]]
#print(len(s))
if window == 'flat': #moving average
w = np.ones(window_len,'d')
else:
w = getattr(np, window)(window_len)
y = np.convolve(w/w.sum(), s, mode='same')
return y[window_len-1:-window_len+1]
| 37,697 | 35.248077 | 289 | py |
SDR | SDR-master/Projects/DarknessFilters/testMakeTemplate.py | from matplotlib import rcParams, rc
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as opt
from baselineIIR import IirFilter
import makeNoiseSpectrum as mNS
import makeArtificialData as mAD
import makeTemplate as mT
reload(mNS)
reload(mAD)
reload(mT)
##### Plot true template vs calculated template #####
if True:
#Turn plotting on or off
isPlot=False
isPlotRes=True
isPlotPoisson=False
isPlotFit=False
#Starting template values
sampleRate=1e6
nPointsBefore=100.
riseTime=2e-6
fallTime=50e-6
tmax=nPointsBefore/sampleRate
t0=tmax+riseTime*np.log(riseTime/(riseTime+fallTime))
#get fake poissonian distributed pulse data
rawdata, rawtime = mAD.makePoissonData(totalTime=2*131.072e-3,isVerbose=True,maxSignalToNoise=2)
if isPlotPoisson:
fig1=plt.figure(0)
plt.plot(rawtime,rawdata)
plt.show()
#calculate templates
finalTemplate, time , _, templateList, _ = mT.makeTemplate(rawdata,nSigmaTrig=4.,numOffsCorrIters=2,isVerbose=True,isPlot=isPlot)
roughTemplate = templateList[0]
#make fitted template
fittedTemplate, startFit, riseFit, fallFit = mT.makeFittedTemplate(finalTemplate,time,riseGuess=3.e-6,fallGuess=55.e-6)
#calculate real template
realTemplate = mAD.makePulse(time,t0,riseTime,fallTime)
realTemplate = mT.hpFilter(realTemplate)
realTemplate /= np.abs(realTemplate[np.argmax(np.abs(realTemplate))])
if isPlotRes:
fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)
h1, = ax0.plot(time*1e6,roughTemplate,'r',linewidth=2); h1Label='initial template'
h2, = ax0.plot(time*1e6,finalTemplate,'g',linewidth=2); h2Label='offset corrected template'
h3, = ax0.plot(time*1e6,realTemplate,'b', linewidth=2); h3Label='real pulse shape'
ax1.plot(time*1e6,realTemplate-roughTemplate,'r',linewidth=2)
ax1.plot(time*1e6,realTemplate-finalTemplate,'g',linewidth=2)
ax1.set_xlabel('time [$\mu$s]')
ax0.set_ylabel('normalized pulse height')
ax1.set_ylabel('residuals')
if realTemplate[np.argmax(np.abs(realTemplate))]>0:
ax0.legend((h1,h2,h3),(h1Label,h2Label,h3Label),'upper right')
else:
ax0.legend((h1,h2,h3),(h1Label,h2Label,h3Label),'lower right')
plt.show()
if isPlotFit:
fig2=plt.figure(2)
plt.plot(time,finalTemplate)
plt.plot(time,fittedTemplate)
plt.show()
##### Test number of itterations of offset correction that are needed #####
if False:
#make templates
template0=()
template1=()
template2=()
template3=()
template4=()
template5=()
for ii in range(0,100):
#generate raw data
rawdata, rawtime = mAD.makePoissonData(totalTime=2*131.072e-3)
#calculate template
finalTemplate, time , _, templateList, _ = mT.makeTemplate(rawdata,numOffsCorrIters=5,nSigmaTrig=4.)
template0+=(templateList[0],)
template1+=(templateList[1],)
template2+=(templateList[2],)
template3+=(templateList[3],)
template4+=(templateList[4],)
template5+=(templateList[5],)
#Calculate residuals for each template variable
sampleRate=1e6
nPointsBefore=100.
riseTime=2e-6
fallTime=50e-6
tmax=nPointsBefore/sampleRate
t0=tmax+riseTime*np.log(riseTime/(riseTime+fallTime))
realTemplate = mAD.makePulse(time,t0,riseTime,fallTime)
realTemplate = mT.hpFilter(realTemplate)
realTemplate /= np.abs(realTemplate[np.argmax(np.abs(realTemplate))])
residual0=()
residual1=()
residual2=()
residual3=()
residual4=()
residual5=()
for ii in range(len(template0)):
residual0+=(np.sum((realTemplate-template0[ii])**2),)
residual1+=(np.sum((realTemplate-template1[ii])**2),)
residual2+=(np.sum((realTemplate-template2[ii])**2),)
residual3+=(np.sum((realTemplate-template3[ii])**2),)
residual4+=(np.sum((realTemplate-template4[ii])**2),)
residual5+=(np.sum((realTemplate-template5[ii])**2),)
#plot histograms
if False:
fig=plt.figure()
plt.hist(residual0, 50, normed=1, facecolor='red', alpha=0.4)
plt.hist(residual1, 50, normed=1, facecolor='orange', alpha=0.4)
plt.hist(residual2, 50, normed=1, facecolor='yellow', alpha=0.4)
plt.hist(residual3, 50, normed=1, facecolor='green', alpha=0.4)
plt.hist(residual4, 50, normed=1, facecolor='blue', alpha=0.4)
plt.hist(residual5, 50, normed=1, facecolor='purple', alpha=0.4)
plt.show()
#plot medians and maxs
if True:
maxes=[np.max(residual0),np.max(residual1),np.max(residual2),np.max(residual3),np.max(residual4),np.max(residual5)]
medians=[np.median(residual0),np.median(residual1),np.median(residual2),np.median(residual3),np.median(residual4),np.median(residual5)]
fig=plt.figure()
plt.plot([0,1,2,3,4,5],medians,label='medians')
plt.legend()
plt.show()
fig=plt.figure()
plt.plot([0,1,2,3,4,5],maxes,label='maxes')
plt.legend()
plt.show()
| 5,314 | 36.695035 | 143 | py |
SDR | SDR-master/Projects/DarknessFilters/avgTemplate.py | from matplotlib import rcParams, rc
import numpy as np
import sys
from fitFunctions import gaussian
import scipy.interpolate
import scipy.signal
from baselineIIR import IirFilter
# common setup for matplotlib
params = {'savefig.dpi': 300, # save figures to 300 dpi
'axes.labelsize': 14,
'text.fontsize': 14,
'legend.fontsize': 14,
'xtick.labelsize': 14,
'ytick.major.pad': 6,
'xtick.major.pad': 6,
'ytick.labelsize': 14}
# use of Sans Serif also in math mode
rc('text.latex', preamble='\usepackage{sfmath}')
rcParams.update(params)
import matplotlib.pyplot as plt
import numpy as np
import os
import struct
def calcThreshold(phase,Nsigma=2.5,nSamples=5000):
n,bins= np.histogram(phase[:nSamples],bins=100)
n = np.array(n,dtype='float32')/np.sum(n)
tot = np.zeros(len(bins))
for i in xrange(len(bins)):
tot[i] = np.sum(n[:i])
med = bins[np.abs(tot-0.5).argmin()]
thresh = bins[np.abs(tot-0.05).argmin()]
threshold = int(med-Nsigma*abs(med-thresh))
return threshold
def oldBaseFilter(data,alpha=0.08):
#construct IIR
alpha = 0.08
numCoeffs = np.zeros(31)
numCoeffs[30] = alpha
denomCoeffs = np.zeros(11)
denomCoeffs[0] = 1
denomCoeffs[10] = -(1-alpha)
baselines = scipy.signal.lfilter(numCoeffs,denomCoeffs,data)
return baselines
def sigmaTrigger(data):
#deadtime in ticks (us)
data = np.array(data)
#threshold = calcThreshold(data[0:2000])
dataSubBase = data - baselines
derivative = np.diff(data)
peakHeights = []
t = 0
negDeriv = derivative <= 0
posDeriv = np.logical_not(negDeriv)
triggerBooleans = dataSubBase[nNegDerivChecks:-2] < threshold
negDerivChecksSum = np.zeros(len(negDeriv[0:-nNegDerivChecks-1]))
for i in range(nNegDerivChecks):
negDerivChecksSum += negDeriv[i:i-nNegDerivChecks-1]
peakCondition0 = negDerivChecksSum >= nNegDerivChecks-negDerivLenience
peakCondition1 = np.logical_and(posDeriv[nNegDerivChecks:-1],posDeriv[nNegDerivChecks+1:])
peakCondition01 = np.logical_and(peakCondition0,peakCondition1)
peakBooleans = np.logical_and(triggerBooleans,peakCondition01)
try:
peakIndices = np.where(peakBooleans)[0]+nNegDerivChecks
i = 0
p = peakIndices[i]
while p < peakIndices[-1]:
peakIndices = peakIndices[np.logical_or(peakIndices-p > deadtime , peakIndices-p <= 0)]#apply deadtime
i+=1
if i < len(peakIndices):
p = peakIndices[i]
else:
p = peakIndices[-1]
except IndexError:
return np.array([]),np.array([]),np.array([])
peakHeights = data[peakIndices]
peakBaselines = baselines[peakIndices]
return peakIndices,peakHeights,peakBaselines
def detectPulses(sample,threshold,baselines,deadtime=10,nNegDerivChecks=10,negDerivLenience=1):
#deadtime in ticks (us)
data = np.array(sample)
#threshold = calcThreshold(data[0:2000])
dataSubBase = data - baselines
derivative = np.diff(data)
peakHeights = []
t = 0
negDeriv = derivative <= 0
posDeriv = np.logical_not(negDeriv)
triggerBooleans = dataSubBase[nNegDerivChecks:-2] < threshold
negDerivChecksSum = np.zeros(len(negDeriv[0:-nNegDerivChecks-1]))
for i in range(nNegDerivChecks):
negDerivChecksSum += negDeriv[i:i-nNegDerivChecks-1]
peakCondition0 = negDerivChecksSum >= nNegDerivChecks-negDerivLenience
peakCondition1 = np.logical_and(posDeriv[nNegDerivChecks:-1],posDeriv[nNegDerivChecks+1:])
peakCondition01 = np.logical_and(peakCondition0,peakCondition1)
peakBooleans = np.logical_and(triggerBooleans,peakCondition01)
try:
peakIndices = np.where(peakBooleans)[0]+nNegDerivChecks
i = 0
p = peakIndices[i]
while p < peakIndices[-1]:
peakIndices = peakIndices[np.logical_or(peakIndices-p > deadtime , peakIndices-p <= 0)]#apply deadtime
i+=1
if i < len(peakIndices):
p = peakIndices[i]
else:
p = peakIndices[-1]
except IndexError:
return np.array([]),np.array([]),np.array([])
peakHeights = data[peakIndices]
peakBaselines = baselines[peakIndices]
return peakIndices,peakHeights,peakBaselines
def oldDetectPulses(sample,threshold,baselines):
filtered = np.array(sample)
#threshold = calcThreshold(filtered[0:2000])
filtered -= baselines
derivative = np.diff(filtered)
peakHeights = []
t = 0
negDeriv = derivative <= 0
posDeriv = np.logical_not(negDeriv)
triggerBooleans = filtered[1:-2] < threshold
peakCondition1 = np.logical_and(negDeriv[0:-2],posDeriv[1:-1])
peakCondition2 = np.logical_and(triggerBooleans,posDeriv[2:])
peakBooleans = np.logical_and(peakCondition1,peakCondition2)
try:
peakIndices = np.where(peakBooleans)[0]+1
i = 0
p = peakIndices[i]
deadtime=10#us
while p < peakIndices[-1]:
peakIndices = peakIndices[np.logical_or(peakIndices-p > deadtime , peakIndices-p <= 0)]#apply deadtime
i+=1
if i < len(peakIndices):
p = peakIndices[i]
else:
p = peakIndices[-1]
except IndexError:
return np.array([]),np.array([]),np.array([])
peakHeights = filtered[peakIndices]
peakBaselines = baselines[peakIndices]
return peakIndices,peakHeights,peakBaselines
rootFolder = '/Scratch/filterData/'
quietFolder = '/Scratch/filterData/20130925/blue/'
sampleRate=1e6 # 1 MHz
#roachNum = 0
#pixelNum = 51
#secs=60
#date = '20130925'
#folder = '/Scratch/filterData/20130925/blue/'
#cps=700
#bFiltered = False
#phaseFilename = os.path.join(folder,'ch_snap_r%dp%d_%dsecs_%dcps.dat'%(roachNum,pixelNum,secs,cps))
#quietFilename = os.path.join(quietFolder,'ch_snap_r%dp%d_%dsecs_%dcps.dat'%(roachNum,pixelNum,30,0))
#label='Blue'
#roachNum = 0
#pixelNum = 51
#secs=60
#folder = '/home/kids/labData/20130925/red/'
#cps=600
#bFiltered = False
#phaseFilename = os.path.join(folder,'ch_snap_r%dp%d_%dsecs_%dcps.dat'%(roachNum,pixelNum,secs,cps))
#quietFilename = os.path.join(quietFolder,'ch_snap_r%dp%d_%dsecs_%dcps.dat'%(roachNum,pixelNum,30,0))
#label='Red'
#roachNum = 0
#pixelNum = 134
#secs=5
#folder = '/home/kids/labData/20130220/'
#cps=700
#bFiltered = True
#phaseFilename = os.path.join(folder,'ch_snap_r%dp%d_%dsecs_%dcps.dat'%(roachNum,pixelNum,secs,cps))
#roachNum = 4
#pixelNum = 2
#secs=20
#folder = os.path.join(rootFolder,'20121123/')
#bFiltered = False
#phaseFilename = os.path.join(folder,'ch_snap_r%dp%d_%dsecs.dat'%(roachNum,pixelNum,secs))
##missing quiet file, so use another
#quietFilename = os.path.join(quietFolder,'ch_snap_r%dp%d_%dsecs_%dcps.dat'%(0,51,30,0))
#roachNum = 4
#pixelNum = 51
#secs=20
#cps=200 #I don't really know. let's check
#label='Red'
#folder = os.path.join(rootFolder,'20121123/')
#bFiltered = False
#phaseFilename = os.path.join(folder,'ch_snap_r%dp%d_%dsecs.dat'%(roachNum,pixelNum,secs))
##missing quiet file, so use another
#quietFilename = phaseFilename
roachNum = 4
pixelNum = 102
secs=50
cps=200 #I don't really know. let's check
date = '20121204'
label='30tap'
folder = os.path.join(rootFolder,'20121204/')
bFiltered = False
phaseFilename = os.path.join(folder,'ch_snap_r{}p{}_{}secs.dat'.format(roachNum,pixelNum,secs))
#missing quiet file, so use another
quietFilename = phaseFilename
bPlotPeaks = True
deadtime=1000
phaseFile = open(phaseFilename,'r')
quietFile = open(quietFilename,'r')
phase = phaseFile.read()
quietPhase = quietFile.read()
numQDRSamples=2**19
numBytesPerSample=4
nLongsnapSamples = numQDRSamples*2*secs
qdrValues = struct.unpack('>%dh'%(nLongsnapSamples),phase)
qdrPhaseValues = np.array(qdrValues,dtype=np.float32)*360./2**16*4/np.pi #convert from adc units to degrees
nPhaseValues=len(qdrValues)
#nPhaseValues=int(1e5)
print nPhaseValues,'us'
quietDuration = secs #or 30
quietQdrValues = struct.unpack('>%dh'%(numQDRSamples*2*quietDuration),quietPhase)
quietQdrPhaseValues = np.array(quietQdrValues,dtype=np.float32)*360./2**16*4/np.pi #convert from adc units to degrees
fig = plt.figure()
NAxes = 1
iAxes = 1
size=26
offset = 3
sampleStart = 5000
nSamples = nPhaseValues-sampleStart
thresholdLength = 5000
thresholdSigma = 2.2
sample=qdrValues[sampleStart:sampleStart+nSamples]
quietSample=quietQdrValues[sampleStart:sampleStart+thresholdLength]
#sample = np.array(qdrPhaseValues)
if bFiltered == False:
rawdata = np.array(sample)
quietRawdata = np.array(quietSample)
#filter= np.loadtxt(os.path.join(rootFolder,'fir/template20121207r%d.txt'%roachNum))[pixelNum,:]
#lpf250kHz= np.loadtxt('/Scratch/filterData/fir/lpf_250kHz.txt')
matched30= np.loadtxt(os.path.join(rootFolder,'fir/matched_30us.txt'))
matched100= np.loadtxt(os.path.join(rootFolder,'fir/matched100_30us.txt'))
filter=matched30
#data = np.correlate(filter,rawdata,mode='same')[::-1]
data = scipy.signal.lfilter(filter,1,rawdata)
#quietData = np.correlate(filter,quietRawdata,mode='same')[::-1]
quietData = scipy.signal.lfilter(filter,1,quietRawdata)
print 'filtering done'
sys.stdout.flush()
else:
data = np.array(sample)
quietData = np.array(quietSample)
criticalFreq = 20 #Hz
hpSos = IirFilter(sampleFreqHz=sampleRate,criticalFreqHz=criticalFreq,btype='highpass')
f=2*np.sin(np.pi*criticalFreq/sampleRate)
Q=.7
q=1./Q
hpSvf = IirFilter(sampleFreqHz=sampleRate,numCoeffs=np.array([1,-2,1]),denomCoeffs=np.array([1+f**2, f*q-2,1-f*q]))
baselines = data - hpSvf.filterData(data)
print 'baselines done'
threshold = calcThreshold(quietData,Nsigma=thresholdSigma)
print 'threshold done'
sys.stdout.flush()
endIdx = 20*thresholdLength
if bPlotPeaks:
ax=fig.add_subplot(NAxes,1,iAxes)
ax.plot(rawdata[0:endIdx],'.-',color='gray',label='raw phase')
ax.plot(data[0:endIdx],'k.-',label='optimal filtered phase')
ax.plot(baselines[0:endIdx],'b',label='lpf baseline')
ax.plot(baselines[0:endIdx]+threshold,'y--',label='threshold')
idx,peaks,bases = detectPulses(data,threshold,baselines,nNegDerivChecks=30,negDerivLenience=2,deadtime=deadtime)
nPeaksDetected = len(peaks)
print len(peaks),'peaks detected'
print 1.*nPeaksDetected/secs, 'cps'
sys.stdout.flush()
nPointsBefore = 100
nPointsAfter = 200
if len(peaks)>0:
if bPlotPeaks:
endPeakIdx = np.searchsorted(idx,endIdx)
ax.plot(idx[0:endPeakIdx],peaks[0:endPeakIdx],'r.',label='detected peak')
ax.plot(idx[0:endPeakIdx],bases[0:endPeakIdx],'g.',label='detected baseline')
ax.set_xlabel('time (us)')
ax.set_ylabel('phase (${}^{\circ}$)')
#ax.set_xlim([5000,15000])
#ax.set_title('detected peaks and baseline for ~%d cps, pixel /r%d/p%d'%(cps,roachNum,pixelNum))
ax.legend(loc='lower right')
iAxes+=1
np.savez('/Scratch/dataProcessing/filterTests/sdetected_{}_r{}p{}_{}.npz'.format(date,roachNum,pixelNum,label),idx=idx,peaks=peaks,bases=bases,baselines=baselines,threshold=threshold,qdrValues=qdrValues,data=rawdata,filtered=data)
sys.stdout.flush()
#collect records of several rawdata points before and after each peak
figHist,axHist = plt.subplots(1,1)
peakHist,peakHistBins = np.histogram(peaks-bases,bins=200,density=True)
axHist.plot(peakHistBins[0:-1],peakHist)
#looked at the histogram for 20121123/r4p56 and picked some cutoffs by eye
peakCutMask = (peaks>-7000) & (peaks<-4959)
peaksCut = peaks[peakCutMask]
idxCut = idx[peakCutMask]
basesCut = bases[peakCutMask]
records = np.zeros((len(peaksCut),nPointsBefore+nPointsAfter),dtype=np.double)
for iPeak,peak in enumerate(peaksCut):
peakIndex = idxCut[iPeak]
# indexAtRawMax = np.argmax(rawdata[peakIndex-10:peakIndex+10])+peakIndex-10
# if indexAtRawMax > nPointsBefore and indexAtRawMax < len(rawdata)-nPointsAfter:
# records[iPeak] = rawdata[indexAtRawMax-nPointsBefore:indexAtRawMax+nPointsAfter]
if peakIndex > nPointsBefore and peakIndex < len(rawdata)-nPointsAfter:
records[iPeak] = rawdata[peakIndex-nPointsBefore:peakIndex+nPointsAfter]
records[iPeak] /= np.min(records[iPeak])
pulseTemplate = np.mean(records,axis=0)
fig2,ax2 = plt.subplots(1,1)
for i in xrange(10):
ax2.plot(records[i])
fig3,ax3 = plt.subplots(1,1)
ax3.plot(pulseTemplate,'.-')
np.savez('/Scratch/dataProcessing/filterTests/rawTemplate_{}_r{}p{}'.format(date,roachNum,pixelNum))
plt.show()
| 12,574 | 33.078591 | 234 | py |
SDR | SDR-master/Projects/DarknessFilters/makeArtificialData.py | import numpy as np
def makePoissonData(rate=1./5e-3,totalTime=65.536e-3, maxSignalToNoise=10. , riseTime=2e-6, fallTime=50e-6, sampleRate=1e6,amplitudes='random',isVerbose=False):
dt = 1./sampleRate
time = np.arange(0,totalTime+dt,dt)
data = np.zeros(time.shape)
#compute time until next pulse assuming a poisson distribution
pulseTimes=[]
currentTime=0
while currentTime<totalTime:
probability = np.random.rand()
currentTime+= -np.log(probability)/rate
pulseTimes=np.append(pulseTimes,currentTime)
pulseTimes=pulseTimes[0:-2]
#add peaks
for peak in pulseTimes:
if amplitudes=='random':
amplitude=np.random.rand()
elif amplitudes=='constant':
amplitude=1
else:
raise ValueError("makePoissonData: amplitudes variable can be either 'random' or 'constant'")
data+= amplitude*makePulse(time,peak,riseTime,fallTime)
#add noise
data+=(np.random.rand(len(time))-.5)/maxSignalToNoise
if isVerbose:
print len(pulseTimes), 'peaks generated'
return data, time
def makePulse(time,t0,riseTime,fallTime,sampleRate=1e6):
time=np.array(time) #double check time is np array
dt=1./sampleRate
startTime=t0+(dt-np.remainder(t0,dt)) #round up to nearest dt
endTime=startTime+10*fallTime
t=np.arange(startTime,endTime,dt)
pulse= -(1-np.exp(-(t-t0)/riseTime))*np.exp(-(t-t0)/fallTime)
pulseTemplate=np.zeros(time.shape)
startIndex=np.where(time>=startTime)[0][0]
endIndex=startIndex+len(pulse)
if endIndex>=len(time):
endIndex=len(time)
pulseTemplate[startIndex:endIndex]=pulse[:len(pulseTemplate[startIndex:endIndex])]
norm=fallTime/(riseTime+fallTime)*(riseTime/(riseTime+fallTime))**(riseTime/fallTime)
pulseTemplate/=norm
return pulseTemplate
| 1,891 | 33.4 | 160 | py |
SDR | SDR-master/Projects/DarknessFilters/testMakeFilters.py | from matplotlib import rcParams, rc
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as opt
from baselineIIR import IirFilter
import makeNoiseSpectrum as mNS
import makeArtificialData as mAD
import makeTemplate as mT
import makeFilters as mF
import struct
import extractRawData as eRD
import triggerPhotons as tP
import os
reload(mNS)
reload(mAD)
reload(mT)
reload(mF)
reload(tP)
##### Test on real data #####
if False:
isPlot=False
isVerbose=True
#get data
rawData = eRD.parseQDRPhaseSnap(os.path.join(os.getcwd(),'TestData/20140915/redLaser'),pixelNum=0,roachNum=0,steps=30)
#make fake data
#rawData, rawTime = mAD.makePoissonData(totalTime=10*131.072e-3,amplitudes='random',maxSignalToNoise=10,isVerbose=isVerbose)
#rawData*=2
print "data extracted"
#make template
template, time, noiseSpectrumDict, _, _ = mT.makeTemplate(rawData,nSigmaTrig=5.,numOffsCorrIters=3,isVerbose=isVerbose,isPlot=isPlot, sigPass=.5)
print "template made"
#noiseSpectrumDict['noiseSpectrum']=np.ones(len(noiseSpectrumDict['noiseSpectrum']))
#noiseSpectrumDict['noiseSpectrum']=np.ones(len(noiseSpectrumDict['noiseSpectrum']))*3e3/np.abs(noiseSpectrumDict['noiseFreqs'])
#noiseSpectrumDict['noiseSpectrum'][0]=2*noiseSpectrumDict['noiseSpectrum'][1]
#noiseSpectrumDict['noiseSpectrum'][np.abs(noiseSpectrumDict['noiseFreqs'])>210000]=5e-5
#make matched filter
matchedFilter=mF.makeMatchedFilter(template, noiseSpectrumDict['noiseSpectrum'], nTaps=50, tempOffs=75)
coef, _ = opt.curve_fit(lambda x, a, t0 : a*exp(-x/t0), time[len(time)*1/5:len(time)*4/5],template[len(time)*1/5:len(time)*4/5], [-1 , 30e-6])
fallFit=coef[1]
superMatchedFilter=mF.makeSuperMatchedFilter(template, noiseSpectrumDict['noiseSpectrum'], fallFit, nTaps=50, tempOffs=75)
print "filters made"
#convolve with filter
filteredData=np.convolve(rawData,matchedFilter,mode='same')
superFilteredData=np.convolve(rawData,superMatchedFilter,mode='same')
print "data filtered"
#find peak indices
peakDict=tP.detectPulses(filteredData, nSigmaThreshold = 3., negDerivLenience = 1, bNegativePulses=False)
superPeakDict=tP.detectPulses(superFilteredData, nSigmaThreshold = 3., negDerivLenience = 1, bNegativePulses=False)
print "peaks found"
#find peak amplitudes
amps=filteredData[peakDict['peakIndices']]
superAmps=superFilteredData[superPeakDict['peakIndices']]
print "amplitudes extracted"
#fig=plt.figure()
#plt.plot(template)
#plt.hist(amps,100,alpha=.7)
#plt.hist(superAmps,100,alpha=.7)
#plt.show()
##### Find expected energy resolution of different filters #####
if False:
isPlot=False
isVerbose=False
#make fake data
rawData, rawTime = mAD.makePoissonData(totalTime=2*131.072e-3,amplitudes='random',maxSignalToNoise=10,isVerbose=isVerbose)
rawData*=2
#make template
finalTemplate, time , noiseSpectrumDict, _ , _ = mT.makeTemplate(rawData,nSigmaTrig=4.,numOffsCorrIters=2,isVerbose=isVerbose,isPlot=isPlot)
#fit to arbitrary pulse shape
fittedTemplate, startFit, riseFit, fallFit = mT.makeFittedTemplate(finalTemplate,time,riseGuess=3.e-6,fallGuess=55.e-6)
#make matched filter
matchedFilter=mF.makeMatchedFilter(fittedTemplate, noiseSpectrumDict['noiseSpectrum'], nTaps=50, tempOffs=75)
superMatchedFilter=mF.makeSuperMatchedFilter(fittedTemplate, noiseSpectrumDict['noiseSpectrum'], fallFit, nTaps=50, tempOffs=75)
#make more fake data
rawData, rawTime = mAD.makePoissonData(totalTime=2*131.072e-3, rate =1./5e-3, amplitudes='constant',maxSignalToNoise=10,isVerbose=isVerbose)
#filter data
data=mT.hpFilter(rawData)
#convolve with filter
filteredData=np.convolve(data,matchedFilter,mode='same')
superFilteredData=np.convolve(data,superMatchedFilter,mode='same')
#find peak indices
peakDict=mT.sigmaTrigger(filteredData,nSigmaTrig=3.)
superPeakDict=mT.sigmaTrigger(superFilteredData,nSigmaTrig=3.)
#find peak amplitudes
amps=filteredData[peakDict['peakMaxIndices']]
superAmps=superFilteredData[superPeakDict['peakMaxIndices']]
#plot histogram
fig=plt.figure()
#plt.hist(amplitudes[np.logical_and(amplitudes<1.04 , amplitudes >.96)])
plt.hist(amps,int(np.max(amps)/0.1))
plt.hist(superAmps,int(np.max(superAmps)/0.1))
plt.show()
##### Test exponential tail robustness of super matched filter #####
if False:
isPlot=False
isVerbose=False
#make Template
rawData, rawTime = mAD.makePoissonData(totalTime=2*131.072e-3,amplitudes='random',maxSignalToNoise=10,isVerbose=isVerbose)
rawData*=2 #make data distributed around amplitude =1
finalTemplate, time , noiseSpectrumDict, _ , _ = mT.makeTemplate(rawData,nSigmaTrig=4.,numOffsCorrIters=2,isVerbose=isVerbose,isPlot=isPlot)
fittedTemplate, startFit, riseFit, fallFit = mT.makeFittedTemplate(finalTemplate,time,riseGuess=3.e-6,fallGuess=55.e-6)
matchedFilter=mF.makeMatchedFilter(fittedTemplate, noiseSpectrumDict['noiseSpectrum'], nTaps=50, tempOffs=75)
superMatchedFilter=mF.makeSuperMatchedFilter(fittedTemplate, noiseSpectrumDict['noiseSpectrum'], fallFit, nTaps=50, tempOffs=75)
#test filters on piled up pulses
time=np.arange(0,400e-6,1e-6)
pulses=np.zeros(len(time))
pulses+=mAD.makePulse(time,50e-6,2e-6,50e-6)
pulses+=mAD.makePulse(time,140e-6,2e-6,50e-6)
pulses+=.6*(np.random.rand(len(pulses))-0.5)
pulses=mT.hpFilter(pulses)
filteredData=np.convolve(pulses,matchedFilter,mode='same')
superFilteredData=np.convolve(pulses,superMatchedFilter,mode='same')
fig=plt.figure()
plt.plot(time,pulses,label='piled-up pulses')
plt.show()
fig=plt.figure()
plt.plot(time,filteredData ,label = 'matched filter')
plt.plot(time,superFilteredData, label= 'pre-pulse robust matched filter')
plt.legend()
plt.show()
##### Find optimal tempOffs for filter #####
if False:
isPlot=False
isVerbose=False
#make fitted template
rawData, rawTime = mAD.makePoissonData(totalTime=2*131.072e-3,amplitudes='random',maxSignalToNoise=100,isVerbose=isVerbose)
rawData*=2 #make data distributed around amplitude =1
finalTemplate, time , noiseSpectrumDict, _ , _ = mT.makeTemplate(rawData,nSigmaTrig=4.,numOffsCorrIters=2,isVerbose=isVerbose,isPlot=isPlot)
fittedTemplate, startFit, riseFit, fallFit = mT.makeFittedTemplate(finalTemplate,time,riseGuess=3.e-6,fallGuess=55.e-6)
#make a single pulse
time=np.arange(0,500e-6,1e-6)
pulse=mAD.makePulse(time,250e-6,2e-6,50e-6)
pulse=mT.hpFilter(pulse)
#make a bunch of filters
tempOffs=arange(40,100)
maximums=np.zeros(len(tempOffs))
superMaximums=np.zeros(len(tempOffs))
for i,offset in enumerate(tempOffs):
matchedFilter=mF.makeMatchedFilter(fittedTemplate, noiseSpectrumDict['noiseSpectrum'], nTaps=50, tempOffs=offset)
superMatchedFilter=mF.makeSuperMatchedFilter(fittedTemplate, noiseSpectrumDict['noiseSpectrum'], fallFit, nTaps=50, tempOffs=offset)
maximums[i]=np.max(np.convolve(pulse,matchedFilter))
superMaximums[i]=np.max(np.convolve(pulse,superMatchedFilter))
fig=plt.figure()
plt.plot(tempOffs,superMaximums-1.)
#plt.plot(tempOffs,maximums-1.)
plt.show()
#print 'matched filter best offset:', tempOffs[np.argmin(np.abs(maximums-1.))] #75
#print 'super matched filter best offset:', tempOffs[np.argmin(np.abs(superMaximums-1.))]
##### Test filters on a single pulse #####
if False:
isPlot=False
isVerbose=False
#make Template
rawData, rawTime = mAD.makePoissonData(totalTime=2*131.072e-3,amplitudes='random',maxSignalToNoise=10,isVerbose=isVerbose)
rawData*=2
finalTemplate, time , noiseSpectrumDict, _ , _ = mT.makeTemplate(rawData,nSigmaTrig=4.,numOffsCorrIters=2,isVerbose=isVerbose,isPlot=isPlot)
fittedTemplate, startFit, riseFit, fallFit = mT.makeFittedTemplate(finalTemplate,time,riseGuess=3.e-6,fallGuess=55.e-6)
matchedFilter=mF.makeMatchedFilter(fittedTemplate, noiseSpectrumDict['noiseSpectrum'], nTaps=50, tempOffs=75)
superMatchedFilter=mF.makeSuperMatchedFilter(fittedTemplate, noiseSpectrumDict['noiseSpectrum'], fallFit, nTaps=50, tempOffs=75)
#test filters on a single pulse
time=np.arange(0,500e-6,1e-6)
pulses=np.zeros(len(time))
pulses+=mAD.makePulse(time,250e-6,2e-6,50e-6)
pulse=mT.hpFilter(pulse)
filteredData=np.convolve(pulses,matchedFilter,mode='same')
superFilteredData=np.convolve(pulses,superMatchedFilter,mode='same')
fig=plt.figure()
#plt.plot(time,-pulses,label='piled-up pulses')
plt.plot(time,filteredData ,label = 'matched filter')
plt.plot(time,superFilteredData, label= 'super matched filter')
plt.legend()
plt.show()
#####Test energy resolution with real data. Assumes constant photon energy#####
if False:
isPlot=False
isVerbose=False
#extract raw data
rawData = eRD.parseQDRPhaseSnap(os.path.join(os.getcwd(),'20140915/redLaser'),pixelNum=1,steps=30)
rawTemplateData = rawData[0:1000000]
rawTestData = rawData[1000000:2000000]
#make template
finalTemplate, time , noiseSpectrumDict, _ , tempPeakIndices = mT.makeTemplate(rawTemplateData,nSigmaTrig=4.,numOffsCorrIters=2,isVerbose=isVerbose,isPlot=isPlot)
#fit to arbitrary pulse shape
fittedTemplate, startFit, riseFit, fallFit = mT.makeFittedTemplate(finalTemplate,time,riseGuess=3.e-6,fallGuess=55.e-6)
noiseSpectrumDictCovMat = mNS.makeWienerNoiseSpectrum(rawTemplateData, tempPeakIndices, 8000, 1000)
#make matched filter
matchedFilter=mF.makeMatchedFilter(finalTemplate, noiseSpectrumDictCovMat['noiseSpectrum'], nTaps=50, tempOffs=75)
superMatchedFilter=mF.makeSuperMatchedFilter(finalTemplate, noiseSpectrumDictCovMat['noiseSpectrum'], fallFit, nTaps=50, tempOffs=75)
#plot templates
plt.plot(time,finalTemplate)
plt.plot(time,fittedTemplate)
plt.show()
#filter data
#data=mT.hpFilter(rawTestData)
data = rawTestData
#convolve with filter
filteredData=np.convolve(data,matchedFilter,mode='same')
superFilteredData=np.convolve(data,superMatchedFilter,mode='same')
#plot filtered data
fig=plt.figure()
plt.plot(filteredData[0:10000])
plt.plot(superFilteredData[0:10000])
plt.plot(rawTestData[0:10000])
plt.show()
#find peak indices
peakDict=tP.detectPulses(filteredData, nSigmaThreshold = 3., negDerivLenience = 1, bNegativePulses=False)
superPeakDict=tP.detectPulses(superFilteredData, nSigmaThreshold = 3., negDerivLenience = 1, bNegativePulses=False)
#find peak amplitudes
amps=filteredData[peakDict['peakIndices']]
superAmps=superFilteredData[superPeakDict['peakIndices']]
print 'default sigma:', np.std(amps)
#plot histogram
fig=plt.figure()
#plt.hist(amplitudes[np.logical_and(amplitudes<1.04 , amplitudes >.96)])
plt.hist(amps)
plt.hist(superAmps)
plt.show()
pulseHist, pulseHistBins = np.histogram(amps, bins='auto')
pulseHistS, pulseHistBinsS = np.histogram(superAmps, bins='auto')
plt.plot(pulseHistBins[:-1],pulseHist)
plt.plot(pulseHistBinsS[:-1],pulseHistS)
plt.show()
#find optimal sigma threshold
thresh, sigmaThresh = tP.findSigmaThresh(filteredData)
threshS, sigmaThreshS = tP.findSigmaThresh(filteredData)
print 'Threshold:', thresh
print 'Sigma Thresh:', sigmaThresh
print 'Super Threshold:', threshS
print 'Super Matched Sigma Thresh:', sigmaThreshS
print ''
#find peak indices
peakDict=tP.detectPulses(filteredData, nSigmaThreshold = sigmaThresh, negDerivLenience = 1, bNegativePulses=False)
superPeakDict=tP.detectPulses(superFilteredData, nSigmaThreshold = sigmaThreshS, negDerivLenience = 1, bNegativePulses=False)
amps=filteredData[peakDict['peakIndices']]
superAmps=superFilteredData[superPeakDict['peakIndices']]
pulseHist, pulseHistBins = np.histogram(amps, bins='auto')
pulseHistS, pulseHistBinsS = np.histogram(superAmps, bins='auto')
plt.plot(pulseHistBins[:-1],pulseHist)
plt.plot(pulseHistBinsS[:-1],pulseHistS)
plt.title('After optimizing sigma threshold')
plt.show()
#optimize trigger conditions
optSigmaThresh, optNNegDerivThresh, optNNegDerivLenience, minSigma, peakDict = tP.optimizeTrigCond(filteredData, 100, [sigmaThresh], np.arange(10,30,1), np.arange(1,4,1), False)
optSigmaThreshS, optNNegDerivThreshS, optNNegDerivLenienceS, minSigmaS, superPeakDict = tP.optimizeTrigCond(superFilteredData, 100, [sigmaThreshS], np.arange(10,30,1), np.arange(1,4,1), False)
print 'Sigma Thresh:', optSigmaThresh
print 'N Neg Derivative Checks:', optNNegDerivThresh
print 'N Neg Derivative Lenience:', optNNegDerivLenience
print 'minSigma:', minSigma
print ''
print 'Super Matched Filter:'
print 'Sigma Thresh:', optSigmaThreshS
print 'N Neg Derivative Checks:', optNNegDerivThreshS
print 'N Neg Derivative Lenience:', optNNegDerivLenienceS
print 'minSigma:', minSigmaS
amps=filteredData[peakDict['peakIndices']]
superAmps=superFilteredData[superPeakDict['peakIndices']]
pulseHist, pulseHistBins = np.histogram(amps, bins='auto')
pulseHistS, pulseHistBinsS = np.histogram(superAmps, bins='auto')
plt.plot(pulseHistBins[:-1],pulseHist)
plt.plot(pulseHistBinsS[:-1],pulseHistS)
plt.title('After optimizing derivative trigger conditions')
plt.show()
| 13,685 | 42.585987 | 196 | py |
SDR | SDR-master/Projects/DarknessFilters/makeTemplate.py | from matplotlib import rcParams, rc
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as opt
from baselineIIR import IirFilter
import makeNoiseSpectrum as mNS
import makeArtificialData as mAD
def makeTemplate(rawData, numOffsCorrIters=1 , decayTime=50, nSigmaTrig=4., isVerbose=False, isPlot=False,sigPass=1):
'''
Make a matched filter template using a raw phase timestream
INPUTS:
rawData - noisy phase timestream with photon pulses
numOffsCorrIters - number of pulse offset corrections to perform
decayTime - approximate decay time of pulses (units: ticks)
nSigmaTrig - threshold to detect pulse in terms of standard deviation of data
isVerbose - print information about the template fitting process
isPlot - plot information about Chi2 cut
sigPass - std of data left after Chi2 cut
OUTPUTS:
finalTemplate - template of pulse shape
time - use as x-axis when plotting template
noiseSpectDict - dictionary containing noise spectrum and corresponding frequencies
templateList - list of template itterations by correcting offsets
peakIndices - list of peak indicies from rawData used for template
'''
#hipass filter data to remove any baseline
data = hpFilter(rawData)
#trigger on pulses in data
peakDict = sigmaTrigger(data,nSigmaTrig=nSigmaTrig, decayTime=decayTime,isVerbose=isVerbose)
#remove pulses with additional triggers in the pulse window
peakIndices = cutPulsePileup(peakDict['peakMaxIndices'], decayTime=decayTime, isVerbose=isVerbose)
#remove pulses with a large chi squared value
peakIndices = cutChiSquared(data,peakIndices,sigPass=sigPass, decayTime=decayTime, isVerbose=isVerbose, isPlot=isPlot)
#Create rough template
roughTemplate, time = averagePulses(data, peakIndices, decayTime=decayTime)
#create noise spectrum from pre-pulse data for filter
noiseSpectDict = mNS.makeWienerNoiseSpectrum(data,peakIndices,template=roughTemplate, isVerbose=isVerbose)
#Correct for errors in peak offsets due to noise
templateList = [roughTemplate]
for i in range(numOffsCorrIters):
peakIndices = correctPeakOffs(data, peakIndices, noiseSpectDict, roughTemplate, 'wiener')
#calculate a new corrected template
roughTemplate, time = averagePulses(data, peakIndices,isoffset=True, decayTime=decayTime)
templateList.append(roughTemplate)
finalTemplate = roughTemplate
return finalTemplate, time, noiseSpectDict, templateList, peakIndices
def hpFilter(rawData, criticalFreq=20, sampleRate = 1e6):
'''
High pass filters the raw phase timestream
INPUTS:
rawData - data to be filtered
criticalFreq - cutoff frequency of filter (in Hz)
sampleRate - sample rate of rawData
OUTPUTS:
data - filtered data
'''
f=2*np.sin(np.pi*criticalFreq/sampleRate)
Q=.7
q=1./Q
hpSvf = IirFilter(sampleFreqHz=sampleRate,numCoeffs=np.array([1,-2,1]),denomCoeffs=np.array([1+f**2, f*q-2,1-f*q]))
data = hpSvf.filterData(rawData)
return data
def sigmaTrigger(data,nSigmaTrig=5.,deadTime=200,decayTime=30,isVerbose=False):
'''
Detects pulses in raw phase timestream
INPUTS:
data - phase timestream
nSigmaTrig - threshold to detect pulse in terms of standard deviation of data
deadTime - minimum amount of time between any two pulses (units: ticks (1 us assuming 1 MHz sample rate))
decayTime - expected pulse decay time (units: ticks)
isVerbose - print information about the template fitting process
OUTPUTS:
peakDict - dictionary of trigger indicies
peakIndices: initial trigger index
peakMaxIndices: index of the max near the initial trigger
'''
data = np.array(data)
med = np.median(data)
#print 'sdev',np.std(data),'med',med,'max',np.max(data)
trigMask = np.logical_or( data > (med + np.std(data)*nSigmaTrig) , data < (med - np.std(data)*nSigmaTrig) )
if np.sum(trigMask) > 0:
peakIndices = np.where(trigMask)[0]
i = 0
p = peakIndices[i]
peakMaxIndices = []
while p < peakIndices[-1]:
peakIndices = peakIndices[np.logical_or(peakIndices-p > deadTime , peakIndices-p <= 0)]#apply deadTime
if p+decayTime<len(data):
peakData = data[p:p+decayTime]
else:
peakData = data[p:]
peakMaxIndices = np.append(peakMaxIndices, np.argmax(np.abs(peakData))+p)
i+=1
if i < len(peakIndices):
p = peakIndices[i]
else:
p = peakIndices[-1]
else:
raise ValueError('sigmaTrigger: No triggers found in dataset')
if isVerbose:
print 'triggered on', len(peakIndices), 'pulses'
peakDict={'peakIndices':peakIndices, 'peakMaxIndices':peakMaxIndices.astype(int)}
return peakDict
def cutPulsePileup(peakIndices, nPointsBefore= 100, nPointsAfter = 700 , decayTime=50, isVerbose=False):
'''
Removes any pulses that have another pulse within 'window' (in ticks) This is
to ensure that template data is not contaminated by extraneous pulses.
INPUTS:
peakIndices - list of pulse positions
nPointsBefore - number of points before peakIndex included in template
nPointsAfter - number of points after peakIndex included in template
decayTime - expected pulse decay time (units: ticks)
isVerbose - print information about the template fitting process
OUTPUS:
newPeakIndices - list of pulse positions, with unwanted pulses deleted
'''
#set window for pulse rejection
window=nPointsBefore+nPointsAfter
if window<10*decayTime:
window=10*decayTime
peakIndices=np.array(peakIndices)
newPeakIndices=np.array([])
#check that no peaks are near current peak and then add to new indices variable
for iPeak, peakIndex in enumerate(peakIndices):
if np.min(np.abs(peakIndices[np.arange(len(peakIndices))!=iPeak]-peakIndex))>window:
newPeakIndices=np.append(newPeakIndices,peakIndex)
if len(newPeakIndices)==0:
raise ValueError('cutPulsePileup: no pulses passed the pileup cut')
if isVerbose:
print len(peakIndices)-len(newPeakIndices), 'indices cut due to pileup'
return newPeakIndices
def cutChiSquared(data,peakIndices,sigPass=1, decayTime=50, nPointsBefore= 100, nPointsAfter=700, isVerbose=False, isPlot=False):
'''
Removes a fraction of pulses (1-fPass) with the worst Chi Squared fit to
the exponential tail. This should remove any triggers that don't look like
pulses. Currently not optimized to fit in the frequency domain.
INPUTS:
data - raw phase timestream
peakIndices - list of pulse positions
fPass - fraction of pulses selected to pass the cut
decayTime - expected pulse decay time (units: ticks)
nPointsBefore - number of points before peakIndex included in template
nPointsAfter - number of points after peakIndex included in template
isVerbose - print information about the template fitting process
OUTPUTS:
newPeakIndices - list of pulse positions, with unwanted pulses deleted
'''
chiSquared=np.zeros(len(peakIndices))
for iPeak, peakIndex in enumerate(peakIndices):
time=np.arange(0,len(data[peakIndex+int(decayTime/2):peakIndex+nPointsAfter]))
currentData=data[peakIndex+int(decayTime/2):peakIndex+nPointsAfter]
ampGuess=currentData[np.argmax(np.abs(currentData))]
try:
expCoef, _ = opt.curve_fit(lambda t, a, tau: a*np.exp(-t/tau) , time, currentData , [ampGuess, decayTime] )
ampFit=expCoef[0]
decayFit=expCoef[1]
chiSquared[iPeak]=np.sum((currentData-ampFit*np.exp(-time/decayFit))**2)
except RuntimeError:
chiSquared[iPeak]=np.nan
chi2Median=np.median(chiSquared)
chi2Sig=np.std(chiSquared[np.invert(np.isnan(chiSquared))])
newPeakIndices=np.array([])
newChiSquared=np.array([])
for iPeak, peakIndex in enumerate(peakIndices):
if np.abs(chiSquared[iPeak]-chi2Median)<sigPass*chi2Sig:
newPeakIndices=np.append(newPeakIndices,peakIndex)
newChiSquared=np.append(newChiSquared,chiSquared[iPeak])
if isVerbose:
print len(peakIndices)-len(newPeakIndices), 'indices cut with worst Chi Squared value'
if len(newPeakIndices)==0:
raise ValueError('cutChiSquared: no pulses passed the Chi Squared cut')
if isPlot:
worstDataIndex=np.argmax(np.abs(newChiSquared-chi2Median))
fig = plt.figure()
plt.plot(data[newPeakIndices[worstDataIndex]-nPointsBefore:newPeakIndices[worstDataIndex]+nPointsAfter])
plt.title('Worst pulse not cut by $\chi^2$ cut')
plt.show()
worstDataIndex=np.argmax(np.abs(chiSquared-chi2Median))
fig=plt.figure()
plt.plot(data[peakIndices[worstDataIndex]-nPointsBefore:peakIndices[worstDataIndex]+nPointsAfter])
plt.title('Worst pulse cut by $\chi^2$ cut')
plt.show()
#fig =plt.figure()
#plt.hist(chiSquared)
#ax = plt.gca()
#ax.set_xlabel('$\chi^2$')
#splt.show()
return newPeakIndices
def averagePulses(data, peakIndices, isoffset=False, nPointsBefore=100, nPointsAfter=700, decayTime=30, sampleRate=1e6):
'''
Average together pulse data to make a template
INPUTS:
data - raw phase timestream
peakIndices - list of pulse positions
isoffset - true if peakIndices are the locations of peak maxima
nPointsBefore - number of points before peakIndex to include in template
nPointsAfter - number of points after peakIndex to include in template
decayTime - expected pulse decay time (in ticks (us))
sampleRate - sample rate of 'data'
OUTPUTS:
template - caluculated pulse template
time - time markers indexing data points in 'template'
(use as x-axis when plotting)
'''
numPeaks = 0
template=np.zeros(nPointsBefore+nPointsAfter)
for iPeak,peakIndex in enumerate(peakIndices):
if peakIndex >= nPointsBefore and peakIndex < len(data)-nPointsAfter:
peakRecord = data[peakIndex-nPointsBefore:peakIndex+nPointsAfter]
peakData = data[peakIndex-decayTime:peakIndex+decayTime]
if isoffset:
peakRecord/=np.abs(data[peakIndex])
else:
peakHeight = np.max(np.abs(peakData))
peakRecord /= peakHeight
template += peakRecord
numPeaks += 1
if numPeaks==0:
raise ValueError('averagePulses: No valid peaks found')
template /= numPeaks
time = np.arange(0,nPointsBefore+nPointsAfter)/sampleRate
return template, time
def correctPeakOffs(data, peakIndices, noiseSpectDict, template, filterType, offsets=np.arange(-20,21), nPointsBefore=100, nPointsAfter=700):
'''
Correct the list of peak indices to improve the alignment of photon pulses.
INPUTS:
data - raw phase timestream
peakIndices - list of photon pulse indices
noiseSpectDict - dictionary containing noise spectrum and corresponding frequencies
template - template of pulse to use for filter
filterType - string specifying the type of filter to use
offsets - list of peak index offsets to check
nPointsBefore - number of points before peakIndex to include in pulse
nPointsAfter - number of points after peakIndex to include in pulse
OUTPUTS:
newPeakIndices - list of corrected peak indices
'''
if filterType=='wiener':
makeFilter = makeWienerFilter
elif filterType=='matched':
#does not work yet 08/18/2016
makeFilter = makeMatchedFilter
else:
raise ValueError('makeFilterSet: Filter not defined')
nOffsets = len(offsets)
nPointsTotal = nPointsBefore + nPointsAfter
filterSet = np.zeros((nOffsets,nPointsTotal),dtype=np.complex64)
newPeakIndices = []
#Create a set of filters from different template offsets
for i,offset in enumerate(offsets):
templateOffs = np.roll(template, offset)
filterSet[i] = makeFilter(noiseSpectDict, templateOffs)
#find which peak index offset is the best for each pulse:
# apply each offset to the pulse, then determine which offset
# maximizes the pulse amplitude after application of the filter
for iPeak,peakIndex in enumerate(peakIndices):
if peakIndex > nPointsBefore-np.min(offsets) and peakIndex < len(data)-(nPointsAfter+np.max(offsets)):
peakRecord = data[peakIndex-nPointsBefore:peakIndex+nPointsAfter]
peakRecord = peakRecord / np.max(np.abs(peakRecord))
#check which time shifted filter results in the biggest signal
peakRecordFft = np.fft.fft(peakRecord)/nPointsTotal
convSums = np.abs(np.sum(filterSet*peakRecordFft,axis=1))
bestOffsetIndex = np.argmax(convSums)
bestConvSum = convSums[bestOffsetIndex]
bestOffset = offsets[bestOffsetIndex]
newPeakIndices=np.append(newPeakIndices, peakIndex+bestOffset)
return newPeakIndices
def makeWienerFilter(noiseSpectDict, template):
'''
Calculate acausal Wiener Filter coefficients in the frequency domain
INPUTS:
noiseSpectDict - Dictionary containing noise spectrum and list of corresponding frequencies
template - template of pulse shape
OUTPUTS:
wienerFilter - list of Wiener Filter coefficients
'''
template /= np.max(np.abs(template)) #should be redundant
noiseSpectrum = noiseSpectDict['noiseSpectrum']
templateFft = np.fft.fft(template)/len(template)
wienerFilter = np.conj(templateFft)/noiseSpectrum
filterNorm = np.sum(np.abs(templateFft)**2/noiseSpectrum)
wienerFilter /= filterNorm
return wienerFilter
def makeMatchedFilter(noiseSpectDict, template):
'''
Calculate Matched Filter coefficients
Does not work yet 08/18/2016
INPUTS:
noiseSpectDict - Dictionary containing noise spectrum and list of corresponding frequencies
template - template of pulse shape
OUTPUTS:
matchedFilter - list of Matched Filter coefficients
'''
noiseSpectrum = noiseSpectDict['noiseSpectrum']
noiseCovInv = mNS.covFromPsd(noiseSpectrum)['covMatrixInv']
filterNorm = np.sqrt(np.dot(template, np.dot(noiseCovInv, template))) #filterNorm not working correctly
matchedFilt = np.dot(noiseCovInv, template)/filterNorm
return matchedFilt
def makeFittedTemplate(template,time,riseGuess=3.e-6, fallGuess=55.e-6, peakGuess=100*1e-6):
'''
Fit template to double exponential pulse
INPUTS:
template - somewhat noisy template to be fitted
time - time variable for template
riseGuess - guess for pulse rise time in same units as 'time' variable
fallGuess - guess for pulse fall time in same units as 'time' variable
peakGuess - guess for what time in your template the fitted peak will be
in same units as 'time' variable
OUTPUTS:
fittedTemplate - fitted template with double exponential pulse
startFit - fitted value of peakGuess
riseFit - fitted value of riseGuess
fallFit - fitted value of fallGuess
'''
if template[np.argmax(np.abs(template[1:len(template)-1]))]>0:
pos_neg=1
else:
pos_neg=-1
startGuess=peakGuess+riseGuess*np.log(riseGuess/(riseGuess+fallGuess))
coef, coefCov =opt.curve_fit(pulseFitFun , time,pos_neg*template,[startGuess,riseGuess,fallGuess, 1., 0.])
startFit=coef[0]
riseFit=coef[1]
fallFit=coef[2]
aFit=coef[3]
bFit=coef[4]
fittedTemplate=pos_neg*pulseFitFun(time,startFit,riseFit,fallFit,aFit,bFit)
#renormalize template to 1 while keeping any small baseline offset imposed by hi-pass filter
fittedTemplate=(fittedTemplate-bFit)/(np.max(np.abs(fittedTemplate))-bFit)*(1+np.abs(bFit))+bFit
return fittedTemplate, startFit, riseFit, fallFit
def pulseFitFun(x,t0,t1,t2,a,b):
'''
double exponential pulse function normalized to one
INPUTS:
x - time array
t0 - pulse start time
t1 - pulse rise time
t2 - pulse fall time
a - pulse amplitude
b - baseline offset
OUTPUTS:
y - double exponential pulse array
'''
x=np.array(x)
t0=float(t0)
t1=float(t1)
t2=float(t2)
heaviside=np.zeros(len(x))
heaviside[x>t0]=1;
if t1<0 or t2<0:
norm=1
else:
norm=t2/(t1+t2)*(t1/(t1+t2))**(t1/t2)
y = a*(1-b/a)*(1-np.exp(-(x-t0)/t1))*np.exp(-(x-t0)/t2)/norm*heaviside + b*np.ones(len(x))
return y
| 17,033 | 38.799065 | 141 | py |