Ejemplo n.º 1
0
def plotstuff(cell, electrode):

    figure = mlab.figure(size=(800,800))
    
    l_list = []
    for sec in neuron.h.allsec():
        idx = cell.get_idx_section(sec.name())
        j = 0
        for seg in sec:
            i = idx[j]
            x = pl.array([cell.xstart[i],cell.xend[i]])
            y = pl.array([cell.ystart[i],cell.yend[i]])
            z = pl.array([cell.zstart[i],cell.zend[i]])
            s = pl.array([seg.v, seg.v])
            
            l = mlab.plot3d(x, y, z, s, colormap = 'Spectral',
                            tube_radius=cell.diam[i],
                            representation='surface', vmin=-70, vmax=10)
            l_list.append(l)
            print j
            j += 1
    
    t0 = time()
    ipdb.set_trace()    
    #ms = l_list[0].mlab_source
    while time()-t0 < 10:
        for l in l_list:
            ms = l.mlab_source
            s = pl.rand()*80 -70
            scalars = pl.array([s, s])
            ms.set(scalars = scalars)
Ejemplo n.º 2
0
 def createCellsFixedNum(self):
     ''' Create population cells based on fixed number of cells'''
     cellModelClass = f.Cell
     cells = []
     seed(f.sim.id32('%d'%(f.cfg['seeds']['loc']+self.tags['numCells']+f.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) / f.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(f.rank), f.net.params['scale'] * self.tags['numCells'], f.nhosts):
         gid = f.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 f.net.params['popTagsCopiedToCells']}  # copy all pop tags to cell tags, except those that are pop-specific
         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'] = f.net.params['sizeX'] * randLocs[i,0] # set x location (um)
         cellTags['y'] = f.net.params['sizeY'] * randLocs[i,1] # set y location (um)
         cellTags['z'] = f.net.params['sizeZ'] * randLocs[i,2] # set z location (um)
         if 'propList' not in cellTags: cellTags['propList'] = []  # initalize list of property sets if doesn't exist
         cells.append(cellModelClass(gid, cellTags)) # instantiate Cell object
         if f.cfg['verbose']: print('Cell %d/%d (gid=%d) of pop %s, on node %d, '%(i, f.net.params['scale'] * self.tags['numCells']-1, gid, self.tags['popLabel'], f.rank))
     f.net.lastGid = f.net.lastGid + self.tags['numCells'] 
     return cells
Ejemplo n.º 3
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
Ejemplo n.º 4
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
Ejemplo n.º 5
0
def harmonics(afun=lambda x: pylab.exp(-0.5 * x),
              pfun=lambda x: pylab.rand() * 2 * pylab.pi,
              **params):
    """
    ::

        Generate a harmonic series using a harmonic weighting function
         afun   - lambda function of one parameter (harmonic index) returning a weight
         pfun   - lambda function of one parameter (harmonic index) returning radian phase offset
         **params - signal_params dict, see default_signal_params()
    """
    params = _check_signal_params(**params)
    f0 = params['f0']
    x = pylab.zeros(params['num_points'])
    for i in pylab.arange(1, params['num_harmonics'] + 1):
        params['f0'] = i * f0
        params['phase_offset'] = pfun(i)
        x += afun(i) * sinusoid(**params)
    x = balance_signal(x, 'maxabs')
    return x
Ejemplo n.º 6
0
#!/usr/bin/env python
# Licensed under a 3-clause BSD style license - see LICENSE.rst

import numpy as np
from matplotlib import pylab
from Ska.Matplotlib import hist_outline

if __name__ == "__main__":
    binsIn = np.arange(0, 1, 0.1)
    angle = pylab.rand(50)

    pylab.subplot(121)
    pylab.hist(angle,binsIn)
    pylab.title("regular histogram")
    pylab.axis(xmax=1.0)

    pylab.subplot(122)

    (bins, data) = hist_outline(angle, binsIn)
    pylab.plot(bins, data, 'k-', linewidth=2)
    pylab.title("hist_outline Demo")
    pylab.show()


Ejemplo n.º 7
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
Ejemplo n.º 8
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
Ejemplo n.º 9
0
    def createCellsDensity(self):
        ''' Create population cells based on density'''
        cellModelClass = f.Cell
        cells = []
        volume =  f.net.params['sizeY']/1e3 * f.net.params['sizeX']/1e3 * f.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 / f.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(f.sim.id32('%d' % f.cfg['seeds']['loc']))  # 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 f.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(f.sim.id32('%d'%(f.cfg['seeds']['loc']+self.tags['numCells'])))
        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 f.cfg['verbose'] and not funcLocs: print 'Volume=%.4f, density=%.2f, numCells=%.0f'%(volume, self.tags['density'], self.tags['numCells'])


        for i in xrange(int(f.rank), self.tags['numCells'], f.nhosts):
            gid = f.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 f.net.params['popTagsCopiedToCells']}  # copy all pop tags to cell tags, except those that are pop-specific
            cellTags['xnorm'] = randLocs[i,0]  # calculate x location (um)
            cellTags['ynorm'] = randLocs[i,1]  # calculate x location (um)
            cellTags['znorm'] = randLocs[i,2]  # calculate z location (um)
            cellTags['x'] = f.net.params['sizeX'] * randLocs[i,0]  # calculate x location (um)
            cellTags['y'] = f.net.params['sizeY'] * randLocs[i,1]  # calculate x location (um)
            cellTags['z'] = f.net.params['sizeZ'] * randLocs[i,2]  # calculate z location (um)
            if 'propList' not in cellTags: cellTags['propList'] = []  # initalize list of property sets if doesn't exist
            cells.append(cellModelClass(gid, cellTags)) # instantiate Cell object
            if f.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['ynorm'], cellTags['z'], f.rank))
        f.net.lastGid = f.net.lastGid + self.tags['numCells'] 
        return cells
Ejemplo n.º 10
0
def metric():
    return 0.9*pl.rand(N)
Ejemplo n.º 11
0
#def f():
#    print args.param

#f(velocity = 2)


#from pylab import *
y =[[0.03, 0.86, 0.65, 0.34, 0.34, 0.02, 0.22, 0.74, 0.66, 0.65],
    [0.43, 0.18, 0.63, 0.29, 0.03, 0.24, 0.86, 0.07, 0.58, 0.55],
    [0.66, 0.75, 0.01, 0.94, 0.72, 0.77, 0.20, 0.66, 0.81, 0.52]]

#print len(y[0])
#print len(x)

N = 10
x = 0.9*pl.rand(N)

area = pl.pi*(10 * pl.rand(N))**2 # 0 to 10 point radiuses
fig = pl.figure()
window = fig.add_subplot(111)
sca = window.scatter(x,y[0],s=30,c=area)

def metric():
    return 0.9*pl.rand(N)

def update(data):
    path = sca.get_paths()
    print "BKN"
    #for pro, value in vars(sca).iteritems():
    #    print pro, ": ", value
    
Ejemplo n.º 12
0
        if bb < len(histIn):
            data[2*bb + 1] = histIn[bb]
            data[2*bb + 2] = histIn[bb]

    bins[0] = bins[1]
    bins[-1] = bins[-2]
    data[0] = 0
    data[-1] = 0
    
    return (bins, data)



if __name__ == "__main__":
    binsIn = np.arange(0, 1, 0.1)
    angle = pylab.rand(50)

    pylab.subplot(121)
    pylab.hist(angle,binsIn)
    pylab.title("regular histogram")
    pylab.axis(xmax=1.0)

    pylab.subplot(122)

    (bins, data) = histOutline(angle, binsIn)
    pylab.plot(bins, data, 'k-', linewidth=2)
    pylab.title("histOutline Demo")
    pylab.show()


Ejemplo n.º 13
0
from keras.regularizers import l2
from keras.layers \
    import Input, Dense, Conv1D, Dropout, Activation, \
    TimeDistributed, add, multiply, Lambda
from keras import backend as KB
from keras.losses import mean_squared_error, mean_absolute_error
from soundfile import read, write
from scipy.signal import resample_poly
from datetime import datetime
import os
import errno

NOW = datetime.now().strftime("%B_%d_%Y_at_%I%M%p")

print("Starting...")
seed = int(10e7 * P.rand())
num_filts = 100  # Number of filters for the conv layers
K = 3  # Number of Dilation layers
D = 9  # Dilation fold (number of dilations per dilation layer).
# dilate by factor of 2**D
dil_reg = 1e-4  # regularization for dilated conv layer
reg_out = 1e-5  # regularization for output relu's
batch_size = 8
samps = 2000  # Number of valid samps per sequence
stride = 600  # hop size
iSNR = 0.01  # inverse signal to noise ratio. basically, volume
# of noise added to input
desired_sr = 16000  # signals are resampled to this rate
mu = 256  # quantization level
C = 400  # number of chunks
drop_prob = 0.1  # Dropout probability for pre-output layer