"""
seq_stim.py
-------------
This script demonstrates the delivery of four independent
stimulation pulses to four different electrodes, all through a
single DAC.
By connecting and disconnecting different stimulation units
(connected to different electrodes) to the DAC within a single
Sequence, many different stimulation sites can be accessed in
rapid succession. Once stimulation units have been connected to
specific electrodes and the configuration downloaded, the
stimulation units connected/disconnected to DACs with little latency.
The best method to selectively stimulate various stimulation units
is to connect stimulation units to an unused DAC when not being
stimulated.
If all DACs are in use, a stimulation unit can also be disabled by
disconnecting the output of the unit with `StimulationUnit.connect(False)`.
However, this methods can produce small electrical artifacts upon connecting
or disconnecting the stimulation unit.
"""
import maxlab as mx
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from time import sleep
from typing import List
from h5py import File
from pathlib import Path
import os
# Recordings will be saved in the current working directory
dir_name = os.getcwd()
# File name of the recording
file_name = "sequential_stimulation"
full_file_name = f"{dir_name}/{file_name}.raw.h5"
# fmt: off
electrodes = [
# Circle 1
7106,7107,7108,7325,7326,7327,7328,7329,7545,7546,7547,
7548,7549,7765,7766,7767,7768,7769,7986,7987,7988,
# Circle 2
10426,10427,10428,10645,10646,10647,10648,10649,10865,10866,10867,
10868,10869,11085,11086,11087,11088,11089,11306,11307,11308,
# Circle 3
13746,13747,13748,13965,13966,13967,13968,13969,14185,14186,14187,
14188,14189,14405,14406,14407,14408,14409,14626,14627,14628,
# Circle 4
17066,17067,17068,17285,17286,17287,17288,17289,17505,17506,17507,
17508,17509,17725,17726,17727,17728,17729,17946,17947,17948
]
# fmt: on
stimulation_electrodes = [7547, 10867, 14187, 17507]
amplitude = 40 # in mV
# Width of one stimulation phase, in 50us samples
phase = 4 # 4 * 50us = 200us
frames_between_pulses = 100 # 100 * 50 us = 5 ms
# This number can be obtained by calling `mx.query_DAC_lsb_mV()`.
dac_lsb_mV = 2.981901
def connect_stim_units_to_stim_electrodes(
stim_electrodes: List[int], array: mx.Array
) -> List[int]:
"""Connect the stimulation units to the stimulation electrodes
Once an array configuration has been obtained, either through routing
or through loading a previous configuration, the stimulation units
can be connected to the desired electrodes.
Notes
-----
In rare cases it can happen that an electrode cannot be stimulated,
for example due to routing constraints. In such situations an error
message "No stimulation channel can connect to electrode: ..." will
be printed. If this happens, it is recommended to select another
electrode, for example the one next to it.
Parameters
----------
stim_electrodes : List[int]
List of the index of the stimulation electrodes
array : mx.Array
The configured array
Returns
-------
List[str]
List of stimulation unit indices which were connected to
stimulation electrodes
Raises
------
RuntimeError
If an electrode cannot be connected to a stimulation unit.
If two electrodes are connected to the same stimulation unit.
"""
stim_units: List[int] = []
for stim_el in stim_electrodes:
array.connect_electrode_to_stimulation(stim_el)
stim = array.query_stimulation_at_electrode(stim_el)
if len(stim) == 0:
raise RuntimeError(
f"No stimulation channel can connect to electrode: {str(stim_el)}"
)
stim_unit_int = int(stim)
if stim_unit_int in stim_units:
raise RuntimeError(
f"Two electrodes connected to the same stim unit.\
This is not allowed. Please Select a neighboring electrode of {stim_el}!"
)
else:
stim_units.append(stim_unit_int)
return stim_units
def append_stimulation_pulse(
seq: mx.Sequence, amplitude: int, phase: int
) -> mx.Sequence:
"""Create stimulation pulse
The stimulation units can be controlled through three independent
sources, what we call DAC channels (for digital analog converter).
By programming a DAC channel with digital values, we can control
the output the stimulation units. DAC inputs are in the range between
0 to 1023 bits, whereas 512 corresponds to zero volt and one bit
corresponds to 2.9 mV. When the stimulation units are set to voltage
mode, they act like an inverting amplifier, hence 512 + a number of bits
corresponds to a negative voltage, or 512 - a number of bits corresponds
to a positive voltage. Thus, to give a pulse of 100mV, the DAC channel
temporarily would need to be set to 512 - 34 (100mV/2.9) and back again
to 512.
Notes
-----
In this example, all 32 units are controlled through the same DAC
channel ( dac_source(0) ), thus by programming a biphasic pulse
on DAC channel 0, all the stimulation units exhibit the biphasic
pulse.
Parameters
----------
seq : mx.Sequence
Sequence object holding a sequence of commands, as generated
by `mx.Sequence()`.
amplitude : int
Amplitude of the pulse, with units [100mV/2.9], as explained above.
phase : int
How many samples should sand between different sequence amplitude.
Returns
-------
mx.Sequence
Sequence object filled by the pulse.
"""
seq.append(mx.DAC(0, 512 - amplitude))
seq.append(mx.DelaySamples(phase))
seq.append(mx.DAC(0, 512 + amplitude))
seq.append(mx.DelaySamples(phase))
seq.append(mx.DAC(0, 512))
return seq
def run_experiment():
if os.path.isfile(full_file_name):
print(f"File {full_file_name} already exists. Please delete or rename the file")
exit()
# Initialize system and enable stimulation
mx.initialize()
if mx.send(mx.Core().enable_stimulation_power(True)) != "Ok":
raise RuntimeError("The system didn't initialize correctly.")
sleep(mx.Timing.waitInit)
# The next step is to select two stimulation electrodes.
# They must be contained in the `electrodes` list.
# The following steps then configure the array, i.e.
# - connect recording electrodes
# - connect stimulation electrodes
# - `Route` the configuration.
array = mx.Array("stimulation")
array.reset()
array.clear_selected_electrodes()
array.select_electrodes(electrodes)
array.select_stimulation_electrodes(stimulation_electrodes)
array.route()
# Select for which wells the above will apply.
# If you have an MX1, the well needs to be [0].
wells = [0]
mx.activate(wells)
stim_units = connect_stim_units_to_stim_electrodes(stimulation_electrodes, array)
# Connect all stimulation units to an inactive DAC channel
for stim in stim_units:
mx.send(
mx.chip.StimulationUnit(stim)
.power_up(True)
.connect(True)
.set_voltage_mode()
.dac_source(1)
)
# All previous settings of the array were not yet applied to the
# actual hardware. So far, they are just stored in memory.
# Next step is to download the configuration to the hardware.
array.download(wells)
# Wait a few seconds to make sure the configuration is downloaded
sleep(mx.Timing.waitAfterDownload)
# Perform offset compensation
mx.offset()
sleep(mx.Timing.waitInMX1Offset)
# Clear out any previously stored `mx.Events` events in the `mxwserver`
mx.clear_events()
# Prepare the stimulation sequence
sequence = mx.Sequence()
for i, unit in enumerate(stim_units):
# Sequentially connect stimulation units one by one, deliver a pulse,
# then disconnect from the active DAC
sequence.append(
mx.StimulationUnit(unit)
.power_up(True)
.connect(True)
.set_voltage_mode()
.dac_source(0)
)
sequence.append(mx.Event(0, 1, i + 1, f"stim_unit {unit}"))
sequence = append_stimulation_pulse(
sequence, int(amplitude / dac_lsb_mV), phase
)
sequence.append(
mx.StimulationUnit(unit)
.power_up(True)
.connect(True)
.set_voltage_mode()
.dac_source(1)
)
# Delay between the pulses on the different electrodes
sequence.append(mx.DelaySamples(frames_between_pulses))
# START EXPERIMENT
# Create a file to save the recording data
s = mx.Saving()
# Set the recording directory
s.open_directory(dir_name)
# Start a recording file
s.start_file(file_name)
# Each recording file needs to have at least one group defined. The
# third parameter lists the channels which should be contained in the
# group. Here, data from all channels are saved, even those that have
# been routed to specific electrodes. See "recordings.py" for an example
# on how to save data only from routed channels.
s.group_define(wells, "all_channels", list(range(1024)))
# Start the actual recording
s.start_recording(wells)
print("Start recording")
# Wait a few seconds before starting the stimulation
sleep(2)
# Deliver the stimulation sequence
sequence.send()
# Wait a few seconds after the stimulation
sleep(10)
print("Stop recording")
# Stop the recording and the file
s.stop_recording()
s.stop_file() # Stop file
s.group_delete_all() # Clear groups for next recording
# Wait few seconds for the file to be closed
sleep(mx.Timing.waitAfterRecording)
del sequence # Remove the sequence from the `mxwserver` and python
def visualize_data():
# Extract the recorded data from the file
file = File(full_file_name)
traces = file["wells/well000/rec0000/groups/all_channels/raw"]
sampling_rate = file["wells/well000/rec0000/settings/sampling"][
0
] # frames per second
# Get the stimulation channels associated with the stimulation
# electrodes using the saved mapping
mapping_df = pd.DataFrame(np.array(file["wells/well000/rec0000/settings/mapping"]))
stimulation_channels = mapping_df.loc[
mapping_df["electrode"].isin(stimulation_electrodes), "channel"
].values
raw_traces = traces[stimulation_channels, :]
events = file["wells/well000/rec0000/events"]
# Plot the stimulation pulses
fig, axs = plt.subplots(
len(stimulation_electrodes),
1,
figsize=(14, 8),
dpi=100,
sharex=True,
facecolor="w",
edgecolor="k",
)
first_event = events[0][0]
last_event = events[-1][0]
first_fno = file["/wells/well000/rec0000/groups/all_channels/frame_nos"][0]
for i, trace in enumerate(raw_traces):
axs[i].set_title(f"Stimulation electrode {stimulation_electrodes[i]}")
# Compute frame number of first event
first_event_time = first_event - first_fno
last_event_time = last_event - first_fno
# Plot the raw traces
axs[i].plot(
np.linspace(0, len(trace) / (sampling_rate / 1000), len(trace)), trace
)
# Add axis labels
axs[i].set_ylabel("bits")
# Adjust the x-axis limits
axs[i].set_xlim(
(
first_event_time / (sampling_rate / 1000) - 2,
last_event_time / (sampling_rate / 1000) + 6,
)
)
axs[i].set_xlabel("ms")
plt.tight_layout()
plt.show()
if __name__ == "__main__":
run_experiment()
visualize_data()