Пример #1
0
def get_contrastLR(session_path, save=False, data=False):
    """
    Get left and right contrasts from raw datafile
    **Optional:** save _ibl_trials.contrastLeft.npy and
        _ibl_trials.contrastRight.npy to alf folder.

    Uses signed_contrast to create left and right contrast vectors.

    :param session_path: absolute path of session folder
    :type session_path: str
    :param save: wether to save the corresponding alf file
                 to the alf folder, defaults to False
    :type save: bool, optional
    :return: numpy.ndarray
    :rtype: dtype('float64')
    """
    if not data:
        data = raw.load_data(session_path)
    contrastLeft = np.array([t['signed_contrast'] for t in data])
    contrastRight = contrastLeft.copy()
    contrastLeft[contrastLeft > 0] = np.nan
    contrastLeft = np.abs(contrastLeft)
    contrastRight[contrastRight < 0] = np.nan
    # save if needed
    check_alf_folder(session_path)
    if raw.save_bool(save, '_ibl_trials.contrastLeft.npy'):
        lpath = os.path.join(session_path, 'alf',
                             '_ibl_trials.contrastLeft.npy')
        np.save(lpath, contrastLeft)
    if raw.save_bool(save, '_ibl_trials.contrastRight.npy'):
        rpath = os.path.join(session_path, 'alf',
                             '_ibl_trials.contrastRight.npy')
        np.save(rpath, contrastRight)
    return (contrastLeft, contrastRight)
Пример #2
0
def get_wheel_data(session_path, save=False):
    """
    Get wheel data from raw files and converts positions into centimeters and
    timestamps into seconds.
    **Optional:** saves _ibl_wheel.times.npy and _ibl_wheel.position.npy

    Times:
    Gets Rotary Encoder timestamps (ms) for each position and converts to times.

    Uses time_converter to extract and convert timstamps (ms) to times (s).

    Positions:
    Positions are in (cm) of RE perimeter relative to 0. The 0 resets every trial.

    cmtick = radius (cm) * 2 * pi / n_ticks
    cmtick = 3.1 * 2 * np.pi / 1024

    :param session_path: absolute path of session folder
    :type session_path: str
    :param save: wether to save the corresponding alf file
                 to the alf folder, defaults to False
    :type save: bool, optional
    :return: Numpy structured array.
    :rtype: numpy.ndarray
    """
    df = raw.load_encoder_positions(session_path)
    names = df.columns.tolist()
    data = structarr(names, shape=(df.index.max() + 1, ))
    data['re_ts'] = df.re_ts.values
    data['re_pos'] = df.re_pos.values
    data['bns_ts'] = df.bns_ts.values
    # ticks to cm factor
    cmtick = 3.1 * 2 * np.pi / 1024
    # Convert position and timestamps to cm and seconds respectively
    data['re_ts'] = data['re_ts'] / 1000.
    data['re_pos'] = data['re_pos'] * cmtick
    # Find timestamps that are repeated
    rep_idx = np.where(np.diff(data['re_ts']) == 0)[0]
    # Change the value of the repeated position
    data['re_pos'][rep_idx] = (data['re_pos'][rep_idx] +
                               data['re_pos'][rep_idx + 1]) / 2
    # get the converter function to translate re_ts into behavior times
    convtime = time_converter_session(session_path, kind='re2b')
    data['re_ts'] = convtime(data['re_ts'])
    # Now remove the repeted times that are rep_idx + 1
    data = np.delete(data, rep_idx + 1)

    check_alf_folder(session_path)
    if raw.save_bool(save, '_ibl_wheel.timestamps.npy'):
        tpath = os.path.join(session_path, 'alf', '_ibl_wheel.timestamps.npy')
        np.save(tpath, data['re_ts'])
    if raw.save_bool(save, '_ibl_wheel.position.npy'):
        ppath = os.path.join(session_path, 'alf', '_ibl_wheel.position.npy')
        np.save(ppath, data['re_pos'])

    return data
Пример #3
0
def get_feedback_times(session_path, save=False, data=False, settings=False):
    """
    Get the times the water or error tone was delivered to the animal.
    **Optional:** saves _ibl_trials.feedback_times.npy

    Gets reward  and error state init times vectors,
    checks if theintersection of nans is empty, then
    merges the 2 vectors.

    :param session_path: Absolute path of session folder
    :type session_path: str
    :param save: wether to save the corresponding alf file
                 to the alf folder, defaults to False
    :param save: bool, optional
    :return: numpy.ndarray
    :rtype: dtype('float64')
    """
    if not data:
        data = raw.load_data(session_path)
    if not settings:
        settings = raw.load_settings(session_path)
    if settings is None or settings['IBLRIG_VERSION_TAG'] == '':
        settings = {'IBLRIG_VERSION_TAG': '100.0.0'}

    # Version check
    if version.ge(settings['IBLRIG_VERSION_TAG'], '5.0.0'):
        merge = get_feedback_times_ge5(session_path, data=data)
    else:
        merge = get_feedback_times_lt5(session_path, data=data)

    if raw.save_bool(save, '_ibl_trials.feedback_times.npy'):
        check_alf_folder(session_path)
        fpath = os.path.join(session_path, 'alf', '_ibl_trials.feedback_times.npy')
        np.save(fpath, merge)
    return np.array(merge)
Пример #4
0
def get_velocity(session_path, save=False, data_wheel=None):
    """
    Compute velocity from non-uniformly acquired positions and timestamps.
    **Optional:** save _ibl_trials.velocity.npy

    Uses signed_contrast to create left and right contrast vectors.

    :param session_path: absolute path of session folder
    :type session_path: str
    :param save: wether to save the corresponding alf file
                 to the alf folder, defaults to False
    :type save: bool, optional
    :return: numpy.ndarray
    :rtype: dtype('float64')
    """

    if not isinstance(data_wheel, np.ndarray):
        data_wheel = get_wheel_data(session_path, save=False)
    dp = np.diff(data_wheel['re_pos'])
    dt = np.diff(data_wheel['re_ts'])
    # Compute raw velocity
    vel = dp / dt
    # Compute velocity time scale
    td = data_wheel['re_ts'][:-1] + dt / 2

    # Get the true velocity function
    velocity = interpolate.interp1d(td, vel, fill_value="extrapolate")

    if raw.save_bool(save, '_ibl_wheel.velocity.npy'):
        check_alf_folder(session_path)
        fpath = os.path.join(session_path, 'alf', '_ibl_wheel.velocity.npy')
        np.save(fpath, velocity(data_wheel['re_ts']))

    return velocity(data_wheel['re_ts'])
Пример #5
0
def get_rewardVolume(session_path, save=False, data=False):
    """
    Load reward volume delivered for each trial.
    **Optional:** saves _ibl_trials.rewardVolume.npy

    Uses reward_current to accumulate the amount of

    :param session_path: Absolute path of session folder
    :type session_path: str
    :param save: wether to save the corresponding alf file
                 to the alf folder, defaults to False
    :param save: bool, optional
    :return: numpy.ndarray
    :rtype: dtype('int64')
    """
    if not data:
        data = raw.load_data(session_path)
    trial_volume = [
        x['reward_amount'] if x['trial_correct'] else 0 for x in data
    ]
    rewardVolume = np.array(trial_volume).astype(np.float64)
    assert len(rewardVolume) == len(data)
    if raw.save_bool(save, '_ibl_trials.rewardVolume.npy'):
        check_alf_folder(session_path)
        fpath = os.path.join(session_path, 'alf',
                             '_ibl_trials.rewardVolume.npy')
        np.save(fpath, rewardVolume)
    return rewardVolume
Пример #6
0
def get_velocity(session_path, save=False, data_wheel=None):
    """
    Compute velocity from non-uniformly acquired positions and timestamps.
    **Optional:** save _ibl_trials.velocity.npy

    Uses signed_contrast to create left and right contrast vectors.

    :param session_path: absolute path of session folder
    :type session_path: str
    :param save: wether to save the corresponding alf file
                 to the alf folder, defaults to False
    :type save: bool, optional
    :return: numpy.ndarray
    :rtype: dtype('float64')
    """
    if not isinstance(data_wheel, np.ndarray):
        data_wheel = get_wheel_data(session_path, save=False)
    if data_wheel is None:
        logger_.error('No wheel data for ' + str(session_path))
        return None

    velocity = wheel.velocity(data_wheel['re_ts'], data_wheel['re_pos'])

    if raw.save_bool(save, '_ibl_wheel.velocity.npy'):
        check_alf_folder(session_path)
        fpath = os.path.join(session_path, 'alf',
                             '_ibl_wheel.velocity.npy')
        np.save(fpath, velocity)

    return velocity
Пример #7
0
def get_intervals(session_path, save=False, data=False):
    """
    Trial start to trial end. Trial end includes 1 or 2 seconds of iti depending
    on if the trial was correct or not.
    TODO: Nick suggested the that the iti be removed from this. In this case the
    end of a trial would be the same as the response time.
    Also consider adding _ibl_trials.iti and _ibl_trials.deadTime
    **Optional:** saves _ibl_trials.intervals.npy

    Uses the corrected Trial start and Trial end timpestamp values form PyBpod.

    :param session_path: Absolute path of session folder
    :type session_path: str
    :param save: wether to save the corresponding alf file
                 to the alf folder, defaults to False
    :param save: bool, optional
    :return: 2D numpy.ndarray (col0 = start, col1 = end)
    :rtype: dtype('float64')
    """
    if not data:
        data = raw.load_data(session_path)
    starts = [t['behavior_data']['Trial start timestamp'] for t in data]
    ends = [t['behavior_data']['Trial end timestamp'] for t in data]
    intervals = np.array([starts, ends]).T
    if raw.save_bool(save, '_ibl_trials.intervals.npy'):
        check_alf_folder(session_path)
        fpath = os.path.join(session_path, 'alf', '_ibl_trials.intervals.npy')
        np.save(fpath, intervals)
    return intervals
Пример #8
0
def get_deadTime(session_path, save=False, data=False):
    """
    Get the time between state machine exit and restart of next trial.

    Uses the corrected Trial start and Trial end timpestamp values form PyBpod.

    :param session_path: Absolute path of session folder
    :type session_path: str
    :param save: wether to save the corresponding alf file
                 to the alf folder, defaults to False
    :param save: bool, optional
    :return: numpy.ndarray
    :rtype: dtype('float64')
    """
    if not data:
        data = raw.load_data(session_path)
    starts = [t['behavior_data']['Trial start timestamp'] for t in data]
    ends = [t['behavior_data']['Trial end timestamp'] for t in data]
    # trial_len = np.array(ends) - np.array(starts)
    deadTime = np.array(starts)[1:] - np.array(ends)[:-1]
    deadTime = np.append(np.array([0]), deadTime)
    if raw.save_bool(save, '_ibl_trials.deadTime.npy'):
        check_alf_folder(session_path)
        fpath = os.path.join(session_path, 'alf', '_ibl_trials.deadTime.npy')
        np.save(fpath, deadTime)
    return deadTime
Пример #9
0
def get_iti_duration(session_path, save=False, data=False):
    """
    Calculate duration of iti from state timestamps.
    **Optional:** saves _ibl_trials.iti_duration.npy

    Uses Trial end timestamp and get_response_times to calculate iti.

    :param session_path: Absolute path of session folder
    :type session_path: str
    :param save: wether to save the corresponding alf file
                 to the alf folder, defaults to False
    :param save: bool, optional
    :return: numpy.ndarray
    :rtype: dtype('float64')
    """
    if not data:
        data = raw.load_data(session_path)
    rt = get_response_times(session_path, save=False, data=False)
    ends = np.array([t['behavior_data']['Trial end timestamp'] for t in data])

    iti_dur = ends - rt
    if raw.save_bool(save, '_ibl_trials.itiDuration.npy'):
        check_alf_folder(session_path)
        fpath = os.path.join(session_path, 'alf',
                             '_ibl_trials.itiDuration.npy')
        np.save(fpath, iti_dur)
    return iti_dur
Пример #10
0
def get_stimOn_times(session_path, save=False, data=False, settings=False):
    """
    Find the time of the statemachine command to turn on hte stim
    (state stim_on start or rotary_encoder_event2)
    Find the next frame change from the photodiodeafter that TS.
    Screen is not displaying anything until then.
    (Frame changes are in BNC1High and BNC1Low)
    """
    if not data:
        data = raw.load_data(session_path)
    if not settings:
        settings = raw.load_settings(session_path)
    if settings is None or settings['IBLRIG_VERSION_TAG'] == '':
        settings = {'IBLRIG_VERSION_TAG': '100.0.0'}
    # Version check
    if version.ge(settings['IBLRIG_VERSION_TAG'], '5.0.0'):
        stimOn_times = get_stimOn_times_ge5(session_path, data=data)
    else:
        stimOn_times = get_stimOn_times_lt5(session_path, data=data)

    if raw.save_bool(save, '_ibl_trials.stimOn_times.npy'):
        check_alf_folder(session_path)
        fpath = os.path.join(session_path, 'alf',
                             '_ibl_trials.stimOn_times.npy')
        np.save(fpath, np.array(stimOn_times))

    return np.array(stimOn_times)
Пример #11
0
def get_intervals(session_path, save=False, data=False, settings=False):
    """
    Trial start to trial end. Trial end includes 1 or 2 seconds after feedback,
    (depending on the feedback) and 0.5 seconds of iti.
    **Optional:** saves _ibl_trials.intervals.npy

    Uses the corrected Trial start and Trial end timpestamp values form PyBpod.

    :param session_path: Absolute path of session folder
    :type session_path: str
    :param save: wether to save the corresponding alf file
                 to the alf folder, defaults to False
    :param save: bool, optional
    :return: 2D numpy.ndarray (col0 = start, col1 = end)
    :rtype: dtype('float64')
    """
    if not data:
        data = raw.load_data(session_path)
    if not settings:
        settings = raw.load_settings(session_path)
    if settings is None or settings['IBLRIG_VERSION_TAG'] == '':
        settings = {'IBLRIG_VERSION_TAG': '100.0.0'}

    starts = [t['behavior_data']['Trial start timestamp'] for t in data]
    ends = [t['behavior_data']['Trial end timestamp'] for t in data]
    intervals = np.array([starts, ends]).T
    if raw.save_bool(save, '_ibl_trials.intervals.npy'):
        check_alf_folder(session_path)
        fpath = os.path.join(session_path, 'alf', '_ibl_trials.intervals.npy')
        np.save(fpath, intervals)
    return intervals
Пример #12
0
def get_response_times(session_path, save=False, data=False):
    """
    Time (in absolute seconds from session start) when a response was recorded.
    **Optional:** saves _ibl_trials.response_times.npy

    Uses the timestamp of the end of the closed_loop state.

    :param session_path: Absolute path of session folder
    :type session_path: str
    :param save: wether to save the corresponding alf file
                 to the alf folder, defaults to False
    :param save: bool, optional
    :return: numpy.ndarray
    :rtype: dtype('float64')
    """
    if not data:
        data = raw.load_data(session_path)
    rt = np.array([
        tr['behavior_data']['States timestamps']['closed_loop'][0][1]
        for tr in data
    ])
    if raw.save_bool(save, '_ibl_trials.response_times.npy'):
        check_alf_folder(session_path)
        fpath = os.path.join(session_path, 'alf',
                             '_ibl_trials.response_times.npy')
        np.save(fpath, rt)
    return rt
Пример #13
0
def get_goCueOnset_times(session_path, save=False, data=False):
    """
    Get trigger times of goCue from state machine.

    Current software solution for triggering sounds uses PyBpod soft codes.
    Delays can be in the order of 10's of ms. This is the time when the command
    to play the sound was executed. To measure accurate time, either getting the
    sound onset from the future microphone OR the new xonar soundcard and
    setup developed by Sanworks guarantees a set latency (in testing).

    :param session_path: Absolute path of session folder
    :type session_path: str
    :param save: wether to save the corresponding alf file
                 to the alf folder, defaults to False
    :param save: bool, optional
    :return: numpy.ndarray
    :rtype: dtype('float64')
    """
    if not data:
        data = raw.load_data(session_path)
    goCue = np.array([
        tr['behavior_data']['States timestamps']['closed_loop'][0][0]
        for tr in data
    ])
    if raw.save_bool(save, '_ibl_trials.goCue_times.npy'):
        check_alf_folder(session_path)
        fpath = Path(session_path).joinpath('alf',
                                            '_ibl_trials.goCue_times.npy')
        np.save(fpath, goCue)
    return goCue
Пример #14
0
def get_choice(session_path, save=False, data=False):
    """
    Get the subject's choice in every trial.
    **Optional:** saves _ibl_trials.choice.npy to alf folder.

    Uses signed_contrast and trial_correct.
    -1 is a CCW turn (towards the left)
    +1 is a CW turn (towards the right)
    0 is a no_go trial
    If a trial is correct the choice of the animal was the inverse of the sign
    of the contrast.

    >>> choice[t] = -np.sign(signed_contrast[t]) if trial_correct[t]

    :param session_path: absolute path of session folder
    :type session_path: str
    :param save: wether to save the corresponding alf file
                 to the alf folder, defaults to False
    :type save: bool, optional
    :return: numpy.ndarray
    :rtype: dtype('int64')
    """
    if not data:
        data = raw.load_data(session_path)
    sitm_side = np.array([np.sign(t['signed_contrast']) for t in data])
    trial_correct = np.array([t['trial_correct'] for t in data])
    choice = sitm_side.copy()
    choice[trial_correct] = -choice[trial_correct]
    choice = choice.astype(int)
    if raw.save_bool(save, '_ibl_trials.choice.npy'):
        check_alf_folder(session_path)
        fpath = os.path.join(session_path, 'alf', '_ibl_trials.choice.npy')
        np.save(fpath, choice)
    return choice
Пример #15
0
def get_probabilityLeft(session_path, save=False, data=False, settings=False):
    if not data:
        data = raw.load_data(session_path)
    if not settings:
        settings = raw.load_settings(session_path)
    if settings is None:
        settings = {"IBLRIG_VERSION_TAG": "100.0.0"}
    elif settings["IBLRIG_VERSION_TAG"] == "":
        settings.update({"IBLRIG_VERSION_TAG": "100.0.0"})
    num = settings.get("PRELOADED_SESSION_NUM", None)
    if num is None:
        num = settings.get("PREGENERATED_SESSION_NUM", None)
    if num is None:
        fn = settings.get('SESSION_LOADED_FILE_PATH', None)
        fn = PureWindowsPath(fn).name
        num = ''.join([d for d in fn if d.isdigit()])
        if num == '':
            raise ValueError("Can't extract left probability behaviour.")
    # Load the pregenerated file
    sessions_folder = Path(raw.__file__).parent.joinpath(
        'extractors', 'ephys_sessions')
    fname = f"session_{num}_ephys_pcqs.npy"
    pcqsp = np.load(sessions_folder.joinpath(fname))
    pLeft = pcqsp[:, 4]
    pLeft = pLeft[:len(data)]

    if raw.save_bool(save, "_ibl_trials.probabilityLeft.npy"):
        lpath = Path(session_path).joinpath("alf",
                                            "_ibl_trials.probabilityLeft.npy")
        np.save(lpath, pLeft)
    return pLeft
Пример #16
0
def get_goCueOnset_times(session_path, save=False, data=False, settings=False):
    """
    Get trigger times of goCue from state machine.

    Current software solution for triggering sounds uses PyBpod soft codes.
    Delays can be in the order of 10's of ms. This is the time when the command
    to play the sound was executed. To measure accurate time, either getting the
    sound onset from the future microphone OR the new xonar soundcard and
    setup developed by Sanworks guarantees a set latency (in testing).

    :param session_path: Absolute path of session folder
    :type session_path: str
    :param save: bool, optional
    :return: numpy.ndarray
    :rtype: dtype('float64')
    """
    if not data:
        data = raw.load_data(session_path)
    if not settings:
        settings = raw.load_settings(session_path)
    if settings is None or settings['IBLRIG_VERSION_TAG'] == '':
        settings = {'IBLRIG_VERSION_TAG': '100.0.0'}

    go_cue_times = np.zeros([
        len(data),
    ])
    for ind, tr in enumerate(data):
        if get_port_events(tr, 'BNC2'):
            bnchigh = tr['behavior_data']['Events timestamps'].get(
                'BNC2High', None)
            if bnchigh:
                go_cue_times[ind] = bnchigh[0]
                continue
            bnclow = tr['behavior_data']['Events timestamps'].get(
                'BNC2Low', None)
            if bnclow:
                go_cue_times[ind] = bnclow[0] - 0.1
                continue
            go_cue_times[ind] = np.nan
        else:
            go_cue_times[ind] = np.nan

    nmissing = np.sum(np.isnan(go_cue_times))
    # Check if all stim_syncs have failed to be detected
    if np.all(np.isnan(go_cue_times)):
        logger_.error(
            f'{session_path}: Missing ALL BNC2 stimulus ({nmissing} trials')

    # Check if any stim_sync has failed be detected for every trial
    if np.any(np.isnan(go_cue_times)):
        logger_.warning(
            f'{session_path}: Missing BNC2 stimulus on {nmissing} trials')

    if raw.save_bool(save, '_ibl_trials.goCue_times.npy'):
        check_alf_folder(session_path)
        fpath = Path(session_path).joinpath('alf',
                                            '_ibl_trials.goCue_times.npy')
        np.save(fpath, go_cue_times)
    return go_cue_times
Пример #17
0
def get_laser(session_path, save=False, data=False):
    if not data:
        data = raw.load_data(session_path)
    laser_on = np.array([t['laser_on'] for t in data])
    if raw.save_bool(save, '_ibl_trials.laseron.npy'):
        lpath = Path(session_path).joinpath('alf', '_ibl_trials.laseron.npy')
        np.save(lpath, laser_on)
    return laser_on
Пример #18
0
def get_stimOn_times(session_path, save=False, data=False):
    """
    Find the time of the statemachine command to turn on hte stim
    (state stim_on start or rotary_encoder_event2)
    Find the next frame change from the photodiodeafter that TS.
    Screen is not displaying anything until then.
    (Frame changes are in BNC1High and BNC1Low)
    """
    if not data:
        data = raw.load_data(session_path)
    stim_on = []
    bnc_h = []
    bnc_l = []
    for tr in data:
        stim_on.append(
            tr['behavior_data']['States timestamps']['stim_on'][0][0])
        if 'BNC1High' in tr['behavior_data']['Events timestamps'].keys():
            bnc_h.append(
                np.array(tr['behavior_data']['Events timestamps']['BNC1High']))
        else:
            bnc_h.append(np.array([np.NINF]))
        if 'BNC1Low' in tr['behavior_data']['Events timestamps'].keys():
            bnc_l.append(
                np.array(tr['behavior_data']['Events timestamps']['BNC1Low']))
        else:
            bnc_l.append(np.array([np.NINF]))

    stim_on = np.array(stim_on)
    bnc_h = np.array(bnc_h)
    bnc_l = np.array(bnc_l)

    count_missing = 0
    stimOn_times = np.zeros_like(stim_on)
    for i in range(len(stim_on)):
        hl = np.sort(np.concatenate([bnc_h[i], bnc_l[i]]))
        stot = hl[hl > stim_on[i]]
        if np.size(stot) == 0:
            stot = np.array([np.nan])
            count_missing += 1
        stimOn_times[i] = stot[0]

    if np.all(np.isnan(stimOn_times)):
        logger_.error(
            f'{session_path}: Missing ALL BNC1 stimulus ({count_missing}: trials'
        )
        return None

    if count_missing > 0:
        logger_.warning(
            f'{session_path}: Missing BNC1 stimulus on {count_missing} trials')

    if raw.save_bool(save, '_ibl_trials.stimOn_times.npy'):
        check_alf_folder(session_path)
        fpath = os.path.join(session_path, 'alf',
                             '_ibl_trials.stimOn_times.npy')
        np.save(fpath, np.array(stimOn_times))

    return np.array(stimOn_times)
Пример #19
0
def get_included_trials(session_path, save=False, data=False):
    if not data:
        data = raw.load_data(session_path)
    trials_included = np.array(
        [t['contrast']['type'] != "RepeatContrast" for t in data])
    if raw.save_bool(save, '_ibl_trials.included'):
        fpath = Path(session_path).joinpath('alf', '_ibl_trials.included.npy')
        np.save(fpath, trials_included)
    return trials_included
Пример #20
0
def get_feedbackType(session_path, save=False, data=False):
    """
    Get the feedback that was delivered to subject.
    **Optional:** saves _ibl_trials.feedbackType.npy

    Checks in raw datafile for error and reward state.
    Will raise an error if more than one of the mutually exclusive states have
    been triggered.

    Sets feedbackType to -1 if error state was trigered
    Sets feedbackType to -2 if correct_unreward state was triggered
    Sets feedbackType to +1 if correct_reward state was triggered
    Sets feedbackType to 0 if no_go state was triggered

    :param session_path: absolute path of session folder
    :type session_path: str
    :param save: wether to save the corresponding alf file
                 to the alf folder, defaults to False
    :type save: bool, optional
    :return: numpy.ndarray
    :rtype: dtype('int64')
    """
    if not data:
        data = raw.load_data(session_path)
    feedbackType = np.empty(len(data))
    feedbackType.fill(np.nan)
    correct_rewarded = []
    correct_unrewarded = []
    error = []
    no_go = []
    for t in data:
        correct_rewarded.append(~np.isnan(
            t['behavior_data']['States timestamps']['correct_rewarded'][0][0]))
        correct_unrewarded.append(
            ~np.isnan(t['behavior_data']['States timestamps']
                      ['correct_unrewarded'][0][0]))
        error.append(
            ~np.isnan(t['behavior_data']['States timestamps']['error'][0][0]))
        no_go.append(
            ~np.isnan(t['behavior_data']['States timestamps']['no_go'][0][0]))

    if not all(
            np.sum([correct_rewarded, correct_unrewarded, error, no_go],
                   axis=0) == np.ones(len(data))):
        raise ValueError

    feedbackType[correct_rewarded] = 1
    feedbackType[correct_unrewarded] = -2
    feedbackType[error] = -1
    feedbackType[no_go] = 0
    feedbackType = feedbackType.astype('int64')
    if raw.save_bool(save, '_ibl_trials.feedbackType.npy'):
        check_alf_folder(session_path)
        fpath = os.path.join(session_path, 'alf',
                             '_ibl_trials.feedbackType.npy')
        np.save(fpath, feedbackType)
    return feedbackType
Пример #21
0
def get_rew_probaLR(session_path, save=False, data=False):
    if not data:
        data = raw.load_data(session_path)
    p_rew_Left = np.array([t['rew_probability_left'] for t in data])
    p_rew_Right = np.array( [1 if x == 0.7 else 0.5 if x==0.5 else 0.7 for x in p_rew_Left])
    if raw.save_bool(save, '_ibl_trials.rewprobabilityLeft.npy'):
        lpath = Path(session_path).joinpath('alf', '_ibl_trials.rewprobabilityLeft.npy')
        np.save(lpath, p_rew_Left)
    return p_rew_Left, p_rew_Right
Пример #22
0
def get_contrastLR(session_path, save=False, data=False, settings=False):
    """
    Get left and right contrasts from raw datafile. Optionally, saves
    _ibl_trials.contrastLeft.npy and _ibl_trials.contrastRight.npy to alf folder.

    Uses signed_contrast to create left and right contrast vectors.

    :param session_path: absolute path of session folder
    :type session_path: str
    :param save: wether to save the corresponding alf file
                 to the alf folder, defaults to False
    :type save: bool, optional
    :return: numpy.ndarray
    :rtype: dtype('float64')
    """
    if not data:
        data = raw.load_data(session_path)
    if not settings:
        settings = raw.load_settings(session_path)
    if settings is None or settings['IBLRIG_VERSION_TAG'] == '':
        settings = {'IBLRIG_VERSION_TAG': '100.0.0'}

    contrastLeft = np.array([
        t['contrast']['value'] if np.sign(t['position']) < 0 else np.nan
        for t in data
    ])
    contrastRight = np.array([
        t['contrast']['value'] if np.sign(t['position']) > 0 else np.nan
        for t in data
    ])
    # save if needed
    check_alf_folder(session_path)
    if raw.save_bool(save, '_ibl_trials.contrastLeft.npy'):
        lpath = os.path.join(session_path, 'alf',
                             '_ibl_trials.contrastLeft.npy')
        np.save(lpath, contrastLeft)

    if raw.save_bool(save, '_ibl_trials.contrastRight.npy'):
        rpath = os.path.join(session_path, 'alf',
                             '_ibl_trials.contrastRight.npy')
        np.save(rpath, contrastRight)

    return (contrastLeft, contrastRight)
Пример #23
0
def get_probaLR(session_path, save=False, data=False):
    if not data:
        data = raw.load_data(session_path)
    pLeft = np.array([t['stim_probability_left'] for t in data])
    pRight = 1 - pLeft
    if raw.save_bool(save, '_ibl_trials.probabilityLeft.npy'):
        lpath = Path(session_path).joinpath('alf',
                                            '_ibl_trials.probabilityLeft.npy')
        np.save(lpath, pLeft)
    return pLeft, pRight
Пример #24
0
def get_probabilityLeft(session_path, save=False, data=False, settings=False):
    if not data:
        data = raw.load_data(session_path)
    if not settings:
        settings = raw.load_settings(session_path)
    if settings is None or settings['IBLRIG_VERSION_TAG'] == '':
        settings = {'IBLRIG_VERSION_TAG': '100.0.0'}

    pLeft = np.array([t['stim_probability_left'] for t in data])
    if raw.save_bool(save, '_ibl_trials.probabilityLeft.npy'):
        lpath = Path(session_path).joinpath('alf', '_ibl_trials.probabilityLeft.npy')
        np.save(lpath, pLeft)
    return pLeft
Пример #25
0
def get_opto(session_path, save=False, data=False, settings=False):
    if not data:
        data = raw.load_data(session_path)
    if not settings:
        settings = raw.load_settings(session_path)
    if settings is None or settings['IBLRIG_VERSION_TAG'] == '':
        settings = {'IBLRIG_VERSION_TAG': '100.0.0'}
    
    opto_probability_left =  np.array([t['opto_probability_left'] for t in data])
    if raw.save_bool(save, '_ibl_trials.opto_probability_left.npy'):
        lpath = Path(session_path).joinpath('alf', '_ibl_trials.opto_probability_left.npy')
        np.save(lpath, opto_probability_left)
    
    opto = fix_opto(Path(session_path).joinpath('alf'))
        # opto = np.array([t['opto'] for t in data]) - old before stable opto protocol
    if raw.save_bool(save, '_ibl_trials.opto.npy'):
        lpath = Path(session_path).joinpath('alf', '_ibl_trials.opto.npy')
        np.save(lpath, opto)     
    
    dummy_opto  = np.array([t['opto'] for t in data]) #Same as opto but not buffer saved
    if raw.save_bool(save, '_ibl_trials.dummy_opto.npy'):
        lpath = Path(session_path).joinpath('alf', '_ibl_trials.opto_dummy.npy')
        np.save(lpath, dummy_opto)
    return opto,opto_probability_left, dummy_opto
Пример #26
0
def get_feedback_times(session_path, save=False, data=False):
    """
    Get the times the water or error tone was delivered to the animal.
    **Optional:** saves _ibl_trials.feedback_times.npy

    Gets reward  and error state init times vectors,
    checks if theintersection of nans is empty, then
    merges the 2 vectors.

    :param session_path: Absolute path of session folder
    :type session_path: str
    :param save: wether to save the corresponding alf file
                 to the alf folder, defaults to False
    :param save: bool, optional
    :return: numpy.ndarray
    :rtype: dtype('float64')
    """
    if not data:
        data = raw.load_data(session_path)
    c_rw_times = [
        tr['behavior_data']['States timestamps']['correct_rewarded'][0][0]
        for tr in data
    ]
    c_urw_times = [
        tr['behavior_data']['States timestamps']['correct_unrewarded'][0][0]
        for tr in data
    ]
    err_times = [
        tr['behavior_data']['States timestamps']['error'][0][0] for tr in data
    ]
    nogo_times = [
        tr['behavior_data']['States timestamps']['no_go'][0][0] for tr in data
    ]
    assert sum(
        np.isnan(c_rw_times) & np.isnan(c_urw_times) & np.isnan(err_times)
        & np.isnan(nogo_times)) == 0
    merge = np.array([
        np.array(times)[~np.isnan(times)]
        for times in zip(c_rw_times, c_urw_times, err_times, nogo_times)
    ]).squeeze()
    if raw.save_bool(save, '_ibl_trials.feedback_times.npy'):
        check_alf_folder(session_path)
        fpath = os.path.join(session_path, 'alf',
                             '_ibl_trials.feedback_times.npy')
        np.save(fpath, merge)
    return np.array(merge)
Пример #27
0
def get_included_trials(session_path, save=False, data=False, settings=False):
    if not data:
        data = raw.load_data(session_path)
    if not settings:
        settings = raw.load_settings(session_path)
    if settings is None or settings['IBLRIG_VERSION_TAG'] == '':
        settings = {'IBLRIG_VERSION_TAG': '100.0.0'}

    if version.ge(settings['IBLRIG_VERSION_TAG'], '5.0.0'):
        trials_included = get_included_trials_ge5(session_path, data=data, settings=settings)
    else:
        trials_included = get_included_trials_lt5(session_path, data=data)

    if raw.save_bool(save, '_ibl_trials.included'):
        fpath = Path(session_path).joinpath('alf', '_ibl_trials.included.npy')
        np.save(fpath, trials_included)
    return trials_included
Пример #28
0
def get_goCueTrigger_times(session_path,
                           save=False,
                           data=False,
                           settings=False):
    """
    Get trigger times of goCue from state machine.

    Current software solution for triggering sounds uses PyBpod soft codes.
    Delays can be in the order of 10's of ms. This is the time when the command
    to play the sound was executed. To measure accurate time, either getting the
    sound onset from xonar soundcard sync pulse (latencies may vary).

    :param session_path: Absolute path of session folder
    :type session_path: str
    :param save: wether to save the corresponding alf file
                 to the alf folder, defaults to False
    :param save: bool, optional
    :return: numpy.ndarray
    :rtype: dtype('float64')
    """
    if not data:
        data = raw.load_data(session_path)
    if not settings:
        settings = raw.load_settings(session_path)
    if settings is None or settings['IBLRIG_VERSION_TAG'] == '':
        settings = {'IBLRIG_VERSION_TAG': '100.0.0'}

    # Version check
    if version.ge(settings['IBLRIG_VERSION_TAG'], '5.0.0'):
        goCue = np.array([
            tr['behavior_data']['States timestamps']['play_tone'][0][0]
            for tr in data
        ])
    else:
        goCue = np.array([
            tr['behavior_data']['States timestamps']['closed_loop'][0][0]
            for tr in data
        ])

    if raw.save_bool(save, '_ibl_trials.goCue_times.npy'):
        check_alf_folder(session_path)
        fpath = os.path.join(session_path, 'alf',
                             '_ibl_trials.goCueTrigger_times.npy')
        np.save(fpath, goCue)
    return goCue
Пример #29
0
def get_stimOnTrigger_times(session_path, save=False, data=False, settings=False):
    if not data:
        data = raw.load_data(session_path)
    if not settings:
        settings = raw.load_settings(session_path)
    if settings is None or settings['IBLRIG_VERSION_TAG'] == '':
        settings = {'IBLRIG_VERSION_TAG': '100.0.0'}
    # Get the stim_on_state that triggers the onset of the stim
    stim_on_state = np.array([tr['behavior_data']['States timestamps']
                             ['stim_on'][0] for tr in data])
    stimOnTrigger_times = stim_on_state[:, 0].T

    if raw.save_bool(save, '_ibl_trials.stimOnTrigger_times.npy'):
        check_alf_folder(session_path)
        fpath = os.path.join(session_path, 'alf', '_ibl_trials.stimOnTrigger_times.npy')
        np.save(fpath, np.array(stimOnTrigger_times))

    return stimOnTrigger_times
Пример #30
0
def get_choice(session_path, save=False, data=False, settings=False):
    """
    Get the subject's choice in every trial.
    **Optional:** saves _ibl_trials.choice.npy to alf folder.

    Uses signed_contrast and trial_correct.
    -1 is a CCW turn (towards the left)
    +1 is a CW turn (towards the right)
    0 is a no_go trial
    If a trial is correct the choice of the animal was the inverse of the sign
    of the position.

    >>> choice[t] = -np.sign(position[t]) if trial_correct[t]

    :param session_path: absolute path of session folder
    :type session_path: str
    :param save: wether to save the corresponding alf file
                 to the alf folder, defaults to False
    :type save: bool, optional
    :return: numpy.ndarray
    :rtype: dtype('int64')
    """
    if not data:
        data = raw.load_data(session_path)
    if not settings:
        settings = raw.load_settings(session_path)
    if settings is None or settings['IBLRIG_VERSION_TAG'] == '':
        settings = {'IBLRIG_VERSION_TAG': '100.0.0'}

    sitm_side = np.array([np.sign(t['position']) for t in data])
    trial_correct = np.array([t['trial_correct'] for t in data])
    trial_nogo = np.array([
        ~np.isnan(t['behavior_data']['States timestamps']['no_go'][0][0])
        for t in data
    ])
    choice = sitm_side.copy()
    choice[trial_correct] = -choice[trial_correct]
    choice[trial_nogo] = 0
    choice = choice.astype(int)
    if raw.save_bool(save, '_ibl_trials.choice.npy'):
        check_alf_folder(session_path)
        fpath = os.path.join(session_path, 'alf', '_ibl_trials.choice.npy')
        np.save(fpath, choice)
    return choice