示例#1
0
    def probConn (self, preCellsTags, postCellsTags, connParam):
        ''' Generates connections between all pre and post-syn cells based on probability values'''
        if sim.cfg.verbose: print 'Generating set of probabilistic connections...'

        seed(sim.id32('%d'%(sim.cfg.seeds['conn']+preCellsTags.keys()[-1]+postCellsTags.keys()[-1])))  
        allRands = {(preGid,postGid): random() for preGid in preCellsTags for postGid in postCellsTags}  # Create an array of random numbers for checking each connection

        # get list of params that have a lambda function
        paramsStrFunc = [param for param in [p+'Func' for p in self.connStringFuncParams] if param in connParam] 

        for postCellGid,postCellTags in postCellsTags.iteritems():  # for each postsyn cell
            if postCellGid in self.lid2gid:  # check if postsyn is in this node
                for preCellGid, preCellTags in preCellsTags.iteritems():  # for each presyn cell
                    probability = connParam['probabilityFunc'][preCellGid,postCellGid] if 'probabilityFunc' in connParam else connParam['probability']
                    
                    for paramStrFunc in paramsStrFunc: # call lambda functions to get weight func args
                        connParam[paramStrFunc+'Args'] = {k:v if isinstance(v, Number) else v(preCellTags,postCellTags) for k,v in connParam[paramStrFunc+'Vars'].iteritems()}  
                  
                    if probability >= allRands[preCellGid,postCellGid]:      
                        seed(sim.id32('%d'%(sim.cfg.seeds['conn']+postCellGid+preCellGid)))  
                        if preCellTags['cellModel'] == 'NetStim':  # if NetStim
                            self._addNetStimParams(connParam, preCellTags) # cell method to add connection       
                            self._addCellConn(connParam, preCellGid, postCellGid) # add connection        
                        elif preCellGid != postCellGid: # if not self-connection
                           self._addCellConn(connParam, preCellGid, postCellGid) # add connection
示例#2
0
文件: pop.py 项目: pgleeson/netpyne
 def createCellsFixedNum (self):
     ''' Create population cells based on fixed number of cells'''
     cellModelClass = sim.Cell
     cells = []
     seed(sim.id32('%d'%(sim.cfg.seeds['loc']+self.tags['numCells']+sim.net.lastGid)))
     randLocs = rand(self.tags['numCells'], 3)  # create random x,y,z locations
     for icoord, coord in enumerate(['x', 'y', 'z']):
         if coord+'Range' in self.tags:  # if user provided absolute range, convert to normalized
             self.tags[coord+'normRange'] = [float(point) / getattr(sim.net.params, 'size'+coord.upper()) for point in self.tags[coord+'Range']]
         if coord+'normRange' in self.tags:  # if normalized range, rescale random locations
             minv = self.tags[coord+'normRange'][0] 
             maxv = self.tags[coord+'normRange'][1] 
             randLocs[:,icoord] = randLocs[:,icoord] * (maxv-minv) + minv
     
     for i in xrange(int(sim.rank), int(sim.net.params.scale * self.tags['numCells']), sim.nhosts):
         gid = sim.net.lastGid+i
         self.cellGids.append(gid)  # add gid list of cells belonging to this population - not needed?
         cellTags = {k: v for (k, v) in self.tags.iteritems() if k in sim.net.params.popTagsCopiedToCells}  # copy all pop tags to cell tags, except those that are pop-specific
         cellTags['popLabel'] = self.tags['popLabel']
         cellTags['xnorm'] = randLocs[i,0] # set x location (um)
         cellTags['ynorm'] = randLocs[i,1] # set y location (um)
         cellTags['znorm'] = randLocs[i,2] # set z location (um)
         cellTags['x'] = sim.net.params.sizeX * randLocs[i,0] # set x location (um)
         cellTags['y'] = sim.net.params.sizeY * randLocs[i,1] # set y location (um)
         cellTags['z'] = sim.net.params.sizeZ * randLocs[i,2] # set z location (um)
         cells.append(cellModelClass(gid, cellTags)) # instantiate Cell object
         if sim.cfg.verbose: print('Cell %d/%d (gid=%d) of pop %s, on node %d, '%(i, sim.net.params.scale * self.tags['numCells']-1, gid, self.tags['popLabel'], sim.rank))
     sim.net.lastGid = sim.net.lastGid + self.tags['numCells'] 
     return cells
示例#3
0
    def fromListConn (self, preCellsTags, postCellsTags, connParam):
        ''' Generates connections between all pre and post-syn cells based list of relative cell ids'''
        if sim.cfg.verbose: print 'Generating set of connections from list...'

        # list of params that can have a lambda function
        paramsStrFunc = [param for param in [p+'Func' for p in self.connStringFuncParams] if param in connParam] 
        for paramStrFunc in paramsStrFunc:
            # replace lambda function (with args as dict of lambda funcs) with list of values
            seed(sim.id32('%d'%(sim.cfg.seeds['conn']+preCellsTags.keys()[0]+postCellsTags.keys()[0])))
            connParam[paramStrFunc[:-4]+'List'] = {(preGid,postGid): connParam[paramStrFunc](**{k:v if isinstance(v, Number) else v(preCellTags,postCellTags) for k,v in connParam[paramStrFunc+'Vars'].iteritems()})  
                    for preGid,preCellTags in preCellsTags.iteritems() for postGid,postCellTags in postCellsTags.iteritems()}

        if isinstance(connParam['weight'], list): connParam['weightFromList'] = list(connParam['weight'])  # if weight is a list, copy to weightFromList
        if isinstance(connParam['delay'], list): connParam['delayFromList'] = list(connParam['delay'])  # if delay is a list, copy to delayFromList
        if isinstance(connParam['loc'], list): connParam['locFromList'] = list(connParam['loc'])  # if delay is a list, copy to locFromList

        
        orderedPreGids = sorted(preCellsTags.keys())
        orderedPostGids = sorted(postCellsTags.keys())

        for iconn, (relativePreId, relativePostId) in enumerate(connParam['connList']):  # for each postsyn cell
            preCellGid = orderedPreGids[relativePreId]
            preCellTags = preCellsTags[preCellGid]  # get pre cell based on relative id        
            postCellGid = orderedPostGids[relativePostId]
            if postCellGid in self.lid2gid:  # check if postsyn is in this node's list of gids
                
                if 'weightFromList' in connParam: connParam['weight'] = connParam['weightFromList'][iconn] 
                if 'delayFromList' in connParam: connParam['delay'] = connParam['delayFromList'][iconn]

                if preCellTags['cellModel'] == 'NetStim':  # if NetStim
                    print 'Error: fromList connectivity for NetStims is not implemented'           
                if preCellGid != postCellGid: # if not self-connection
                    self._addCellConn(connParam, preCellGid, postCellGid) # add connection
示例#4
0
    def createCellsFixedNum (self):
        ''' Create population cells based on fixed number of cells'''
        cells = []
        seed(sim.id32('%d'%(sim.cfg.seeds['loc']+self.tags['numCells']+sim.net.lastGid)))
        randLocs = rand(self.tags['numCells'], 3)  # create random x,y,z locations

        if sim.net.params.shape == 'cylinder':
            # Use the x,z random vales 
            rho = randLocs[:,0] # use x rand value as the radius rho in the interval [0, 1)
            phi = 2 * pi * randLocs[:,2] # use z rand value as the angle phi in the interval [0, 2*pi) 
            x = (1 + sqrt(rho) * cos(phi))/2.0
            z = (1 + sqrt(rho) * sin(phi))/2.0
            randLocs[:,0] = x
            randLocs[:,2] = z
    
        elif sim.net.params.shape == 'ellipsoid':
            # Use the x,y,z random vales 
            rho = np.power(randLocs[:,0], 1.0/3.0) # use x rand value as the radius rho in the interval [0, 1); cuberoot
            phi = 2 * pi * randLocs[:,1] # use y rand value as the angle phi in the interval [0, 2*pi) 
            costheta = (2 * randLocs[:,2]) - 1 # use z rand value as cos(theta) in the interval [-1, 1); ensures uniform dist 
            theta = arccos(costheta)  # obtain theta from cos(theta)
            x = (1 + rho * cos(phi) * sin(theta))/2.0
            y = (1 + rho * sin(phi) * sin(theta))/2.0
            z = (1 + rho * cos(theta))/2.0 
            randLocs[:,0] = x
            randLocs[:,1] = y
            randLocs[:,2] = z
        
        for icoord, coord in enumerate(['x', 'y', 'z']):
            if coord+'Range' in self.tags:  # if user provided absolute range, convert to normalized
                self.tags[coord+'normRange'] = [float(point) / getattr(sim.net.params, 'size'+coord.upper()) for point in self.tags[coord+'Range']]
            # constrain to range set by user
            if coord+'normRange' in self.tags:  # if normalized range, rescale random locations
                minv = self.tags[coord+'normRange'][0] 
                maxv = self.tags[coord+'normRange'][1] 
                randLocs[:,icoord] = randLocs[:,icoord] * (maxv-minv) + minv

        for i in self._distributeCells(int(sim.net.params.scale * self.tags['numCells']))[sim.rank]:
            gid = sim.net.lastGid+i
            self.cellGids.append(gid)  # add gid list of cells belonging to this population - not needed?
            cellTags = {k: v for (k, v) in self.tags.iteritems() if k in sim.net.params.popTagsCopiedToCells}  # copy all pop tags to cell tags, except those that are pop-specific
            cellTags['popLabel'] = self.tags['popLabel']
            cellTags['xnorm'] = randLocs[i,0] # set x location (um)
            cellTags['ynorm'] = randLocs[i,1] # set y location (um)
            cellTags['znorm'] = randLocs[i,2] # set z location (um)
            cellTags['x'] = sim.net.params.sizeX * randLocs[i,0] # set x location (um)
            cellTags['y'] = sim.net.params.sizeY * randLocs[i,1] # set y location (um)
            cellTags['z'] = sim.net.params.sizeZ * randLocs[i,2] # set z location (um)
            cells.append(self.cellModelClass(gid, cellTags)) # instantiate Cell object
            if sim.cfg.verbose: print('Cell %d/%d (gid=%d) of pop %s, on node %d, '%(i, sim.net.params.scale * self.tags['numCells']-1, gid, self.tags['popLabel'], sim.rank))
        sim.net.lastGid = sim.net.lastGid + self.tags['numCells'] 
        return cells
示例#5
0
    def createCellsFixedNum(self):
        ''' Create population cells based on fixed number of cells'''
        cellModelClass = sim.Cell
        cells = []
        seed(
            sim.id32('%d' % (sim.cfg.seeds['loc'] + self.tags['numCells'] +
                             sim.net.lastGid)))
        randLocs = rand(self.tags['numCells'],
                        3)  # create random x,y,z locations
        for icoord, coord in enumerate(['x', 'y', 'z']):
            if coord + 'Range' in self.tags:  # if user provided absolute range, convert to normalized
                self.tags[coord + 'normRange'] = [
                    float(point) /
                    getattr(sim.net.params, 'size' + coord.upper())
                    for point in self.tags[coord + 'Range']
                ]
            if coord + 'normRange' in self.tags:  # if normalized range, rescale random locations
                minv = self.tags[coord + 'normRange'][0]
                maxv = self.tags[coord + 'normRange'][1]
                randLocs[:,
                         icoord] = randLocs[:, icoord] * (maxv - minv) + minv

        for i in xrange(int(sim.rank),
                        sim.net.params.scale * self.tags['numCells'],
                        sim.nhosts):
            gid = sim.net.lastGid + i
            self.cellGids.append(
                gid
            )  # add gid list of cells belonging to this population - not needed?
            cellTags = {
                k: v
                for (k, v) in self.tags.iteritems()
                if k in sim.net.params.popTagsCopiedToCells
            }  # copy all pop tags to cell tags, except those that are pop-specific
            cellTags['popLabel'] = self.tags['popLabel']
            cellTags['xnorm'] = randLocs[i, 0]  # set x location (um)
            cellTags['ynorm'] = randLocs[i, 1]  # set y location (um)
            cellTags['znorm'] = randLocs[i, 2]  # set z location (um)
            cellTags['x'] = sim.net.params.sizeX * randLocs[
                i, 0]  # set x location (um)
            cellTags['y'] = sim.net.params.sizeY * randLocs[
                i, 1]  # set y location (um)
            cellTags['z'] = sim.net.params.sizeZ * randLocs[
                i, 2]  # set z location (um)
            cells.append(cellModelClass(gid,
                                        cellTags))  # instantiate Cell object
            if sim.cfg.verbose:
                print('Cell %d/%d (gid=%d) of pop %s, on node %d, ' %
                      (i, sim.net.params.scale * self.tags['numCells'] - 1,
                       gid, self.tags['popLabel'], sim.rank))
        sim.net.lastGid = sim.net.lastGid + self.tags['numCells']
        return cells
示例#6
0
    def divConn (self, preCellsTags, postCellsTags, connParam):
        ''' Generates connections between all pre and post-syn cells based on probability values'''
        if sim.cfg.verbose: print 'Generating set of divergent connections...'
         
        # get list of params that have a lambda function
        paramsStrFunc = [param for param in [p+'Func' for p in self.connStringFuncParams] if param in connParam] 

        for preCellGid, preCellTags in preCellsTags.iteritems():  # for each presyn cell
            divergence = connParam['divergenceFunc'][preCellGid] if 'divergenceFunc' in connParam else connParam['divergence']  # num of presyn conns / postsyn cell
            divergence = max(min(int(round(divergence)), len(postCellsTags)), 0)
            seed(sim.id32('%d'%(sim.cfg.seeds['conn']+preCellGid)))  
            postCellsSample = sample(postCellsTags, divergence)  # selected gids of postsyn cells
            postCellsDiv = {postGid:postConds  for postGid,postConds in postCellsTags.iteritems() if postGid in postCellsSample and postGid in self.lid2gid}  # dict of selected postsyn cells tags
            for postCellGid, postCellTags in postCellsDiv.iteritems():  # for each postsyn cell
                
                for paramStrFunc in paramsStrFunc: # call lambda functions to get weight func args
                    connParam[paramStrFunc+'Args'] = {k:v if isinstance(v, Number) else v(preCellTags,postCellTags) for k,v in connParam[paramStrFunc+'Vars'].iteritems()}  
 
                seed(sim.id32('%d'%(sim.cfg.seeds['conn']+postCellGid+preCellGid)))  
                if preCellTags['cellModel'] == 'NetStim':  # if NetStim
                    print 'Error: Divergent connectivity for NetStims is not implemented'           
                if preCellGid != postCellGid: # if not self-connection
                    self._addCellConn(connParam, preCellGid, postCellGid) # add connection
示例#7
0
    def _stimStrToFunc (self, postCellsTags, sourceParams, targetParams):
        # list of params that have a function passed in as a string
        #params = sourceParams+targetParams
        params = sourceParams.copy()
        params.update(targetParams)

        paramsStrFunc = [param for param in self.stimStringFuncParams+self.connStringFuncParams if param in params and isinstance(params[param], str)]  

        # dict to store correspondence between string and actual variable
        dictVars = {}   
        dictVars['post_x']      = lambda postConds: postConds['x'] 
        dictVars['post_y']      = lambda postConds: postConds['y'] 
        dictVars['post_z']      = lambda postConds: postConds['z'] 
        dictVars['post_xnorm']  = lambda postConds: postConds['xnorm'] 
        dictVars['post_ynorm']  = lambda postConds: postConds['ynorm'] 
        dictVars['post_znorm']  = lambda postConds: postConds['znorm'] 
         
        # add netParams variables
        for k,v in self.params.__dict__.iteritems():
            if isinstance(v, Number):
                dictVars[k] = v

        # for each parameter containing a function, calculate lambda function and arguments
        strParams = {}
        for paramStrFunc in paramsStrFunc:
            strFunc = params[paramStrFunc]  # string containing function
            strVars = [var for var in dictVars.keys() if var in strFunc and var+'norm' not in strFunc]  # get list of variables used (eg. post_ynorm or dist_xyz)
            lambdaStr = 'lambda ' + ','.join(strVars) +': ' + strFunc # convert to lambda function 
            lambdaFunc = eval(lambdaStr)

            # store lambda function and func vars in connParam (for weight, delay and synsPerConn since only calculated for certain conns)
            params[paramStrFunc+'Func'] = lambdaFunc
            params[paramStrFunc+'FuncVars'] = {strVar: dictVars[strVar] for strVar in strVars} 
 
            # initialize randomizer in case used in function
            seed(sim.id32('%d'%(sim.cfg.seeds['conn']+postCellsTags.keys()[0])))

            # replace lambda function (with args as dict of lambda funcs) with list of values
            strParams[paramStrFunc+'List'] = {postGid: params[paramStrFunc+'Func'](**{k:v if isinstance(v, Number) else v(postCellTags) for k,v in params[paramStrFunc+'FuncVars'].iteritems()})  
                    for postGid,postCellTags in postCellsTags.iteritems()}

        return strParams
示例#8
0
    def fullConn (self, preCellsTags, postCellsTags, connParam):
        ''' Generates connections between all pre and post-syn cells '''
        if sim.cfg.verbose: print 'Generating set of all-to-all connections...'

        # get list of params that have a lambda function
        paramsStrFunc = [param for param in [p+'Func' for p in self.connStringFuncParams] if param in connParam] 

        for paramStrFunc in paramsStrFunc:
            # replace lambda function (with args as dict of lambda funcs) with list of values
            seed(sim.id32('%d'%(sim.cfg.seeds['conn']+preCellsTags.keys()[0]+postCellsTags.keys()[0])))
            connParam[paramStrFunc[:-4]+'List'] = {(preGid,postGid): connParam[paramStrFunc](**{k:v if isinstance(v, Number) else v(preCellTags,postCellTags) for k,v in connParam[paramStrFunc+'Vars'].iteritems()})  
                    for preGid,preCellTags in preCellsTags.iteritems() for postGid,postCellTags in postCellsTags.iteritems()}
        
        for postCellGid in postCellsTags:  # for each postsyn cell
            if postCellGid in self.lid2gid:  # check if postsyn is in this node's list of gids
                for preCellGid, preCellTags in preCellsTags.iteritems():  # for each presyn cell
                    if preCellTags['cellModel'] == 'NetStim':  # if NetStim
                        self._addNetStimParams(connParam, preCellTags) # cell method to add connection  
                        self._addCellConn(connParam, preCellGid, postCellGid) # add connection             
                    elif preCellGid != postCellGid: # if not self-connection
                        self._addCellConn(connParam, preCellGid, postCellGid) # add connection
示例#9
0
    def createCellsGrid (self):
        ''' Create population cells based on fixed number of cells'''
        cells = []
        seed(sim.id32('%d'%(sim.cfg.seeds['loc']+self.tags['gridSpacing']+sim.net.lastGid)))
        
        rangeLocs = [[0, getattr(sim.net.params, 'size'+coord)] for coord in ['X','Y','Z']]
        for icoord, coord in enumerate(['x', 'y', 'z']):
            # constrain to range set by user
            if coord+'normRange' in self.tags:  # if normalized range, convert to normalized
                self.tags[coord+'Range'] = [float(point) * getattr(sim.net.params, 'size'+coord.upper()) for point in self.tags[coord+'Range']]                
            if coord+'Range' in self.tags:  # if user provided absolute range, calculate range
                self.tags[coord+'normRange'] = [float(point) / getattr(sim.net.params, 'size'+coord.upper()) for point in self.tags[coord+'Range']]
                rangeLocs[icoord] = [self.tags[coord+'Range'][0], self.tags[coord+'Range'][1]] 
              
        gridSpacing = self.tags['gridSpacing']
        gridLocs = []
        for x in np.arange(rangeLocs[0][0], rangeLocs[0][1]+1, gridSpacing):
            for y in np.arange(rangeLocs[1][0], rangeLocs[1][1]+1, gridSpacing):
                for z in np.arange(rangeLocs[2][0], rangeLocs[2][1]+1, gridSpacing):
                    gridLocs.append((x, y, z))

        numCells = len(gridLocs)

        for i in self._distributeCells(numCells)[sim.rank]:
            gid = sim.net.lastGid+i
            self.cellGids.append(gid)  # add gid list of cells belonging to this population - not needed?
            cellTags = {k: v for (k, v) in self.tags.iteritems() if k in sim.net.params.popTagsCopiedToCells}  # copy all pop tags to cell tags, except those that are pop-specific
            cellTags['popLabel'] = self.tags['popLabel']
            cellTags['xnorm'] = gridLocs[i][0] / sim.net.params.sizeX # set x location (um)
            cellTags['ynorm'] = gridLocs[i][1] / sim.net.params.sizeY # set y location (um)
            cellTags['znorm'] = gridLocs[i][2] / sim.net.params.sizeZ # set z location (um)
            cellTags['x'] = gridLocs[i][0]   # set x location (um)
            cellTags['y'] = gridLocs[i][1] # set y location (um)
            cellTags['z'] = gridLocs[i][2] # set z location (um)
            cells.append(self.cellModelClass(gid, cellTags)) # instantiate Cell object
            if sim.cfg.verbose: print('Cell %d/%d (gid=%d) of pop %s, on node %d, '%(i, numCells, gid, self.tags['popLabel'], sim.rank))
        sim.net.lastGid = sim.net.lastGid + numCells
        return cells
示例#10
0
    def createCellsDensity (self):
        ''' Create population cells based on density'''
        cells = []
        shape = sim.net.params.shape
        sizeX = sim.net.params.sizeX
        sizeY = sim.net.params.sizeY
        sizeZ = sim.net.params.sizeZ
        
        # calculate volume
        if shape == 'cuboid':
            volume = sizeY/1e3 * sizeX/1e3 * sizeZ/1e3  
        elif shape == 'cylinder':
            volume = sizeY/1e3 * sizeX/1e3/2 * sizeZ/1e3/2 * pi
        elif shape == 'ellipsoid':
            volume = sizeY/1e3/2.0 * sizeX/1e3/2.0 * sizeZ/1e3/2.0 * pi * 4.0 / 3.0

        for coord in ['x', 'y', 'z']:
            if coord+'Range' in self.tags:  # if user provided absolute range, convert to normalized
                self.tags[coord+'normRange'] = [point / sim.net.params['size'+coord.upper()] for point in self.tags[coord+'Range']]
            if coord+'normRange' in self.tags:  # if normalized range, rescale volume
                minv = self.tags[coord+'normRange'][0] 
                maxv = self.tags[coord+'normRange'][1] 
                volume = volume * (maxv-minv)

        funcLocs = None  # start with no locations as a function of density function
        if isinstance(self.tags['density'], str): # check if density is given as a function 
            if shape == 'cuboid':  # only available for cuboids
                strFunc = self.tags['density']  # string containing function
                strVars = [var for var in ['xnorm', 'ynorm', 'znorm'] if var in strFunc]  # get list of variables used 
                if not len(strVars) == 1:
                    print 'Error: density function (%s) for population %s does not include "xnorm", "ynorm" or "znorm"'%(strFunc,self.tags['popLabel'])
                    return
                coordFunc = strVars[0] 
                lambdaStr = 'lambda ' + coordFunc +': ' + strFunc # convert to lambda function 
                densityFunc = eval(lambdaStr)
                minRange = self.tags[coordFunc+'Range'][0]
                maxRange = self.tags[coordFunc+'Range'][1]

                interval = 0.001  # interval of location values to evaluate func in order to find the max cell density
                maxDensity = max(map(densityFunc, (arange(minRange, maxRange, interval))))  # max cell density 
                maxCells = volume * maxDensity  # max number of cells based on max value of density func 
                
                seed(sim.id32('%d' % sim.cfg.seeds['loc']+sim.net.lastGid))  # reset random number generator
                locsAll = minRange + ((maxRange-minRange)) * rand(int(maxCells), 1)  # random location values 
                locsProb = array(map(densityFunc, locsAll)) / maxDensity  # calculate normalized density for each location value (used to prune)
                allrands = rand(len(locsProb))  # create an array of random numbers for checking each location pos 
                
                makethiscell = locsProb>allrands  # perform test to see whether or not this cell should be included (pruning based on density func)
                funcLocs = [locsAll[i] for i in range(len(locsAll)) if i in array(makethiscell.nonzero()[0],dtype='int')] # keep only subset of yfuncLocs based on density func
                self.tags['numCells'] = len(funcLocs)  # final number of cells after pruning of location values based on density func
                if sim.cfg.verbose: print 'Volume=%.2f, maxDensity=%.2f, maxCells=%.0f, numCells=%.0f'%(volume, maxDensity, maxCells, self.tags['numCells'])
            else:
                print 'Error: Density functions are only implemented for cuboid shaped networks'
                exit(0)
        else:  # NO ynorm-dep
            self.tags['numCells'] = int(self.tags['density'] * volume)  # = density (cells/mm^3) * volume (mm^3)

        # calculate locations of cells 
        seed(sim.id32('%d'%(sim.cfg.seeds['loc']+self.tags['numCells']+sim.net.lastGid)))
        randLocs = rand(self.tags['numCells'], 3)  # create random x,y,z locations

        if sim.net.params.shape == 'cylinder':
            # Use the x,z random vales 
            rho = randLocs[:,0] # use x rand value as the radius rho in the interval [0, 1)
            phi = 2 * pi * randLocs[:,2] # use z rand value as the angle phi in the interval [0, 2*pi) 
            x = (1 + sqrt(rho) * cos(phi))/2.0
            z = (1 + sqrt(rho) * sin(phi))/2.0
            randLocs[:,0] = x
            randLocs[:,2] = z
    
        elif sim.net.params.shape == 'ellipsoid':
            # Use the x,y,z random vales 
            rho = np.power(randLocs[:,0], 1.0/3.0) # use x rand value as the radius rho in the interval [0, 1); cuberoot
            phi = 2 * pi * randLocs[:,1] # use y rand value as the angle phi in the interval [0, 2*pi) 
            costheta = (2 * randLocs[:,2]) - 1 # use z rand value as cos(theta) in the interval [-1, 1); ensures uniform dist 
            theta = arccos(costheta)  # obtain theta from cos(theta)
            x = (1 + rho * cos(phi) * sin(theta))/2.0
            y = (1 + rho * sin(phi) * sin(theta))/2.0
            z = (1 + rho * cos(theta))/2.0 
            randLocs[:,0] = x
            randLocs[:,1] = y
            randLocs[:,2] = z

        for icoord, coord in enumerate(['x', 'y', 'z']):
            if coord+'normRange' in self.tags:  # if normalized range, rescale random locations
                minv = self.tags[coord+'normRange'][0] 
                maxv = self.tags[coord+'normRange'][1] 
                randLocs[:,icoord] = randLocs[:,icoord] * (maxv-minv) + minv
            if funcLocs and coordFunc == coord+'norm':  # if locations for this coordinate calculated using density function
                randLocs[:,icoord] = funcLocs

        if sim.cfg.verbose and not funcLocs: print 'Volume=%.4f, density=%.2f, numCells=%.0f'%(volume, self.tags['density'], self.tags['numCells'])

        for i in self._distributeCells(self.tags['numCells'])[sim.rank]:
            gid = sim.net.lastGid+i
            self.cellGids.append(gid)  # add gid list of cells belonging to this population - not needed?
            cellTags = {k: v for (k, v) in self.tags.iteritems() if k in sim.net.params.popTagsCopiedToCells}  # copy all pop tags to cell tags, except those that are pop-specific
            cellTags['popLabel'] = self.tags['popLabel']
            cellTags['xnorm'] = randLocs[i,0]  # calculate x location (um)
            cellTags['ynorm'] = randLocs[i,1]  # calculate y location (um)
            cellTags['znorm'] = randLocs[i,2]  # calculate z location (um)
            cellTags['x'] = sizeX * randLocs[i,0]  # calculate x location (um)
            cellTags['y'] = sizeY * randLocs[i,1]  # calculate y location (um)
            cellTags['z'] = sizeZ * randLocs[i,2]  # calculate z location (um)
            cells.append(self.cellModelClass(gid, cellTags)) # instantiate Cell object
            if sim.cfg.verbose: 
                print('Cell %d/%d (gid=%d) of pop %s, pos=(%2.f, %2.f, %2.f), on node %d, '%(i, self.tags['numCells']-1, gid, self.tags['popLabel'],cellTags['x'], cellTags['y'], cellTags['z'], sim.rank))
        sim.net.lastGid = sim.net.lastGid + self.tags['numCells'] 
        return cells
示例#11
0
    def createCellsDensity(self):
        ''' Create population cells based on density'''
        cellModelClass = sim.Cell
        cells = []
        volume = sim.net.params.sizeY / 1e3 * sim.net.params.sizeX / 1e3 * sim.net.params.sizeZ / 1e3  # calculate full volume
        for coord in ['x', 'y', 'z']:
            if coord + 'Range' in self.tags:  # if user provided absolute range, convert to normalized
                self.tags[coord + 'normRange'] = [
                    point / sim.net.params['size' + coord.upper()]
                    for point in self.tags[coord + 'Range']
                ]
            if coord + 'normRange' in self.tags:  # if normalized range, rescale volume
                minv = self.tags[coord + 'normRange'][0]
                maxv = self.tags[coord + 'normRange'][1]
                volume = volume * (maxv - minv)

        funcLocs = None  # start with no locations as a function of density function
        if isinstance(self.tags['density'],
                      str):  # check if density is given as a function
            strFunc = self.tags['density']  # string containing function
            strVars = [
                var for var in ['xnorm', 'ynorm', 'znorm'] if var in strFunc
            ]  # get list of variables used
            if not len(strVars) == 1:
                print 'Error: density function (%s) for population %s does not include "xnorm", "ynorm" or "znorm"' % (
                    strFunc, self.tags['popLabel'])
                return
            coordFunc = strVars[0]
            lambdaStr = 'lambda ' + coordFunc + ': ' + strFunc  # convert to lambda function
            densityFunc = eval(lambdaStr)
            minRange = self.tags[coordFunc + 'Range'][0]
            maxRange = self.tags[coordFunc + 'Range'][1]

            interval = 0.001  # interval of location values to evaluate func in order to find the max cell density
            maxDensity = max(
                map(densityFunc, (arange(minRange, maxRange,
                                         interval))))  # max cell density
            maxCells = volume * maxDensity  # max number of cells based on max value of density func

            seed(sim.id32('%d' % sim.cfg.seeds['loc'] +
                          sim.net.lastGid))  # reset random number generator
            locsAll = minRange + ((maxRange - minRange)) * rand(
                int(maxCells), 1)  # random location values
            locsProb = array(
                map(densityFunc, locsAll)
            ) / maxDensity  # calculate normalized density for each location value (used to prune)
            allrands = rand(
                len(locsProb)
            )  # create an array of random numbers for checking each location pos

            makethiscell = locsProb > allrands  # perform test to see whether or not this cell should be included (pruning based on density func)
            funcLocs = [
                locsAll[i] for i in range(len(locsAll))
                if i in array(makethiscell.nonzero()[0], dtype='int')
            ]  # keep only subset of yfuncLocs based on density func
            self.tags['numCells'] = len(
                funcLocs
            )  # final number of cells after pruning of location values based on density func
            if sim.cfg.verbose:
                print 'Volume=%.2f, maxDensity=%.2f, maxCells=%.0f, numCells=%.0f' % (
                    volume, maxDensity, maxCells, self.tags['numCells'])

        else:  # NO ynorm-dep
            self.tags['numCells'] = int(
                self.tags['density'] *
                volume)  # = density (cells/mm^3) * volume (mm^3)

        # calculate locations of cells
        seed(
            sim.id32('%d' % (sim.cfg.seeds['loc'] + self.tags['numCells'] +
                             sim.net.lastGid)))
        randLocs = rand(self.tags['numCells'],
                        3)  # create random x,y,z locations
        for icoord, coord in enumerate(['x', 'y', 'z']):
            if coord + 'normRange' in self.tags:  # if normalized range, rescale random locations
                minv = self.tags[coord + 'normRange'][0]
                maxv = self.tags[coord + 'normRange'][1]
                randLocs[:,
                         icoord] = randLocs[:, icoord] * (maxv - minv) + minv
            if funcLocs and coordFunc == coord + 'norm':  # if locations for this coordinate calcualated using density function
                randLocs[:, icoord] = funcLocs

        if sim.cfg.verbose and not funcLocs:
            print 'Volume=%.4f, density=%.2f, numCells=%.0f' % (
                volume, self.tags['density'], self.tags['numCells'])

        for i in xrange(int(sim.rank), self.tags['numCells'], sim.nhosts):
            gid = sim.net.lastGid + i
            self.cellGids.append(
                gid
            )  # add gid list of cells belonging to this population - not needed?
            cellTags = {
                k: v
                for (k, v) in self.tags.iteritems()
                if k in sim.net.params.popTagsCopiedToCells
            }  # copy all pop tags to cell tags, except those that are pop-specific
            cellTags['popLabel'] = self.tags['popLabel']
            cellTags['xnorm'] = randLocs[i, 0]  # calculate x location (um)
            cellTags['ynorm'] = randLocs[i, 1]  # calculate y location (um)
            cellTags['znorm'] = randLocs[i, 2]  # calculate z location (um)
            cellTags['x'] = sim.net.params.sizeX * randLocs[
                i, 0]  # calculate x location (um)
            cellTags['y'] = sim.net.params.sizeY * randLocs[
                i, 1]  # calculate y location (um)
            cellTags['z'] = sim.net.params.sizeZ * randLocs[
                i, 2]  # calculate z location (um)
            cells.append(cellModelClass(gid,
                                        cellTags))  # instantiate Cell object
            if sim.cfg.verbose:
                print(
                    'Cell %d/%d (gid=%d) of pop %s, pos=(%2.f, %2.f, %2.f), on node %d, '
                    %
                    (i, self.tags['numCells'] - 1, gid, self.tags['popLabel'],
                     cellTags['x'], cellTags['y'], cellTags['z'], sim.rank))
        sim.net.lastGid = sim.net.lastGid + self.tags['numCells']
        return cells
示例#12
0
文件: pop.py 项目: pgleeson/netpyne
    def createCellsDensity (self):
        ''' Create population cells based on density'''
        cellModelClass = sim.Cell
        cells = []
        volume =  sim.net.params.sizeY/1e3 * sim.net.params.sizeX/1e3 * sim.net.params.sizeZ/1e3  # calculate full volume
        for coord in ['x', 'y', 'z']:
            if coord+'Range' in self.tags:  # if user provided absolute range, convert to normalized
                self.tags[coord+'normRange'] = [point / sim.net.params['size'+coord.upper()] for point in self.tags[coord+'Range']]
            if coord+'normRange' in self.tags:  # if normalized range, rescale volume
                minv = self.tags[coord+'normRange'][0] 
                maxv = self.tags[coord+'normRange'][1] 
                volume = volume * (maxv-minv)

        funcLocs = None  # start with no locations as a function of density function
        if isinstance(self.tags['density'], str): # check if density is given as a function
            strFunc = self.tags['density']  # string containing function
            strVars = [var for var in ['xnorm', 'ynorm', 'znorm'] if var in strFunc]  # get list of variables used 
            if not len(strVars) == 1:
                print 'Error: density function (%s) for population %s does not include "xnorm", "ynorm" or "znorm"'%(strFunc,self.tags['popLabel'])
                return
            coordFunc = strVars[0] 
            lambdaStr = 'lambda ' + coordFunc +': ' + strFunc # convert to lambda function 
            densityFunc = eval(lambdaStr)
            minRange = self.tags[coordFunc+'Range'][0]
            maxRange = self.tags[coordFunc+'Range'][1]

            interval = 0.001  # interval of location values to evaluate func in order to find the max cell density
            maxDensity = max(map(densityFunc, (arange(minRange, maxRange, interval))))  # max cell density 
            maxCells = volume * maxDensity  # max number of cells based on max value of density func 
            
            seed(sim.id32('%d' % sim.cfg.seeds['loc']+sim.net.lastGid))  # reset random number generator
            locsAll = minRange + ((maxRange-minRange)) * rand(int(maxCells), 1)  # random location values 
            locsProb = array(map(densityFunc, locsAll)) / maxDensity  # calculate normalized density for each location value (used to prune)
            allrands = rand(len(locsProb))  # create an array of random numbers for checking each location pos 
            
            makethiscell = locsProb>allrands  # perform test to see whether or not this cell should be included (pruning based on density func)
            funcLocs = [locsAll[i] for i in range(len(locsAll)) if i in array(makethiscell.nonzero()[0],dtype='int')] # keep only subset of yfuncLocs based on density func
            self.tags['numCells'] = len(funcLocs)  # final number of cells after pruning of location values based on density func
            if sim.cfg.verbose: print 'Volume=%.2f, maxDensity=%.2f, maxCells=%.0f, numCells=%.0f'%(volume, maxDensity, maxCells, self.tags['numCells'])

        else:  # NO ynorm-dep
            self.tags['numCells'] = int(self.tags['density'] * volume)  # = density (cells/mm^3) * volume (mm^3)

        # calculate locations of cells 
        seed(sim.id32('%d'%(sim.cfg.seeds['loc']+self.tags['numCells']+sim.net.lastGid)))
        randLocs = rand(self.tags['numCells'], 3)  # create random x,y,z locations
        for icoord, coord in enumerate(['x', 'y', 'z']):
            if coord+'normRange' in self.tags:  # if normalized range, rescale random locations
                minv = self.tags[coord+'normRange'][0] 
                maxv = self.tags[coord+'normRange'][1] 
                randLocs[:,icoord] = randLocs[:,icoord] * (maxv-minv) + minv
            if funcLocs and coordFunc == coord+'norm':  # if locations for this coordinate calcualated using density function
                randLocs[:,icoord] = funcLocs

        if sim.cfg.verbose and not funcLocs: print 'Volume=%.4f, density=%.2f, numCells=%.0f'%(volume, self.tags['density'], self.tags['numCells'])

        for i in xrange(int(sim.rank), self.tags['numCells'], sim.nhosts):
            gid = sim.net.lastGid+i
            self.cellGids.append(gid)  # add gid list of cells belonging to this population - not needed?
            cellTags = {k: v for (k, v) in self.tags.iteritems() if k in sim.net.params.popTagsCopiedToCells}  # copy all pop tags to cell tags, except those that are pop-specific
            cellTags['popLabel'] = self.tags['popLabel']
            cellTags['xnorm'] = randLocs[i,0]  # calculate x location (um)
            cellTags['ynorm'] = randLocs[i,1]  # calculate y location (um)
            cellTags['znorm'] = randLocs[i,2]  # calculate z location (um)
            cellTags['x'] = sim.net.params.sizeX * randLocs[i,0]  # calculate x location (um)
            cellTags['y'] = sim.net.params.sizeY * randLocs[i,1]  # calculate y location (um)
            cellTags['z'] = sim.net.params.sizeZ * randLocs[i,2]  # calculate z location (um)
            cells.append(cellModelClass(gid, cellTags)) # instantiate Cell object
            if sim.cfg.verbose: 
                print('Cell %d/%d (gid=%d) of pop %s, pos=(%2.f, %2.f, %2.f), on node %d, '%(i, self.tags['numCells']-1, gid, self.tags['popLabel'],cellTags['x'], cellTags['y'], cellTags['z'], sim.rank))
        sim.net.lastGid = sim.net.lastGid + self.tags['numCells'] 
        return cells
示例#13
0
    def _connStrToFunc (self, preCellsTags, postCellsTags, connParam):
        # list of params that have a function passed in as a string
        paramsStrFunc = [param for param in self.connStringFuncParams+['probability', 'convergence', 'divergence'] if param in connParam and isinstance(connParam[param], str)]  

        # dict to store correspondence between string and actual variable
        dictVars = {}  
        dictVars['pre_x']       = lambda preConds,postConds: preConds['x'] 
        dictVars['pre_y']       = lambda preConds,postConds: preConds['y'] 
        dictVars['pre_z']       = lambda preConds,postConds: preConds['z'] 
        dictVars['pre_xnorm']   = lambda preConds,postConds: preConds['xnorm'] 
        dictVars['pre_ynorm']   = lambda preConds,postConds: preConds['ynorm'] 
        dictVars['pre_znorm']   = lambda preConds,postConds: preConds['znorm'] 
        dictVars['post_x']      = lambda preConds,postConds: postConds['x'] 
        dictVars['post_y']      = lambda preConds,postConds: postConds['y'] 
        dictVars['post_z']      = lambda preConds,postConds: postConds['z'] 
        dictVars['post_xnorm']  = lambda preConds,postConds: postConds['xnorm'] 
        dictVars['post_ynorm']  = lambda preConds,postConds: postConds['ynorm'] 
        dictVars['post_znorm']  = lambda preConds,postConds: postConds['znorm'] 
        dictVars['dist_x']      = lambda preConds,postConds: abs(preConds['x'] - postConds['x'])
        dictVars['dist_y']      = lambda preConds,postConds: abs(preConds['y'] - postConds['y']) 
        dictVars['dist_z']      = lambda preConds,postConds: abs(preConds['z'] - postConds['z'])
        dictVars['dist_3D']    = lambda preConds,postConds: sqrt((preConds['x'] - postConds['x'])**2 +
                                (preConds['y'] - postConds['y'])**2 + 
                                (preConds['z'] - postConds['z'])**2)
        dictVars['dist_2D']     = lambda preConds,postConds: sqrt((preConds['x'] - postConds['x'])**2 +
                                (preConds['z'] - postConds['z'])**2)
        dictVars['dist_xnorm']  = lambda preConds,postConds: abs(preConds['xnorm'] - postConds['xnorm'])
        dictVars['dist_ynorm']  = lambda preConds,postConds: abs(preConds['ynorm'] - postConds['ynorm']) 
        dictVars['dist_znorm']  = lambda preConds,postConds: abs(preConds['znorm'] - postConds['znorm'])
        dictVars['dist_norm3D'] = lambda preConds,postConds: sqrt((preConds['xnorm'] - postConds['xnorm'])**2 +
                                sqrt(preConds['ynorm'] - postConds['ynorm']) + 
                                sqrt(preConds['znorm'] - postConds['znorm']))
        dictVars['dist_norm2D'] = lambda preConds,postConds: sqrt((preConds['xnorm'] - postConds['xnorm'])**2 +
                                sqrt(preConds['znorm'] - postConds['znorm']))
        
        # add netParams variables
        for k,v in self.params.__dict__.iteritems():
            if isinstance(v, Number):
                dictVars[k] = v

        # for each parameter containing a function, calculate lambda function and arguments
        for paramStrFunc in paramsStrFunc:
            strFunc = connParam[paramStrFunc]  # string containing function
            strVars = [var for var in dictVars.keys() if var in strFunc and var+'norm' not in strFunc]  # get list of variables used (eg. post_ynorm or dist_xyz)
            lambdaStr = 'lambda ' + ','.join(strVars) +': ' + strFunc # convert to lambda function 
            lambdaFunc = eval(lambdaStr)
       
            # initialize randomizer in case used in function
            seed(sim.id32('%d'%(sim.cfg.seeds['conn'])))

            if paramStrFunc in ['probability']:
                # replace function with dict of values derived from function (one per pre+post cell)
                connParam[paramStrFunc+'Func'] = {(preGid,postGid): lambdaFunc(
                    **{strVar: dictVars[strVar] if isinstance(dictVars[strVar], Number) else dictVars[strVar](preCellTags, postCellTags) for strVar in strVars})  
                    for preGid,preCellTags in preCellsTags.iteritems() for postGid,postCellTags in postCellsTags.iteritems()}

            elif paramStrFunc in ['convergence']:
                # replace function with dict of values derived from function (one per post cell)
                connParam[paramStrFunc+'Func'] = {postGid: lambdaFunc(
                    **{strVar: dictVars[strVar] if isinstance(dictVars[strVar], Number) else dictVars[strVar](None, postCellTags) for strVar in strVars}) 
                    for postGid,postCellTags in postCellsTags.iteritems()}

            elif paramStrFunc in ['divergence']:
                # replace function with dict of values derived from function (one per post cell)
                connParam[paramStrFunc+'Func'] = {preGid: lambdaFunc(
                    **{strVar: dictVars[strVar] if isinstance(dictVars[strVar], Number) else dictVars[strVar](preCellTags, None) for strVar in strVars}) 
                    for preGid, preCellTags in preCellsTags.iteritems()}

            else:
                # store lambda function and func vars in connParam (for weight, delay and synsPerConn since only calculated for certain conns)
                connParam[paramStrFunc+'Func'] = lambdaFunc
                connParam[paramStrFunc+'FuncVars'] = {strVar: dictVars[strVar] for strVar in strVars}