How to use the netpyne.sim 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 / examples / M1 / M1_export.py View on Github external
import M1  # import parameters file
from netpyne import sim  # import netpyne sim module

np = M1.netParams
print("********************\n*\n*  Note: setting noise to 1, since noise can only be 0 or 1 in NeuroML export currently!\n*\n********************")
np.stimSourceParams['background_E']['noise'] = 1
np.stimSourceParams['background_I']['noise'] = 1

sim.createExportNeuroML2(netParams = np, 
                       simConfig = M1.simConfig,
                       reference = 'M1',
                       connections=True,
                       stimulations=True)  # create and export network to NeuroML 2
github Neurosim-lab / netpyne / examples / HHTut / HHTut_export.py View on Github external
import HHTut  # import parameters file
from netpyne import sim  # import netpyne sim module

np = HHTut.netParams
print("********************\n*\n*  Note: setting noise to 1, since noise can only be 0 or 1 in NeuroML export currently!\n*\n********************")
np.stimSourceParams['bkg']['noise'] = 1

sim.createExportNeuroML2(netParams = np, 
                       simConfig = HHTut.simConfig,
                       reference = 'HHTut')  # create and export network to NeuroML 2
github Neurosim-lab / netpyne / examples / RL_arm / main.py View on Github external
sim.maxPrate = 100

# Motor encoding
sim.nMuscles = 4 # number of muscles
motorGids = [gid for gid,tags in allCellTags.iteritems() if tags['pop'] == 'EM']
cellsPerMuscle = len(motorGids) / sim.nMuscles
sim.motorCmdCellRange = [motorGids[i:i+cellsPerMuscle] for i in xrange(0, len(motorGids), cellsPerMuscle)]  # cell gids of motor output to each muscle
sim.cmdmaxrate = 120  # value to normalize motor command num spikes
sim.cmdtimewin = 50  # window to sum spikes of motor commands
sim.antagInh = 1  # inhibition from antagonic muscle

# RL
sim.useRL = 1
sim.timeoflastRL = -1
sim.RLinterval = 50
sim.minRLerror = 0.002 # minimum error change for RL (m)
sim.targetid = 1 # initial target 
sim.allWeights = [] # list to store weights
sim.weightsfilename = 'weights.txt'  # file to store weights
sim.plotWeights = 1  # plot weights

# Exploratory movements
sim.explorMovs = 1 # exploratory movements (noise to EM pop)
sim.explorMovsRate = 100 # stim max firing rate for motor neurons of specific muscle groups to enforce explor movs
sim.explorMovsDur = 500 # max duration of each excitation to each muscle during exploratory movments init = 1000
sim.timeoflastexplor = -inf # time when last exploratory movement was updated
sim.randseed = 5  # random seed

# reset arm every trial
sim.trialReset = True # whether to reset the arm after every trial time
sim.timeoflastreset = 0 # time when arm was last reseted
github Neurosim-lab / netpyne / netpyne / analysis / interactive.py View on Github external
dpl = {'L2': np.array(sim.simData['dipole']['L2']),
               'L5': np.array(sim.simData['dipole']['L5'])}
        dpl['L2'] -= dpl_offset['L2']

        # L5 dipole offset should be different for interval [50., 500.] and then it can be offset
        # slope (m) and intercept (b) params for L5 dipole offset
        # uncorrected for N_cells
        # these values were fit over the range [37., 750.)
        m = 3.4770508e-3
        b = -51.231085
        # these values were fit over the range [750., 5000]
        t1 = 750.
        m1 = 1.01e-4
        b1 = -48.412078

        t = sim.simData['t']

        # piecewise normalization
        dpl['L5'][t <= 37.] -= dpl_offset['L5']
        dpl['L5'][(t > 37.) & (t < t1)] -= N_pyr * (m * t[(t > 37.) & (t < t1)] + b)
        dpl['L5'][t >= t1] -= N_pyr * (m1 * t[t >= t1] + b1)
        # recalculate the aggregate dipole based on the baseline normalized ones
        dpl['agg'] = dpl['L2'] + dpl['L5']

        return dpl
github Neurosim-lab / netpyne / netpyne / conversion / sonataImport.py View on Github external
#print(self.substitutes)
            #print(self.subs(self.rootFolder + '/' + self.simulation_config['node_sets_file']))
            # TEMPORARY FIX - FIX!
            sim.cfg.node_sets = load_json(self.subs(self.rootFolder+'/'+self.simulation_config['node_sets_file']).replace('$BASE_DIR',''))
        elif 'node_sets' in self.simulation_config:
            sim.cfg.node_sets = self.simulation_config['node_sets']
        # except:
        #     print('Could not load node_sets...')
        #     sim.cfg.node_sets = {}
        
        # inputs - add as 'spkTimes' to external population

        # output
        sim.cfg.log_file = self.simulation_config['output']['log_file']
        sim.cfg.simLabel = os.path.abspath(self.configFile)
        sim.saveFolder = self.simulation_config['output']['output_dir']
        sim.saveJson = True

        # recording
        for k,v in self.simulation_config['reports'].items():
            try:
                sim.cfg.recordTraces[k] = {'sec': v['sections'], 'loc': 0.5, 'var': v['variable_name']}
                sim.cfg.analysis.plotTraces = {'include': sim.cfg.node_sets[v['cells']].values()}  # use 'conds' so works for 'model_type' # UPDATE!
            except:
                pass
github Neurosim-lab / netpyne / netpyne / sim / utils.py View on Github external
def cellByGid (gid):
    from .. import sim

    cell = next((c for c in sim.net.cells if c.gid==gid), None)
    return cell
github Neurosim-lab / netpyne / examples / intervalSaving / M1_run.py View on Github external
def saveAndClear(t):
    df = pd.DataFrame(pd.lib.to_object_array([list(sim.simData['spkt']), list(sim.simData['spkid'])]).transpose(), columns=['spkt', 'spkid'])
    name = 'temp/spk_{:4.0f}.h5'.format(t)
    df.to_hdf(name, 'df')
    sim.simData.update({name:h.Vector(1e4).resize(0) for name in ['spkt','spkid']}) #reinitialize the hoce vectors
    sim.pc.spike_record(-1, sim.simData['spkt'], sim.simData['spkid'])
    del df
    # count spikes then clear them see if it adds up to number
github MetaCell / NetPyNE-UI / netpyne_ui / netpyne_geppetto.py View on Github external
def simulateNetPyNEModelInGeppetto(self, args):
        try:
            with redirect_stdout(sys.__stdout__):
                if args['parallelSimulation']: # TODO mpi is not finding  libmpi.dylib.. set LD_LIBRARY_PATH to openmpi bin folder, but nothing
                    logging.debug('Running parallel simulation')
                    if not 'usePrevInst' in args or not args['usePrevInst']:
                        self.netParams.save("netParams.json")
                        self.simConfig.saveJson = True
                        self.simConfig.save("simParams.json")
                        template = os.path.join(os.path.dirname(__file__), 'template.py')
                    else:
                        sim.cfg.saveJson = True
                        oldName = sim.cfg.filename
                        sim.cfg.filename = 'model_output'
                        sim.saveData()
                        sim.cfg.filename = oldName
                        template = os.path.join(os.path.dirname(__file__), 'template2.py')
                    copyfile(template, './init.py')
                    
                    cp = subprocess.run(["mpiexec", "-n", args['cores'], "nrniv", "-mpi", "-python", "init.py"], capture_output=True)
                    print(cp.stdout.decode()+cp.stderr.decode())
                    if cp.returncode!=0: return utils.getJSONError("Error while simulating the NetPyNE model", cp.stderr.decode())
                    sim.load('model_output.json')
                    self.geppetto_model = self.model_interpreter.getGeppettoModel(sim)
                    netpyne_model = sim
                    
                else: # single cpu computation
                    if not 'usePrevInst' in args or not args['usePrevInst']:
                        logging.debug('Instantiating single thread simulation')
github Neurosim-lab / netpyne / doc / source / code / hopbrodnetpyne.py View on Github external
def create ():
  global pops,cells
  sim.initialize(netParams, simConfig)
  pops = sim.net.createPops()                      # instantiate network populations
  cells = sim.net.createCells()                     # instantiate network cells based on defined populations
  sim.net.addStims()
  sim.net.connectCells()                    # create connections between cells based on params
  sim.setupRecording()                      # setup variables to record for each cell (spikes, V traces, etc)

def run (): sim.simulate()
def plot (): sim.analysis.plotData()


create()
run()
sim.analysis.plotRaster()
sim.analysis.plotRaster(syncLines=True)
sim.analysis.plotData()

sim.net.modifyConns({'conds': {'label': 'hop->hop'}, 'weight': 0.5}) # increase inh conns weight increase sync