How to use the neuron.h.Random function in NEURON

To help you get started, we’ve selected a few NEURON examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Neurosim-lab / netpyne / netpyne / cell / compartCell.py View on Github external
print("Error: The length of the list of locations does not match synsPerConn (with cfg.distributeSynsUniformly = False")
                                return
                        else: # single loc
                            synMechLocs = [params['loc']] * synsPerConn
                    else:
                            print("Error: The length of the list of sections does not match synsPerConn (with cfg.distributeSynsUniformly = False")
                            return            
                
        else:  # if 1 synapse
            # by default place on 1st section of list and location available 
            synMechSecs = secLabels
            synMechLocs = params['loc'] if isinstance(params['loc'], list) else [params['loc']] 

            # randomize the section to connect to and move it to beginning of list
            if sim.cfg.connRandomSecFromList and len(synMechSecs)>1:
                rand = h.Random()
                preGid = params['preGid'] if isinstance(params['preGid'], int) else 0
                rand.Random123(sim.hashStr('connSynMechsSecs'), self.gid, preGid) # initialize randomizer 
                pos = int(rand.discunif(0, len(synMechSecs)-1))
                synMechSecs[pos], synMechSecs[0] = synMechSecs[0], synMechSecs[pos]
                if len(synMechLocs)>1: 
                    synMechLocs[pos], synMechLocs[0] = synMechLocs[0], synMechLocs[pos]

        # add synaptic mechanism to section based on synMechSecs and synMechLocs (if already exists won't be added)
        synMechs = [self.addSynMech(synLabel=params['synMech'], secLabel=synMechSecs[i], loc=synMechLocs[i]) for i in range(synsPerConn)] 

        return synMechs, synMechSecs, synMechLocs
github Neurosim-lab / netpyne / netpyne / cell / compartCell.py View on Github external
def create (self):
        from .. import sim

        # generate random rotation angle for each cell
        if sim.net.params.rotateCellsRandomly:
            if isinstance(sim.net.params.rotateCellsRandomly, list):
                [rotMin, rotMax] = sim.net.params.rotateCellsRandomly
            else:
                [rotMin, rotMax] = 0, 6.2832
            rand = h.Random()
            rand.Random123(self.gid)
            self.randRotationAngle = rand.uniform(0, 6.2832)  # 0 to 2pi


        for propLabel, prop in sim.net.params.cellParams.items():  # for each set of cell properties
            conditionsMet = 1
            for (condKey,condVal) in prop['conds'].items():  # check if all conditions are met
                if isinstance(condVal, list): 
                    if isinstance(condVal[0], Number):
                        if self.tags.get(condKey) < condVal[0] or self.tags.get(condKey) > condVal[1]:
                            conditionsMet = 0
                            break
                    elif isinstance(condVal[0], str):
                        if self.tags.get(condKey) not in condVal:
                            conditionsMet = 0
                            break
github Neurosim-lab / netpyne / netpyne / cell / pointCell.py View on Github external
noise = self.params['noise'] if 'noise' in self.params else 0.0

                maxReproducibleSpks = 1e4  # num of rand spikes generated; only a subset is used; ensures reproducibility 

                # fixed interval of duration (1 - noise)*interval 
                fixedInterval = np.full(int(((1+1.5*noise)*sim.cfg.duration/interval)), [(1.0-noise)*interval])  # generate 1+1.5*noise spikes to account for noise
                numSpks = len(fixedInterval)

                # randomize the first spike so on average it occurs at start + noise*interval
                # invl = (1. - noise)*mean + noise*mean*erand() - interval*(1. - noise)    
                if noise == 0.0:
                    vec = h.Vector(len(fixedInterval))
                    spkTimes =  np.cumsum(fixedInterval) + (start - interval) 
                else:
                    # plus negexp interval of mean duration noise*interval. Note that the most likely negexp interval has duration 0.
                    rand = h.Random()
                    rand.Random123(sim.hashStr('vecstim_spkt'), self.gid, self.params['seed'])

                    # Method 1: vec length depends on duration -- not reproducible
                    # vec = h.Vector(numSpks)
                    # rand.negexp(noise*interval)
                    # vec.setrand(rand)
                    # negexpInterval= np.array(vec)                     
                    # #print negexpInterval
                    # spkTimes = np.cumsum(fixedInterval + negexpInterval) + (start - interval*(1-noise))

                    if numSpks < 100:
                        # Method 2: vec length=1, slower but reproducible
                        vec = h.Vector(1) 
                        rand.negexp(noise*interval)
                        negexpInterval = []
                        for i in range(numSpks):
github Neurosim-lab / netpyne / netpyne / network.py View on Github external
def __init__ (self, params = None):
        self.params = params

        # params that can be expressed using string-based functions in connections
        self.connStringFuncParams = ['weight', 'delay', 'synsPerConn', 'loc']  

        # params that can be expressed using string-based functions in stims
        self.stimStringFuncParams = ['delay', 'dur', 'amp', 'gain', 'rstim', 'tau1', 'tau2', 
        'onset', 'tau', 'gmax', 'e', 'i', 'interval', 'rate', 'number', 'start', 'noise']  

        # list of h.Random() methods allowed in string-based functions (both for conns and stims)
        self.stringFuncRandMethods = ['binomial', 'discunif', 'erlang', 'geometric', 'hypergeo', 
        'lognormal', 'negexp', 'normal', 'poisson', 'uniform', 'weibull']

        self.rand = h.Random()  # random number generator

        self.pops = ODict()  # list to store populations ('Pop' objects)
        self.cells = [] # list to store cells ('Cell' objects)

        self.lid2gid = [] # Empty list for storing local index -> GID (index = local id; value = gid)
        self.gid2lid = {} # Empty dict for storing GID -> local index (key = gid; value = local id) -- ~x6 faster than .index() 
        self.lastGid = 0  # keep track of last cell gid 
        self.lastGapId = 0  # keep track of last gap junction gid 
github Neurosim-lab / netpyne / netpyne / cell / pointCell.py View on Github external
def createNEURONObj (self):
        from .. import sim

        # add point processes
        try:
            self.hPointp = getattr(h, self.tags['cellModel'])()
        except:
            print("Error creating point process mechanism %s in cell with gid %d" % (self.tags['cellModel'], self.gid))
            return 

        # if rate is list with 2 items generate random value from uniform 
        
        #from IPython import embed; embed()

        if 'rate' in self.params and isinstance(self.params['rate'], list) and len(self.params['rate']) == 2:
            rand = h.Random()
            rand.Random123(sim.hashStr('point_rate'), self.gid, sim.cfg.seeds['stim']) # initialize randomizer 
            self.params['rate'] = rand.uniform(self.params['rate'][0], self.params['rate'][1])
 
        # set pointp params - for PointCells these are stored in self.params
        params = {k: v for k,v in self.params.items()}
        for paramName, paramValue in params.items():
            try:
                if paramName == 'rate':
                    self.params['interval'] = 1000.0/paramValue
                    setattr(self.hPointp, 'interval', self.params['interval'])
                else:
                    setattr(self.hPointp, paramName, paramValue)
            except:
                pass

        # add random num generator, and set number and seed for NetStims
github Neurosim-lab / netpyne / netpyne / cell / pointCell.py View on Github external
elif numSpks < maxReproducibleSpks:
                        # Method 3: vec length=maxReproducibleSpks, then select subset; slower but reproducible
                        vec = h.Vector(maxReproducibleSpks)
                        rand.negexp(noise*interval)
                        vec.setrand(rand)
                        negexpInterval = np.array(vec.c(0,len(fixedInterval)-1))                  
                        spkTimes = np.cumsum(fixedInterval + negexpInterval) + (start - interval*(1-noise))

                    else:
                        print('\nError: exceeded the maximum number of VecStim spikes per cell (%d > %d)' % (numSpks, maxReproducibleSpks))
                        return

            # spikePattern
            elif 'spikePattern' in self.params:
                patternType = self.params['spikePattern'].get('type', None)
                rand = h.Random()

                # if sync, don't initialize randomizer based on gid
                if self.params.get('sync', False):
                    rand.Random123(sim.hashStr('vecstim_spikePattern'), self.params['seed'])
                else:
                    rand.Random123(sim.hashStr('vecstim_spikePattern'), self.gid, self.params['seed'])

                if patternType == 'rhythmic':
                    from .inputs import createRhythmicPattern
                    spkTimes = createRhythmicPattern(self.params['spikePattern'], rand)
                elif patternType == 'evoked':
                    from .inputs import createEvokedPattern
                    spkTimes = createEvokedPattern(self.params['spikePattern'], rand) 
                elif patternType == 'poisson':
                    from .inputs import createPoissonPattern
                    spkTimes = createPoissonPattern(self.params['spikePattern'], rand)
github Neurosim-lab / netpyne / netpyne / cell / pointCell.py View on Github external
end = pulse['end']

                        # fixed interval of duration (1 - noise)*interval 
                        fixedInterval = np.full(int(((1+1.5*noise)*(end-start)/interval)), [(1.0-noise)*interval])  # generate 1+0.5*noise spikes to account for noise
                        numSpks = len(fixedInterval)

                        # randomize the first spike so on average it occurs at start + noise*interval
                        # invl = (1. - noise)*mean + noise*mean*erand() - interval*(1. - noise)
                        if noise == 0.0:
                            vec = h.Vector(len(fixedInterval))
                            pulseSpikes = np.cumsum(fixedInterval) + (start - interval)
                            pulseSpikes[pulseSpikes < start] = start
                            spkTimes = np.append(spkTimes, pulseSpikes[pulseSpikes <= end])
                        else:
                            # plus negexp interval of mean duration noise*interval. Note that the most likely negexp interval has duration 0.
                            rand = h.Random()
                            rand.Random123(ipulse, self.gid, self.params['seed'])
                            
                            # Method 1: vec length depends on duration -- not reproducible
                            # vec = h.Vector(len(fixedInterval))
                            # rand.negexp(noise*interval)
                            # vec.setrand(rand)
                            # negexpInterval = np.array(vec) 
                            # pulseSpikes = np.cumsum(fixedInterval + negexpInterval) + (start - interval*(1-noise))

                            # Method 2: vec length=1, slower but reproducible
                            vec = h.Vector(1) 
                            rand.negexp(noise*interval)
                            negexpInterval = []
                            for i in range(numSpks):
                                vec.setrand(rand)
                                negexpInterval.append(vec.x[0])  # = np.array(vec)[0:len(fixedInterval)]                    
github Neurosim-lab / netpyne / netpyne / cell / compartCell.py View on Github external
def create (self):
        from .. import sim
                
        if sim.cfg.recordDipoles:
            h("dp_total_L2 = 0."); h("dp_total_L5 = 0.") # put here since these variables used in cells

        # generate random rotation angle for each cell
        if sim.net.params.rotateCellsRandomly:
            if isinstance(sim.net.params.rotateCellsRandomly, list):
                [rotMin, rotMax] = sim.net.params.rotateCellsRandomly
            else:
                [rotMin, rotMax] = 0, 6.2832
            rand = h.Random()
            rand.Random123(self.gid)
            self.randRotationAngle = rand.uniform(0, 6.2832)  # 0 to 2pi

        
        for propLabel, prop in sim.net.params.cellParams.items():  # for each set of cell properties
            conditionsMet = 1
            for (condKey,condVal) in prop['conds'].items():  # check if all conditions are met
                if isinstance(condVal, list): 
                    if isinstance(condVal[0], Number):
                        if self.tags.get(condKey) < condVal[0] or self.tags.get(condKey) > condVal[1]:
                            conditionsMet = 0
                            break
                    elif isinstance(condVal[0], basestring):
                        if self.tags.get(condKey) not in condVal:
                            conditionsMet = 0
                            break
github Neurosim-lab / netpyne / netpyne / cell / NML2SpikeSource.py View on Github external
def initRandom(self):
        from .. import sim
        
        rand = h.Random()
        self.stims.append(Dict())  # add new stim to Cell object
        randContainer = self.stims[-1]
        randContainer['hRandom'] = rand 
        randContainer['type'] = self.tags['cellType'] 
        seed = sim.cfg.seeds['stim']
        randContainer['seed'] = seed 
        self.secs['soma']['pointps'][self.tags['cellType']].hPointp.noiseFromRandom(rand)  # use random number generator 
        sim._init_stim_randomizer(rand, self.tags['pop'], self.tags['cellLabel'], seed)
        randContainer['hRandom'].negexp(1)
        #print("Created Random: %s with %s (%s)"%(rand,seed, sim.cfg.seeds))