Compare commits
96 Commits
b0fe6c5723
...
calibratio
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
565d6e5318 | ||
|
|
b35a9212ac | ||
|
|
56c8b59ccd | ||
|
|
cbc86598b0 | ||
|
|
031b5098d5 | ||
|
|
c33e4cc32f | ||
|
|
4868b0e196 | ||
|
|
00f6b11740 | ||
|
|
e0491c5917 | ||
|
|
9c80091d16 | ||
| b0897bf52d | |||
| 09dd7f3d51 | |||
|
|
2e264fb582 | ||
| 0a00875d2e | |||
|
|
ab51fa7475 | ||
|
|
6a3a610cd3 | ||
|
|
8b02b9083f | ||
|
|
5dadf1bd7c | ||
|
|
9e8dc06c26 | ||
|
|
bf8f3f5cb7 | ||
| 0378317d7b | |||
| b2f223168c | |||
| 58decf0283 | |||
| fe6e438189 | |||
| d241d88168 | |||
| a1b0e723f6 | |||
| a818bf75a4 | |||
|
|
13d4db25fa | ||
|
|
5c274c713d | ||
|
|
85c9637ce3 | ||
|
|
7cf9683744 | ||
|
|
2110286abb | ||
|
|
f04f28dd11 | ||
|
|
e9a509c0f7 | ||
|
|
bdd323ad20 | ||
|
|
cadf2e5dde | ||
|
|
a7b73fa09a | ||
|
|
3433ef7132 | ||
|
|
a16fe0b735 | ||
|
|
5c3c2c407a | ||
|
|
8ef8ac7506 | ||
|
|
7d3224f351 | ||
|
|
a748385335 | ||
|
|
cd6bc0dc04 | ||
|
|
cb5c08bc94 | ||
| 45a267c8c7 | |||
| 291ed8859c | |||
| aa792bcb1d | |||
| 6a73f38fba | |||
| 6008cc03d6 | |||
| 938d70fbac | |||
|
|
dd3e0d045d | ||
| 8d616847f5 | |||
| 836d6dc3d9 | |||
|
|
43e0d4b75a | ||
|
|
66ea22fb4a | ||
|
|
d3800ddfa2 | ||
|
|
1dc72d00bb | ||
|
|
26f43151a2 | ||
|
|
a9be09dc06 | ||
|
|
06f5a6ae46 | ||
|
|
b912159b76 | ||
|
|
9cd6aadb3b | ||
|
|
1a2185d5e4 | ||
|
|
deb60fa84c | ||
|
|
1579c947c9 | ||
|
|
d6e2f8c5ba | ||
|
|
8e73b2ae1f | ||
|
|
9f7d28ccf8 | ||
|
|
3865bb8216 | ||
|
|
2317fd73c8 | ||
|
|
fbb4d3b81d | ||
|
|
7d02cb994f | ||
|
|
31bbffc480 | ||
|
|
fa3c704497 | ||
|
|
ebf7fe89bf | ||
|
|
2100a0205f | ||
|
|
971c1f4347 | ||
|
|
a298b48bdd | ||
|
|
cd414da6de | ||
|
|
0e0262a3af | ||
|
|
558e0de315 | ||
|
|
4d210831c8 | ||
|
|
dc96359f1d | ||
|
|
bb88053aaa | ||
|
|
1a642c6783 | ||
|
|
3766ea0ea2 | ||
|
|
e00259b15f | ||
|
|
e19c147059 | ||
|
|
e975bcd7e1 | ||
|
|
25cd1c0585 | ||
|
|
281640e80c | ||
|
|
74007668a9 | ||
|
|
bb2b7979b7 | ||
|
|
dadd061147 | ||
|
|
2c963c5085 |
5
.gitignore
vendored
5
.gitignore
vendored
@@ -161,3 +161,8 @@ cython_debug/
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
|
||||
# ignore created data files
|
||||
*.nix
|
||||
|
||||
# ignore reource.py as it is created by pyside6-rcc resources.qrc -o resources.py
|
||||
resources.py
|
||||
@@ -5,9 +5,13 @@ Relaxed ELectrophysiology Acquisition, Control, and Stimulation in python
|
||||
Implementing [relacs](https://github.com/relacs/relacs) with MCC USB 1608GX-2AO / 1808X devices ([multifunction-usb-daq-devices](https://digilent.com/shop/mcc-daq/data-acquisition/low-cost-daq/))
|
||||
|
||||
# Installation
|
||||
You have to install the MCC library (follow the installing instructions for [linux](https://github.com/mccdaq/uldaq) or [windows](https://github.com/mccdaq/mcculw)).
|
||||
You have to install the MCC library (follow the installing instructions for [linux/macOS](https://github.com/mccdaq/uldaq) or [windows](https://github.com/mccdaq/mcculw)).
|
||||
|
||||
After successful installing, you can use clone the reposity and install it with
|
||||
For MacOs if you run into problems with the libusb library if installed with homebrew, there is an issue thread on the uldaq repository.
|
||||
|
||||
[https://github.com/mccdaq/uldaq/issues/44](https://github.com/mccdaq/uldaq/issues/44)
|
||||
|
||||
After successful installing, you can use clone the repository and install it with
|
||||
|
||||
```sh
|
||||
pip install -e .
|
||||
|
||||
BIN
docs/AttCS3310.pdf
Normal file
BIN
docs/AttCS3310.pdf
Normal file
Binary file not shown.
964
poetry.lock
generated
964
poetry.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -1,16 +1,43 @@
|
||||
[project]
|
||||
organization = "de.uni-tuebingen.neuroetho"
|
||||
copyright = "(c) 2020, Neuroethology lab, Uni Tuebingen"
|
||||
|
||||
[tool.poetry]
|
||||
name = "pyrelacs"
|
||||
version = "0.1.0"
|
||||
description = "Relaxed ELectrophysiology Acquisition, Control, and Stimulation in python"
|
||||
authors = ["wendtalexander <wendtalexander@protonmail.com>"]
|
||||
repository = "https://whale.am28.uni-tuebingen.de/git/awendt/pyrelacs"
|
||||
readme = "README.md"
|
||||
license = "MIT"
|
||||
classifiers = [
|
||||
"Topic :: Scientific/Engineering",
|
||||
"Intended Audience :: Science/Research",
|
||||
"Intended Audience :: End Users/Desktop",
|
||||
]
|
||||
include = [
|
||||
{ path = "pyproject.toml" },
|
||||
"pyrelacs/resources.py"
|
||||
]
|
||||
|
||||
[tool.poetry.dependencies]
|
||||
python = "^3.12"
|
||||
python = "^3.10"
|
||||
uldaq = "^1.2.3"
|
||||
typer = "^0.12.5"
|
||||
matplotlib = "^3.9.2"
|
||||
numpy = "^1.9"
|
||||
pyqt6 = "^6.7.1"
|
||||
tomlkit = "^0.13.2"
|
||||
scipy = "^1.14.1"
|
||||
nixio = "^1.5.3"
|
||||
pyqtgraph = "^0.13.7"
|
||||
|
||||
[tool.poetry.scripts]
|
||||
pyrelacs = "pyrelacs.app:main"
|
||||
|
||||
[tool.poetry.group.dev.dependencies]
|
||||
ipython = "^8.27.0"
|
||||
|
||||
[build-system]
|
||||
requires = ["poetry-core"]
|
||||
requires = ["poetry-core>=1.0.0"]
|
||||
build-backend = "poetry.core.masonry.api"
|
||||
|
||||
0
pyrelacs/__init__.py
Normal file
0
pyrelacs/__init__.py
Normal file
49
pyrelacs/app.py
Normal file
49
pyrelacs/app.py
Normal file
@@ -0,0 +1,49 @@
|
||||
import sys
|
||||
|
||||
from PyQt6.QtCore import QSettings
|
||||
from PyQt6.QtWidgets import QApplication
|
||||
|
||||
from pyrelacs import info
|
||||
from pyrelacs.ui.mainwindow import PyRelacs
|
||||
from pyrelacs.util.logging import config_logging
|
||||
|
||||
log = config_logging()
|
||||
|
||||
from pyrelacs import (
|
||||
resources,
|
||||
) # best created with pyside6-rcc resources.qrc -o resources.py (rcc produces an error...)
|
||||
|
||||
|
||||
def main():
|
||||
app = QApplication(sys.argv)
|
||||
app.setApplicationName(info.NAME)
|
||||
app.setApplicationVersion(str(info.VERSION))
|
||||
app.setOrganizationDomain(info.ORGANIZATION)
|
||||
# app.setAttribute(Qt.ApplicationAttribute.AA_DontShowIconsInMenus, False)
|
||||
|
||||
# read window settings
|
||||
settings = QSettings(info.ORGANIZATION, info.NAME)
|
||||
width = int(settings.value("app/width", 1024))
|
||||
height = int(settings.value("app/height", 768))
|
||||
x = int(settings.value("app/pos_x", 100))
|
||||
y = int(settings.value("app/pos_y", 100))
|
||||
|
||||
window = PyRelacs()
|
||||
window.setMinimumWidth(200)
|
||||
window.setMinimumHeight(200)
|
||||
window.resize(width, height)
|
||||
window.move(x, y)
|
||||
window.show()
|
||||
exit_code = app.exec()
|
||||
|
||||
# store window position and size
|
||||
pos = window.pos()
|
||||
settings.setValue("app/width", window.width())
|
||||
settings.setValue("app/height", window.height())
|
||||
settings.setValue("app/pos_x", pos.x())
|
||||
settings.setValue("app/pos_y", pos.y())
|
||||
sys.exit(exit_code)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
0
pyrelacs/devices/__init__.py
Normal file
0
pyrelacs/devices/__init__.py
Normal file
425
pyrelacs/devices/mccdac.py
Normal file
425
pyrelacs/devices/mccdac.py
Normal file
@@ -0,0 +1,425 @@
|
||||
from ctypes import Array, c_double
|
||||
import time
|
||||
from typing import Union
|
||||
from IPython import embed
|
||||
import numpy.typing as npt
|
||||
import uldaq
|
||||
import numpy as np
|
||||
|
||||
from pyrelacs.util.logging import config_logging
|
||||
|
||||
log = config_logging()
|
||||
|
||||
|
||||
class MccDac:
|
||||
"""
|
||||
Represents the Digital/Analog Converter from Meassuring Computing.
|
||||
provides methods for writing and reading the Analog / Digital input and output.
|
||||
|
||||
Connects to the DAC device.
|
||||
|
||||
Attributes
|
||||
----------
|
||||
daq_device : uldaq.DaqDevice
|
||||
DaqDevice for handling connecting, releasing and disconnecting
|
||||
ai_device : uldaq.AiDevice
|
||||
The Analog input Device
|
||||
ao_device :
|
||||
Analog output Device
|
||||
dio_device :
|
||||
Digital Input Output
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
devices = uldaq.get_daq_device_inventory(uldaq.InterfaceType.USB)
|
||||
log.debug(f"Found daq devices {len(devices)}, connecting to the first one")
|
||||
try:
|
||||
self.daq_device = uldaq.DaqDevice(devices[0])
|
||||
except uldaq.ul_exception.ULException as e:
|
||||
log.error("Did not found daq devices, please connect one")
|
||||
raise e
|
||||
try:
|
||||
self.daq_device.connect()
|
||||
except uldaq.ul_exception.ULException:
|
||||
self.disconnect_dac()
|
||||
self.connect_dac()
|
||||
self.ai_device = self.daq_device.get_ai_device()
|
||||
self.ao_device = self.daq_device.get_ao_device()
|
||||
self.dio_device = self.daq_device.get_dio_device()
|
||||
log.debug("Connected")
|
||||
|
||||
def connect_dac(self):
|
||||
"""
|
||||
Connecting to the DAQ device
|
||||
|
||||
"""
|
||||
devices = uldaq.get_daq_device_inventory(uldaq.InterfaceType.USB)
|
||||
log.debug(f"Found daq devices {len(devices)}, connecting to the first one")
|
||||
if len(devices) == 0:
|
||||
log.error("Did not found daq devices, please connect one")
|
||||
exit(1)
|
||||
self.daq_device = uldaq.DaqDevice(devices[0])
|
||||
self.daq_device.connect()
|
||||
self.ai_device = self.daq_device.get_ai_device()
|
||||
self.ao_device = self.daq_device.get_ao_device()
|
||||
self.dio_device = self.daq_device.get_dio_device()
|
||||
log.debug("Connected")
|
||||
|
||||
def read_analog(
|
||||
self,
|
||||
channels: list[int],
|
||||
duration: int,
|
||||
samplerate: float,
|
||||
AiInputMode: uldaq.AiInputMode = uldaq.AiInputMode.SINGLE_ENDED,
|
||||
Range: uldaq.Range = uldaq.Range.BIP10VOLTS,
|
||||
ScanOption: uldaq.ScanOption = uldaq.ScanOption.DEFAULTIO,
|
||||
AInScanFlag: uldaq.AInScanFlag = uldaq.AInScanFlag.DEFAULT,
|
||||
) -> Array[c_double]:
|
||||
"""
|
||||
Reading the analog input of the DAC device
|
||||
Creates a c_double Array for storing the acquired data
|
||||
|
||||
Parameters
|
||||
----------
|
||||
channels : list[int]
|
||||
channels to read from, provide only two int's in a list (ex [0, 1] or [0, 4])
|
||||
for sampling from the range(channel0, channel4)
|
||||
|
||||
duration : int
|
||||
duration of sampling period
|
||||
|
||||
samplerate : float
|
||||
samplerate for the duration of sampling
|
||||
|
||||
AiInputMode : uldaq.AiInputMode = uldaq.AiInputMode.SINGLE_ENDED
|
||||
Contains attributes indicating A/D channel input modes.
|
||||
Compares to Ground
|
||||
|
||||
Range : uldaq.Range = uldaq.Range.BIP10VOLTS
|
||||
Range of the output
|
||||
|
||||
ScanOption : uldaq.ScanOption = uldaq.ScanOption.DEFAULTIO
|
||||
Specific Flags for acuiring the input
|
||||
|
||||
AInScanFlag : uldaq.AInScanFlag = uldaq.AInScanFlag.DEFAULT
|
||||
Scaling of the data
|
||||
|
||||
Returns
|
||||
-------
|
||||
Array[c_double]
|
||||
|
||||
"""
|
||||
assert len(channels) == 2, log.error("You can only provide two channels [0, 1]")
|
||||
|
||||
if channels[0] != channels[1]:
|
||||
buffer_len_channels = 2
|
||||
else:
|
||||
buffer_len_channels = 1
|
||||
|
||||
buffer_len = np.shape(np.arange(0, duration, 1 / samplerate))[0]
|
||||
data_analog_input = uldaq.create_float_buffer(buffer_len_channels, buffer_len)
|
||||
|
||||
er = self.ai_device.a_in_scan(
|
||||
channels[0],
|
||||
channels[1],
|
||||
AiInputMode,
|
||||
Range,
|
||||
buffer_len,
|
||||
samplerate,
|
||||
ScanOption,
|
||||
AInScanFlag,
|
||||
data=data_analog_input,
|
||||
)
|
||||
|
||||
return data_analog_input
|
||||
|
||||
def write_analog(
|
||||
self,
|
||||
data: Union[list, npt.NDArray],
|
||||
channels: list[int],
|
||||
samplerate: float,
|
||||
Range: uldaq.Range = uldaq.Range.BIP10VOLTS,
|
||||
ScanOption: uldaq.ScanOption = uldaq.ScanOption.DEFAULTIO,
|
||||
AOutScanFlag: uldaq.AOutScanFlag = uldaq.AOutScanFlag.DEFAULT,
|
||||
) -> Array[c_double]:
|
||||
"""
|
||||
Writes data to the DAC device.
|
||||
Creates a c_double Array for writing the data
|
||||
|
||||
Parameters
|
||||
----------
|
||||
data : Union[list, npt.NDArray]
|
||||
data which should be written to the DAC
|
||||
|
||||
channels : list[int]
|
||||
channels to read from, provide only two int's in a list (ex [0, 1])
|
||||
for sampling from the range(channel0, channel1)
|
||||
DAC USB 1608GX-2AO has only 2 output channels
|
||||
|
||||
samplerate : float
|
||||
samplerate for the duration of sampling
|
||||
|
||||
Range : uldaq.Range = uldaq.Range.BIP10VOLTS
|
||||
Range of the output
|
||||
|
||||
ScanOption : uldaq.ScanOption = uldaq.ScanOption.DEFAULTIO
|
||||
Specific Flags for acuiring the input
|
||||
|
||||
AOutScanFlag : uldaq.AOutScanFlag = uldaq.AOutScanFlag.DEFAULT
|
||||
For Scaling the data
|
||||
|
||||
Returns
|
||||
-------
|
||||
Array[c_double]
|
||||
"""
|
||||
|
||||
assert len(channels) == 2, log.error("You can only provide two channels [0, 1]")
|
||||
|
||||
buffer = c_double * len(data)
|
||||
data_analog_output = buffer(*data)
|
||||
log.debug(f"Created C_double data {data_analog_output}")
|
||||
|
||||
try:
|
||||
err = self.ao_device.a_out_scan(
|
||||
channels[0],
|
||||
channels[1],
|
||||
Range,
|
||||
int(len(data)),
|
||||
samplerate,
|
||||
ScanOption,
|
||||
AOutScanFlag,
|
||||
data_analog_output,
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"{e}")
|
||||
self.set_analog_to_zero()
|
||||
self.disconnect_dac()
|
||||
|
||||
return data_analog_output
|
||||
|
||||
def set_analog_to_zero(self, channels: list[int] = [0, 1]) -> None:
|
||||
"""
|
||||
Sets all analog outputs to zero
|
||||
|
||||
Parameters
|
||||
----------
|
||||
channels : list[int]
|
||||
channels to read from, provide only two int's in a list (ex [0, 1])
|
||||
for sampling from the range(channel0, channel1)
|
||||
DAC USB 1608GX-2AO has only 2 output channels
|
||||
|
||||
"""
|
||||
try:
|
||||
err = self.ao_device.a_out_list(
|
||||
channels[0],
|
||||
channels[1],
|
||||
[
|
||||
uldaq.Range.BIP10VOLTS,
|
||||
uldaq.Range.BIP10VOLTS,
|
||||
],
|
||||
uldaq.AOutListFlag.DEFAULT,
|
||||
[0, 0],
|
||||
)
|
||||
except Exception as e:
|
||||
log.error("f{e}")
|
||||
log.error("disconnection dac")
|
||||
self.disconnect_dac()
|
||||
|
||||
def digital_trigger(self, ch: int = 0) -> None:
|
||||
"""
|
||||
Writes a 1 to a specified digital channel, if the channel is already on 1 switches it to
|
||||
0 and after Nano second it writes a 1 to the specified digital channel
|
||||
|
||||
Parameters
|
||||
----------
|
||||
ch : int
|
||||
Channel to trigger
|
||||
"""
|
||||
data = self.read_bit(channel=ch)
|
||||
if data:
|
||||
self.write_bit(channel=ch, bit=0)
|
||||
time.time_ns()
|
||||
self.write_bit(channel=ch, bit=1)
|
||||
else:
|
||||
self.write_bit(channel=ch, bit=1)
|
||||
|
||||
def write_bit(self, channel: int = 0, bit: int = 1) -> None:
|
||||
"""
|
||||
Writes a 0 / 1 to a specified digitial channel
|
||||
|
||||
Parameters
|
||||
----------
|
||||
channel : int
|
||||
Digital channel to write
|
||||
|
||||
bit : int
|
||||
0 / 1 for writing to the digital channel
|
||||
|
||||
"""
|
||||
self.dio_device.d_config_bit(
|
||||
uldaq.DigitalPortType.AUXPORT, channel, uldaq.DigitalDirection.OUTPUT
|
||||
)
|
||||
self.dio_device.d_bit_out(
|
||||
uldaq.DigitalPortType.AUXPORT, bit_number=channel, data=bit
|
||||
)
|
||||
|
||||
def read_bit(self, channel: int = 0) -> int:
|
||||
"""
|
||||
Reads a 0 / 1 from the specified digital channel
|
||||
|
||||
Parameters
|
||||
----------
|
||||
channel : int
|
||||
Digital channel to read from
|
||||
|
||||
Returns
|
||||
-------
|
||||
bit : int
|
||||
0 or 1 from the digital channel
|
||||
"""
|
||||
bit = self.dio_device.d_bit_in(uldaq.DigitalPortType.AUXPORT, channel)
|
||||
return bit
|
||||
|
||||
def disconnect_dac(self):
|
||||
self.daq_device.disconnect()
|
||||
self.daq_device.release()
|
||||
|
||||
def check_attenuator(self) -> None:
|
||||
"""
|
||||
For checking the attenuator in the DAC device that was implemented to attenuate the
|
||||
analog signal to mV.
|
||||
|
||||
Writes to Channel 0 of the analog output with different attenuation levels
|
||||
0, 0, -2, -5, -10, -20, -50 dB and the second 0 has a software mute
|
||||
|
||||
"""
|
||||
SAMPLERATE = 40_000.0
|
||||
DURATION = 5
|
||||
AMPLITUDE = 1
|
||||
SINFREQ = 1
|
||||
t = np.arange(0, DURATION, 1 / SAMPLERATE)
|
||||
data = AMPLITUDE * np.sin(2 * np.pi * SINFREQ * t)
|
||||
# data_channels = np.concatenate((data, data))
|
||||
|
||||
db_values = [0, 0, -2, -5, -10, -20, -50]
|
||||
for i, db_value in enumerate(db_values):
|
||||
log.info(f"Attenuating the Channels, with {db_value}")
|
||||
if i == 1:
|
||||
log.info("Muting the Channels")
|
||||
self.set_attenuation_level(
|
||||
db_value, db_value, mute_channel1=True, mute_channel2=True
|
||||
)
|
||||
else:
|
||||
self.set_attenuation_level(db_value, db_value)
|
||||
|
||||
_ = self.write_analog(
|
||||
data,
|
||||
[0, 0],
|
||||
SAMPLERATE,
|
||||
ScanOption=uldaq.ScanOption.EXTTRIGGER,
|
||||
Range=uldaq.Range.BIP10VOLTS,
|
||||
)
|
||||
self.digital_trigger()
|
||||
|
||||
try:
|
||||
self.ao_device.scan_wait(uldaq.WaitType.WAIT_UNTIL_DONE, 15)
|
||||
self.write_bit(channel=0, bit=0)
|
||||
self.set_analog_to_zero()
|
||||
except uldaq.ul_exception.ULException:
|
||||
log.debug("Operation timed out")
|
||||
self.write_bit(channel=0, bit=0)
|
||||
self.disconnect_dac()
|
||||
self.connect_dac()
|
||||
self.set_analog_to_zero()
|
||||
finally:
|
||||
self.write_bit(channel=0, bit=0)
|
||||
self.disconnect_dac()
|
||||
self.connect_dac()
|
||||
self.set_analog_to_zero()
|
||||
|
||||
log.info("Sleeping for 1 second, before next attenuation")
|
||||
time.sleep(1)
|
||||
|
||||
def set_attenuation_level(
|
||||
self,
|
||||
db_channel1: float = 5.0,
|
||||
db_channel2: float = 5.0,
|
||||
mute_channel1: bool = False,
|
||||
mute_channel2: bool = False,
|
||||
):
|
||||
"""
|
||||
Setting the attenuation level of the chip that is connected to the DAQ
|
||||
The attenuation level is set by writing to the connected digital output pin 5
|
||||
where the strobepin 6 is signaling the when the bit was send.
|
||||
The cspin is set from 1 to 0 for the start and 0 to 1 for signaling the end
|
||||
of the data write process.
|
||||
|
||||
The mute pin should be set to 1 for the device to be working.
|
||||
|
||||
More information in the AttCS3310.pdf in the doc
|
||||
|
||||
ident : attdev-1
|
||||
strobepin : 6
|
||||
datainpin : 5
|
||||
dataoutpin: -1
|
||||
cspin : 4
|
||||
mutepin : 7
|
||||
zcenpin : -1
|
||||
|
||||
Parameters
|
||||
----------
|
||||
db_channel1 : float
|
||||
dB Attenuation level for the first channel
|
||||
|
||||
db_channel2 : float
|
||||
dB Attenuation level for the second channel
|
||||
|
||||
mute_channel1 : bool
|
||||
Software mute for the first channel
|
||||
|
||||
mute_channel2 : bool
|
||||
Software mute for the second channel
|
||||
|
||||
|
||||
"""
|
||||
self.activate_attenuator()
|
||||
hardware_possible_db = np.arange(-95.5, 32.0, 0.5)
|
||||
byte_number = np.arange(1, 256)
|
||||
byte_number_db1 = byte_number[hardware_possible_db == db_channel1][0]
|
||||
binary_db1 = np.binary_repr(byte_number_db1, width=8)
|
||||
byte_number_db2 = byte_number[hardware_possible_db == db_channel2][0]
|
||||
binary_db2 = np.binary_repr(byte_number_db2, width=8)
|
||||
if mute_channel1:
|
||||
log.info("Muting channel one")
|
||||
binary_db1 = "00000000"
|
||||
if mute_channel2:
|
||||
log.info("Muting channel one")
|
||||
binary_db2 = "00000000"
|
||||
|
||||
channels_db = binary_db2 + binary_db1
|
||||
self.write_bit(channel=4, bit=0)
|
||||
for b in channels_db:
|
||||
self.write_bit(channel=5, bit=int(b))
|
||||
time.time_ns()
|
||||
self.write_bit(channel=6, bit=1)
|
||||
time.time_ns()
|
||||
self.write_bit(channel=6, bit=0)
|
||||
time.time_ns()
|
||||
self.write_bit(channel=4, bit=1)
|
||||
|
||||
def activate_attenuator(self):
|
||||
"""
|
||||
Activation of the attenuator, where the cspin and mute pin is set to 1,
|
||||
and the datapin and strobpin to 0
|
||||
|
||||
"""
|
||||
for ch, b in zip([4, 5, 6, 7], [1, 0, 0, 1]):
|
||||
self.write_bit(channel=ch, bit=b)
|
||||
|
||||
def deactivate_attenuator(self):
|
||||
"""
|
||||
Writes a 0 to the mute pin, which is deactivating the attenuator
|
||||
|
||||
"""
|
||||
# mute should be enabled for starting calibration
|
||||
self.write_bit(channel=7, bit=0)
|
||||
BIN
pyrelacs/icons/connect.png
Normal file
BIN
pyrelacs/icons/connect.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 6.9 KiB |
BIN
pyrelacs/icons/disconnect.png
Normal file
BIN
pyrelacs/icons/disconnect.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 5.3 KiB |
BIN
pyrelacs/icons/exit.png
Normal file
BIN
pyrelacs/icons/exit.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 7.0 KiB |
BIN
pyrelacs/icons/record.png
Normal file
BIN
pyrelacs/icons/record.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 4.9 KiB |
BIN
pyrelacs/icons/relacstuxheader.png
Normal file
BIN
pyrelacs/icons/relacstuxheader.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 255 KiB |
BIN
pyrelacs/icons/stop.png
Normal file
BIN
pyrelacs/icons/stop.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.2 KiB |
39
pyrelacs/info.py
Normal file
39
pyrelacs/info.py
Normal file
@@ -0,0 +1,39 @@
|
||||
import tomlkit
|
||||
import pathlib
|
||||
|
||||
|
||||
def load_project_settings(project_root):
|
||||
print(project_root)
|
||||
# Read the pyproject.toml file
|
||||
with open(pathlib.Path.joinpath(project_root, "pyproject.toml"), "r") as f:
|
||||
pyproject_content = f.read()
|
||||
|
||||
# Parse the toml content
|
||||
pyproject = tomlkit.parse(pyproject_content)
|
||||
|
||||
# Access project settings
|
||||
return {
|
||||
"name": pyproject["tool"]["poetry"]["name"],
|
||||
"version": pyproject["tool"]["poetry"]["version"],
|
||||
"description": pyproject["tool"]["poetry"]["description"],
|
||||
"authors": pyproject["tool"]["poetry"]["authors"],
|
||||
"readme": pyproject["tool"]["poetry"]["authors"],
|
||||
"licence": pyproject["tool"]["poetry"]["license"],
|
||||
"organization": pyproject["project"]["organization"],
|
||||
"classifiers": pyproject["tool"]["poetry"]["classifiers"],
|
||||
"copyright": pyproject["project"]["copyright"],
|
||||
"repository": pyproject["tool"]["poetry"]["repository"],
|
||||
}
|
||||
|
||||
|
||||
_root = pathlib.Path(__file__).parent.parent
|
||||
_infodict = load_project_settings(_root)
|
||||
|
||||
NAME = _infodict["name"]
|
||||
VERSION = _infodict["version"]
|
||||
AUTHORS = _infodict["authors"]
|
||||
COPYRIGHT = _infodict["copyright"]
|
||||
HOMEPAGE = _infodict["repository"]
|
||||
CLASSIFIERS = _infodict["classifiers"]
|
||||
DESCRIPTION = _infodict["description"]
|
||||
ORGANIZATION = _infodict["organization"]
|
||||
@@ -1,29 +0,0 @@
|
||||
import uldaq
|
||||
from IPython import embed
|
||||
import typer
|
||||
|
||||
from pyrelacs.util.logging import config_logging
|
||||
|
||||
log = config_logging()
|
||||
|
||||
class ReadData():
|
||||
def __init__(self) -> None:
|
||||
devices = uldaq.get_daq_device_inventory(uldaq.InterfaceType.USB)
|
||||
log.debug(f"Found daq devices {len(devices)}, connecting to the first one")
|
||||
self.daq_device = uldaq.DaqDevice(devices[0])
|
||||
self.daq_device.connect()
|
||||
log.debug("Connected")
|
||||
|
||||
def read_analog_in(self):
|
||||
# Get the Ananlog In device and Analog Info
|
||||
ai_device = self.daq_device.get_ai_device()
|
||||
ai_info = self.daq_device.get_info()
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
daq_input = Input_daq()
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
import uldaq
|
||||
from IPython import embed
|
||||
import typer
|
||||
|
||||
class Output_daq():
|
||||
def __init__(self) -> None:
|
||||
devices = uldaq.get_daq_device_inventory(uldaq.InterfaceType.USB)
|
||||
daq_device = uldaq.DaqDevice(devices[0])
|
||||
daq_device.connect()
|
||||
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
daq_input = Input_daq()
|
||||
|
||||
0
pyrelacs/repros/__init__.py
Normal file
0
pyrelacs/repros/__init__.py
Normal file
201
pyrelacs/repros/calbi.py
Normal file
201
pyrelacs/repros/calbi.py
Normal file
@@ -0,0 +1,201 @@
|
||||
import faulthandler
|
||||
import time
|
||||
|
||||
import nixio as nix
|
||||
import uldaq
|
||||
from IPython import embed
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
from scipy.signal import welch
|
||||
from scipy.signal import find_peaks
|
||||
|
||||
from pyrelacs.devices.mccdac import MccDac
|
||||
from pyrelacs.util.logging import config_logging
|
||||
|
||||
log = config_logging()
|
||||
# for more information on seg faults
|
||||
faulthandler.enable()
|
||||
|
||||
|
||||
class Calibration(MccDac):
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.SAMPLERATE = 40_000.0
|
||||
self.DURATION = 5
|
||||
self.AMPLITUDE = 1
|
||||
self.SINFREQ = 750
|
||||
|
||||
@staticmethod
|
||||
def run(nix_file: nix.File):
|
||||
calb = Calibration()
|
||||
calb.check_beat(nix_file)
|
||||
|
||||
def check_amplitude(self):
|
||||
db_values = [0.0, -5.0, -10.0, -20.0, -50.0]
|
||||
colors = ["red", "green", "blue", "black", "yellow"]
|
||||
self.set_attenuation_level(db_channel1=0.0, db_channel2=0.0)
|
||||
# write to ananlog 1
|
||||
t = np.arange(0, self.DURATION, 1 / self.SAMPLERATE)
|
||||
data = self.AMPLITUDE * np.sin(2 * np.pi * self.SINFREQ * t)
|
||||
fig, ax = plt.subplots()
|
||||
|
||||
for i, db_value in enumerate(db_values):
|
||||
self.set_attenuation_level(db_channel1=db_value, db_channel2=db_value)
|
||||
log.debug(f"{db_value}")
|
||||
|
||||
stim = self.write_analog(
|
||||
data,
|
||||
[0, 0],
|
||||
self.SAMPLERATE,
|
||||
ScanOption=uldaq.ScanOption.EXTTRIGGER,
|
||||
)
|
||||
|
||||
data_channel_one = self.read_analog(
|
||||
[0, 0],
|
||||
self.DURATION,
|
||||
self.SAMPLERATE,
|
||||
ScanOption=uldaq.ScanOption.EXTTRIGGER,
|
||||
)
|
||||
time.sleep(1)
|
||||
|
||||
log.debug("Starting the Scan")
|
||||
self.digital_trigger()
|
||||
|
||||
try:
|
||||
self.ao_device.scan_wait(uldaq.WaitType.WAIT_UNTIL_DONE, 15)
|
||||
log.debug("Scan finished")
|
||||
self.write_bit(channel=0, bit=0)
|
||||
time.sleep(1)
|
||||
self.set_analog_to_zero()
|
||||
except uldaq.ul_exception.ULException:
|
||||
log.debug("Operation timed out")
|
||||
# reset the diggital trigger
|
||||
self.write_bit(channel=0, bit=0)
|
||||
time.sleep(1)
|
||||
self.set_analog_to_zero()
|
||||
self.disconnect_dac()
|
||||
|
||||
if i == 0:
|
||||
ax.plot(t, stim, label=f"Input_{db_value}", color=colors[i])
|
||||
ax.plot(t, data_channel_one, label=f"Reaout {db_value}", color=colors[i])
|
||||
|
||||
ax.legend()
|
||||
plt.show()
|
||||
|
||||
self.disconnect_dac()
|
||||
|
||||
def check_beat(self, nix_file: nix.File):
|
||||
self.set_attenuation_level(db_channel1=-10.0, db_channel2=0.0)
|
||||
t = np.arange(0, self.DURATION, 1 / self.SAMPLERATE)
|
||||
data = self.AMPLITUDE * np.sin(2 * np.pi * self.SINFREQ * t)
|
||||
# data = np.concatenate((data, data))
|
||||
db_values = [0.0, -5.0, -8.5, -10.0]
|
||||
colors = ["red", "blue", "black", "green"]
|
||||
colors_in = ["lightcoral", "lightblue", "grey", "lightgreen"]
|
||||
block = nix_file.create_block("Calibration", "data")
|
||||
# fig, axes = plt.subplots(2, 2, sharex="col")
|
||||
for i, db_value in enumerate(db_values):
|
||||
self.set_attenuation_level(db_channel1=db_value)
|
||||
stim = self.write_analog(
|
||||
data,
|
||||
[0, 0],
|
||||
self.SAMPLERATE,
|
||||
ScanOption=uldaq.ScanOption.EXTTRIGGER,
|
||||
)
|
||||
readout = self.read_analog(
|
||||
[0, 1],
|
||||
self.DURATION,
|
||||
self.SAMPLERATE,
|
||||
ScanOption=uldaq.ScanOption.EXTTRIGGER,
|
||||
)
|
||||
self.digital_trigger()
|
||||
log.info(self.ao_device)
|
||||
ai_status = uldaq.ScanStatus.RUNNING
|
||||
ao_status = uldaq.ScanStatus.RUNNING
|
||||
|
||||
log.debug(
|
||||
f"Status Analog_output {ao_status}\n, Status Analog_input {ai_status}"
|
||||
)
|
||||
while (ai_status != uldaq.ScanStatus.IDLE) and (
|
||||
ao_status != uldaq.ScanStatus.IDLE
|
||||
):
|
||||
# log.debug("Scanning")
|
||||
time.time_ns()
|
||||
ai_status = self.ai_device.get_scan_status()[0]
|
||||
ao_status = self.ao_device.get_scan_status()[0]
|
||||
|
||||
self.write_bit(channel=0, bit=0)
|
||||
log.debug(
|
||||
f"Status Analog_output {ao_status}\n, Status Analog_input {ai_status}"
|
||||
)
|
||||
|
||||
channel1 = np.array(readout[::2])
|
||||
channel2 = np.array(readout[1::2])
|
||||
|
||||
stim_data = block.create_data_array(
|
||||
f"stimulus_{db_value}",
|
||||
"nix.regular_sampled",
|
||||
shape=data.shape,
|
||||
data=channel1,
|
||||
label="Voltage",
|
||||
unit="V",
|
||||
)
|
||||
stim_data.append_sampled_dimension(
|
||||
self.SAMPLERATE,
|
||||
label="time",
|
||||
unit="s",
|
||||
)
|
||||
fish_data = block.create_data_array(
|
||||
f"fish_{db_value}",
|
||||
"Array",
|
||||
shape=data.shape,
|
||||
data=channel2,
|
||||
label="Voltage",
|
||||
unit="V",
|
||||
)
|
||||
fish_data.append_sampled_dimension(
|
||||
self.SAMPLERATE,
|
||||
label="time",
|
||||
unit="s",
|
||||
)
|
||||
|
||||
self.set_analog_to_zero()
|
||||
|
||||
|
||||
def decibel(power, ref_power=1.0, min_power=1e-20):
|
||||
"""Transform power to decibel relative to ref_power.
|
||||
|
||||
\\[ decibel = 10 \\cdot \\log_{10}(power/ref\\_power) \\]
|
||||
Power values smaller than `min_power` are set to `-np.inf`.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
power: float or array
|
||||
Power values, for example from a power spectrum or spectrogram.
|
||||
ref_power: float or None or 'peak'
|
||||
Reference power for computing decibel.
|
||||
If set to `None` or 'peak', the maximum power is used.
|
||||
min_power: float
|
||||
Power values smaller than `min_power` are set to `-np.inf`.
|
||||
|
||||
Returns
|
||||
-------
|
||||
decibel_psd: array
|
||||
Power values in decibel relative to `ref_power`.
|
||||
"""
|
||||
if np.isscalar(power):
|
||||
tmp_power = np.array([power])
|
||||
decibel_psd = np.array([power])
|
||||
else:
|
||||
tmp_power = power
|
||||
decibel_psd = power.copy()
|
||||
if ref_power is None or ref_power == "peak":
|
||||
ref_power = np.max(decibel_psd)
|
||||
decibel_psd[tmp_power <= min_power] = float("-inf")
|
||||
decibel_psd[tmp_power > min_power] = 10.0 * np.log10(
|
||||
decibel_psd[tmp_power > min_power] / ref_power
|
||||
)
|
||||
if np.isscalar(power):
|
||||
return decibel_psd[0]
|
||||
else:
|
||||
return decibel_psd
|
||||
76
pyrelacs/repros/repros.py
Normal file
76
pyrelacs/repros/repros.py
Normal file
@@ -0,0 +1,76 @@
|
||||
import sys
|
||||
import ast
|
||||
import pathlib
|
||||
from typing import Tuple
|
||||
|
||||
from IPython import embed
|
||||
import nixio as nix
|
||||
import importlib.util
|
||||
|
||||
from pyrelacs.util.logging import config_logging
|
||||
|
||||
log = config_logging()
|
||||
|
||||
|
||||
class Repro:
|
||||
"""
|
||||
Repro Class that searches in the repro folder for classes instances and executes the
|
||||
the run function in the searched class
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
pass
|
||||
|
||||
def run_repro(
|
||||
self, nix_file: nix.File, name: str, file: pathlib.Path, *args, **kwargs
|
||||
) -> None:
|
||||
spec = importlib.util.spec_from_file_location("rep", file)
|
||||
if not spec:
|
||||
log.error("Could not load the file")
|
||||
else:
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
if not module:
|
||||
log.error("Could not load the module of the repro")
|
||||
else:
|
||||
sys.modules[name] = module
|
||||
if spec.loader is not None:
|
||||
spec.loader.exec_module(module)
|
||||
else:
|
||||
log.error(f"{spec.loader} is None")
|
||||
if hasattr(module, name):
|
||||
rep_class = getattr(module, name)
|
||||
rep_class.run(nix_file)
|
||||
else:
|
||||
raise AttributeError(f"{file.name} has no {name} class")
|
||||
|
||||
def names_of_repros(self) -> Tuple[list, list]:
|
||||
"""
|
||||
Searches for class names in the repro folder in all python files
|
||||
|
||||
Returns
|
||||
-------
|
||||
Tuple[list, list]
|
||||
list of class names
|
||||
list of file names from the class names
|
||||
"""
|
||||
|
||||
file_path_cur = pathlib.Path(__file__).parent
|
||||
python_files = list(file_path_cur.glob("**/*.py"))
|
||||
exclude_files = ["repros.py", "__init__.py"]
|
||||
python_files = [f for f in python_files if f.name not in exclude_files]
|
||||
repro_names = []
|
||||
file_names = []
|
||||
for python_file in python_files:
|
||||
with open(python_file, "r") as file:
|
||||
file_content = file.read()
|
||||
tree = ast.parse(file_content)
|
||||
class_name = [
|
||||
node.name
|
||||
for node in ast.walk(tree)
|
||||
if isinstance(node, ast.ClassDef)
|
||||
]
|
||||
repro_names.extend(class_name)
|
||||
file_names.append(python_file)
|
||||
file.close()
|
||||
return repro_names, file_names
|
||||
10
pyrelacs/resources.qrc
Normal file
10
pyrelacs/resources.qrc
Normal file
@@ -0,0 +1,10 @@
|
||||
<!DOCTYPE RCC><RCC version="1.0">
|
||||
<qresource>
|
||||
<file>icons/exit.png</file>
|
||||
<file>icons/connect.png</file>
|
||||
<file>icons/disconnect.png</file>
|
||||
<file>icons/record.png</file>
|
||||
<file>icons/stop.png</file>
|
||||
<file>icons/relacstuxheader.png</file>
|
||||
</qresource>
|
||||
</RCC>
|
||||
0
pyrelacs/ui/__init__.py
Normal file
0
pyrelacs/ui/__init__.py
Normal file
54
pyrelacs/ui/about.py
Normal file
54
pyrelacs/ui/about.py
Normal file
@@ -0,0 +1,54 @@
|
||||
from PyQt6.QtGui import QPixmap
|
||||
from PyQt6.QtWidgets import QDialog, QDialogButtonBox, QLabel, QVBoxLayout, QWidget
|
||||
from PyQt6.QtCore import Qt
|
||||
|
||||
|
||||
class AboutDialog(QDialog):
|
||||
|
||||
def __init__(self, parent=None) -> None:
|
||||
super().__init__(parent=parent)
|
||||
self.setModal(True)
|
||||
about = About(self)
|
||||
self.setLayout(QVBoxLayout())
|
||||
self.layout().addWidget(about)
|
||||
bbox = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok)
|
||||
bbox.accepted.connect(self.accept)
|
||||
self.layout().addWidget(bbox)
|
||||
|
||||
|
||||
class About(QWidget):
|
||||
|
||||
def __init__(self, parent=None) -> None:
|
||||
super().__init__(parent=parent)
|
||||
self.setLayout(QVBoxLayout())
|
||||
|
||||
heading = QLabel("pyRelacs")
|
||||
font = heading.font()
|
||||
font.setPointSize(18)
|
||||
font.setBold(True)
|
||||
heading.setFont(font)
|
||||
heading.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
subheading = QLabel("relacsed electrophysiological recordings")
|
||||
subheading.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
nix_link = QLabel("https://github.com/relacs")
|
||||
nix_link.setOpenExternalLinks(True)
|
||||
nix_link.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
rtd_link = QLabel("https://relacs.net")
|
||||
rtd_link.setOpenExternalLinks(True)
|
||||
rtd_link.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
|
||||
iconlabel = QLabel()
|
||||
pixmap = QPixmap(":/icons/relacstuxheader.png")
|
||||
s = pixmap.size()
|
||||
new_height = int(s.height() * 300/s.width())
|
||||
pixmap = pixmap.scaled(300, new_height, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.FastTransformation)
|
||||
iconlabel.setPixmap(pixmap)
|
||||
iconlabel.setMaximumWidth(300)
|
||||
iconlabel.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
iconlabel.setScaledContents(True)
|
||||
|
||||
self.layout().addWidget(heading)
|
||||
self.layout().addWidget(subheading)
|
||||
self.layout().addWidget(iconlabel)
|
||||
self.layout().addWidget(nix_link)
|
||||
self.layout().addWidget(rtd_link)
|
||||
227
pyrelacs/ui/mainwindow.py
Normal file
227
pyrelacs/ui/mainwindow.py
Normal file
@@ -0,0 +1,227 @@
|
||||
from PyQt6.QtGui import QAction, QIcon, QKeySequence
|
||||
from PyQt6.QtCore import Qt, QSize, QThreadPool
|
||||
from PyQt6.QtWidgets import (
|
||||
QGridLayout,
|
||||
QPushButton,
|
||||
QToolBar,
|
||||
QWidget,
|
||||
QMainWindow,
|
||||
QPlainTextEdit,
|
||||
QMenuBar,
|
||||
QStatusBar,
|
||||
)
|
||||
import uldaq
|
||||
import numpy as np
|
||||
import nixio as nix
|
||||
import pyqtgraph as pg
|
||||
|
||||
from pathlib import Path as path
|
||||
from scipy.signal import welch, find_peaks
|
||||
|
||||
from pyrelacs.worker import Worker
|
||||
from pyrelacs.repros.repros import Repro
|
||||
from pyrelacs.util.logging import config_logging
|
||||
from pyrelacs.ui.about import AboutDialog
|
||||
from pyrelacs.ui.plots.calibration import CalibrationPlot
|
||||
|
||||
log = config_logging()
|
||||
_root = path(__file__).parent.parent
|
||||
|
||||
from IPython import embed
|
||||
|
||||
|
||||
class PyRelacs(QMainWindow):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.setToolButtonStyle(
|
||||
Qt.ToolButtonStyle.ToolButtonTextBesideIcon
|
||||
) # Ensure icons are displayed with text
|
||||
self.setWindowTitle("PyRelacs")
|
||||
|
||||
self.figure = pg.GraphicsLayoutWidget()
|
||||
|
||||
filename = path.joinpath(path.cwd(), "data.nix")
|
||||
if filename.exists():
|
||||
self.nix_file = nix.File.open(str(filename), nix.FileMode.ReadOnly)
|
||||
else:
|
||||
self.nix_file = nix.File.open(str(filename), nix.FileMode.Overwrite)
|
||||
|
||||
self.calibration_plot = CalibrationPlot(self.figure, self.nix_file)
|
||||
|
||||
self.threadpool = QThreadPool()
|
||||
self.repros = Repro()
|
||||
|
||||
self.text = QPlainTextEdit()
|
||||
self.text.setReadOnly(True)
|
||||
|
||||
self.setMenuBar(QMenuBar(self))
|
||||
self.setStatusBar(QStatusBar(self))
|
||||
self.create_actions()
|
||||
self.create_buttons()
|
||||
self.create_toolbars()
|
||||
|
||||
layout = QGridLayout()
|
||||
layout.addWidget(self.figure, 0, 0, 2, 2)
|
||||
layout.addWidget(self.text, 2, 0, 1, 2)
|
||||
|
||||
widget = QWidget()
|
||||
widget.setLayout(layout)
|
||||
self.setCentralWidget(widget)
|
||||
|
||||
def create_actions(self):
|
||||
self._rlx_exitaction = QAction(QIcon(":/icons/exit.png"), "Exit", self)
|
||||
self._rlx_exitaction.setStatusTip("Close relacs")
|
||||
self._rlx_exitaction.setShortcut(QKeySequence("Alt+q"))
|
||||
self._rlx_exitaction.triggered.connect(self.on_exit)
|
||||
|
||||
self._rlx_aboutaction = QAction("about")
|
||||
self._rlx_aboutaction.setStatusTip("Show about dialog")
|
||||
self._rlx_aboutaction.setEnabled(True)
|
||||
self._rlx_aboutaction.triggered.connect(self.on_about)
|
||||
|
||||
self._daq_connectaction = QAction(
|
||||
QIcon(":icons/connect.png"), "Connect DAQ", self
|
||||
)
|
||||
self._daq_connectaction.setStatusTip("Connect to daq device")
|
||||
# self._daq_connectaction.setShortcut(QKeySequence("Alt+d"))
|
||||
self._daq_connectaction.triggered.connect(self.connect_dac)
|
||||
|
||||
self._daq_disconnectaction = QAction(
|
||||
QIcon(":/icons/disconnect.png"), "Disconnect DAQ", self
|
||||
)
|
||||
self._daq_disconnectaction.setStatusTip("Disconnect the DAQ device")
|
||||
# self._daq_connectaction.setShortcut(QKeySequence("Alt+d"))
|
||||
self._daq_disconnectaction.triggered.connect(self.disconnect_dac)
|
||||
|
||||
self._daq_calibaction = QAction(
|
||||
QIcon(":/icons/calibration.png"), "Plot calibration", self
|
||||
)
|
||||
self._daq_calibaction.setStatusTip("Calibrate the attenuator device")
|
||||
# self._daq_calibaction.setShortcut(QKeySequence("Alt+d"))
|
||||
self._daq_calibaction.triggered.connect(self.calibration_plot.plot)
|
||||
self.create_menu()
|
||||
|
||||
def create_menu(self):
|
||||
menu = self.menuBar()
|
||||
if menu is not None:
|
||||
file_menu = menu.addMenu("&File")
|
||||
device_menu = menu.addMenu("&DAQ")
|
||||
help_menu = menu.addMenu("&Help")
|
||||
|
||||
if file_menu is not None:
|
||||
file_menu.addAction(self._rlx_exitaction)
|
||||
file_menu.addAction(self._rlx_aboutaction)
|
||||
|
||||
if device_menu is not None:
|
||||
device_menu.addAction(self._daq_connectaction)
|
||||
device_menu.addAction(self._daq_disconnectaction)
|
||||
device_menu.addSeparator()
|
||||
device_menu.addAction(self._daq_calibaction)
|
||||
|
||||
if help_menu is not None:
|
||||
help_menu.addSeparator()
|
||||
# help_menu.addAction(self._help_action)
|
||||
else:
|
||||
log.error("could not create file menu and device menu")
|
||||
self.on_exit()
|
||||
|
||||
self.setMenuBar(menu)
|
||||
|
||||
def create_toolbars(self):
|
||||
rlx_toolbar = QToolBar("Relacs")
|
||||
rlx_toolbar.addAction(self._rlx_exitaction)
|
||||
rlx_toolbar.setIconSize(QSize(24, 24))
|
||||
|
||||
self.addToolBar(Qt.ToolBarArea.TopToolBarArea, rlx_toolbar)
|
||||
daq_toolbar = QToolBar("DAQ")
|
||||
daq_toolbar.addAction(self._daq_connectaction)
|
||||
daq_toolbar.addAction(self._daq_disconnectaction)
|
||||
daq_toolbar.addAction(self._daq_calibaction)
|
||||
self.addToolBar(Qt.ToolBarArea.TopToolBarArea, daq_toolbar)
|
||||
|
||||
repro_toolbar = QToolBar("Repros")
|
||||
repro_names, file_names = self.repros.names_of_repros()
|
||||
for rep, fn in zip(repro_names, file_names):
|
||||
repro_action = QAction(rep, self)
|
||||
repro_action.setStatusTip(rep)
|
||||
repro_action.triggered.connect(
|
||||
lambda checked, n=rep, f=fn: self.run_repro(n, f)
|
||||
)
|
||||
repro_toolbar.addAction(repro_action)
|
||||
self.addToolBar(Qt.ToolBarArea.TopToolBarArea, repro_toolbar)
|
||||
|
||||
def create_buttons(self):
|
||||
self.daq_connect_button = QPushButton("Connect Daq")
|
||||
self.daq_connect_button.setCheckable(True)
|
||||
self.daq_connect_button.clicked.connect(self.connect_dac)
|
||||
|
||||
self.daq_disconnect_button = QPushButton("Disconnect Daq")
|
||||
self.daq_disconnect_button.setCheckable(True)
|
||||
self.daq_disconnect_button.clicked.connect(self.disconnect_dac)
|
||||
|
||||
self.plot_calibration_button = QPushButton("Plot Calibration")
|
||||
self.plot_calibration_button.setCheckable(True)
|
||||
self.plot_calibration_button.clicked.connect(self.calibration_plot.plot)
|
||||
|
||||
def connect_dac(self):
|
||||
devices = uldaq.get_daq_device_inventory(uldaq.InterfaceType.USB)
|
||||
try:
|
||||
self.daq_device = uldaq.DaqDevice(devices[0])
|
||||
log.debug(f"Found daq devices {len(devices)}, connecting to the first one")
|
||||
except IndexError:
|
||||
log.error("DAQ is not connected")
|
||||
log.error("Please connect a DAQ device to the system")
|
||||
|
||||
if hasattr(PyRelacs, "daq_device"):
|
||||
try:
|
||||
self.daq_device.connect()
|
||||
log.debug("Connected")
|
||||
except uldaq.ul_exception.ULException as e:
|
||||
log.error(f"Could not Connect to DAQ: {e}")
|
||||
self.daq_connect_button.setDisabled(True)
|
||||
else:
|
||||
log.debug("Already handeld the error")
|
||||
pass
|
||||
|
||||
def disconnect_dac(self):
|
||||
try:
|
||||
log.debug(f"{self.daq_device}")
|
||||
self.daq_device.disconnect()
|
||||
self.daq_device.release()
|
||||
log.debug(f"{self.daq_device}")
|
||||
self.daq_disconnect_button.setDisabled(True)
|
||||
self.daq_connect_button.setEnabled(True)
|
||||
except AttributeError:
|
||||
log.debug("DAQ was not connected")
|
||||
|
||||
def run_repro(self, n, fn):
|
||||
self.text.appendPlainText(f"started Repro {n}, {fn}")
|
||||
worker = Worker(self.repros.run_repro, self.nix_file, n, fn)
|
||||
worker.signals.result.connect(self.print_output)
|
||||
worker.signals.finished.connect(self.thread_complete)
|
||||
worker.signals.progress.connect(self.progress_fn)
|
||||
|
||||
self.threadpool.start(worker)
|
||||
|
||||
def add_to_textfield(self, s: str):
|
||||
self.text.appendPlainText(s)
|
||||
|
||||
def on_exit(self):
|
||||
log.info("exit button!")
|
||||
self.add_to_textfield("exiting")
|
||||
self.close()
|
||||
|
||||
def on_about(self, e):
|
||||
about = AboutDialog(self)
|
||||
about.show()
|
||||
|
||||
def print_output(self, s):
|
||||
log.info(s)
|
||||
self.add_to_textfield(s)
|
||||
|
||||
def thread_complete(self):
|
||||
log.info("Thread complete!")
|
||||
self.add_to_textfield("Thread complete!")
|
||||
|
||||
def progress_fn(self, n):
|
||||
print("%d%% done" % n)
|
||||
113
pyrelacs/ui/plots/calibration.py
Normal file
113
pyrelacs/ui/plots/calibration.py
Normal file
@@ -0,0 +1,113 @@
|
||||
from IPython import embed
|
||||
import pyqtgraph as pg
|
||||
import numpy as np
|
||||
from scipy.signal import welch, find_peaks
|
||||
from scipy.integrate import romb
|
||||
|
||||
|
||||
class CalibrationPlot:
|
||||
def __init__(self, figure: pg.GraphicsLayoutWidget, nix_file):
|
||||
self.figure = figure
|
||||
self.nix_file = nix_file
|
||||
|
||||
def plot(self):
|
||||
self.figure.setBackground("w")
|
||||
self.beat_plot = self.figure.addPlot(row=0, col=0)
|
||||
self.power_plot = self.figure.addPlot(row=1, col=0)
|
||||
self.beat_plot.addLegend()
|
||||
self.power_plot.addLegend()
|
||||
# self.power_plot.setLogMode(x=False, y=True)
|
||||
|
||||
block = self.nix_file.blocks[0]
|
||||
colors = ["red", "green", "blue", "black", "yellow"]
|
||||
for i, (stim, fish) in enumerate(
|
||||
zip(list(block.data_arrays)[::2], list(block.data_arrays)[1::2])
|
||||
):
|
||||
f_stim, stim_power = welch(
|
||||
stim[:],
|
||||
fs=40_000.0,
|
||||
window="flattop",
|
||||
nperseg=100_000,
|
||||
)
|
||||
stim_power = self.decibel(stim_power)
|
||||
stim_max_power_index = np.argmax(stim_power)
|
||||
freq_stim = f_stim[stim_max_power_index]
|
||||
|
||||
f_fish, fish_power = welch(
|
||||
fish[:],
|
||||
fs=40_000.0,
|
||||
window="flattop",
|
||||
nperseg=100_000,
|
||||
)
|
||||
fish_power = self.decibel(fish_power)
|
||||
fish_max_power_index = np.argmax(fish_power)
|
||||
freq_fish = f_fish[fish_max_power_index]
|
||||
|
||||
beat_frequency = np.abs(freq_fish - freq_stim)
|
||||
|
||||
beat = stim[:] + fish[:]
|
||||
beat_squared = beat**2
|
||||
|
||||
f, powerspec = welch(
|
||||
beat_squared,
|
||||
window="flattop",
|
||||
fs=40_000.0,
|
||||
nperseg=100_000,
|
||||
)
|
||||
powerspec = self.decibel(powerspec)
|
||||
|
||||
padding = 20
|
||||
integration_window = powerspec[
|
||||
(f > beat_frequency - padding) & (f < beat_frequency + padding)
|
||||
]
|
||||
|
||||
peaks = find_peaks(powerspec, prominence=40)[0]
|
||||
|
||||
pen = pg.mkPen(colors[i])
|
||||
|
||||
self.beat_plot.plot(
|
||||
np.arange(0, len(beat)) / 40_000.0,
|
||||
beat,
|
||||
pen=pen,
|
||||
name=stim.name,
|
||||
)
|
||||
self.power_plot.plot(f, powerspec, pen=pen, name=stim.name)
|
||||
self.power_plot.plot(f[peaks], powerspec[peaks], pen=None, symbol="x")
|
||||
|
||||
def decibel(self, power, ref_power=1.0, min_power=1e-20):
|
||||
"""Transform power to decibel relative to ref_power.
|
||||
|
||||
\\[ decibel = 10 \\cdot \\log_{10}(power/ref\\_power) \\]
|
||||
Power values smaller than `min_power` are set to `-np.inf`.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
power: float or array
|
||||
Power values, for example from a power spectrum or spectrogram.
|
||||
ref_power: float or None or 'peak'
|
||||
Reference power for computing decibel.
|
||||
If set to `None` or 'peak', the maximum power is used.
|
||||
min_power: float
|
||||
Power values smaller than `min_power` are set to `-np.inf`.
|
||||
|
||||
Returns
|
||||
-------
|
||||
decibel_psd: array
|
||||
Power values in decibel relative to `ref_power`.
|
||||
"""
|
||||
if np.isscalar(power):
|
||||
tmp_power = np.array([power])
|
||||
decibel_psd = np.array([power])
|
||||
else:
|
||||
tmp_power = power
|
||||
decibel_psd = power.copy()
|
||||
if ref_power is None or ref_power == "peak":
|
||||
ref_power = np.max(decibel_psd)
|
||||
decibel_psd[tmp_power <= min_power] = float("-inf")
|
||||
decibel_psd[tmp_power > min_power] = 10.0 * np.log10(
|
||||
decibel_psd[tmp_power > min_power] / ref_power
|
||||
)
|
||||
if np.isscalar(power):
|
||||
return decibel_psd[0]
|
||||
else:
|
||||
return decibel_psd
|
||||
0
pyrelacs/util/__init__.py
Normal file
0
pyrelacs/util/__init__.py
Normal file
75
pyrelacs/worker.py
Normal file
75
pyrelacs/worker.py
Normal file
@@ -0,0 +1,75 @@
|
||||
import sys
|
||||
import traceback
|
||||
|
||||
from PyQt6.QtCore import QRunnable, pyqtSlot, QObject, pyqtSignal
|
||||
|
||||
|
||||
class WorkerSignals(QObject):
|
||||
"""
|
||||
Defines the signals available from a running worker thread.
|
||||
|
||||
Supported signals are:
|
||||
|
||||
finished
|
||||
No data
|
||||
|
||||
error
|
||||
tuple (exctype, value, traceback.format_exc() )
|
||||
|
||||
result
|
||||
object data returned from processing, anything
|
||||
|
||||
progress
|
||||
int indicating % progress
|
||||
|
||||
"""
|
||||
|
||||
finished = pyqtSignal()
|
||||
error = pyqtSignal(tuple)
|
||||
result = pyqtSignal(object)
|
||||
progress = pyqtSignal(int)
|
||||
|
||||
|
||||
class Worker(QRunnable):
|
||||
"""
|
||||
Worker thread
|
||||
|
||||
Inherits from QRunnable to handler worker thread setup, signals and wrap-up.
|
||||
|
||||
:param callback: The function callback to run on this worker thread. Supplied args and
|
||||
kwargs will be passed through to the runner.
|
||||
:type callback: function
|
||||
:param args: Arguments to pass to the callback function
|
||||
:param kwargs: Keywords to pass to the callback function
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, fn, *args, **kwargs):
|
||||
super(Worker, self).__init__()
|
||||
|
||||
# Store constructor arguments (re-used for processing)
|
||||
self.fn = fn
|
||||
self.args = args
|
||||
self.kwargs = kwargs
|
||||
self.signals = WorkerSignals()
|
||||
|
||||
# Add the callback to our kwargs
|
||||
self.kwargs["progress_callback"] = self.signals.progress
|
||||
|
||||
@pyqtSlot()
|
||||
def run(self):
|
||||
"""
|
||||
Initialise the runner function with passed args, kwargs.
|
||||
"""
|
||||
|
||||
# Retrieve args/kwargs here; and fire processing using them
|
||||
try:
|
||||
result = self.fn(*self.args, **self.kwargs)
|
||||
except:
|
||||
traceback.print_exc()
|
||||
exctype, value = sys.exc_info()[:2]
|
||||
self.signals.error.emit((exctype, value, traceback.format_exc()))
|
||||
else:
|
||||
self.signals.result.emit(result) # Return the result of the processing
|
||||
finally:
|
||||
self.signals.finished.emit() # Done
|
||||
Reference in New Issue
Block a user