|
| 1 | +""" |
| 2 | +This task is a replica of max_staticTrainingChoiceWorld with the addition of optogenetic stimulation |
| 3 | +An `opto_stimulation` column is added to the trials_table, which is a boolean array of length NTRIALS_INIT |
| 4 | +The PROBABILITY_OPTO_STIMULATION parameter is used to determine the probability of optogenetic stimulation |
| 5 | +for each trial |
| 6 | +
|
| 7 | +Additionally the state machine is modified to add output TTLs for optogenetic stimulation |
| 8 | +""" |
| 9 | + |
| 10 | +import logging |
| 11 | +import random |
| 12 | +import sys |
| 13 | +from importlib.util import find_spec |
| 14 | +from pathlib import Path |
| 15 | +from typing import Literal |
| 16 | +import pandas as pd |
| 17 | + |
| 18 | +import numpy as np |
| 19 | +import yaml |
| 20 | +import time |
| 21 | + |
| 22 | +import iblrig |
| 23 | +from iblrig.base_choice_world import SOFTCODE |
| 24 | +from pybpodapi.protocol import StateMachine |
| 25 | +from iblrig_custom_tasks.max_staticTrainingChoiceWorld.task import Session as StaticTrainingChoiceSession |
| 26 | +from iblrig_custom_tasks.max_optoStaticTrainingChoiceWorld.PulsePal import PulsePalMixin, PulsePalStateMachine |
| 27 | + |
| 28 | +stim_location_history = [] |
| 29 | + |
| 30 | +log = logging.getLogger('iblrig.task') |
| 31 | + |
| 32 | +NTRIALS_INIT = 2000 |
| 33 | +SOFTCODE_FIRE_LED = max(SOFTCODE).value + 1 |
| 34 | +SOFTCODE_RAMP_DOWN_LED = max(SOFTCODE).value + 2 |
| 35 | +RAMP_SECONDS = .25 # time to ramp down the opto stim # TODO: make this a parameter |
| 36 | +LED_V_MAX = 5 # maximum voltage for LED control # TODO: make this a parameter |
| 37 | + |
| 38 | +# read defaults from task_parameters.yaml |
| 39 | +with open(Path(__file__).parent.joinpath('task_parameters.yaml')) as f: |
| 40 | + DEFAULTS = yaml.safe_load(f) |
| 41 | + |
| 42 | +class Session(StaticTrainingChoiceSession, PulsePalMixin): |
| 43 | + protocol_name = 'max_optoStaticTrainingChoiceWorld' |
| 44 | + extractor_tasks = ['PulsePalTrials'] |
| 45 | + |
| 46 | + def __init__( |
| 47 | + self, |
| 48 | + *args, |
| 49 | + probability_opto_stim: float = DEFAULTS['PROBABILITY_OPTO_STIM'], |
| 50 | + opto_ttl_states: list[str] = DEFAULTS['OPTO_TTL_STATES'], |
| 51 | + opto_stop_states: list[str] = DEFAULTS['OPTO_STOP_STATES'], |
| 52 | + max_laser_time: float = DEFAULTS['MAX_LASER_TIME'], |
| 53 | + estimated_led_power_mW: float = DEFAULTS['ESTIMATED_LED_POWER_MW'], |
| 54 | + **kwargs, |
| 55 | + ): |
| 56 | + super().__init__(*args, **kwargs) |
| 57 | + self.task_params['OPTO_TTL_STATES'] = opto_ttl_states |
| 58 | + self.task_params['OPTO_STOP_STATES'] = opto_stop_states |
| 59 | + self.task_params['PROBABILITY_OPTO_STIM'] = probability_opto_stim |
| 60 | + self.task_params['MAX_LASER_TIME'] = max_laser_time |
| 61 | + self.task_params['LED_POWER'] = estimated_led_power_mW |
| 62 | + # generates the opto stimulation for each trial |
| 63 | + opto = np.random.choice( |
| 64 | + [0, 1], |
| 65 | + p=[1 - probability_opto_stim, probability_opto_stim], |
| 66 | + size=NTRIALS_INIT, |
| 67 | + ).astype(bool) |
| 68 | + |
| 69 | + opto[0] = False |
| 70 | + self.trials_table['opto_stimulation'] = opto |
| 71 | + |
| 72 | + # get the calibration values for the LED |
| 73 | + # TODO: do a calibration curve instead |
| 74 | + dat = pd.read_csv(r'Y:/opto_fiber_calibration_values.csv') |
| 75 | + l_cannula = f'{kwargs["subject"]}L' #TODO: where is SUBJECT defined? |
| 76 | + r_cannula = f'{kwargs["subject"]}R' |
| 77 | + l_cable = 0 |
| 78 | + r_cable = 1 |
| 79 | + l_cal_power = dat[(dat['Cannula'] == l_cannula) & (dat['cable_ID'] == l_cable)].cable_power.values[0] |
| 80 | + r_cal_power = dat[(dat['Cannula'] == r_cannula) & (dat['cable_ID'] == r_cable)].cable_power.values[0] |
| 81 | + |
| 82 | + mean_cal_power = np.mean([l_cal_power, r_cal_power]) |
| 83 | + vmax = LED_V_MAX * self.task_params['LED_POWER'] / mean_cal_power |
| 84 | + log.warning(f'Using VMAX: {vmax}V for target LED power {self.task_params["LED_POWER"]}mW') |
| 85 | + self.task_params['VMAX_LED'] = vmax |
| 86 | + |
| 87 | + def _instantiate_state_machine(self, trial_number=None): |
| 88 | + """ |
| 89 | + We override this using the custom class PulsePalStateMachine that appends TTLs for optogenetic stimulation where needed |
| 90 | + :param trial_number: |
| 91 | + :return: |
| 92 | + """ |
| 93 | + # PWM1 is the LED OUTPUT for port interface board |
| 94 | + # Input is PortIn1 |
| 95 | + # TODO: enable input port? |
| 96 | + log.warning('Instantiating state machine') |
| 97 | + is_opto_stimulation = self.trials_table.at[trial_number, 'opto_stimulation'] |
| 98 | + if is_opto_stimulation: |
| 99 | + self.arm_opto_stim() |
| 100 | + self.arm_ttl_stim() |
| 101 | + return PulsePalStateMachine( |
| 102 | + self.bpod, |
| 103 | + trigger_type='soft', # software trigger |
| 104 | + is_opto_stimulation=is_opto_stimulation, |
| 105 | + states_opto_ttls=self.task_params['OPTO_TTL_STATES'], |
| 106 | + states_opto_stop=self.task_params['OPTO_STOP_STATES'], |
| 107 | + opto_t_max_seconds=self.task_params['MAX_LASER_TIME'], |
| 108 | + ) |
| 109 | + |
| 110 | + def arm_opto_stim(self): |
| 111 | + # define a contant offset voltage with a ramp down at the end to avoid rebound excitation |
| 112 | + log.warning('Arming opto stim') |
| 113 | + ramp = np.linspace(self.task_params['VMAX_LED'], 0, 1000) # SET POWER |
| 114 | + t = np.linspace(0, RAMP_SECONDS, 1000) |
| 115 | + v = np.concatenate((np.array([self.task_params['VMAX_LED']]), ramp)) # SET POWER |
| 116 | + t = np.concatenate((np.array([0]), t + self.task_params['MAX_LASER_TIME'])) |
| 117 | + |
| 118 | + self.pulsepal_connection.programOutputChannelParam('phase1Duration', 1, self.task_params['MAX_LASER_TIME']) |
| 119 | + self.pulsepal_connection.sendCustomPulseTrain(1, t, v) |
| 120 | + self.pulsepal_connection.programOutputChannelParam('customTrainID', 1, 1) |
| 121 | + |
| 122 | + def start_opto_stim(self): |
| 123 | + super().start_opto_stim() |
| 124 | + self.opto_start_time = time.time() |
| 125 | + |
| 126 | + @property |
| 127 | + def stim_length_seconds(self): |
| 128 | + return self.task_params['MAX_LASER_TIME'] |
| 129 | + |
| 130 | + def stop_opto_stim(self): |
| 131 | + if time.time() - self.opto_start_time >= self.task_params['MAX_LASER_TIME']: |
| 132 | + # the LED should have turned off by now, we don't need to force the ramp down |
| 133 | + log.warning('Stopped opto stim - hit opto timeout') |
| 134 | + return |
| 135 | + |
| 136 | + # we will modify this function to ramp down the opto stim rather than abruptly stopping it |
| 137 | + # send instructions to set the TTL back to 0 |
| 138 | + self.pulsepal_connection.programOutputChannelParam('phase1Duration', 2, self.task_params['MAX_LASER_TIME']) |
| 139 | + self.pulsepal_connection.sendCustomPulseTrain(2, [0,], [0,]) |
| 140 | + self.pulsepal_connection.programOutputChannelParam('customTrainID', 2, 2) |
| 141 | + |
| 142 | + # send instructions to ramp the opto stim down to 0 |
| 143 | + v = np.linspace(self.task_params['VMAX_LED'], 0, 1000) |
| 144 | + t = np.linspace(0, RAMP_SECONDS, 1000) |
| 145 | + self.pulsepal_connection.programOutputChannelParam('phase1Duration', 1, self.task_params['MAX_LASER_TIME']) |
| 146 | + self.pulsepal_connection.sendCustomPulseTrain(1, t, v) |
| 147 | + self.pulsepal_connection.programOutputChannelParam('customTrainID', 1, 1) |
| 148 | + |
| 149 | + # trigger these instructions |
| 150 | + self.pulsepal_connection.triggerOutputChannels(1, 1, 0, 0) |
| 151 | + log.warning('Stopped opto stim - hit a stop opto state') |
| 152 | + |
| 153 | + def start_hardware(self): |
| 154 | + super().start_hardware() |
| 155 | + super().start_opto_hardware() |
| 156 | + |
| 157 | + |
| 158 | + @staticmethod |
| 159 | + def extra_parser(): |
| 160 | + """:return: argparse.parser()""" |
| 161 | + parser = super(Session, Session).extra_parser() |
| 162 | + parser.add_argument( |
| 163 | + '--probability_opto_stim', |
| 164 | + option_strings=['--probability_opto_stim'], |
| 165 | + dest='probability_opto_stim', |
| 166 | + default=DEFAULTS['PROBABILITY_OPTO_STIM'], |
| 167 | + type=float, |
| 168 | + help=f'probability of opto-genetic stimulation (default: {DEFAULTS["PROBABILITY_OPTO_STIM"]})', |
| 169 | + ) |
| 170 | + |
| 171 | + parser.add_argument( |
| 172 | + '--opto_ttl_states', |
| 173 | + option_strings=['--opto_ttl_states'], |
| 174 | + dest='opto_ttl_states', |
| 175 | + default=DEFAULTS['OPTO_TTL_STATES'], |
| 176 | + nargs='+', |
| 177 | + type=str, |
| 178 | + help='list of the state machine states where opto stim should be delivered', |
| 179 | + ) |
| 180 | + parser.add_argument( |
| 181 | + '--opto_stop_states', |
| 182 | + option_strings=['--opto_stop_states'], |
| 183 | + dest='opto_stop_states', |
| 184 | + default=DEFAULTS['OPTO_STOP_STATES'], |
| 185 | + nargs='+', |
| 186 | + type=str, |
| 187 | + help='list of the state machine states where opto stim should be stopped', |
| 188 | + ) |
| 189 | + parser.add_argument( |
| 190 | + '--max_laser_time', |
| 191 | + option_strings=['--max_laser_time'], |
| 192 | + dest='max_laser_time', |
| 193 | + default=DEFAULTS['MAX_LASER_TIME'], |
| 194 | + type=float, |
| 195 | + help='Maximum laser duration in seconds', |
| 196 | + ) |
| 197 | + parser.add_argument( |
| 198 | + '--estimated_led_power_mW', |
| 199 | + option_strings=['--estimated_led_power_mW'], |
| 200 | + dest='estimated_led_power_mW', |
| 201 | + default=DEFAULTS['ESTIMATED_LED_POWER_MW'], |
| 202 | + type=float, |
| 203 | + help='The estimated LED power in mW. Computed from a calibration curve' |
| 204 | + ) |
| 205 | + |
| 206 | + return parser |
| 207 | + |
| 208 | + |
| 209 | +if __name__ == '__main__': # pragma: no cover |
| 210 | + kwargs = iblrig.misc.get_task_arguments(parents=[Session.extra_parser()]) |
| 211 | + sess = Session(**kwargs) |
| 212 | + sess.run() |
0 commit comments