How to use the netpyne.sim.net.cells function in netpyne

To help you get started, we’ve selected a few netpyne 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 / conversion / sonataImport.py View on Github external
for i in range(len(self.conn_info[conn]['pre_id'])):
                pre_id = self.conn_info[conn]['pre_id'][i]
                post_id = self.conn_info[conn]['post_id'][i]
                pre_gid = self.cell_info[pre_node]['gid_from_id'][pre_id] 
                post_gid = self.cell_info[post_node]['gid_from_id'][post_id]


                if post_gid in sim.net.gid2lid:

                    type = self.conn_info[conn]['edge_type_id'][i]

                    print('   Conn: type %s pop %s (id %s) -> pop %s (id %s) MAPPED TO: cell gid %s -> cell gid %s'%(type,pre_node,pre_id,post_node,post_id, pre_gid,post_gid))
                    #print(self.edges_info[conn][type])
                    
                    connParams = {}
                    postCell = sim.net.cells[sim.net.gid2lid[post_gid]]

                    # preGid
                    connParams['preGid'] = pre_gid

                    # synMech
                    connParams['synMech'] = self.edges_info[conn][type]['dynamics_params'].split('.')[0]                
                    
                    # weight
                    sign = syn_dyn_params['sign'] if 'sign' in syn_dyn_params else 1
                    try:
                        weight = self.conn_info[conn]['syn_weight'][i] 
                    except:
                        weight = self.edges_info[conn][type]['syn_weight'] if 'syn_weight' in self.edges_info[conn][type] else 1.0
                    connParams['weight'] = sign*weight
                    
                    # delay
github Neurosim-lab / netpyne / netpyne / sim / setup.py View on Github external
def setupRecordLFP():
    from .. import sim
    from netpyne.support.recxelectrode import RecXElectrode
    
    nsites = len(sim.cfg.recordLFP)
    saveSteps = int(np.ceil(sim.cfg.duration/sim.cfg.recordStep))
    sim.simData['LFP'] = np.zeros((saveSteps, nsites))
    if sim.cfg.saveLFPCells:
        for c in sim.net.cells:
            sim.simData['LFPCells'][c.gid] = np.zeros((saveSteps, nsites))
    
    if not sim.net.params.defineCellShapes: sim.net.defineCellShapes()  # convert cell shapes (if not previously done already)
    sim.net.calcSegCoords()  # calculate segment coords for each cell
    sim.net.recXElectrode = RecXElectrode(sim)  # create exctracellular recording electrode
    
    if sim.cfg.createNEURONObj:
        for cell in sim.net.compartCells:
            nseg = cell._segCoords['p0'].shape[1]
            sim.net.recXElectrode.calcTransferResistance(cell.gid, cell._segCoords)  # transfer resistance for each cell
            cell.imembPtr = h.PtrVector(nseg)  # pointer vector
            cell.imembPtr.ptr_update_callback(cell.setImembPtr)   # used for gathering an array of  i_membrane values from the pointer vector
            cell.imembVec = h.Vector(nseg)

        sim.cvode.use_fast_imem(1)   # make i_membrane_ a range variable
github MetaCell / NetPyNE-UI / netpyne_ui / netpyne_geppetto.py View on Github external
def doIhaveInstOrSimData(self): # return [bool, bool] telling if we have an instance and simulated data
        with redirect_stdout(sys.__stdout__):
            out = [False, False]
            if hasattr(sim, 'net'):
                if hasattr(sim.net, 'cells') and hasattr(sim.net, 'pops'):
                    if len(sim.net.cells)>0 and len(sim.net.pops.keys())>0:
                        out[0] = True
            if hasattr(sim, 'allSimData'):
                if 'spkt' in sim.allSimData.keys() and 'spkid' in sim.allSimData.keys():
                    if len(sim.allSimData['spkt'])>0 and len(sim.allSimData['spkid'])>0:
                        out[1] = True
            
        return {'haveInstance': out[0], 'haveSimData': out[1]}
github Neurosim-lab / netpyne / netpyne / sim / load.py View on Github external
cell.create()
                            sim.cfg.createNEURONObj = createNEURONObjorig
                    except:
                        if sim.cfg.verbose: print(' Unable to load cell secs')

                    try:
                        cell.conns = [Dict(conn) for conn in cellLoad['conns']]
                    except:
                        if sim.cfg.verbose: print(' Unable to load cell conns')

                    try:
                        cell.stims = [Dict(stim) for stim in cellLoad['stims']]
                    except:
                        if sim.cfg.verbose: print(' Unable to load cell stims')

                    sim.net.cells.append(cell)
                print(('  Created %d cells' % (len(sim.net.cells))))
                print(('  Created %d connections' % (sum([len(c.conns) for c in sim.net.cells]))))
                print(('  Created %d stims' % (sum([len(c.stims) for c in sim.net.cells]))))

                # only create NEURON objs, if there is Python struc (fix so minimal Python struct is created)
                if sim.cfg.createNEURONObj:
                    if sim.cfg.verbose: print("  Adding NEURON objects...")
                    # create NEURON sections, mechs, syns, etc; and associate gid
                    for cell in sim.net.cells:
                        prop = {'secs': cell.secs}
                        cell.createNEURONObj(prop)  # use same syntax as when creating based on high-level specs
                        cell.associateGid()  # can only associate once the hSection obj has been created
                    # create all NEURON Netcons, NetStims, etc
                    sim.pc.barrier()
                    for cell in sim.net.cells:
                        try:
github Neurosim-lab / netpyne / netpyne / network.py View on Github external
# apply subcellular connectivity params (distribution of synaspes)
        if self.params.subConnParams:
            self.subcellularConn(allCellTags, allPopTags)
            sim.cfg.createNEURONObj = origCreateNEURONObj # set to original value
            sim.cfg.addSynMechs = origAddSynMechs # set to original value
            cellsUpdate = [c for c in sim.net.cells if c.tags['cellModel'] not in ['NetStim', 'VecStim']]
            if sim.cfg.createNEURONObj:
                for cell in cellsUpdate:
                    # Add synMechs, stim and conn NEURON objects
                    cell.addStimsNEURONObj()
                    #cell.addSynMechsNEURONObj()
                    cell.addConnsNEURONObj()

        nodeSynapses = sum([len(cell.conns) for cell in sim.net.cells]) 
        if sim.cfg.createPyStruct:
            nodeConnections = sum([len(set([conn['preGid'] for conn in cell.conns])) for cell in sim.net.cells])   
        else:
            nodeConnections = nodeSynapses

        print(('  Number of connections on node %i: %i ' % (sim.rank, nodeConnections)))
        if nodeSynapses != nodeConnections:
            print(('  Number of synaptic contacts on node %i: %i ' % (sim.rank, nodeSynapses)))
        sim.pc.barrier()
        sim.timing('stop', 'connectTime')
        if sim.rank == 0 and sim.cfg.timing: print(('  Done; cell connection time = %0.2f s.' % sim.timingData['connectTime']))

        return [cell.conns for cell in self.cells]
github Neurosim-lab / netpyne / netpyne / network.py View on Github external
def defineCellShapes(self):
        from . import sim
        if sim.cfg.createNEURONObj:
            sim.net.compartCells = [c for c in sim.net.cells if type(c) is sim.CompartCell]
            h.define_shape()
            for cell in sim.net.compartCells:
                cell.updateShape()
github Neurosim-lab / netpyne / netpyne / network / conn.py View on Github external
connFunc = getattr(self, connParam['connFunc'])  # get function name from params

        # process string-based funcs and call conn function
        if preCellsTags and postCellsTags:
            # initialize randomizer in case used in string-based function (see issue #89 for more details)
            self.rand.Random123(sim.id32('conn_'+connParam['connFunc']), 
                                sim.id32('%d%d%d%d'%(len(preCellsTags), len(postCellsTags), sum(preCellsTags), sum(postCellsTags))), 
                                sim.cfg.seeds['conn'])
            self._connStrToFunc(preCellsTags, postCellsTags, connParam)  # convert strings to functions (for the delay, and probability params)
            connFunc(preCellsTags, postCellsTags, connParam)  # call specific conn function

        # check if gap junctions in any of the conn rules
        if not gapJunctions and 'gapJunction' in connParam: gapJunctions = True

        if sim.cfg.printSynsAfterRule:
            nodeSynapses = sum([len(cell.conns) for cell in sim.net.cells])
            print(('  Number of synaptic contacts on node %i after conn rule %s: %i ' % (sim.rank, connParamLabel, nodeSynapses)))


    # add presynaptoc gap junctions
    if gapJunctions:
        # distribute info on presyn gap junctions across nodes
        if not getattr(sim.net, 'preGapJunctions', False): 
            sim.net.preGapJunctions = []  # if doesn't exist, create list to store presynaptic cell gap junctions
        data = [sim.net.preGapJunctions]*sim.nhosts  # send cells data to other nodes
        data[sim.rank] = None
        gather = sim.pc.py_alltoall(data)  # collect cells data from other nodes (required to generate connections)
        sim.pc.barrier()
        for dataNode in gather:
            if dataNode: sim.net.preGapJunctions.extend(dataNode)

        # add gap junctions of presynaptic cells (need to do separately because could be in different ranks)
github Neurosim-lab / netpyne / doc / source / code / tut_optimization.py View on Github external
def evaluate_netparams(candidates, args):
    fitnessCandidates = []

    for icand,cand in enumerate(candidates):
        # modify network params based on this candidate params (genes)
        tut2.netParams.connParams['S->M']['probability'] = cand[0]
        tut2.netParams.connParams['S->M']['weight'] = cand[1]
        tut2.netParams.connParams['S->M']['delay'] = cand[2]

        # create network
        sim.createSimulate(netParams=tut2.netParams, simConfig=tut2.simConfig)

        # calculate firing rate
        numSpikes = float(len(sim.simData['spkt']))
        numCells = float(len(sim.net.cells))
        duration = tut2.simConfig.duration/1000.0
        netFiring = numSpikes/numCells/duration

        # calculate fitness for this candidate
        fitness = abs(targetFiring - netFiring)  # minimize absolute difference in firing rate

        # add to list of fitness for each candidate
        fitnessCandidates.append(fitness)

        # print candidate parameters, firing rate, and fitness
        print('\n CHILD/CANDIDATE %d: Network with prob:%.2f, weight:%.2f, delay:%.1f \n  firing rate: %.1f, FITNESS = %.2f \n'\
        %(icand, cand[0], cand[1], cand[2], netFiring, fitness))


    return fitnessCandidates
github Neurosim-lab / netpyne / netpyne / sim / load.py View on Github external
if sim.cfg.verbose: print("  Adding NEURON objects...")
                    # create NEURON sections, mechs, syns, etc; and associate gid
                    for cell in sim.net.cells:
                        prop = {'secs': cell.secs}
                        cell.createNEURONObj(prop)  # use same syntax as when creating based on high-level specs
                        cell.associateGid()  # can only associate once the hSection obj has been created
                    # create all NEURON Netcons, NetStims, etc
                    sim.pc.barrier()
                    for cell in sim.net.cells:
                        try:
                            cell.addStimsNEURONObj()  # add stims first so can then create conns between netstims
                            cell.addConnsNEURONObj()
                        except:
                            if sim.cfg.verbose: ' Unable to load instantiate cell conns or stims'

                    print(('  Added NEURON objects to %d cells' % (len(sim.net.cells))))

            if sim.rank == 0 and sim.cfg.timing:
                sim.timing('stop', 'loadNetTime')
                print(('  Done; re-instantiate net time = %0.2f s' % sim.timingData['loadNetTime']))
    else:
        print(('  netCells and/or netPops not found in file %s'%(filename)))
github Neurosim-lab / netpyne / netpyne / sim / gather.py View on Github external
from .. import sim
        
    sim.timing('start', 'gatherTime')
    ## Pack data from all hosts
    if sim.rank==0:
        print('\nGathering data...')

    # flag to avoid saving sections data for each cell (saves gather time and space; cannot inspect cell secs or re-simulate)
    if not sim.cfg.saveCellSecs:
        for cell in sim.net.cells:
            cell.secs = None
            cell.secLists = None

    # flag to avoid saving conns data for each cell (saves gather time and space; cannot inspect cell conns or re-simulate)
    if not sim.cfg.saveCellConns:
        for cell in sim.net.cells:
            cell.conns = []

    # Store conns in a compact list format instead of a long dict format (cfg.compactConnFormat contains list of keys to include)
    elif sim.cfg.compactConnFormat:
        sim.compactConnFormat()
            
    # remove data structures used to calculate LFP 
    if gatherLFP and sim.cfg.recordLFP and hasattr(sim.net, 'compartCells') and sim.cfg.createNEURONObj:
        for cell in sim.net.compartCells:
            try:
                del cell.imembVec
                del cell.imembPtr
                del cell._segCoords
            except:
                pass
        for pop in list(sim.net.pops.values()):