Beispiel #1
0
def ar1(N, alpha=0.2, sigma=1, prng=None):
    """ Create AR1 noise.
    
    Parameters
    ---------
    N : numeric
        Length of 1d noise array to return
    alpha : float
        Degree of autocorrelation
    sigma : numeric
        Standard deviation of white noise
    prng : np.random.RandomState, None
        A RandomState instance, or None
        
    Alpha of 0.2 was taken from the 'temporalnoise.R' function 
    in the R neuRosim package (ver 02-10)
    """
    
    if (alpha > 1) or (alpha < 0):
        raise ValueError("alpha must be between 0-1.")
    
    prng = process_prng(prng)
    
    noise, prng = white(N=N, sigma=sigma, prng=prng)
    arnoise = [noise[0], ]
    
    [arnoise.append(
            noise[ii] + (alpha * noise[ii-1])
            ) for ii in range(1, len(noise))]
    
    return arnoise, prng
Beispiel #2
0
def learn(N, k, loc=3, prng=None):
    """Simulate learning behavior"""
    
    prng = process_prng(prng)
    
    trials, prng = tlib.random(N, k, prng=prng)
    trials, prng = tlib.jitter(trials, prng=prng)
    l = trials.shape[0]
    
    acc = np.zeros(l)
    p = np.zeros(l)

    conds = np.unique(trials)
    for n in conds:
        ## Skip null trials
        if (n == 0) | (n == '0'):
            continue

        p_n, prng = probability.learn(k, loc, prng=prng)
        acc_n, prng = acclib.accuracy(p_n, prng=prng)
        
        for t in enumerate(trials):
            acc[trials == n] = acc_n
            p[trials == n] = p_n

    return trials, acc, p, prng
def learn(N, loc=3, prng=None):
    """Simulate learning moving p(correct) from random to a sigmoid
    
    Note
    ----
    * Transition from random to learn is itself random, sampled from 
        uniform(1, N).
    * loc of 3 gives 'realistic' learning curves
    """

    prng = process_prng(prng)
    np.random.set_state(prng.get_state())
    
    # Random and learn are divided by T
    T = int(prng.randint(0, N, 1))
    
    # Random p
    p_1, prng = random(T, prng)
    
    # Learn p
    trials = np.arange(.01, 10, (10/float(N - T)))
    trials = trials + stats.norm.rvs(size=trials.shape[0]) 
    p_2 = stats.norm.cdf(trials,loc)
    p_2[p_2 < 0.5] = prng.rand(np.sum(p_2 < 0.5))
        ## Remove p vals les than 0.5 otherwise
        ## p drops badly as learning is suppose
        ## to start
        
    prng.set_state(np.random.get_state())

    return np.concatenate([p_1, p_2]), prng
Beispiel #4
0
def random(N, k, prng=None):
    """Creates a randomly list of trials (int) of N cond with 
    k trials / cond.
    """

    prng = process_prng(prng)
    
    trials = []
    [trials.extend([n, ] * k) for n in range(1, N+1)]
    
    trials = np.asarray(trials)
    prng.shuffle(trials) 

    return trials, prng
Beispiel #5
0
def white(N, sigma=1, prng=None):
    """ Create white noise.
    
    Parameters
    ---------
    N : numeric
        Length of 1d noise array to return
    sigma : numeric
        Standard deviation
    prng : np.random.RandomState, None
        A RandomState instance, or None
    """
    
    prng = process_prng(prng)
    
    return prng.normal(loc=0, scale=sigma, size=N), prng
Beispiel #6
0
def jitter(trials, code=0, fraction=.5, jit=(1,7), prng=None):
    """Introduce random (uniform) jitter to trials"""
    
    prng = process_prng(prng)
    
    jittimes = np.arange(*jit, dtype=np.int)
    jittered = []
    for t in trials:
        if fraction >= prng.rand(1):
            prng.shuffle(jittimes)
            jt = [t, ] + [code, ] * jittimes[0]
            jittered.extend(jt)
        else:
            jittered.append(t)
    
    return np.asarray(jittered), prng
def rescorla_wagner(trials, acc, p, alpha=None, prng=None):
    """Create a RW learning dataset
    
    Parameters
    ----------
    trials : list([int, ])
        Trials coded by condition
    acc : list([int((0,1)), ])
         Accuracy data
    p : list([float])
        p(correct)
    alpha : float, None
        The learning rate (None fits by ML)
    """
    
    prng = process_prng(prng)
    l = trials.shape[0]
    
    # fit RW models?
    if alpha is None:
        best_rl_pars, best_logL = rl.fit.ml_delta(acc, trials, 0.05)
        v_dict, rpe_dict = rl.reinforce.b_delta(acc, trials, best_rl_pars[0])
    else:
        best_rl_pars, best_logL = None, None
        v_dict, rpe_dict = rl.reinforce.b_delta(acc, trials, alpha)
        
    values = rl.misc.unpack(v_dict, trials) ## Reformat from dict to array
    rpes = rl.misc.unpack(rpe_dict, trials)
    
    # Store sim data
    box = np.zeros_like(trials)
    box[trials > 0] = 1
    rand = prng.rand(l)
    
    df = pd.DataFrame(data={
                'trials' : trials,
                'box' : box,
                'acc' : acc,
                'p' : p,
                'value' : np.asarray(values),
                'rpe' : np.asarray(rpes),
                'rand' : rand
                })
        
    return df, {'best_rl_pars' : best_rl_pars, 'best_logL' : best_logL}
    
Beispiel #8
0
def _preturb(weight, width=32, TR=1, a1=6.0, a2=12., b1=0.9, b2=0.9, c=0.35, prng=None):    
    prng = process_prng(prng)    
    np.random.set_state(prng.get_state())

    # Parameters to preturb
    params = {a1:6.0, a2:12.0, b1:0.9, b2:0.9, c:0.35}

    # Preturb it
    keys = params.keys()
    prng.shuffle(keys)
    par = params[keys[0]]
    params[keys[0]] = prng.normal(loc=par, scale=par / (1. * weight))
    
    # Add unpreturbed params
    params['width'] = width
    params['TR'] = TR
    
    return params, prng
Beispiel #9
0
def lowfreqdrift(N, TR=1, sigma=1, prng=None):
    """ Create noise with a low frequency drift (0.002-0.015 Hz)  
    
    Parameters
    ---------
    N : numeric
        Length of 1d noise array to return
    TR : float
        The repetition rate (BOLD signal)
    prng : np.random.RandomState, None
        A RandomState instance, or None
    
    Note
    ----  
    Smith et al (1999), Investigation of the Low Frequency Drift in fMRI 
    Signal, NeuroImage 9, 526-533.
    
    This function was ported form a similar function ('lowfreqdrift.R')
    in the R 'neuRosim' package (ver 02-10):
    
    http://cran.r-project.org/web/packages/neuRosim/index.html
    """

    prng = process_prng(prng)
    
    freq = prng.randint(66, 500)
        ## i.e. 0.002-0.015 Hz
    
    nbasis = int(np.floor(2 * (N * TR) / freq + 1))
    noise = _gen_drifts(N, nbasis)
    noise = noise[:,1:]     ## Drop the first col
    noise = noise.sum(1)    ## Sum the rows, creating
                            ## creating the final noise
    
    # Now add white noise
    whiten, prng = white(N, sigma=sigma, prng=prng)
    noise += whiten

    return noise, prng
Beispiel #10
0
def random(N, k, prng=None):
    """Simulate random behavior
    
    Parameters
    ----------
    N : int
        Number of conditions
    k : int
        Number of trials / condition
    prng : RandomState object, None
        Explicit passing of random state.  None create
        a new state
    """
    prng = process_prng(prng)
    
    trials, prng = tlib.random(N, k, prng=prng)
    trials, prng = tlib.jitter(trials, prng=prng)
    l = trials.shape[0]
    
    acc = np.zeros(l)
    p = np.zeros(l)

    conds = np.unique(trials)
    for n in conds:
        ## Skip null trials
        if (n == 0) | (n == '0'):
            continue

        p_n, prng = probability.random(k, prng=prng)
        acc_n, prng = acclib.accuracy(p_n, prng=prng)
        
        for t in enumerate(trials):
            acc[trials == n] = acc_n
            p[trials == n] = p_n

    return trials, acc, p, prng
def random(N, prng=None):
    """Create N p(correct) sampled from a uniform distribution (0-1)"""
    
    prng = process_prng(prng)
    return prng.rand(N), prng
Beispiel #12
0
def accuracy(p, prng=None):
    prng = process_prng(prng)
    
    N = len(p)
    return prng.binomial(1, p, N), prng