Stimulation#

#!/usr/bin/python

"""
stimulate.py
-------------

This script can be used to run stimulation on a MaxTwo or
MaxOne system via the Python API. Several combinations of pulse
trains can be run and the script can be called from the command
line directly. 

Warning: No recordings are made in this example, but you can find
an example about how to record in another script, called `recordings.py`.
"""

import time

import maxlab as mx

from typing import List, Optional
from pathlib import Path

# fmt: off
electrodes = [4446,4447,4448,4665,4666,4667,4668,4669,4885,
              4886,4887,4888,4889,5105,5106,5107,5108,5109,
              5326,5327,5328,
              17095,17096,17097,17314,17315,17316,17317,17318,
              17533,17534,17535,17536,17537,17538,17539,17753,
              17754,17755,17756,17757,17758,17759,17973,17974,
              17975,17976,17977,17978,17979,18194,18195,18196,
              18197,18198,18415,18416,18417]

# fmt: on
event_counter = 1  # variable to keep track of the event_id. Useful to mark notable events or occurances when analyzing saved data.


def load_config(config_file: str) -> mx.Array:
    """Load a previously created configuration

    Load and configure an array from a previously generated
    configuration, either through the Python API or through
    the Scope GUI.

    Parameters
    ----------
    config_file : str
        Name of the previously generated config file.

    Returns
    -------
    mx.Array
        The configured array.

    Raises
    ------
    FileNotFoundError
        If the file cannot be found.
    Exception
        If the config_file cannot be loaded properly.

    """
    path = Path(config_file)
    if not path.is_file():
        raise FileNotFoundError(f"Config file '{config_file}' not found.")
    array = mx.Array("stimulation")
    try:
        array.load_config(config_file)
    except Exception as e:
        raise Exception(f"Error loading config file '{config_file}': {str(e)}")
    return array


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
    -----
    With this step, one needs to be careful, in rare cases it can happen
    that an electrode cannot be stimulated. For example, the electrode
    could not be routed (due to routing constraints), and the error message
    "No stimulation channel can connect to electrode: ..." will be printed.
    If this situation occurs, it is recommended to then select the electrode
    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 units indices corresponding to the connected
        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 create_stim_pulse(
    seq: mx.Sequence, amplitude: int, phase: int, dac: 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. "0" must be passed into the "dac" parameter of the function.

    Parameters
    ----------
    seq : mx.Sequence
        Sequence object holding a sequence of commands, as generated
        by `mx.Sequence()`.
    amplitude : int
        Amplitude of the pulse, with units [mV * 1 bit/2.9 mV], as explained above.
    phase : int
        How many samples should send between different sequence amplitude.
    dac: int
        The DAC through which signals are sent.

    Returns
    -------
    mx.Sequence
        Sequence object filled by the pulse.

    """
    global event_counter
    event_counter += 1
    seq.append(mx.Event(0, 1, event_counter, f"amplitude {amplitude} event_id {event_counter}"))
    seq.append(mx.DAC(dac, 512 - amplitude))
    seq.append(mx.DelaySamples(phase))
    seq.append(mx.DAC(dac, 512 + amplitude))
    seq.append(mx.DelaySamples(phase))
    seq.append(mx.DAC(dac, 512))
    return seq


def prepare_stim_sequence(
    number_pulses_per_train: int,
    inter_pulse_interval: int,
    phase: int,
    amplitude: int,
    changing_amplitude: Optional[bool] = False,
    max_amplitude: Optional[int] = None,
    amplitude_interval: Optional[int] = None,
) -> mx.Sequence:
    """Prepare a stimulation sequence.

    This is just and example and it only illustrates how sequences
    can be constructed.

    Parameters
    ----------
    number_pulses_per_train : int
        Number of repetitions of one pulse.
    inter_pulse_interval : int
        Number of samples to delay between two consecutive pulses.
    phase : int
        Number of samples before the switch from high-low (and vice versa)
        voltage when creating stimulation pulse.
    amplitude : int
        Amplitude of the pulse (minimal if changing_amplitude is True).
        Unit is millivolt.
    changing_amplitude : Optional[bool]
        Whether the pulse amplitude changes, by default False.
    max_amplitude : Optional[int]
        Maximal amplitude of the pulse if changing_amplitude is True.
        Unit is millivolt.
    amplitude_interval : Optional[int]
        Increment amplitude interval if changing_amplitude is True.
        Unit is millivolt.

    Returns
    -------
    mx.Sequence
        Sequence object filled with the stimulation sequence.

    """
    seq = mx.Sequence()
    dac_lsb_mV = float(mx.query_DAC_lsb_mV())
    if changing_amplitude:
        if max_amplitude is None or amplitude_interval is None:
            raise ValueError(
                "Both max_amplitude and amplitude_interval are required for changing_amplitude."
            )
        for cur_amplitude in range(amplitude, max_amplitude, amplitude_interval):
            for _ in range(number_pulses_per_train):
                seq = create_stim_pulse(seq, int(cur_amplitude/dac_lsb_mV), phase, 0)
                seq.append(mx.DelaySamples(inter_pulse_interval))
            seq.append(mx.DelaySamples(inter_pulse_interval))
    else:
        for _ in range(number_pulses_per_train):
            seq = create_stim_pulse(seq, int(amplitude/dac_lsb_mV), phase, 0)
            seq.append(mx.DelaySamples(inter_pulse_interval))
    return seq


if __name__ == "__main__":
    #Initialize the system
    mx.initialize()
    if mx.send(mx.Core().enable_stimulation_power(True)) != "Ok":
        raise RuntimeError("The system didn't initialize correctly.")\

    # We have selected some recording electrodes (see at the top,
    # directly after the imports) and here we write down some
    # stimulation electrodes.
    # Note that these choices follow certain rules, i.e.
    #   * You cannot choose more than 32 stimulation electrodes.
    #   * You cannot choose more than 1024 recording electrodes.
    #   * You cannot choose two stimulation electrodes that get connected
    # to the same stimulation unit.
    # The above selected recording electrodes are just an example and
    # should showcase how one can select specific electrodes on the array.
        
    stim_electrodes = [4887, 17756]
    array = mx.Array("stimulation")
    array.reset()
    array.clear_selected_electrodes()
    array.select_electrodes(electrodes)
    array.select_stimulation_electrodes(stim_electrodes)
    array.route()

    # If instead we use a pre-defined config, we can load it like this:
    # array = load_config("path/to/config/file.cfg")

    # Select the subset of wells we want to stimulate.
    wells = list(range(1))
    mx.activate(wells)
    stim_units = connect_stim_units_to_stim_electrodes(stim_electrodes, array)
    array.download(wells)
    # Wait a few seconds to make sure the configuration is downloaded
    time.sleep(mx.Timing.waitAfterDownload)
    mx.offset()
    # Wait a few more seconds to make sure the offset compensation is done
    time.sleep(15)

    mx.clear_events()  # Empty event-buffer before adding anything to it


    # RUN EXPERIMENT
    # Here we demonstrate the simultaneous stimulation of multiple electrodes, 
    # with the same amplitude used for multiple pulses. However, the variety
    # of stimulations possible is open-ended: the amplitude between pulses can 
    # be changed (see the parameters for `prepare_stim_sequence()`), stimulation
    # units can be powered on and off between pulses, and much more. See the 
    # advanced examples for more information.

    #Power up all stim units
    for stim_unit in stim_units:
        mx.send(mx.StimulationUnit(stim_unit)
                .power_up(True)
                .connect(True)
                .set_voltage_mode()
                .dac_source(0)
        )

    #Prepare stimulation sequences  
    seq = prepare_stim_sequence(
        number_pulses_per_train=10,
        inter_pulse_interval=2000,  # samples
        phase=4,  # 4 samples = 200us (4*50us)
        amplitude=200,  # mV
    )

    # Note that since the loop to send the pulse trains is done in python,
    # the timing between the pulse trains won't be particularly precise.
    # Instead consider createing one large sequence (although there are
    # some limitations here as well; please see the documentation).
    number_pulse_trains = 5
    for _ in range(number_pulse_trains):
        print("Send pulse")
        seq.send()

        # Sending multiple sequences to the system in succession places them in a queue to be executed.
        # A long "sleep" command is sent to allow the previous commands to finish and to create a small 
        # break in time prior to sending pulses to the next stim unit.
        time.sleep(5)



    # If one wishes to send 2 sequences (pulse trains) with variable times in between the two, run for example:
    #
    # seq_1 = prepare_stim_sequence(number_pulses_per_train, inter_pulse_interval, phase, amplitude=200)
    # seq_2 = prepare_stim_sequence(number_pulses_per_train, inter_pulse_interval, phase, amplitude=150)

    # The pulse trains can be delivered whenever seems reasonable, or following
    # a specific stimulation schedudle, such as:

    # time.sleep(1)
    # send_stim_pulses_all_units(number_pulse_trains, seq_1)
    # time.sleep(5)
    # send_stim_pulses_all_units(number_pulse_trains, seq_2)