Exemplo n.º 1
0
    def go(self, parallel=False):
        """ Run an experimental run, results are stored the 
        results attribute. """
        
        if parallel:
            # ----
            # Setup chunks and seeds
            self.run_chunks = create_chunks(self.nrun, self.ncore)
            self.prngs = [process_prng(ii+10) for ii in range(
                    len(self.run_chunks))]
            
            # ----
            # Create a pool, and use it,
            # and store the results
            pool = Pool(self.ncore)
            results_in_chunks = pool.map(self, zip(self.run_chunks, self.prngs))
                    ## Calling self here works via __call__

            self.results = reduce_chunks(results_in_chunks)
        else:
            # Run an experimental Run, and save to
            # self.results
            self.prngs = [process_prng(42), ]
            
            self.results = self._singleloop((range(self.nrun), self.prngs[0]))
Exemplo n.º 2
0
    def __init__(self, n, alphas, TR=2, ISI=2, prng=None):
        try:
            Exp.__init__(self, TR=2, ISI=2, prng=None)
        except AttributeError:
            pass

        self.prng = process_prng(prng)

        # Simulate a learning task and acc.
        ncond = 1
        trials, acc, p, self.prng = simBehave.behave.learn(ncond, n, 3, True, self.prng)

        # And hand the results off of self
        self.trials = np.array(trials)
        self.durations = np.array([1] * len(self.trials))

        # Or add them to the data attr
        self.data["ncond"] = ncond
        self.data["acc"] = acc
        self.data["p"] = p

        # Run the RL sim, and save the results keying (partly)
        # off of alpha an alpha counter
        for ii, alpha in enumerate(alphas):
            v_dict, rpe_dict = rl.reinforce.b_delta(acc, trials, alpha)
            values = rl.misc.unpack(v_dict, trials)
            rpes = rl.misc.unpack(rpe_dict, trials)

            self.data["value" + str(ii)] = values
            self.data["rpe" + str(ii)] = rpes

        self.data["alphas"] = alphas

        # Create random data too.
        self.data["rand"] = self.prng.rand(n)
Exemplo n.º 3
0
def white(N, sigma=1, prng=None):
    """ Create and return a white noise array of length <N>.
    
    Notes on prng:
    If <prng> is a np.random.RandomState() instance, it is used for random
        number generation.  
    If <prng> is a number that number is used to seed (i.e., 
        RandomState(<prng>)).
    If <prng> is None, the seed is set automagically. """

    prng = process_prng(prng)

    np.random.set_state(prng.get_state())
    ## Pass random state from prng to np so that
    ## stats.<> will inherit the irght state.
    ## There does not seem to be a way to set random
    ## state of stats.* functions directly.

    noise = stats.norm.rvs(size=N, loc=0, scale=sigma)

    prng.set_state(np.random.get_state())
    ## Pass the seed stat from np back to
    ## prng, then we can use prng again...

    return noise, prng
Exemplo n.º 4
0
def white(N, sigma=1, prng=None):
    """ Create and return a white noise array of length <N>.
    
    Notes on prng:
    If <prng> is a np.random.RandomState() instance, it is used for random
        number generation.  
    If <prng> is a number that number is used to seed (i.e., 
        RandomState(<prng>)).
    If <prng> is None, the seed is set automagically. """
    
    prng = process_prng(prng)
    
    np.random.set_state(prng.get_state())
        ## Pass random state from prng to np so that
        ## stats.<> will inherit the irght state.
        ## There does not seem to be a way to set random
        ## state of stats.* functions directly.
    
    noise = stats.norm.rvs(size=N, loc=0, scale=sigma)
    
    prng.set_state(np.random.get_state())
        ## Pass the seed stat from np back to
        ## prng, then we can use prng again...
    
    return noise, prng
Exemplo n.º 5
0
def ar1(N, alpha=0.2, prng=None):
    """ Create AR1 noise (of length <N>, and strength <alpha>), based on 
    a white noise stream. 
    
    Te default of alpha of 0.2 was taken from the 'temporalnoise.R' function
    in the R 'neuRosim' package (ver 02-10):
    
    http://cran.r-project.org/web/packages/neuRosim/index.html 
    
    Notes on prng:
    If <prng> is a np.random.RandomState() instance, it is used for random
        number generation.  
    If <prng> is a number that number is used to seed (i.e., 
        RandomState(<prng>)).
    If <prng> is None, the seed is set automagically. """
    
    if (alpha > 1) or (alpha < 0):
        raise ValueError("alpha must be between 0-1.")
    
    prng = process_prng(prng)
    
    noise, prng = white(N=N, prng=prng)
    arnoise = [noise[0], ]
        ## Init by copying over the first
        ## so the loop below
        ## has someting to work with for
        ## the first iteration
    
    [arnoise.append(noise[ii]+(alpha * noise[ii-1])) for ii in range(
            1, len(noise))]
    
    return arnoise, prng
Exemplo n.º 6
0
def lowfreqdrift(N, TR, prng=None):
    """ Create noise of length <N> with a low frequency drift.  Frequency is    
    randomly selected from a uniform distribution spanning 0.002-0.015 Hz,  
    a range taken from:
    
    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
    
    Notes on prng:
    If <prng> is a np.random.RandomState() instance, it is used for random
        number generation.  
    If <prng> is a number that number is used to seed (i.e., 
        RandomState(<prng>)).
    If <prng> is None, the seed is set automagically.
    """

    prng = process_prng(prng)

    freq = prng.randint(66, 500)
    ## i.e. 0.002-0.015 Hz

    ## The number of bases is n
    nbasis = int(np.floor(2 * (N * TR) / freq + 1))

    ## Creates the drifts; magic!
    def _gen_drifts(nrow, ncol):
        idx = np.arange(0, nrow)

        drifts = np.zeros((nrow, ncol + 1))
        drifts[:, 0] = np.repeat(1 / np.sqrt(nrow), nrow)
        for col in range(2, ncol + 1):
            drift = np.sqrt(2. / nrow) * 10. * np.cos(np.pi * (2. * idx + 1.) *
                                                      (col - 1.) / (2. * nrow))
            drifts[:, col] = drift

        return drifts

    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=1, prng=prng)
    noise += whiten

    return noise, prng
Exemplo n.º 7
0
def lowfreqdrift(N, TR, prng=None):
    """ Create noise of length <N> with a low frequency drift.  Frequency is    
    randomly selected from a uniform distribution spanning 0.002-0.015 Hz,  
    a range taken from:
    
    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
    
    Notes on prng:
    If <prng> is a np.random.RandomState() instance, it is used for random
        number generation.  
    If <prng> is a number that number is used to seed (i.e., 
        RandomState(<prng>)).
    If <prng> is None, the seed is set automagically.
    """

    prng = process_prng(prng)
    
    freq = prng.randint(66, 500)
        ## i.e. 0.002-0.015 Hz
    
    ## The number of bases is n
    nbasis = int(np.floor(2 * (N * TR) / freq + 1))

    ## Creates the drifts; magic!
    def _gen_drifts(nrow, ncol):
        idx = np.arange(0, nrow)

        drifts = np.zeros((nrow, ncol+1))
        drifts[:,0] = np.repeat(1 / np.sqrt(nrow), nrow)
        for col in range(2, ncol+1):
            drift = np.sqrt(2. / nrow) * 10. * np.cos(
                    np.pi * (2. * idx + 1.) * (col - 1.) / (2. * nrow))
            drifts[:, col] = drift
            
        return drifts
    
    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=1, prng=prng)
    noise += whiten

    return noise, prng
Exemplo n.º 8
0
 def __init__(self, n, TR=2, ISI=2, prng=None):
     try: 
         Exp.__init__(self, TR=2, ISI=2, prng=None)
     except AttributeError: 
         pass
     
     self.prng = process_prng(prng)
     
     self.trials = np.array([0,]*n + [1,]*n)
     self.durations = [1, ] * len(self.trials)
     
     self.prng.shuffle(self.trials)
Exemplo n.º 9
0
 def __init__(self, n, TR=2, ISI=2, prng=None):
     try: 
         Exp.__init__(self, TR=2, ISI=2, prng=None)
     except AttributeError: 
         pass
     
     self.prng = process_prng(prng)
     
     # event_random(N,k,mult=1)
     self.trials, self.prng = event_random(2, n, 1, self.prng)
     self.trials = np.array(self.trials)
     
     self.durations = [1, ] * len(self.trials)
Exemplo n.º 10
0
 def __init__(self, n, behave='learn', TR=2, ISI=2, prng=None):
     try: 
         Exp.__init__(self, TR=2, ISI=2, prng=None)
     except AttributeError: 
         pass
     
     self.prng = process_prng(prng)
     
     n_cond = 1
     n_trials_cond = n
     trials = []
     acc = []
     p = []
     if behave == 'learn':
 		trials, acc, p, self.prng = simBehave.behave.learn(
 				n_cond, n_trials_cond, 3, True, self.prng)
     elif behave == 'random':
 			trials, acc, p, self.prng = simBehave.behave.random(
                     n_cond,n_trials_cond, 3, self.prng)
     else:
         raise ValueError(
                 '{0} is not known.  Try learn or random.'.format(behave))
     
     # Find best RL learning parameters for the behavoiral data
     # then generate the final data and unpack it into a list.
     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])
     values = rl.misc.unpack(v_dict, trials)
     rpes = rl.misc.unpack(rpe_dict, trials)
     
     # Store the results in appropriate places
     self.trials = np.array(trials)
     self.durations = np.array([1, ] * len(self.trials))
     self.data['acc'] = acc
     self.data['p'] = p
     self.data['best_logL'] = best_logL
     self.data['best_rl_pars'] = best_rl_pars
     self.data['value'] = values
     self.data['rpe'] = rpes
     self.data['rand'] = self.prng.rand(len(self.trials))
Exemplo n.º 11
0
def ar1(N, alpha=0.2, prng=None):
    """ Create AR1 noise (of length <N>, and strength <alpha>), based on 
    a white noise stream. 
    
    Te default of alpha of 0.2 was taken from the 'temporalnoise.R' function
    in the R 'neuRosim' package (ver 02-10):
    
    http://cran.r-project.org/web/packages/neuRosim/index.html 
    
    Notes on prng:
    If <prng> is a np.random.RandomState() instance, it is used for random
        number generation.  
    If <prng> is a number that number is used to seed (i.e., 
        RandomState(<prng>)).
    If <prng> is None, the seed is set automagically. """

    if (alpha > 1) or (alpha < 0):
        raise ValueError("alpha must be between 0-1.")

    prng = process_prng(prng)

    noise, prng = white(N=N, prng=prng)
    arnoise = [
        noise[0],
    ]
    ## Init by copying over the first
    ## so the loop below
    ## has someting to work with for
    ## the first iteration

    [
        arnoise.append(noise[ii] + (alpha * noise[ii - 1]))
        for ii in range(1, len(noise))
    ]

    return arnoise, prng