def test_ConnectPrePostParams(self): """Connect pre to post with a params dict""" # Connect([pre], [post], params) nest.ResetKernel() pre = nest.Create("iaf_neuron", 2) post = nest.Create("iaf_neuron", 2) nest.Connect(pre, post, {"weight": 2.0}) connections = nest.FindConnections(pre) weights = nest.GetStatus(connections, "weight") self.assertEqual(weights, [2.0, 2.0]) # Connect([pre], [post], [params]) nest.ResetKernel() pre = nest.Create("iaf_neuron", 2) post = nest.Create("iaf_neuron", 2) nest.Connect(pre, post, [{"weight": 2.0}]) connections = nest.FindConnections(pre) weights = nest.GetStatus(connections, "weight") self.assertEqual(weights, [2.0, 2.0]) # Connect([pre], [post], [params, params]) nest.ResetKernel() pre = nest.Create("iaf_neuron", 2) post = nest.Create("iaf_neuron", 2) nest.Connect(pre, post, [{"weight": 2.0}, {"weight": 3.0}]) connections = nest.FindConnections(pre) weights = nest.GetStatus(connections, "weight") self.assertEqual(weights, [2.0, 3.0])
def test_ConnectPrePostWD(self): """Connect pre to post with a weight and delay""" # Connect([pre], [post], w, d) nest.ResetKernel() pre = nest.Create("iaf_neuron", 2) post = nest.Create("iaf_neuron", 2) nest.Connect(pre, post, 2.0, 2.0) connections = nest.FindConnections(pre) weights = nest.GetStatus(connections, "weight") self.assertEqual(weights, [2.0, 2.0]) # Connect([pre], [post], [w], [d]) nest.ResetKernel() pre = nest.Create("iaf_neuron", 2) post = nest.Create("iaf_neuron", 2) nest.Connect(pre, post, [2.0], [2.0]) connections = nest.FindConnections(pre) weights = nest.GetStatus(connections, "weight") delays = nest.GetStatus(connections, "delay") self.assertEqual(weights, [2.0, 2.0]) self.assertEqual(delays, [2.0, 2.0]) # Connect([pre], [post], [w, w], [d, d]) nest.ResetKernel() pre = nest.Create("iaf_neuron", 2) post = nest.Create("iaf_neuron", 2) nest.Connect(pre, post, [2.0, 3.0], [2.0, 3.0]) connections = nest.FindConnections(pre) weights = nest.GetStatus(connections, "weight") delays = nest.GetStatus(connections, "delay") self.assertEqual(weights, [2.0, 3.0]) self.assertEqual(delays, [2.0, 3.0])
def from_device(detec, title=None, hist=False, hist_binwidth=5.0, grayscale=False, plot_lid=False): """ Plot raster from spike detector """ if not nest.GetStatus(detec)[0]["model"] == "spike_detector": raise nest.NESTError("Please provide a spike_detector.") if nest.GetStatus(detec, "to_memory")[0]: ts, gids = _from_memory(detec) if not len(ts): raise nest.NESTError("No events recorded!") if plot_lid: gids = [nest.GetLID([x]) for x in gids] if title is None: title = "Raster plot from device '%i'" % detec[0] if nest.GetStatus(detec)[0]["time_in_steps"]: xlabel = "Steps" else: xlabel = "Time (ms)" return _make_plot(ts, ts, gids, gids, hist, hist_binwidth, grayscale, title, xlabel) elif nest.GetStatus(detec, "to_file")[0]: fname = nest.GetStatus(detec, "filenames")[0] return from_file(fname, title, hist, hist_binwidth, grayscale) else: raise nest.NESTError("No data to plot. Make sure that either to_memory or to_file are set.")
def test_ModelDicts(self): """sample_neuron Creation with N and dicts""" cynest.ResetKernel() V_m = [0.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.] n = cynest.Create("sample_neuron", 10, [{'V_m': v} for v in V_m]) self.assertEqual(cynest.GetStatus(n, 'V_m'), V_m) self.assertEqual([key['V_m'] for key in cynest.GetStatus(n)], V_m)
def test_ModelDict(self): """sample_neuron Creation with N and dict""" cynest.ResetKernel() n = cynest.Create("sample_neuron", 10, [{'V_m': 12.0}]) V_m = [12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0] self.assertEqual(cynest.GetStatus(n, 'V_m'), V_m) self.assertEqual([key['V_m'] for key in cynest.GetStatus(n)], V_m)
def test_GetStatus(self): """GetStatus""" m = "sample_neuron" cynest.ResetKernel() n = cynest.Create(m) d = cynest.GetStatus(n) v1 = cynest.GetStatus(n)[0]['param'] v2 = cynest.GetStatus(n, 'param')[0] self.assertEqual(v1, v2) n = cynest.Create(m, 10) self.assertEqual(len(cynest.GetStatus(n, 'param')), 10)
def connPlot(spop, smod, tmod, syn, titl): '''Plot connections. spop, smod source population and model tmod target model syn synapse type titl figure title''' # center location, cast to int since ``pyreport`` makes all div double ctr = [int(Params["N"] / 2), int(Params["N"] / 2)] # get element at center src = topo.GetElement(spop, ctr) # if center element is not individual neuron, find one # neuron of desired model in center element if nest.GetStatus(src, 'model')[0] == 'subnet': src = [ n for n in nest.GetLeaves(src)[0] if nest.GetStatus([n], 'model')[0] == smod ][:1] # get position (in degrees) of chosen source neuron srcpos = topo.GetPosition(src) # get all targets tgts = nest.GetConnections(src, syn)[0]['targets'] # pick targets of correct model type, get their positions, # convert list of (x,y) pairs to pair of x- and y-lists pos = zip(*[ topo.GetPosition([n]) for n in tgts if nest.GetStatus([n], 'model')[0] == tmod ]) # plot source neuron in red, slightly larger, targets on blue pylab.clf() pylab.plot(pos[0], pos[1], 'bo', markersize=5, zorder=99, label='Targets') pylab.plot(srcpos[:1], srcpos[1:], 'ro', markersize=10, markeredgecolor='r', zorder=1, label='Source') axsz = Params['visSize'] / 2 + 0.2 pylab.axis([-axsz, axsz, -axsz, axsz]) pylab.title(titl) pylab.legend() # pylab.show() required for `pyreport` pylab.show()
def test_DivergentConnectWD(self): """DivergentConnect pre to post with weight and delay""" nest.ResetKernel() pre = nest.Create("iaf_neuron", 1) post = nest.Create("iaf_neuron", 3) nest.DivergentConnect(pre, post, weight=[2.0, 2.0, 2.0], delay=[1.0, 2.0, 3.0]) connections = nest.FindConnections(pre) weights = nest.GetStatus(connections, "weight") delays = nest.GetStatus(connections, "delay") self.assertEqual(weights, [2.0, 2.0, 2.0]) self.assertEqual(delays, [1.0, 2.0, 3.0])
def test_Events_1(self): """Recorder Events""" nest.ResetKernel() sd = nest.Create('spike_detector', 1, {'withtime': True}) d = nest.GetStatus(sd, 'events')[0] senders = d['senders'] times = d['times'] vm = nest.Create('voltmeter', 1, {'withtime': True}) d = nest.GetStatus(vm, 'events')[0] senders = d['V_m'] times = d['times']
def test_ParamTypes(self): """Test of all parameter types""" cynest.ResetKernel() node = cynest.Create("sample_neuron") cynest.SetStatus(node, {"param1":2, "param2":6.5, "param3": True, "param4":"sd", "param5":'r', \ "param6":[1,2,3,4], "param7":{"c1":1, "c2":2}, "param8":{"e1":{"s1":1}}}) cynest.Simulate(1) s = cynest.GetStatus(node)[0] self.assertEqual(s["param1"], 2) self.assertEqual(s["param2"], 6.5) self.assertEqual(s["param3"], True) self.assertEqual(s["param4"], "sd") self.assertEqual(s["param5"], 'r') self.assertEqual(s["param6"][0], 1) self.assertEqual(s["param6"][1], 2) self.assertEqual(s["param6"][2], 3) self.assertEqual(s["param6"][3], 4) self.assertEqual(s["param7"]["c1"], 1) self.assertEqual(s["param7"]["c2"], 2) self.assertEqual(s["param8"]["e1"]["s1"], 1)
def test_CopyModel(self): """CopyModel""" cynest.ResetKernel() cynest.CopyModel("sample_neuron", 'new_neuron', {'V_m': 10.0}) vm = cynest.GetDefaults('new_neuron')['V_m'] self.assertEqual(vm, 10.0) n = cynest.Create('new_neuron', 10) vm = cynest.GetStatus([n[0]])[0]['V_m'] self.assertEqual(vm, 10.0) cynest.CopyModel('static_synapse', 'new_synapse', {'weight': 10.}) cynest.Connect([n[0]], [n[1]], model='new_synapse') w = cynest.GetDefaults('new_synapse')['weight'] self.assertEqual(w, 10.0) try: cynest.CopyModel( "sample_neuron", 'new_neuron') # shouldn't be possible a second time self.fail('an error should have risen!') # should not be reached except: info = sys.exc_info()[1] if not "NewModelNameExists" in info.__str__(): self.fail('could not pass error message to cynest!')
def output_rate(guess): print "Inhibitory rate estimate: %5.2f Hz ->" % guess, rate = float(abs(n_in * guess)) nest.SetStatus([noise[1]], "rate", rate) nest.SetStatus(spikedetector, "n_events", 0) nest.Simulate(t_sim) out = nest.GetStatus(spikedetector, "n_events")[0] * 1000.0 / t_sim print "Neuron rate: %6.2f Hz (goal: %4.2f Hz)" % (out, r_ex) return out
def test_SetStatusParam(self): """SetStatus with parameter""" m = "sample_neuron" cynest.ResetKernel() n = cynest.Create(m) cynest.SetStatus(n, 'V_m', 3.) self.assertEqual(cynest.GetStatus(n, 'V_m')[0], 3.)
def test_SetStatusList(self): """SetStatus with list""" m = "sample_neuron" cynest.ResetKernel() n = cynest.Create(m) cynest.SetStatus(n, [{'V_m': 2.}]) self.assertEqual(cynest.GetStatus(n, 'V_m')[0], 2.)
def test_SetStatus(self): """SetStatus with dict""" m = "sample_neuron" cynest.ResetKernel() n = cynest.Create(m) cynest.SetStatus(n, {'V_m': 1.}) self.assertEqual(cynest.GetStatus(n, 'V_m')[0], 1.)
def test_DivergentConnect(self): """DivergentConnect pre to post""" nest.ResetKernel() pre = nest.Create("iaf_neuron", 1) post = nest.Create("iaf_neuron", 3) nest.DivergentConnect(pre, post) connections = nest.FindConnections(pre) targets = nest.GetStatus(connections, "target") self.assertEqual(targets, post)
def test_ModelCreateSimulate(self): """Model Creation and Simulation""" cynest.ResetKernel() cynest.SetDefaults("sample_neuron", {"param": 20}) node = cynest.Create("sample_neuron") cynest.Simulate(1) self.assertEqual(cynest.GetStatus(node)[0]["param"], 30)
def test_ConnectPrePost(self): """Connect pre to post""" # Connect([pre], [post]) nest.ResetKernel() pre = nest.Create("iaf_neuron", 2) post = nest.Create("iaf_neuron", 2) nest.Connect(pre, post) connections = nest.FindConnections(pre) targets = nest.GetStatus(connections, "target") self.assertEqual(targets, post)
def test_ConvergentConnect(self): """ConvergentConnect pre to post""" nest.ResetKernel() pre = nest.Create("iaf_neuron", 3) post = nest.Create("iaf_neuron", 1) nest.ConvergentConnect(pre, post) expected_targets = [post[0] for x in range(len(pre))] connections = nest.FindConnections(pre) targets = nest.GetStatus(connections, "target") self.assertEqual(expected_targets, targets)
def output_rate(self,mean, std): t=nest.GetKernelStatus('time') if t>100000: # prevent overflow of clock self.build() self.connect() t=0.0 nest.Simulate(self.t_inter_trial) nest.SetStatus(self.spike, "n_events", 0) nest.SetStatus(self.noise,[{'mean':mean, 'std':std, 'start': 0.0, 'stop': 1000., 'origin':t}]) nest.Simulate(self.t_sim) rate=nest.GetStatus(self.spike, "n_events")[0]*1000.0/(self.n_neurons*self.t_sim) return rate
def test_BeginEndSubnet(self): """Begin/End Subnet""" nest.ResetKernel() nest.BeginSubnet() sn = nest.EndSubnet() nest.BeginSubnet(label='testlabel') sn = nest.EndSubnet() self.assertEqual(nest.GetStatus(sn, 'label')[0], 'testlabel')
def test_ThreadsGetEvents(self): """ Gathering events across threads """ # Test if we have a thread-enabled NEST nest.sr("statusdict /have_pthreads get") if not nest.spp(): return threads = [1, 2, 4, 8] n_events_sd = [] n_events_vm = [] N = 128 Simtime = 1000. for t in threads: nest.ResetKernel() nest.SetKernelStatus({'local_num_threads': t}) n = nest.Create('iaf_psc_alpha', N, {'I_e': 2000.}) # force a lot of spike events sd = nest.Create('spike_detector') vm = nest.Create('voltmeter') nest.ConvergentConnect(n, sd) nest.DivergentConnect(vm, n) nest.Simulate(Simtime) n_events_sd.append(nest.GetStatus(sd, 'n_events')[0]) n_events_vm.append(nest.GetStatus(vm, 'n_events')[0]) ref_vm = N * (Simtime - 1) ref_sd = n_events_sd[0] # could be done more elegantly with any(), ravel(), # but we dont want to be dependent on numpy et al [self.assertEqual(x, ref_vm) for x in n_events_vm] [self.assertEqual(x, ref_sd) for x in n_events_sd]
def test_SetStatusVth_E_L(self): """SetStatus of reversal and threshold potential """ m = "sample_neuron" cynest.ResetKernel() neuron1 = cynest.Create(m) neuron2 = cynest.Create(m) # must not depend on the order. new_EL = -90. new_Vth = -10. cynest.SetStatus(neuron1, {'E_L': new_EL}) cynest.SetStatus(neuron2, {'V_th': new_Vth}) cynest.SetStatus(neuron1, {'V_th': new_Vth}) cynest.SetStatus(neuron2, {'E_L': new_EL}) # next three lines for debugging vth1, vth2 = cynest.GetStatus(neuron1, 'V_th'), cynest.GetStatus( neuron2, 'V_th') if vth1 != vth2: print(m, vth1, vth2, cynest.GetStatus(neuron1, 'E_L'), cynest.GetStatus(neuron2, 'E_L')) assert (cynest.GetStatus(neuron1, 'V_th') == cynest.GetStatus(neuron2, 'V_th'))
def run(self, neuronName, simtime=40.): """ Simulate the model for simtime milliseconds and print the firing rates of the network during htis period. """ if not self.connected: self.connect(neuronName) cynest.Simulate(simtime) events = cynest.GetStatus(self.spikes, "n_events") self.rate_ex = events[0] / simtime * 1000.0 / self.N_rec print "Excitatory rate : %.2f Hz" % self.rate_ex self.rate_in = events[1] / simtime * 1000.0 / self.N_rec print "Inhibitory rate : %.2f Hz" % self.rate_in
def test_DivergentConnect(self): """DivergentConnect""" cynest.ResetKernel() a=cynest.Create("iaf_neuron", 10) source=[1] targets=[1 * x for x in list(range(2,11))] cynest.DivergentConnect(source, targets, [1.0], [1.0]) conn1=cynest.GetConnections(source) stat1=cynest.GetStatus(conn1) target1=[ d['target'] for d in stat1] self.assertEqual(targets, target1)
def test_ConvergentConnect(self): """ConvergentConnect""" cynest.ResetKernel() a=cynest.Create("iaf_neuron", 10) target=[1] sources=[1 * x for x in list(range(2,11))] cynest.ConvergentConnect(sources, target, [1.0], [1.0]) conn1=cynest.GetConnections(sources) stat1=cynest.GetStatus(conn1) target1=[ d['source'] for d in stat1] self.assertEqual(sources, target1)
def _from_memory(detec): import array ev = nest.GetStatus(detec, 'events')[0] potentials = ev['V_m'] senders = ev['senders'] v = {} t = {} if 'times' in ev: times = ev['times'] for s, currentsender in enumerate(senders): if currentsender not in v: v[currentsender] = array.array('f') t[currentsender] = array.array('f') v[currentsender].append(float(potentials[s])) t[currentsender].append(float(times[s])) else: # reconstruct the time vector, if not stored explicitly detec_status = nest.GetStatus(detec)[0] origin = detec_status['origin'] start = detec_status['start'] interval = detec_status['interval'] senders_uniq = numpy.unique(senders) num_intvls = len(senders) / len(senders_uniq) times_s = origin + start + interval + interval * numpy.array( list(range(num_intvls))) for s, currentsender in enumerate(senders): if currentsender not in v: v[currentsender] = array.array('f') t[currentsender] = times_s v[currentsender].append(float(potentials[s])) return t, v
def test_Threads(self): """Multiple threads""" # Test if we have a thread-enabled NEST nest.sr("statusdict /have_pthreads get") if not nest.spp(): return nest.ResetKernel() self.assertEqual(nest.GetKernelStatus()['local_num_threads'], 1) nest.SetKernelStatus({'local_num_threads': 8}) n = nest.Create('iaf_neuron', 8) st = nest.GetStatus(n, 'vp') st.sort() self.assertEqual(st, [0, 1, 2, 3, 4, 5, 6, 7])
def test_DataConnect2(self): """DataConnect""" cynest.ResetKernel() a=cynest.Create("iaf_neuron", 100000) sources=[1] target=[x for x in list(range(2,100000))] weight=[2.0 * x for x in target] delay=[1.0 * x for x in target] connections=[{'target':target, 'weight':weight, 'delay':delay} for t in target ] cynest.DataConnect(sources,connections, "static_synapse", 2) conn1=cynest.GetConnections(sources) stat1=cynest.GetStatus(conn1) target1=[ d['target'] for d in stat1] self.assertEqual(target, target1)
def test_EventsVoltage(self): """Voltage Events""" nest.ResetKernel() nest.sr('20 setverbosity') n = nest.Create('iaf_neuron') vm = nest.Create('voltmeter', 1, {'withtime': True, 'interval': 1.}) nest.Connect(vm, n) nest.SetKernelStatus({'print_time': False}) nest.Simulate(10) d = nest.GetStatus(vm, 'events')[0] self.assertEqual(len(d['V_m']), 9)