Exemple #1
0
def run_trials(p, args):
    # Model
    m = p['model']

    # Number of trials
    try:
        ntrials = int(args[0])
    except:
        ntrials = 100
    ntrials *= m.nconditions

    # RNN
    rng = np.random.RandomState(p['seed'])
    rnn = RNN(p['savefile'], {'dt': p['dt']}, verbose=False)

    w = len(str(ntrials))
    trials = []
    backspaces = 0
    try:
        for i in xrange(ntrials):
            # Condition
            k = tasktools.unravel_index(
                i % m.nconditions, (len(m.cohs), len(m.left_rights), len(
                    m.cohs), len(m.left_rights), len(m.contexts)))
            coh_m = m.cohs[k[0]]
            left_right_m = m.left_rights[k[1]]
            coh_c = m.cohs[k[2]]
            left_right_c = m.left_rights[k[3]]
            context = m.contexts[k[4]]

            # Trial
            trial_func = m.generate_trial
            trial_args = {
                'name': 'test',
                'catch': False,
                'coh_m': coh_m,
                'left_right_m': left_right_m,
                'coh_c': coh_c,
                'left_right_c': left_right_c,
                'context': context
            }
            info = rnn.run(inputs=(trial_func, trial_args), rng=rng)

            # Display trial type
            s = ("Trial {:>{}}/{}: ({}) m{:>+3}, c{:>+3}".format(
                i + 1, w, ntrials, info['context'],
                info['left_right_m'] * info['coh_m'],
                info['left_right_c'] * info['coh_c']))
            sys.stdout.write(backspaces * '\b' + s)
            sys.stdout.flush()
            backspaces = len(s)

            # Save
            dt = rnn.t[1] - rnn.t[0]
            step = int(p['dt_save'] / dt)
            trial = {
                't': rnn.t[::step],
                'u': rnn.u[:, ::step],
                'r': rnn.r[:, ::step],
                'z': rnn.z[:, ::step],
                'info': info,
            }
            trials.append(trial)
    except KeyboardInterrupt:
        pass
    print("")

    # Save all
    filename = get_trialsfile(p)
    with open(filename, 'wb') as f:
        pickle.dump(trials, f, pickle.HIGHEST_PROTOCOL)
    size = os.path.getsize(filename) * 1e-9
    print("[ {}.run_trials ] Trials saved to {} ({:.1f} GB)".format(
        THIS, filename, size))

    # Compute the psychometric function
    psychometric_function(filename)
def run_trials(p, args):
    """
    Run trials.

    """
    # Model
    m = p['model']

    # Number of trials
    try:
        ntrials = int(args[0])
    except:
        ntrials = 100
    ntrials *= m.nconditions

    # RNN
    rng = np.random.RandomState(p['seed'])
    rnn = RNN(p['savefile'], {'dt': p['dt']}, verbose=False)

    # Trials
    w = len(str(ntrials))
    trials = []
    backspaces = 0
    try:
        for i in xrange(ntrials):
            b        = i % m.nconditions
            k1, k2   = tasktools.unravel_index(b, (len(m.modalities), len(m.freqs)))
            modality = m.modalities[k1]
            freq     = m.freqs[k2]

            # Trial
            trial_func = m.generate_trial
            trial_args = {
                'name':     'test',
                'catch':    False,
                'modality': modality,
                'freq':     freq
                }
            info = rnn.run(inputs=(trial_func, trial_args), rng=rng)

            # Display trial type
            if info['modality'] == 'v':
                s = "Trial {:>{}}/{}: v |{:>2}".format(i+1, w, ntrials, info['freq'])
            elif info['modality'] == 'a':
                s = "Trial {:>{}}/{}:  a|{:>2}".format(i+1, w, ntrials, info['freq'])
            else:
                s = "Trial {:>{}}/{}: va|{:>2}".format(i+1, w, ntrials, info['freq'])
            sys.stdout.write(backspaces*'\b' + s)
            sys.stdout.flush()
            backspaces = len(s)

            # Save
            dt    = rnn.t[1] - rnn.t[0]
            step  = int(p['dt_save']/dt)
            trial = {
                't':    rnn.t[::step],
                'u':    rnn.u[:,::step],
                'r':    rnn.r[:,::step],
                'z':    rnn.z[:,::step],
                'info': info
                }
            trials.append(trial)
    except KeyboardInterrupt:
        pass
    print("")

    # Save all
    filename = get_trialsfile(p)
    with open(filename, 'wb') as f:
        pickle.dump(trials, f, pickle.HIGHEST_PROTOCOL)
    size = os.path.getsize(filename)*1e-9
    print("[ {}.run_trials ] Trials saved to {} ({:.1f} GB)".format(THIS, filename, size))

    # Compute the psychometric function
    psychometric_function(filename)
Exemple #3
0
def run_trials(p, args):
    """
    Run trials.

    """
    # Model
    m = p['model']

    # Number of trials
    try:
        ntrials = int(args[0])
    except:
        ntrials = 100
    ntrials *= m.nconditions

    # RNN
    rng = np.random.RandomState(p['seed'])
    rnn = RNN(p['savefile'], {'dt': p['dt']}, verbose=False)

    # Trials
    w = len(str(ntrials))
    trials = []
    backspaces = 0
    try:
        for i in xrange(ntrials):
            # Condition
            b = i % m.nconditions
            k0, k1 = tasktools.unravel_index(b, (len(m.fpairs), len(m.gt_lts)))
            fpair = m.fpairs[k0]
            gt_lt = m.gt_lts[k1]

            # Trial
            trial_func = m.generate_trial
            trial_args = {
                'name': 'test',
                'catch': False,
                'fpair': fpair,
                'gt_lt': gt_lt
            }
            info = rnn.run(inputs=(trial_func, trial_args), rng=rng)

            # Display trial type
            if info['f1'] > info['f2']:
                gt_lt = '>'
            else:
                gt_lt = '<'
            s = ("Trial {:>{}}/{}: {:>2} {} {:>2}".format(
                i + 1, w, ntrials, info['f1'], gt_lt, info['f2']))
            sys.stdout.write(backspaces * '\b' + s)
            sys.stdout.flush()
            backspaces = len(s)

            # Save
            dt = rnn.t[1] - rnn.t[0]
            step = int(p['dt_save'] / dt)
            trial = {
                't': rnn.t[::step],
                'u': rnn.u[:, ::step],
                'r': rnn.r[:, ::step],
                'z': rnn.z[:, ::step],
                'info': info
            }
            trials.append(trial)
    except KeyboardInterrupt:
        pass
    print("")

    # Save all
    filename = get_trialsfile(p)
    with open(filename, 'wb') as f:
        pickle.dump(trials, f, pickle.HIGHEST_PROTOCOL)
    size = os.path.getsize(filename) * 1e-9
    print("[ {}.run_trials ] Trials saved to {} ({:.1f} GB)".format(
        THIS, filename, size))

    # Psychometric function
    psychometric_function(filename)
Exemple #4
0
def generate_trial(rng, dt, params):
    #-------------------------------------------------------------------------------------
    # Select task condition
    #-------------------------------------------------------------------------------------

    catch_trial = False
    if params['name'] in ['gradient', 'test']:
        if params.get('catch', rng.rand() < pcatch):
            catch_trial = True
        else:
            # Context
            context = params.get('context', rng.choice(contexts))

            # Coherences
            coh_m = params.get('coh_m', rng.choice(cohs))
            coh_c = params.get('coh_c', rng.choice(cohs))

            # Left/right
            left_right_m = params.get('left_right_m', rng.choice(left_rights))
            left_right_c = params.get('left_right_c', rng.choice(left_rights))
    elif params['name'] == 'validation':
        b = params['minibatch_index'] % (nconditions + 1)
        if b == 0:
            catch_trial = True
        else:
            k = tasktools.unravel_index(b - 1,
                                        (len(contexts), len(cohs), len(cohs),
                                         len(left_rights), len(left_rights)))
            context = contexts[k[0]]
            coh_m = cohs[k[1]]
            coh_c = cohs[k[2]]
            left_right_m = left_rights[k[3]]
            left_right_c = left_rights[k[4]]
    else:
        raise ValueError("Unknown trial type.")

    #-------------------------------------------------------------------------------------
    # Epochs
    #-------------------------------------------------------------------------------------

    if catch_trial:
        epochs = {'T': 2000}
    else:
        if params['name'] == 'test':
            fixation = 400
        else:
            fixation = 100
        stimulus = 800
        decision = 300
        T = fixation + stimulus + decision

        epochs = {
            'fixation': (0, fixation),
            'stimulus': (fixation, fixation + stimulus),
            'decision': (fixation + stimulus, T)
        }
        epochs['T'] = T

    #-------------------------------------------------------------------------------------
    # Trial info
    #-------------------------------------------------------------------------------------

    t, e = tasktools.get_epochs_idx(
        dt, epochs)  # Time, task epochs in discrete time
    trial = {'t': t, 'epochs': epochs}  # Trial

    if catch_trial:
        trial['info'] = {}
    else:
        if context == 'm':
            left_right = left_right_m
        else:
            left_right = left_right_c

        # Correct choice
        if left_right > 0:
            choice = 0
        else:
            choice = 1

        # Trial info
        trial['info'] = {
            'coh_m': coh_m,
            'left_right_m': left_right_m,
            'coh_c': coh_c,
            'left_right_c': left_right_c,
            'context': context,
            'choice': choice
        }

    #-------------------------------------------------------------------------------------
    # Inputs
    #-------------------------------------------------------------------------------------

    X = np.zeros((len(t), Nin))
    if not catch_trial:
        # Context
        if context == 'm':
            X[e['stimulus'], 0] = 1
        else:
            X[e['stimulus'], 1] = 1

        # Motion stimulus
        if left_right_m > 0:
            choice_m = 0
        else:
            choice_m = 1
        X[e['stimulus'], 2 + choice_m] = scale(+coh_m)
        X[e['stimulus'], 2 + (1 - choice_m)] = scale(-coh_m)

        # Colour stimulus
        if left_right_c > 0:
            choice_c = 0
        else:
            choice_c = 1
        X[e['stimulus'], 4 + choice_c] = scale(+coh_c)
        X[e['stimulus'], 4 + (1 - choice_c)] = scale(-coh_c)
    trial['inputs'] = X

    #-------------------------------------------------------------------------------------
    # Target output
    #-------------------------------------------------------------------------------------

    if params.get('target_output', False):
        Y = np.zeros((len(t), Nout))  # Output matrix
        M = np.zeros_like(Y)  # Mask matrix

        # Hold values
        hi = 1
        lo = 0.2

        if catch_trial:
            Y[:] = lo
            M[:] = 1
        else:
            # Fixation
            Y[e['fixation'], :] = lo

            # Decision
            Y[e['decision'], choice] = hi
            Y[e['decision'], 1 - choice] = lo

            # Only care about fixation and decision periods
            M[e['fixation'] + e['decision'], :] = 1

        # Outputs and mask
        trial['outputs'] = Y
        trial['mask'] = M

    #-------------------------------------------------------------------------------------

    return trial
Exemple #5
0
def generate_trial(rng, dt, params):
    #-------------------------------------------------------------------------------------
    # Select task condition
    #-------------------------------------------------------------------------------------

    catch_trial = False
    if params['name'] in ['gradient', 'test']:
        if params.get('catch', rng.rand() < pcatch):
            catch_trial = True
        else:
            modality = params.get('modality', rng.choice(modalities))
            freq = params.get('freq', rng.choice(freqs))
    elif params['name'] == 'validation':
        b = params['minibatch_index'] % (nconditions + 1)
        if b == 0:
            catch_trial = True
        else:
            k1, k2 = tasktools.unravel_index(b - 1,
                                             (len(modalities), len(freqs)))
            modality = modalities[k1]
            freq = freqs[k2]
    else:
        raise ValueError("Unknown trial type.")

    #-------------------------------------------------------------------------------------
    # Epochs
    #-------------------------------------------------------------------------------------

    if catch_trial:
        epochs = {'T': 2500}
    else:
        if params['name'] == 'test':
            fixation = 500
        else:
            fixation = 100
        stimulus = 1000
        decision = 300
        T = fixation + stimulus + decision

        epochs = {
            'fixation': (0, fixation),
            'stimulus': (fixation, fixation + stimulus),
            'decision': (fixation + stimulus, T)
        }
        epochs['T'] = T

    #-------------------------------------------------------------------------------------
    # Trial info
    #-------------------------------------------------------------------------------------

    t, e = tasktools.get_epochs_idx(
        dt, epochs)  # Time, task epochs in discrete time
    trial = {'t': t, 'epochs': epochs}  # Trial

    if catch_trial:
        trial['info'] = {}
    else:
        # Correct choice
        if freq > boundary:
            choice = 0
        else:
            choice = 1

        # Trial info
        trial['info'] = {'modality': modality, 'freq': freq, 'choice': choice}

    #-------------------------------------------------------------------------------------
    # Inputs
    #-------------------------------------------------------------------------------------

    X = np.zeros((len(t), Nin))
    if not catch_trial:
        if 'v' in modality:
            X[e['stimulus'], VISUAL_P] = scale_v_p(freq)
            X[e['stimulus'], VISUAL_N] = scale_v_n(freq)
        if 'a' in modality:
            X[e['stimulus'], AUDITORY_P] = scale_a_p(freq)
            X[e['stimulus'], AUDITORY_N] = scale_a_n(freq)
        X[e['stimulus'] + e['decision'], START] = 1
    trial['inputs'] = X

    #-------------------------------------------------------------------------------------
    # Target output
    #-------------------------------------------------------------------------------------

    if params.get('target_output', False):
        Y = np.zeros((len(t), Nout))  # Output matrix
        M = np.zeros_like(Y)  # Mask matrix

        # Hold values
        hi = 1
        lo = 0.2

        if catch_trial:
            Y[:] = lo
            M[:] = 1
        else:
            # Fixation
            Y[e['fixation'], :] = lo

            # Decision
            Y[e['decision'], choice] = hi
            Y[e['decision'], 1 - choice] = lo

            # Only care about fixation and decision periods
            M[e['fixation'] + e['decision'], :] = 1

        # Outputs and mask
        trial['outputs'] = Y
        trial['mask'] = M

    #-------------------------------------------------------------------------------------

    return trial
def generate_trial(rng, dt, params):
    #-------------------------------------------------------------------------------------
    # Select task condition
    #-------------------------------------------------------------------------------------

    catch_trial = False
    if params['name'] in ['gradient', 'test']:
        if params.get('catch',
                      rng.rand() < pcatch):  #pcatch chance of a catch trial
            catch_trial = True
        else:
            cond = params.get('conditions',
                              conditions[rng.choice(len(conditions))])
            #Revert back to cohs if this brings up an issue
            in_out = params.get('in_out', rng.choice(in_outs))
    elif params['name'] == 'validation':
        b = params['minibatch_index'] % (nconditions + 1)
        if b == 0:
            catch_trial = True
        else:
            k0, k1 = tasktools.unravel_index(b - 1,
                                             (len(conditions), len(in_outs)))
            cond = conditions[k0]
            in_out = in_outs[k1]
    else:
        raise ValueError("Unknown trial type.")

    #-------------------------------------------------------------------------------------
    # Epochs
    #-------------------------------------------------------------------------------------

    if catch_trial:
        epochs = {'T': 2500}
    else:
        if params['name'] == 'test':
            fixation = 300
        else:
            fixation = 100
        f1 = 100
        delay = 200
        f2 = 100
        decision = 200
        # else:
        #     if params['name'] == 'test':
        #         firstInterval = 300
        #     else:
        #         firstInterval = 100
        #     secondInterval = 200
        #     decision = 200
        T = fixation + f1 + delay + f2 + decision

        epochs = {
            'fixation': (0, fixation),
            'f1': (fixation, fixation + f1),
            'delay': (fixation + f1, fixation + f1 + delay),
            'f2': (fixation + f1 + delay, fixation + f1 + delay + f2),
            'decision': (fixation + f1 + delay + f2, T)
        }
        epochs['T'] = T

    #-------------------------------------------------------------------------------------
    # Trial info
    #-------------------------------------------------------------------------------------

    t, e = tasktools.get_epochs_idx(
        dt, epochs)  # Time, e is array of epochs w/ points
    trial = {'t': t, 'epochs': epochs}  # Trial

    if catch_trial:
        trial['info'] = {}
    else:
        # Correct choice

        if cond in [(yes, yes), (no, no)]:
            choice = 0
        else:
            choice = 1

        #if in_out == 'equal':
        #    choice = 0
        #else:
        #    choice = 1

        # Trial info
        trial['info'] = {'cond': cond, 'in_out': in_out, 'choice': choice}

    #-------------------------------------------------------------------------------------
    # Inputs
    #-------------------------------------------------------------------------------------

    X = np.zeros((len(t), Nin))
    if not catch_trial:
        # Stimulus 1
        X[e['f1'], POS] = cond[0]
        X[e['f1'],
          NEG] = yes + no - cond[0]  #flipped frequency 1->0.2, 0.2 -> 1

        # Stimulus 2
        X[e['f2'], POS] = cond[1]
        X[e['f2'],
          NEG] = yes + no - cond[1]  #flipped frequency 1->0.2, 0.2 -> 1
    trial['inputs'] = X

    #-------------------------------------------------------------------------------------
    # Target output
    #-------------------------------------------------------------------------------------

    if params.get('target_output', False):
        Y = np.zeros((len(t), Nout))  # Output
        M = np.zeros_like(Y)  # Mask

        # Hold values
        hi = 1
        lo = 0.2

        if catch_trial:
            Y[:] = lo
            M[:] = 1
        else:
            # Fixation
            Y[e['fixation'], :] = lo

            # Decision
            Y[e['decision'], choice] = hi  # One neuron spikes high
            Y[e['decision'], 1 - choice] = lo  # The other spikes low

            # Only care about fixation and decision periods
            M[e['fixation'] + e['decision'], :] = 1

        # Outputs and mask
        trial['outputs'] = Y
        trial['mask'] = M

    #-------------------------------------------------------------------------------------

    return trial
Exemple #7
0
def run_trials(p, args):
    """
    Run trials.

    """
    # Model
    m = p['model']

    # Number of trials
    try:
        ntrials = int(args[0])
    except:
        ntrials = 100
    ntrials *= m.nconditions + 1

    # RNN
    rng = np.random.RandomState(p['seed'])
    rnn = RNN(p['savefile'], {'dt': p['dt']}, verbose=False)
    if 'ant_level' in p:
        rnn.Wrec[np.where(rnn.Wrec<0)] *= (1 - p['ant_level'])

    # Trials
    w = len(str(ntrials))
    trials = []
    backspaces = 0
    try:
        for i in xrange(ntrials):
            b = i % (m.nconditions + 1)
            if b == 0:
                # Zero-coherence condition
                coh    = 0
                in_out = rng.choice(m.in_outs)
            else:
                # All other conditions
                k1, k2 = tasktools.unravel_index(b-1, (len(m.cohs), len(m.in_outs)))
                coh    = m.cohs[k1]
                in_out = m.in_outs[k2]

            # Trial
            trial_func = m.generate_trial
            trial_args = {
                'name':   'test',
                'catch':  False,
                'coh':    coh,
                'in_out': in_out
                }
            info = rnn.run(inputs=(trial_func, trial_args), rng=rng)

            # Display trial type
            #if coh == 0:
            #    s = "Trial {:>{}}/{}: {:>3}".format(i+1, w, ntrials, info['coh'])
            #else:
            #    s = ("Trial {:>{}}/{}: {:>+3}"
            #         .format(i+1, w, ntrials, info['in_out']*info['coh']))
            
            # Update the user with the current progress
            if (i/100) % 1 == 0:
                print("We are {:.2f}% complete".format(100*i/ntrials)) 
                sys.stdout.flush()

            # Save
            dt    = rnn.t[1] - rnn.t[0]
            step  = int(p['dt_save']/dt)
            trial = {
                't':    rnn.t[::step],
                'u':    rnn.u[:,::step],
                'r':    rnn.r[:,::step],
                'z':    rnn.z[:,::step],
                'info': info
                }
            trials.append(trial)
    except KeyboardInterrupt:
        pass
    print("")

    # Save all
    filename = get_trialsfile(p)
    dump(filename, trials)
    size = os.path.getsize(filename)*1e-9
    print("[ {}.run_trials ] Trials saved to {} ({:.1f} GB)".format(THIS, filename, size))

    # Compute the psychometric function
    psychometric_function(filename)
def run_trials(p, args):
    """
    Run trials.

    """
    # Model
    m = p['model']

    # Number of trials
    try:
        ntrials = int(args[0])
    except:
        ntrials = 100
    ntrials *= m.nconditions + 1

    # RNN
    rng = np.random.RandomState(p['seed'])
    rnn = RNN(p['savefile'], {'dt': p['dt']}, verbose=False)

    # Trials
    w = len(str(ntrials))
    trials = []
    backspaces = 0
    try:
        for i in xrange(ntrials):
            b = i % (m.nconditions + 1)
            if b == 0:
                # Zero-coherence condition
                coh    = 0
                in_out = rng.choice(m.in_outs)
            else:
                # All other conditions
                k1, k2 = tasktools.unravel_index(b-1, (len(m.cohs), len(m.in_outs)))
                coh    = m.cohs[k1]
                in_out = m.in_outs[k2]

            # Trial
            trial_func = m.generate_trial
            trial_args = {
                'name':   'test',
                'catch':  False,
                'coh':    coh,
                'in_out': in_out
                }
            info = rnn.run(inputs=(trial_func, trial_args), rng=rng)

            # Display trial type
            if coh == 0:
                s = "Trial {:>{}}/{}: {:>3}".format(i+1, w, ntrials, info['coh'])
            else:
                s = ("Trial {:>{}}/{}: {:>+3}"
                     .format(i+1, w, ntrials, info['in_out']*info['coh']))
            sys.stdout.write(backspaces*'\b' + s)
            sys.stdout.flush()
            backspaces = len(s)

            # Save
            dt    = rnn.t[1] - rnn.t[0]
            step  = int(p['dt_save']/dt)
            trial = {
                't':    rnn.t[::step],
                'u':    rnn.u[:,::step],
                'r':    rnn.r[:,::step],
                'z':    rnn.z[:,::step],
                'info': info
                }
            trials.append(trial)
    except KeyboardInterrupt:
        pass
    print("")

    # Save all
    filename = get_trialsfile(p)
    with open(filename, 'wb') as f:
        pickle.dump(trials, f, pickle.HIGHEST_PROTOCOL)
    size = os.path.getsize(filename)*1e-9
    print("[ {}.run_trials ] Trials saved to {} ({:.1f} GB)".format(THIS, filename, size))

    # Compute the psychometric function
    psychometric_function(filename)
Exemple #9
0
def generate_trial(rng, dt, params):
    #---------------------------------------------------------------------------------
    # Select task condition
    #---------------------------------------------------------------------------------

    catch_trial = False
    if params['name'] in ['gradient', 'test']:
        if params.get('catch', rng.rand() < pcatch):
            catch_trial = True
        else:
            fpair = params.get('fpair', fpairs[rng.choice(len(fpairs))])
            gt_lt = params.get('gt_lt', rng.choice(gt_lts))
    elif params['name'] == 'validation':
        b = params['minibatch_index'] % (nconditions + 1)
        if b == 0:
            catch_trial = True
        else:
            k0, k1 = tasktools.unravel_index(b-1, (len(fpairs), len(gt_lts)))
            fpair  = fpairs[k0]
            gt_lt  = gt_lts[k1]
    else:
        raise ValueError("Unknown trial type.")

    #---------------------------------------------------------------------------------
    # Epochs
    #---------------------------------------------------------------------------------

    if catch_trial:
        epochs = {'T': 2500}
    else:
        if params['name'] == 'test':
            fixation = 500
        else:
            fixation = 100
        f1 = 500
        if params['name'] == 'test':
            delay = 3000
        else:
            delay = tasktools.uniform(rng, dt, 2500, 3500)
        f2       = 500
        decision = 300
        T        = fixation + f1 + delay + f2 + decision

        epochs = {
            'fixation': (0, fixation),
            'f1':       (fixation, fixation + f1),
            'delay':    (fixation + f1, fixation + f1 + delay),
            'f2':       (fixation + f1 + delay, fixation + f1 + delay + f2),
            'decision': (fixation + f1 + delay + f2, T)
            }
        epochs['T'] = T

    #---------------------------------------------------------------------------------
    # Trial info
    #---------------------------------------------------------------------------------

    t, e  = tasktools.get_epochs_idx(dt, epochs) # Task epochs in discrete time
    trial = {'t': t, 'epochs': epochs}           # Trial

    if catch_trial:
        trial['info'] = {}
    else:
        # Correct choice
        if gt_lt == '>':
            f1, f2 = fpair
            choice = 0
        else:
            f2, f1 = fpair
            choice = 1

        # Info
        trial['info'] = {'f1': f1, 'f2': f2, 'choice': choice}

    #---------------------------------------------------------------------------------
    # Inputs
    #---------------------------------------------------------------------------------

    X = np.zeros((len(t), Nin))
    if not catch_trial:
        # Stimulus 1
        X[e['f1'],POS] = scale_p(f1)
        X[e['f1'],NEG] = scale_n(f1)

        # Stimulus 2
        X[e['f2'],POS] = scale_p(f2)
        X[e['f2'],NEG] = scale_n(f2)
    trial['inputs'] = X

    #---------------------------------------------------------------------------------
    # Target output
    #---------------------------------------------------------------------------------

    if params.get('target_output', False):
        Y = np.zeros((len(t), Nout)) # Output matrix
        M = np.zeros_like(Y)         # Mask matrix

        # Hold values
        hi = 1
        lo = 0.2

        if catch_trial:
            Y[:] = lo
            M[:] = 1
        else:
            # Fixation
            Y[e['fixation'],:] = lo

            # Decision
            Y[e['decision'],choice]   = hi
            Y[e['decision'],1-choice] = lo

            # Mask
            M[e['fixation']+e['decision'],:] = 1

        trial['outputs'] = Y
        trial['mask']    = M

    #---------------------------------------------------------------------------------

    return trial
def generate_trial(rng, dt, params):
    #-------------------------------------------------------------------------------------
    # Select task condition
    #-------------------------------------------------------------------------------------

    catch_trial = False
    if params['name'] in ['gradient', 'test']:
        if params.get('catch', rng.rand() < pcatch):
            catch_trial = True
        else:
            modality = params.get('modality', rng.choice(modalities))
            freq     = params.get('freq',     rng.choice(freqs))
    elif params['name'] == 'validation':
        b = params['minibatch_index'] % (nconditions + 1)
        if b == 0:
            catch_trial = True
        else:
            k1, k2   = tasktools.unravel_index(b-1,
                                               (len(modalities), len(freqs)))
            modality = modalities[k1]
            freq     = freqs[k2]
    else:
        raise ValueError("Unknown trial type.")

    #-------------------------------------------------------------------------------------
    # Epochs
    #-------------------------------------------------------------------------------------

    if catch_trial:
        epochs = {'T': 2500}
    else:
        if params['name'] == 'test':
            fixation = 500
        else:
            fixation = 100
        stimulus = 1000
        decision = 300
        T        = fixation + stimulus + decision

        epochs = {
            'fixation': (0, fixation),
            'stimulus': (fixation, fixation + stimulus),
            'decision': (fixation + stimulus, T)
            }
        epochs['T'] = T

    #-------------------------------------------------------------------------------------
    # Trial info
    #-------------------------------------------------------------------------------------

    t, e  = tasktools.get_epochs_idx(dt, epochs) # Time, task epochs in discrete time
    trial = {'t': t, 'epochs': epochs}           # Trial

    if catch_trial:
        trial['info'] = {}
    else:
        # Correct choice
        if freq > boundary:
            choice = 0
        else:
            choice = 1

        # Trial info
        trial['info'] = {'modality':  modality, 'freq': freq, 'choice': choice}

    #-------------------------------------------------------------------------------------
    # Inputs
    #-------------------------------------------------------------------------------------

    X = np.zeros((len(t), Nin))
    if not catch_trial:
        if 'v' in modality:
            X[e['stimulus'],VISUAL_P] = scale_v_p(freq)
            X[e['stimulus'],VISUAL_N] = scale_v_n(freq)
        if 'a' in modality:
            X[e['stimulus'],AUDITORY_P] = scale_a_p(freq)
            X[e['stimulus'],AUDITORY_N] = scale_a_n(freq)
        X[e['stimulus'] + e['decision'],START] = 1
    trial['inputs'] = X

    #-------------------------------------------------------------------------------------
    # Target output
    #-------------------------------------------------------------------------------------

    if params.get('target_output', False):
        Y = np.zeros((len(t), Nout)) # Output matrix
        M = np.zeros_like(Y)         # Mask matrix

        # Hold values
        hi = 1
        lo = 0.2

        if catch_trial:
            Y[:] = lo
            M[:] = 1
        else:
            # Fixation
            Y[e['fixation'],:] = lo

            # Decision
            Y[e['decision'],choice]   = hi
            Y[e['decision'],1-choice] = lo

            # Only care about fixation and decision periods
            M[e['fixation']+e['decision'],:] = 1

        # Outputs and mask
        trial['outputs'] = Y
        trial['mask']    = M

    #-------------------------------------------------------------------------------------

    return trial
Exemple #11
0
def generate_trial(rng, dt, params):
    # -------------------------------------------------------------------------------------
    # Select task condition
    # -------------------------------------------------------------------------------------

    catch_trial = False
    if params["name"] in ["gradient", "test"]:
        if params.get("catch", rng.rand() < pcatch):
            catch_trial = True
        else:
            coh = params.get("coh", rng.choice(cohs))
            in_out = params.get("in_out", rng.choice(in_outs))
    elif params["name"] == "validation":
        b = params["minibatch_index"] % (nconditions + 1)
        if b == 0:
            catch_trial = True
        else:
            k0, k1 = tasktools.unravel_index(b - 1, (len(cohs), len(in_outs)))
            coh = cohs[k0]
            in_out = in_outs[k1]
    else:
        raise ValueError("Unknown trial type.")

    # -------------------------------------------------------------------------------------
    # Epochs
    # -------------------------------------------------------------------------------------

    if catch_trial:
        epochs = {"T": 2000}
    else:
        if params["name"] == "test":
            fixation = 300
            stimulus = 1500
        else:
            fixation = 100
            stimulus = 800
        no_reward = 300
        T = fixation + stimulus

        epochs = {"fixation": (0, fixation), "stimulus": (fixation, T), "decision": (fixation + no_reward, T)}
        epochs["T"] = T

    # -------------------------------------------------------------------------------------
    # Trial info
    # -------------------------------------------------------------------------------------

    t, e = tasktools.get_epochs_idx(dt, epochs)  # Time, task epochs in discrete time
    trial = {"t": t, "epochs": epochs}  # Trial

    if catch_trial:
        trial["info"] = {}
    else:
        # Correct choice
        if in_out > 0:
            choice = 0
        else:
            choice = 1

        # Trial info
        trial["info"] = {"coh": coh, "in_out": in_out, "choice": choice}

    # -------------------------------------------------------------------------------------
    # Inputs
    # -------------------------------------------------------------------------------------

    X = np.zeros((len(t), Nin))
    if not catch_trial:
        # Stimulus
        X[e["stimulus"], choice] = scale(+coh)
        X[e["stimulus"], 1 - choice] = scale(-coh)

        # Start cue
        X[e["stimulus"], START] = 1
    trial["inputs"] = X

    # -------------------------------------------------------------------------------------
    # Target output
    # -------------------------------------------------------------------------------------

    if params.get("target_output", False):
        Y = np.zeros((len(t), Nout))  # Output matrix
        M = np.zeros_like(Y)  # Mask matrix

        # Hold values
        hi = 1.2
        lo = 0.2

        if catch_trial:
            Y[:] = lo
            M[:] = 1
        else:
            # Fixation
            Y[e["fixation"], :] = lo

            # Decision
            Y[e["decision"], choice] = hi
            Y[e["decision"], 1 - choice] = lo

            # Only care about fixation and decision periods
            M[e["fixation"] + e["decision"], :] = 1

        # Outputs and mask
        trial["outputs"] = Y
        trial["mask"] = M

    # -------------------------------------------------------------------------------------

    return trial
def run_trials(p, args):
    # Model
    m = p['model']

    # Number of trials
    try:
        ntrials = int(args[0])
    except:
        ntrials = 100
    ntrials *= m.nconditions

    # RNN
    rng = np.random.RandomState(p['seed'])
    rnn = RNN(p['savefile'], {'dt': p['dt']}, verbose=False)

    w = len(str(ntrials))
    trials = []
    backspaces = 0
    try:
        for i in xrange(ntrials):
            # Condition
            k = tasktools.unravel_index(i % m.nconditions,
                                        (len(m.cohs), len(m.left_rights),
                                         len(m.cohs), len(m.left_rights),
                                         len(m.contexts)))
            coh_m        = m.cohs[k[0]]
            left_right_m = m.left_rights[k[1]]
            coh_c        = m.cohs[k[2]]
            left_right_c = m.left_rights[k[3]]
            context      = m.contexts[k[4]]

            # Trial
            trial_func = m.generate_trial
            trial_args = {
                'name':         'test',
                'catch':        False,
                'coh_m':        coh_m,
                'left_right_m': left_right_m,
                'coh_c':        coh_c,
                'left_right_c': left_right_c,
                'context':      context
                }
            info = rnn.run(inputs=(trial_func, trial_args), rng=rng)

            # Display trial type
            s = ("Trial {:>{}}/{}: ({}) m{:>+3}, c{:>+3}"
                 .format(i+1, w, ntrials, info['context'],
                         info['left_right_m']*info['coh_m'],
                         info['left_right_c']*info['coh_c']))
            sys.stdout.write(backspaces*'\b' + s)
            sys.stdout.flush()
            backspaces = len(s)

            # Save
            dt    = rnn.t[1] - rnn.t[0]
            step  = int(p['dt_save']/dt)
            trial = {
                't':    rnn.t[::step],
                'u':    rnn.u[:,::step],
                'r':    rnn.r[:,::step],
                'z':    rnn.z[:,::step],
                'info': info,
                }
            trials.append(trial)
    except KeyboardInterrupt:
        pass
    print("")

    # Save all
    filename = get_trialsfile(p)
    with open(filename, 'wb') as f:
        pickle.dump(trials, f, pickle.HIGHEST_PROTOCOL)
    size = os.path.getsize(filename)*1e-9
    print("[ {}.run_trials ] Trials saved to {} ({:.1f} GB)".format(THIS, filename, size))

    # Compute the psychometric function
    psychometric_function(filename)
Exemple #13
0
def generate_trial(rng, dt, params):
    # -------------------------------------------------------------------------------------
    # Select task condition
    # -------------------------------------------------------------------------------------

    catch_trial = False
    if params["name"] in ["gradient", "test"]:
        if params.get("catch", rng.rand() < pcatch):
            catch_trial = True
        else:
            # Context
            context = params.get("context", rng.choice(contexts))

            # Coherences
            coh_m = params.get("coh_m", rng.choice(cohs))
            coh_c = params.get("coh_c", rng.choice(cohs))

            # Left/right
            left_right_m = params.get("left_right_m", rng.choice(left_rights))
            left_right_c = params.get("left_right_c", rng.choice(left_rights))
    elif params["name"] == "validation":
        b = params["minibatch_index"] % (nconditions + 1)
        if b == 0:
            catch_trial = True
        else:
            k = tasktools.unravel_index(
                b - 1, (len(contexts), len(cohs), len(cohs), len(left_rights), len(left_rights))
            )
            context = contexts[k[0]]
            coh_m = cohs[k[1]]
            coh_c = cohs[k[2]]
            left_right_m = left_rights[k[3]]
            left_right_c = left_rights[k[4]]
    else:
        raise ValueError("Unknown trial type.")

    # -------------------------------------------------------------------------------------
    # Epochs
    # -------------------------------------------------------------------------------------

    if catch_trial:
        epochs = {"T": 2000}
    else:
        if params["name"] == "test":
            fixation = 400
        else:
            fixation = 100
        stimulus = 800
        decision = 300
        T = fixation + stimulus + decision

        epochs = {
            "fixation": (0, fixation),
            "stimulus": (fixation, fixation + stimulus),
            "decision": (fixation + stimulus, T),
        }
        epochs["T"] = T

    # -------------------------------------------------------------------------------------
    # Trial info
    # -------------------------------------------------------------------------------------

    t, e = tasktools.get_epochs_idx(dt, epochs)  # Time, task epochs in discrete time
    trial = {"t": t, "epochs": epochs}  # Trial

    if catch_trial:
        trial["info"] = {}
    else:
        if context == "m":
            left_right = left_right_m
        else:
            left_right = left_right_c

        # Correct choice
        if left_right > 0:
            choice = 0
        else:
            choice = 1

        # Trial info
        trial["info"] = {
            "coh_m": coh_m,
            "left_right_m": left_right_m,
            "coh_c": coh_c,
            "left_right_c": left_right_c,
            "context": context,
            "choice": choice,
        }

    # -------------------------------------------------------------------------------------
    # Inputs
    # -------------------------------------------------------------------------------------

    X = np.zeros((len(t), Nin))
    if not catch_trial:
        # Context
        if context == "m":
            X[e["stimulus"], 0] = 1
        else:
            X[e["stimulus"], 1] = 1

        # Motion stimulus
        if left_right_m > 0:
            choice_m = 0
        else:
            choice_m = 1
        X[e["stimulus"], 2 + choice_m] = scale(+coh_m)
        X[e["stimulus"], 2 + (1 - choice_m)] = scale(-coh_m)

        # Colour stimulus
        if left_right_c > 0:
            choice_c = 0
        else:
            choice_c = 1
        X[e["stimulus"], 4 + choice_c] = scale(+coh_c)
        X[e["stimulus"], 4 + (1 - choice_c)] = scale(-coh_c)
    trial["inputs"] = X

    # -------------------------------------------------------------------------------------
    # Target output
    # -------------------------------------------------------------------------------------

    if params.get("target_output", False):
        Y = np.zeros((len(t), Nout))  # Output matrix
        M = np.zeros_like(Y)  # Mask matrix

        # Hold values
        hi = 1
        lo = 0.2

        if catch_trial:
            Y[:] = lo
            M[:] = 1
        else:
            # Fixation
            Y[e["fixation"], :] = lo

            # Decision
            Y[e["decision"], choice] = hi
            Y[e["decision"], 1 - choice] = lo

            # Only care about fixation and decision periods
            M[e["fixation"] + e["decision"], :] = 1

        # Outputs and mask
        trial["outputs"] = Y
        trial["mask"] = M

    # -------------------------------------------------------------------------------------

    return trial
def run_trials(p, args):        #args are the number of trials
    """
    Run trials.

    """
    # Model
    m = p['model']

    # Number of trials
    try:
        ntrials = int(args[0])
    except:
        ntrials = 100
    ntrials *= m.nconditions

    # RNN
    rng = np.random.RandomState(p['seed'])
    rnn = RNN(p['savefile'], {'dt': p['dt']}, verbose=False)

    # Trials
    w = len(str(ntrials))
    trials = []
    backspaces = 0
    try:
        for i in xrange(ntrials):
            # Condition
            b      = i % m.nconditions  #iterate through all conditions
            k0, k1 = tasktools.unravel_index(b, (len(m.pairs), 1))
            pair  = m.pairs[k0]

            # Trial
            trial_func = m.generate_trial
            trial_args = {
                'name':  'test',
                'catch': False,
                'pair': pair,
                }
            info = rnn.run(inputs=(trial_func, trial_args), rng=rng)

            # Display trial type
            s = ("Trial {:>{}}/{}: {:>2} {:>2}"
                 .format(i+1, w, ntrials, info['f1'], info['f2']))
            sys.stdout.write(backspaces*'\b' + s)
            sys.stdout.flush()
            backspaces = len(s)

            # Save
            dt    = rnn.t[1] - rnn.t[0]
            step  = int(p['dt_save']/dt)
            trial = {
                't':    rnn.t[::step],
                'u':    rnn.u[:,::step],
                'r':    rnn.r[:,::step],
                'z':    rnn.z[:,::step],
                'info': info
                }
            trials.append(trial)
    except KeyboardInterrupt:
        pass
    print("")

    # Save all
    filename = get_trialsfile(p)
    with open(filename, 'wb') as f:
        pickle.dump(trials, f, pickle.HIGHEST_PROTOCOL)
    size = os.path.getsize(filename)*1e-9
    print("[ {}.run_trials ] Trials saved to {} ({:.1f} GB)".format(THIS, filename, size))

    # Psychometric function
    psychometric_function(filename)
Exemple #15
0
def generate_trial(rng, dt, params):
    #-------------------------------------------------------------------------------------
    # Select task condition
    #-------------------------------------------------------------------------------------

    catch_trial = False
    if params['name'] in ['gradient', 'test']:
        if params.get('catch', rng.rand() < pcatch):
            catch_trial = True
        else:
            coh = params.get('coh', rng.choice(cohs))
            in_out = params.get('in_out', rng.choice(in_outs))
    elif params['name'] == 'validation':
        b = params['minibatch_index'] % (nconditions + 1)
        if b == 0:
            catch_trial = True
        else:
            k0, k1 = tasktools.unravel_index(b - 1, (len(cohs), len(in_outs)))
            coh = cohs[k0]
            in_out = in_outs[k1]
    else:
        raise ValueError("Unknown trial type.")

    #-------------------------------------------------------------------------------------
    # Epochs
    #-------------------------------------------------------------------------------------

    if catch_trial:
        epochs = {'T': 2000}
    else:
        if params['name'] == 'test':
            fixation = 300
        else:
            fixation = 100
        stimulus = 800
        decision = 300
        T = fixation + stimulus + decision

        epochs = {
            'fixation': (0, fixation),
            'stimulus': (fixation, fixation + stimulus),
            'decision': (fixation + stimulus, T)
        }
        epochs['T'] = T

    #-------------------------------------------------------------------------------------
    # Trial info
    #-------------------------------------------------------------------------------------

    t, e = tasktools.get_epochs_idx(
        dt, epochs)  # Time, task epochs in discrete time
    trial = {'t': t, 'epochs': epochs}  # Trial

    if catch_trial:
        trial['info'] = {}
    else:
        # Correct choice
        if in_out > 0:
            choice = 0
        else:
            choice = 1

        # Trial info
        trial['info'] = {'coh': coh, 'in_out': in_out, 'choice': choice}

    #-------------------------------------------------------------------------------------
    # Inputs
    #-------------------------------------------------------------------------------------

    X = np.zeros((len(t), Nin))
    if not catch_trial:
        X[e['stimulus'], choice] = scale(+coh)
        X[e['stimulus'], 1 - choice] = scale(-coh)
    trial['inputs'] = X

    #-------------------------------------------------------------------------------------
    # Target output
    #-------------------------------------------------------------------------------------

    if params.get('target_output', False):
        Y = np.zeros((len(t), Nout))  # Output
        M = np.zeros_like(Y)  # Mask

        # Hold values
        hi = 1
        lo = 0.2

        if catch_trial:
            Y[:] = lo
            M[:] = 1
        else:
            # Fixation
            Y[e['fixation'], :] = lo

            # Decision
            Y[e['decision'], choice] = hi
            Y[e['decision'], 1 - choice] = lo

            # Only care about fixation and decision periods
            M[e['fixation'] + e['decision'], :] = 1

        # Outputs and mask
        trial['outputs'] = Y
        trial['mask'] = M

    #-------------------------------------------------------------------------------------

    return trial
def generate_trial(rng, dt, params):
    #---------------------------------------------------------------------------------
    # Select task condition
    #---------------------------------------------------------------------------------

    catch_trial = False
    if params['name'] in ['gradient', 'test']:
        if params.get('catch', rng.rand() < pcatch):  #pcatch probability of catch trial
            catch_trial = True
        else:
            pair = params.get('pair', pairs[rng.choice(len(pairs))]) #random pair
            #gt_lt = params.get('gt_lt', rng.choice(gt_lts)) #random order
    elif params['name'] == 'validation':    
        b = params['minibatch_index'] % (nconditions + 1) #0 to 4
        
        if b == 0:
            catch_trial = True
        else:       #b-1 is 0 to 3, len(pairs) = 0 to 1
            k0, k1 = tasktools.unravel_index(b-1, (len(pairs),1))#len(gt_lts)))
            pair  = pairs[b-1]
            #gt_lt  = gt_lts[k1]
    else:
        raise ValueError("Unknown trial type.")

    #---------------------------------------------------------------------------------
    # Epochs
    #---------------------------------------------------------------------------------

    if catch_trial:
        epochs = {'T': 2500}
    else:
        if params['name'] == 'test':
            fixation = 500
        else:
            fixation = 100
        f1 = 500
        if params['name'] == 'test':
            delay = 3000
        else:
            delay = 3000
        f2       = 500
        decision = 300
        T        = fixation + f1 + delay + f2 + decision

        epochs = {
            'fixation': (0, fixation),
            'f1':       (fixation, fixation + f1),
            'delay':    (fixation + f1, fixation + f1 + delay),
            'f2':       (fixation + f1 + delay, fixation + f1 + delay + f2),
            'decision': (fixation + f1 + delay + f2, T)
            }
        epochs['T'] = T

    #---------------------------------------------------------------------------------
    # Trial info
    #---------------------------------------------------------------------------------

    t, e  = tasktools.get_epochs_idx(dt, epochs) # Task epochs in discrete time
    trial = {'t': t, 'epochs': epochs}           # Trial

    if catch_trial:
        trial['info'] = {}
    else:
        a1, a2 = pair
        # Correct choice
        if a1 == a2:     
            choice = 0
        else:                
            choice = 1

        # Info
        trial['info'] = {'f1': a1, 'f2': a2, 'choice': choice}

    #---------------------------------------------------------------------------------
    # Inputs
    #---------------------------------------------------------------------------------

    X = np.zeros((len(t), Nin))
    if not catch_trial:
        # Stimulus 1
        X[e['f1'],POS] = scale_p(a1)
        #X[e['f1'],NEG] = scale_n(f1)

        # Stimulus 2
        X[e['f2'],POS] = scale_p(a2)
        #X[e['f2'],NEG] = scale_n(f2)
    trial['inputs'] = X

    #---------------------------------------------------------------------------------
    # Target output
    #---------------------------------------------------------------------------------

    if params.get('target_output', False):
        Y = np.zeros((len(t), Nout)) # Output matrix by time
        M = np.zeros_like(Y)         # Mask matrix by time

        # Hold values
        hi = 1
        lo = 0.2

        if catch_trial:
            Y[:] = lo
            M[:] = 1
        else:
            # Fixation
            Y[e['fixation'],:] = lo #while fixating it should not be spiking

            # Decision
            Y[e['decision'],choice]   = hi  #output corresponding to choice = hi
            Y[e['decision'],1-choice] = lo  #other one goes to lo

            # Mask
            M[e['fixation']+e['decision'],:] = 1

        trial['outputs'] = Y
        trial['mask']    = M

    #---------------------------------------------------------------------------------

    return trial
Exemple #17
0
def run_trials(p, args):
    """
    Run trials.

    """
    # Model
    m = p['model']

    # Number of trials
    try:
        ntrials = int(args[0])
    except:
        ntrials = 100
    ntrials *= m.nconditions + 1

    # RNN
    rng = np.random.RandomState(p['seed'])
    rnn = RNN(p['savefile'], {'dt': p['dt']}, verbose=False)

    # Trials
    w = len(str(ntrials))
    trials = []
    backspaces = 0
    try:
        for i in xrange(ntrials):
            b = i % (m.nconditions + 1)
            if b == 0:
                # Zero-coherence condition
                coh = 0
                in_out = rng.choice(m.in_outs)
            else:
                # All other conditions
                k1, k2 = tasktools.unravel_index(b - 1,
                                                 (len(m.cohs), len(m.in_outs)))
                coh = m.cohs[k1]
                in_out = m.in_outs[k2]

            # Trial
            trial_func = m.generate_trial
            trial_args = {
                'name': 'test',
                'catch': False,
                'coh': coh,
                'in_out': in_out
            }
            info = rnn.run(inputs=(trial_func, trial_args), rng=rng)

            # Display trial type
            if coh == 0:
                s = "Trial {:>{}}/{}: {:>3}".format(i + 1, w, ntrials,
                                                    info['coh'])
            else:
                s = ("Trial {:>{}}/{}: {:>+3}".format(
                    i + 1, w, ntrials, info['in_out'] * info['coh']))
            sys.stdout.write(backspaces * '\b' + s)
            sys.stdout.flush()
            backspaces = len(s)

            # Save
            dt = rnn.t[1] - rnn.t[0]
            step = int(p['dt_save'] / dt)
            trial = {
                't': rnn.t[::step],
                'u': rnn.u[:, ::step],
                'r': rnn.r[:, ::step],
                'z': rnn.z[:, ::step],
                'info': info
            }
            trials.append(trial)
    except KeyboardInterrupt:
        pass
    print("")

    # Save all
    filename = get_trialsfile(p)
    with open(filename, 'wb') as f:
        pickle.dump(trials, f, pickle.HIGHEST_PROTOCOL)
    size = os.path.getsize(filename) * 1e-9
    print("[ {}.run_trials ] Trials saved to {} ({:.1f} GB)".format(
        THIS, filename, size))

    # Compute the psychometric function
    psychometric_function(filename)
Exemple #18
0
def generate_trial(rng, dt, params):
    #---------------------------------------------------------------------------------
    # Select task condition
    #---------------------------------------------------------------------------------

    catch_trial = False
    if params['name'] in ['gradient', 'test']:
        if params.get('catch', rng.rand() < pcatch):
            catch_trial = True
        else:
            fpair = params.get('fpair', fpairs[rng.choice(len(fpairs))])
            gt_lt = params.get('gt_lt', rng.choice(gt_lts))
    elif params['name'] == 'validation':
        b = params['minibatch_index'] % (nconditions + 1)
        if b == 0:
            catch_trial = True
        else:
            k0, k1 = tasktools.unravel_index(b - 1, (len(fpairs), len(gt_lts)))
            fpair = fpairs[k0]
            gt_lt = gt_lts[k1]
    else:
        raise ValueError("Unknown trial type.")

    #---------------------------------------------------------------------------------
    # Epochs
    #---------------------------------------------------------------------------------

    if catch_trial:
        epochs = {'T': 2500}
    else:
        if params['name'] == 'test':
            fixation = 500
        else:
            fixation = 100
        f1 = 500
        if params['name'] == 'test':
            delay = 3000
        else:
            delay = tasktools.uniform(rng, dt, 2500, 3500)
        f2 = 500
        decision = 300
        T = fixation + f1 + delay + f2 + decision

        epochs = {
            'fixation': (0, fixation),
            'f1': (fixation, fixation + f1),
            'delay': (fixation + f1, fixation + f1 + delay),
            'f2': (fixation + f1 + delay, fixation + f1 + delay + f2),
            'decision': (fixation + f1 + delay + f2, T)
        }
        epochs['T'] = T

    #---------------------------------------------------------------------------------
    # Trial info
    #---------------------------------------------------------------------------------

    t, e = tasktools.get_epochs_idx(dt, epochs)  # Task epochs in discrete time
    trial = {'t': t, 'epochs': epochs}  # Trial

    if catch_trial:
        trial['info'] = {}
    else:
        # Correct choice
        if gt_lt == '>':
            f1, f2 = fpair
            choice = 0
        else:
            f2, f1 = fpair
            choice = 1

        # Info
        trial['info'] = {'f1': f1, 'f2': f2, 'choice': choice}

    #---------------------------------------------------------------------------------
    # Inputs
    #---------------------------------------------------------------------------------

    X = np.zeros((len(t), Nin))
    if not catch_trial:
        # Stimulus 1
        X[e['f1'], POS] = scale_p(f1)
        X[e['f1'], NEG] = scale_n(f1)

        # Stimulus 2
        X[e['f2'], POS] = scale_p(f2)
        X[e['f2'], NEG] = scale_n(f2)
    trial['inputs'] = X

    #---------------------------------------------------------------------------------
    # Target output
    #---------------------------------------------------------------------------------

    if params.get('target_output', False):
        Y = np.zeros((len(t), Nout))  # Output matrix
        M = np.zeros_like(Y)  # Mask matrix

        # Hold values
        hi = 1
        lo = 0.2

        if catch_trial:
            Y[:] = lo
            M[:] = 1
        else:
            # Fixation
            Y[e['fixation'], :] = lo

            # Decision
            Y[e['decision'], choice] = hi
            Y[e['decision'], 1 - choice] = lo

            # Mask
            M[e['fixation'] + e['decision'], :] = 1

        trial['outputs'] = Y
        trial['mask'] = M

    #---------------------------------------------------------------------------------

    return trial
Exemple #19
0
def generate_trial(rng, dt, params):
    #-------------------------------------------------------------------------------------
    # Select task condition
    #-------------------------------------------------------------------------------------

    catch_trial = False
    if params['name'] in ['gradient', 'test']:
        if params.get('catch', rng.rand() < pcatch):
            catch_trial = True
        else:
            coh    = params.get('coh',    rng.choice(cohs))
            in_out = params.get('in_out', rng.choice(in_outs))
    elif params['name'] == 'validation':
        b = params['minibatch_index'] % (nconditions + 1)
        if b == 0:
            catch_trial = True
        else:
            k0, k1 = tasktools.unravel_index(b-1, (len(cohs), len(in_outs)))
            coh    = cohs[k0]
            in_out = in_outs[k1]
    else:
        raise ValueError("Unknown trial type.")

    #-------------------------------------------------------------------------------------
    # Epochs
    #-------------------------------------------------------------------------------------

    if catch_trial:
        epochs = {'T': 2000}
    else:
        if params['name'] == 'test':
            fixation = 300
        else:
            fixation = 100
        stimulus = 800
        decision = 300
        T        = fixation + stimulus + decision

        epochs = {
            'fixation': (0, fixation),
            'stimulus': (fixation, fixation + stimulus),
            'decision': (fixation + stimulus, T)
            }
        epochs['T'] = T

    #-------------------------------------------------------------------------------------
    # Trial info
    #-------------------------------------------------------------------------------------

    t, e  = tasktools.get_epochs_idx(dt, epochs) # Time, task epochs in discrete time
    trial = {'t': t, 'epochs': epochs}           # Trial

    if catch_trial:
        trial['info'] = {}
    else:
        # Correct choice
        if in_out > 0:
            choice = 0
        else:
            choice = 1

        # Trial info
        trial['info'] = {'coh': coh, 'in_out': in_out, 'choice': choice}

    #-------------------------------------------------------------------------------------
    # Inputs
    #-------------------------------------------------------------------------------------

    X = np.zeros((len(t), Nin))
    if not catch_trial:
        X[e['stimulus'],choice]   = scale(+coh)
        X[e['stimulus'],1-choice] = scale(-coh)
    trial['inputs'] = X

    #-------------------------------------------------------------------------------------
    # Target output
    #-------------------------------------------------------------------------------------

    if params.get('target_output', False):
        Y = np.zeros((len(t), Nout)) # Output
        M = np.zeros_like(Y)         # Mask

        # Hold values
        hi = 1
        lo = 0.2

        if catch_trial:
            Y[:] = lo
            M[:] = 1
        else:
            # Fixation
            Y[e['fixation'],:] = lo

            # Decision
            Y[e['decision'],choice]   = hi
            Y[e['decision'],1-choice] = lo

            # Only care about fixation and decision periods
            M[e['fixation']+e['decision'],:] = 1

        # Outputs and mask
        trial['outputs'] = Y
        trial['mask']    = M

    #-------------------------------------------------------------------------------------

    return trial
def generate_trial(rng, dt, params):
    #-------------------------------------------------------------------------------------
    # Select task condition
    #-------------------------------------------------------------------------------------

    catch_trial = False
    if params['name'] in ['gradient', 'test']:
        if params.get('catch', rng.rand() < pcatch):
            catch_trial = True
        else:
            # Context
            context = params.get('context', rng.choice(contexts))

            # Coherences
            coh_m = params.get('coh_m', rng.choice(cohs))
            coh_c = params.get('coh_c', rng.choice(cohs))

            # Left/right
            left_right_m = params.get('left_right_m', rng.choice(left_rights))
            left_right_c = params.get('left_right_c', rng.choice(left_rights))
    elif params['name'] == 'validation':
        b = params['minibatch_index'] % (nconditions + 1)
        if b == 0:
            catch_trial = True
        else:
            k = tasktools.unravel_index(b-1, (len(contexts),
                                              len(cohs), len(cohs),
                                              len(left_rights), len(left_rights)))
            context      = contexts[k[0]]
            coh_m        = cohs[k[1]]
            coh_c        = cohs[k[2]]
            left_right_m = left_rights[k[3]]
            left_right_c = left_rights[k[4]]
    else:
        raise ValueError("Unknown trial type.")

    #-------------------------------------------------------------------------------------
    # Epochs
    #-------------------------------------------------------------------------------------

    if catch_trial:
        epochs = {'T': 2000}
    else:
        if params['name'] == 'test':
            fixation = 400
        else:
            fixation = 100
        stimulus = 800
        decision = 300
        T        = fixation + stimulus + decision

        epochs = {
            'fixation': (0, fixation),
            'stimulus': (fixation, fixation + stimulus),
            'decision': (fixation + stimulus, T)
            }
        epochs['T'] = T

    #-------------------------------------------------------------------------------------
    # Trial info
    #-------------------------------------------------------------------------------------

    t, e  = tasktools.get_epochs_idx(dt, epochs) # Time, task epochs in discrete time
    trial = {'t': t, 'epochs': epochs}           # Trial

    if catch_trial:
        trial['info'] = {}
    else:
        if context == 'm':
            left_right = left_right_m
        else:
            left_right = left_right_c

        # Correct choice
        if left_right > 0:
            choice = 0
        else:
            choice = 1

        # Trial info
        trial['info'] = {
            'coh_m':        coh_m,
            'left_right_m': left_right_m,
            'coh_c':        coh_c,
            'left_right_c': left_right_c,
            'context':      context,
            'choice':       choice
            }

    #-------------------------------------------------------------------------------------
    # Inputs
    #-------------------------------------------------------------------------------------

    X = np.zeros((len(t), Nin))
    if not catch_trial:
        # Context
        if context == 'm':
            X[e['stimulus'],0] = 1
        else:
            X[e['stimulus'],1] = 1

        # Motion stimulus
        if left_right_m > 0:
            choice_m = 0
        else:
            choice_m = 1
        X[e['stimulus'],2+choice_m]     = scale(+coh_m)
        X[e['stimulus'],2+(1-choice_m)] = scale(-coh_m)

        # Colour stimulus
        if left_right_c > 0:
            choice_c = 0
        else:
            choice_c = 1
        X[e['stimulus'],4+choice_c]     = scale(+coh_c)
        X[e['stimulus'],4+(1-choice_c)] = scale(-coh_c)
    trial['inputs'] = X

    #-------------------------------------------------------------------------------------
    # Target output
    #-------------------------------------------------------------------------------------

    if params.get('target_output', False):
        Y = np.zeros((len(t), Nout)) # Output matrix
        M = np.zeros_like(Y)         # Mask matrix

        # Hold values
        hi = 1
        lo = 0.2

        if catch_trial:
            Y[:] = lo
            M[:] = 1
        else:
            # Fixation
            Y[e['fixation'],:] = lo

            # Decision
            Y[e['decision'],choice]   = hi
            Y[e['decision'],1-choice] = lo

            # Only care about fixation and decision periods
            M[e['fixation']+e['decision'],:] = 1

        # Outputs and mask
        trial['outputs'] = Y
        trial['mask']    = M

    #-------------------------------------------------------------------------------------

    return trial