def test_HH(): cc = ninemlcatalog.load('/neuron/HodgkinHuxley', 'HodgkinHuxley') comp = ninemlcatalog.load('neuron/HodgkinHuxley', 'SampleHodgkinHuxley') # Convert to PyDSTool.ModelSpec and create NonHybridModel object # Provide extra parameter Isyn which is missing from component definition # in absence of any synaptic inputs coupled to the model membrane HHmodel = get_nineml_model(cc, 'HH_9ML', extra_args=[Par('isyn')]) pars = dict((p.name, p.value) for p in comp.properties) pars['isyn'] = 20.0 ics = dict((i.name, i.value) for i in comp.initial_values) HHmodel.set(pars=pars, ics=ics, tdata=[0, 15]) HHmodel.compute('HHtest', force=True) pts = HHmodel.sample('HHtest') plt.figure(1) plt.plot(pts['t'], pts['V'], 'k') plt.title('Hodgkin-Huxley membrane potential') ev_info = pts.labels.by_label['Event:spikeoutput'] for ev_ix, ev_tdata in list(ev_info.items()): plt.plot(ev_tdata['t'], pts[ev_ix]['V'], 'ko') plt.xlabel('t') plt.ylabel('V')
def test_izhiFS(self, plot=False, print_comparisons=False, simulators=['nest', 'neuron'], dt=0.001, duration=100.0, build_mode='force', **kwargs): # @UnusedVariable # Force compilation of code generation # Perform comparison in subprocess comparer = Comparer( nineml_model=ninemlcatalog.load( 'neuron/Izhikevich', 'IzhikevichFastSpiking'), state_variable='V', dt=dt, simulators=simulators, properties=ninemlcatalog.load( 'neuron/Izhikevich', 'SampleIzhikevichFastSpiking'), initial_states={'U': -1.625 * pq.pA, 'V': -65.0 * pq.mV}, input_signal=input_step('iSyn', 100 * pq.pA, 25.0, 100, dt), initial_regime='subVb', neuron_build_args={'build_mode': build_mode, 'external_currents': ['iSyn']}, nest_build_args={'build_mode': build_mode}) #, auxiliary_states=['U']) # @IgnorePep8 comparer.simulate(duration, nest_rng_seed=NEST_RNG_SEED, neuron_rng_seed=NEURON_RNG_SEED) comparisons = comparer.compare() if print_comparisons: for (name1, name2), diff in comparisons.iteritems(): print '{} v {}: {}'.format(name1, name2, diff) if plot: comparer.plot() if 'nest' in simulators and 'neuron' in simulators: self.assertLess( comparisons[('9ML-nest', '9ML-neuron')], 0.4 * pq.mV, "Izhikevich 2007 NEURON 9ML simulation did not match NEST 9ML")
def test_aeIF(): """Adaptive Integrate and Fire""" cc = ninemlcatalog.load('/neuron/AdaptiveExpIntegrateAndFire', 'AdaptiveExpIntegrateAndFire') comp = ninemlcatalog.load('/neuron/AdaptiveExpIntegrateAndFire', 'SampleAdaptiveExpIntegrateAndFire') # Convert to PyDSTool.ModelSpec and create HybridModel object # Provide extra parameter Isyn which is missing from component definition # in absence of any synaptic inputs coupled to the model membrane aeIF = get_nineml_model(cc, 'aeIF_9ML', extra_args=[Par('Isyn')], max_t=100) pars = dict((p.name, p.value) for p in comp.properties) pars['Isyn'] = 5.0 ics = dict((i.name, i.value) for i in comp.initial_values) ics['regime_'] = 0 aeIF.set(pars=pars, ics=ics, tdata=[0, 30], algparams={'init_step': 0.04}) aeIF.compute('test', verboselevel=0) pts = aeIF.sample('test', dt=0.1) plt.figure(2) plt.plot(pts['t'], pts['V']) plt.xlabel('t') plt.ylabel('V') plt.title('adaptive IF model') plt.figure(3) plt.plot(pts['t'], pts['w']) plt.xlabel('t') plt.ylabel('w') plt.title('adaptive IF model')
def test_Izh(): """Basic Izhikevich hybrid model""" cc = ninemlcatalog.load('/neuron/Izhikevich', 'Izhikevich') comp = ninemlcatalog.load('/neuron/Izhikevich', 'SampleIzhikevich') # Convert to PyDSTool.ModelSpec and create HybridModel object # Provide extra parameter Isyn which is missing from component definition # in absence of any synaptic inputs coupled to the model membrane izh = get_nineml_model(cc, 'izh_9ML', extra_args=[Par('Isyn')], max_t=100) pars = dict((p.name, p.value) for p in comp.properties) pars['Isyn'] = 20.0 ics = dict((i.name, i.value) for i in comp.initial_values) ics['regime_'] = 0 izh.set(pars=pars, ics=ics, tdata=[0, 80], algparams={'init_step': 0.04}) izh.compute('test', verboselevel=0) pts = izh.sample('test') evs = izh.getTrajEventTimes('test')['spike'] theta = izh.query('pars')['theta'] plt.figure(4) plt.plot(pts['t'], pts['V'], 'k') plt.plot(evs, [theta] * len(evs), 'ko') plt.title('Izhikevich model') plt.xlabel('t') plt.ylabel('V') plt.figure(5) plt.plot(pts['t'], pts['U']) plt.xlabel('t') plt.ylabel('U') plt.title('Izhikevich model')
def setUp(self): # Perform comparison in subprocess iaf = ninemlcatalog.load( 'neuron/LeakyIntegrateAndFire#PyNNLeakyIntegrateAndFire') alpha_psr = ninemlcatalog.load( 'postsynapticresponse/Alpha#PyNNAlpha') static = ninemlcatalog.load( 'plasticity/Static', 'Static') iaf_alpha = MultiDynamics( name='IafAlpha', sub_components={ 'cell': iaf, 'syn': MultiDynamics( name="IafAlaphSyn", sub_components={'psr': alpha_psr, 'pls': static}, port_connections=[ ('pls', 'fixed_weight', 'psr', 'q')], port_exposures=[('psr', 'i_synaptic'), ('psr', 'spike')])}, port_connections=[ ('syn', 'i_synaptic__psr', 'cell', 'i_synaptic')], port_exposures=[('syn', 'spike__psr', 'spike')]) self.model = WithSynapses.wrap( iaf_alpha, connection_parameter_sets=[ ConnectionParameterSet( 'spike', [iaf_alpha.parameter('weight__pls__syn')])])
def test_liaf(self, plot=PLOT_DEFAULT, print_comparisons=False, simulators=SIMULATORS_TO_TEST, dt=0.001, duration=100.0, build_mode=BUILD_MODE_DEFAULT, **kwargs): # @UnusedVariable # Perform comparison in subprocess comparer = Comparer( nineml_model=ninemlcatalog.load('neuron/LeakyIntegrateAndFire', 'PyNNLeakyIntegrateAndFire'), state_variable='v', dt=dt, simulators=simulators, properties=ninemlcatalog.load( 'neuron/LeakyIntegrateAndFire', 'PyNNLeakyIntegrateAndFireProperties'), initial_states=self.liaf_initial_states, initial_regime='subthreshold', neuron_ref='ResetRefrac', nest_ref='iaf_psc_alpha', input_signal=input_step('i_synaptic', 1, 50, 100, dt, 20), nest_translations=self.liaf_nest_translations, neuron_translations=self.liaf_neuron_translations, neuron_build_args={'build_mode': build_mode}, nest_build_args={'build_mode': build_mode}, # auxiliary_states=['end_refractory'], extra_mechanisms=['pas']) comparer.simulate(duration * un.ms, nest_rng_seed=NEST_RNG_SEED, neuron_rng_seed=NEURON_RNG_SEED) comparisons = comparer.compare() if print_comparisons: for (name1, name2), diff in comparisons.items(): print('{} v {}: {}'.format(name1, name2, diff)) if plot: comparer.plot() if 'neuron' in simulators: self.assertLess( comparisons[('9ML-neuron', 'Ref-neuron')], 0.55 * pq.mV, "LIaF NEURON 9ML simulation did not match reference PyNN " "within {} ({})".format( 0.55 * pq.mV, comparisons[('9ML-neuron', 'Ref-neuron')])) if 'nest' in simulators: self.assertLess( comparisons[('9ML-nest', 'Ref-nest')], 0.01 * pq.mV, "LIaF NEST 9ML simulation did not match reference built-in " "within {} ({})".format(0.01 * pq.mV, comparisons[('9ML-nest', 'Ref-nest')])) if 'nest' in simulators and 'neuron' in simulators: self.assertLess( comparisons[('9ML-nest', '9ML-neuron')], 0.55 * pq.mV, "LIaF NEURON 9ML simulation did not match NEST 9ML simulation " "within {} ({})".format( 0.55 * pq.mV, comparisons[('9ML-nest', '9ML-neuron')]))
def test_izhi(self, plot=PLOT_DEFAULT, print_comparisons=False, simulators=SIMULATORS_TO_TEST, dt=0.001, duration=100.0, build_mode=BUILD_MODE_DEFAULT, **kwargs): # @UnusedVariable # Force compilation of code generation # Perform comparison in subprocess comparer = Comparer( nineml_model=ninemlcatalog.load( 'neuron/Izhikevich', 'Izhikevich'), state_variable='V', dt=dt, simulators=simulators, properties=ninemlcatalog.load( 'neuron/Izhikevich', 'SampleIzhikevich'), initial_states={'U': -14.0 * pq.mV / pq.ms, 'V': -65.0 * pq.mV}, neuron_ref='Izhikevich', nest_ref='izhikevich', # auxiliary_states=['U'], input_signal=input_step('Isyn', 0.02, 50, 100, dt, 30), nest_translations={'V': ('V_m', 1), 'U': ('U_m', 1), 'weight': (None, 1), 'C_m': (None, 1), 'theta': ('V_th', 1), 'alpha': (None, 1), 'beta': (None, 1), 'zeta': (None, 1)}, neuron_translations={'C_m': (None, 1), 'weight': (None, 1), 'V': ('v', 1), 'U': ('u', 1), 'alpha': (None, 1), 'beta': (None, 1), 'zeta': (None, 1), 'theta': ('vthresh', 1)}, neuron_build_args={'build_mode': build_mode, 'build_version': 'TestDyn'}, nest_build_args={'build_mode': build_mode, 'build_version': 'TestDyn'}) comparer.simulate(duration * un.ms, nest_rng_seed=NEST_RNG_SEED, neuron_rng_seed=NEURON_RNG_SEED) comparisons = comparer.compare() if print_comparisons: for (name1, name2), diff in comparisons.items(): print('{} v {}: {}'.format(name1, name2, diff)) if plot: comparer.plot() if 'nest' in simulators and 'neuron' in simulators: self.assertLess( comparisons[('9ML-nest', '9ML-neuron')], 0.4 * pq.mV, "Izhikevich NEURON 9ML simulation did not match NEST 9ML " "within {} ({})".format( 0.4 * pq.mV, comparisons[('9ML-nest', '9ML-neuron')])) if 'neuron' in simulators: self.assertLess( comparisons[('9ML-neuron', 'Ref-neuron')], 0.01 * pq.mV, "Izhikevich NEURON 9ML simulation did not match reference " "PyNN within {} ({})".format( 0.01 * pq.mV, comparisons[('9ML-neuron', 'Ref-neuron')])) if 'nest' in simulators: self.assertLess( comparisons[('9ML-nest', 'Ref-nest')], 0.02 * pq.mV, "Izhikevich NEST 9ML simulation did not match reference " "built-in within {} ({})".format( 0.02 * pq.mV, comparisons[('9ML-nest', 'Ref-nest')]))
def test_load_name(self): liaf = ninemlcatalog.load(LIAF_PATH, LIAF_NAME) self.assertEqual(liaf.name, LIAF_NAME, "Element loaded from '{}' did not match name " "supplied '{}'".format(LIAF_PATH, LIAF_NAME)) liaf2 = ninemlcatalog.load(LIAF_PATH + '#' + LIAF_NAME) self.assertEqual(liaf2.name, LIAF_NAME, "Element loaded from '{}' did not match name " "supplied '{}'".format(LIAF_PATH, LIAF_NAME)) self.assertRaises( ninemlcatalog.NineMLCatalogSpecifiedMultipleNamesError, ninemlcatalog.load, LIAF_PATH + '#' + LIAF_NAME, LIAF_NAME)
def test_load_name(self): liaf = ninemlcatalog.load(LIAF_PATH, LIAF_NAME) self.assertEqual( liaf.name, LIAF_NAME, "Element loaded from '{}' did not match name " "supplied '{}'".format(LIAF_PATH, LIAF_NAME)) liaf2 = ninemlcatalog.load(LIAF_PATH + '#' + LIAF_NAME) self.assertEqual( liaf2.name, LIAF_NAME, "Element loaded from '{}' did not match name " "supplied '{}'".format(LIAF_PATH, LIAF_NAME)) self.assertRaises( ninemlcatalog.NineMLCatalogSpecifiedMultipleNamesError, ninemlcatalog.load, LIAF_PATH + '#' + LIAF_NAME, LIAF_NAME)
def test_izhi(self, plot=False, print_comparisons=False, simulators=['nest', 'neuron'], dt=0.001, duration=100.0, build_mode='force', **kwargs): # @UnusedVariable # Force compilation of code generation # Perform comparison in subprocess comparer = Comparer( nineml_model=ninemlcatalog.load( 'neuron/Izhikevich', 'Izhikevich'), state_variable='V', dt=dt, simulators=simulators, properties=ninemlcatalog.load( 'neuron/Izhikevich', 'SampleIzhikevich'), initial_states={'U': -14.0 * pq.mV / pq.ms, 'V': -65.0 * pq.mV}, neuron_ref='Izhikevich', nest_ref='izhikevich', input_signal=input_step('Isyn', 0.02, 50, 100, dt), nest_translations={'V': ('V_m', 1), 'U': ('U_m', 1), 'weight': (None, 1), 'C_m': (None, 1), 'theta': ('V_th', 1), 'alpha': (None, 1), 'beta': (None, 1), 'zeta': (None, 1)}, neuron_translations={'C_m': (None, 1), 'weight': (None, 1), 'V': ('v', 1), 'U': ('u', 1), 'alpha': (None, 1), 'beta': (None, 1), 'zeta': (None, 1), 'theta': ('vthresh', 1)}, neuron_build_args={'build_mode': build_mode}, nest_build_args={'build_mode': build_mode}, build_name='Izhikevich9ML') comparer.simulate(duration, nest_rng_seed=NEST_RNG_SEED, neuron_rng_seed=NEURON_RNG_SEED) comparisons = comparer.compare() if print_comparisons: for (name1, name2), diff in comparisons.iteritems(): print '{} v {}: {}'.format(name1, name2, diff) if plot: comparer.plot() if 'nest' in simulators and 'neuron' in simulators: self.assertLess( comparisons[('9ML-nest', '9ML-neuron')], 0.4 * pq.mV, "Izhikevich NEURON 9ML simulation did not match NEST 9ML") if 'neuron' in simulators: self.assertLess( comparisons[('9ML-neuron', 'Ref-neuron')], 0.0015 * pq.mV, "Izhikevich NEURON 9ML simulation did not match reference " "PyNN") if 'nest' in simulators: self.assertLess( comparisons[('9ML-nest', 'Ref-nest')], 0.02 * pq.mV, "Izhikevich NEST 9ML simulation did not match reference " "built-in")
def test_Izh_FS(iSyns=None): """Izhikevich Fast Spiker model""" if iSyns is None: iSyns = [200] cc = ninemlcatalog.load('/neuron/Izhikevich', 'IzhikevichFastSpiking') comp = ninemlcatalog.load('/neuron/Izhikevich', 'SampleIzhikevichFastSpiking') # Convert to PyDSTool.ModelSpec and create HybridModel object # Provide extra parameter Isyn which is missing from component definition # in absence of any synaptic inputs coupled to the model membrane izh = get_nineml_model(cc, 'izh_FS_9ML', extra_args=[Par('iSyn')], max_t=100) pars = dict((p.name, p.value) for p in comp.properties) ics = dict((i.name, i.value) for i in comp.initial_values) ics['regime_'] = 0 # set starting regime to be sub-threshold (PyDSTool will check consistency # with V initial condition) izh.set(pars=pars, ics=ics, tdata=[0, 80], algparams={'init_step': 0.03}) for iSyn in iSyns: izh.set(pars={'iSyn': iSyn}) name = 'iSyn=%.1f' % (float(iSyn)) izh.compute(name, verboselevel=0) pts = izh.sample(name) evs = izh.getTrajEventTimes(name)['spikeOutput'] ISIs = np.diff(evs) print("iSyn ={}:\n Mean ISI = {}, variance = {}".format( iSyn, np.mean(ISIs), np.var(ISIs))) Vp = izh.query('pars')['Vpeak'] plt.figure(6) plt.plot(pts['t'], pts['V'], label=name) plt.plot(evs, [Vp] * len(evs), 'ko') plt.title('Izhikevich fast spiking model') plt.xlabel('t') plt.ylabel('V') plt.legend() plt.figure(7) plt.plot(pts['t'], pts['U'], label=name) plt.xlabel('t') plt.ylabel('U') plt.legend() plt.title('Izhikevich FS model')
def test_liaf(self, plot=PLOT_DEFAULT, print_comparisons=False, simulators=SIMULATORS_TO_TEST, dt=0.001, duration=100.0, build_mode=BUILD_MODE_DEFAULT, **kwargs): # @UnusedVariable # Perform comparison in subprocess comparer = Comparer( nineml_model=ninemlcatalog.load( 'neuron/LeakyIntegrateAndFire', 'PyNNLeakyIntegrateAndFire'), state_variable='v', dt=dt, simulators=simulators, properties=ninemlcatalog.load( 'neuron/LeakyIntegrateAndFire', 'PyNNLeakyIntegrateAndFireProperties'), initial_states=self.liaf_initial_states, initial_regime='subthreshold', neuron_ref='ResetRefrac', nest_ref='iaf_psc_alpha', input_signal=input_step('i_synaptic', 1, 50, 100, dt, 20), nest_translations=self.liaf_nest_translations, neuron_translations=self.liaf_neuron_translations, neuron_build_args={'build_mode': build_mode}, nest_build_args={'build_mode': build_mode}, # auxiliary_states=['end_refractory'], extra_mechanisms=['pas']) comparer.simulate(duration * un.ms, nest_rng_seed=NEST_RNG_SEED, neuron_rng_seed=NEURON_RNG_SEED) comparisons = comparer.compare() if print_comparisons: for (name1, name2), diff in comparisons.items(): print('{} v {}: {}'.format(name1, name2, diff)) if plot: comparer.plot() if 'neuron' in simulators: self.assertLess( comparisons[('9ML-neuron', 'Ref-neuron')], 0.55 * pq.mV, "LIaF NEURON 9ML simulation did not match reference PyNN " "within {} ({})".format( 0.55 * pq.mV, comparisons[('9ML-neuron', 'Ref-neuron')])) if 'nest' in simulators: self.assertLess( comparisons[('9ML-nest', 'Ref-nest')], 0.01 * pq.mV, "LIaF NEST 9ML simulation did not match reference built-in " "within {} ({})".format( 0.01 * pq.mV, comparisons[('9ML-nest', 'Ref-nest')])) if 'nest' in simulators and 'neuron' in simulators: self.assertLess( comparisons[('9ML-nest', '9ML-neuron')], 0.55 * pq.mV, "LIaF NEURON 9ML simulation did not match NEST 9ML simulation " "within {} ({})".format( 0.55 * pq.mV, comparisons[('9ML-nest', '9ML-neuron')]))
def test_cell_seed(self): poisson_model = ninemlcatalog.load('input/Poisson#Poisson') for CellMetaClass, Simulation in ( (NeuronCellMetaClass, NeuronSimulation), (NESTCellMetaClass, NESTSimulation)): Poisson = CellMetaClass(poisson_model, build_version='SeedTest') rate = 300 / un.s t_next = 0.0 * un.s with Simulation(dt=0.01 * un.ms, seed=1) as sim: poisson1 = Poisson(rate=rate, t_next=t_next) poisson1.record('spike_output') sim.run(100 * un.ms) poisson1_spikes = poisson1.recording('spike_output') with Simulation(dt=0.01 * un.ms, seed=1) as sim: poisson2 = Poisson(rate=rate, t_next=t_next) poisson2.record('spike_output') sim.run(100 * un.ms) poisson2_spikes = poisson2.recording('spike_output') with Simulation(dt=0.01 * un.ms, seed=2) as sim: poisson3 = Poisson(rate=rate, t_next=t_next) poisson3.record('spike_output') sim.run(100 * un.ms) poisson3_spikes = poisson3.recording('spike_output') self.assertEqual(list(poisson1_spikes), list(poisson2_spikes), "Poisson spike train not the same despite using " "the same seed") self.assertNotEqual(list(poisson1_spikes), list(poisson3_spikes), "Poisson spike train the same despite using " "different seeds")
def test_network_plot(self): # Generate test signal brunel_ai = ninemlcatalog.load('network/Brunel2000/AI.xml').as_network( 'Brunel2000AI') scaled_brunel_ai_path = os.path.join(self.work_dir, 'brunel_scaled.xml') brunel_ai.scale(0.01).write(scaled_brunel_ai_path) argv = ("{} nest 100.0 0.1 " "--record Exc.spike_output {}".format( scaled_brunel_ai_path, self.network_signal_path)) simulate.run(argv.split()) # Run plotting command for pop_name in self.recorded_pops: out_path = '{}/{}.png'.format(self.work_dir, pop_name) argv = ("{in_path} --save {out_path} --hide --dims 5 5 " "--resolution 100.0".format( in_path=self.network_signal_path, out_path=out_path, name='v')) plot.run(argv.split()) image = img.imread(out_path) self._ref_network_plot() ref_image = img.imread(self.ref_network_path) self.assertEqual(image.shape, ref_image.shape) self.assertTrue( (image == ref_image).all(), "Plotted spike data using 'plot' command (saved to '{}') " "did not match loaded image from '{}'".format( out_path, self.ref_network_path))
def test_network_plot(self): # Generate test signal brunel_ai = ninemlcatalog.load( 'network/Brunel2000/AI.xml').as_network('Brunel2000AI') scaled_brunel_ai_path = os.path.join(self.work_dir, 'brunel_scaled.xml') brunel_ai.scale(0.01).write(scaled_brunel_ai_path) argv = ("{} nest 100.0 0.1 " "--record Exc.spike_output {}" .format(scaled_brunel_ai_path, self.network_signal_path)) simulate.run(argv.split()) # Run plotting command for pop_name in self.recorded_pops: out_path = '{}/{}.png'.format(self.work_dir, pop_name) argv = ("{in_path} --save {out_path} --hide --dims 5 5 " "--resolution 100.0" .format(in_path=self.network_signal_path, out_path=out_path, name='v')) plot.run(argv.split()) image = img.imread(out_path) self._ref_network_plot() ref_image = img.imread(self.ref_network_path) self.assertEqual( image.shape, ref_image.shape) self.assertTrue( (image == ref_image).all(), "Plotted spike data using 'plot' command (saved to '{}') " "did not match loaded image from '{}'" .format(out_path, self.ref_network_path))
def test_izhiFS(self, plot=PLOT_DEFAULT, print_comparisons=False, simulators=SIMULATORS_TO_TEST, dt=0.001, duration=100.0, build_mode=BUILD_MODE_DEFAULT, **kwargs): # @UnusedVariable @IgnorePep8 # Force compilation of code generation # Perform comparison in subprocess comparer = Comparer( nineml_model=ninemlcatalog.load('neuron/Izhikevich', 'IzhikevichFastSpiking'), state_variable='V', dt=dt, simulators=simulators, properties=ninemlcatalog.load('neuron/Izhikevich', 'SampleIzhikevichFastSpiking'), initial_states={ 'U': -1.625 * pq.pA, 'V': -65.0 * pq.mV }, input_signal=input_step('iSyn', 100 * pq.pA, 25.0, 100, dt, 15), initial_regime='subVb', neuron_build_args={ 'build_mode': build_mode, 'build_version': 'TestDyn', 'external_currents': ['iSyn'] }, # auxiliary_states=['U'], nest_build_args={ 'build_mode': build_mode, 'build_version': 'TestDyn' }) comparer.simulate(duration * un.ms, nest_rng_seed=NEST_RNG_SEED, neuron_rng_seed=NEURON_RNG_SEED) comparisons = comparer.compare() if print_comparisons: for (name1, name2), diff in comparisons.items(): print('{} v {}: {}'.format(name1, name2, diff)) if plot: comparer.plot() if 'nest' in simulators and 'neuron' in simulators: self.assertLess( comparisons[('9ML-nest', '9ML-neuron')], 0.4 * pq.mV, "Izhikevich 2007 NEURON 9ML simulation did not match NEST 9ML")
def nineml_document(doc_path): if doc_path.startswith('//'): model = ninemlcatalog.load(doc_path[2:]) else: if not doc_path.startswith('/') or not doc_path.startswith('.'): doc_path = './' + doc_path model = nineml.read(doc_path, relative_to=os.getcwd()) return model
def test_Izh_FS(iSyns=None): """Izhikevich Fast Spiker model""" if iSyns is None: iSyns = [200] cc = ninemlcatalog.load('/neuron/Izhikevich', 'IzhikevichFastSpiking') comp = ninemlcatalog.load('/neuron/Izhikevich', 'SampleIzhikevichFastSpiking') # Convert to PyDSTool.ModelSpec and create HybridModel object # Provide extra parameter Isyn which is missing from component definition # in absence of any synaptic inputs coupled to the model membrane izh = get_nineml_model(cc, 'izh_FS_9ML', extra_args=[Par('iSyn')], max_t=100) pars = dict((p.name, p.value) for p in comp.properties) ics = dict((i.name, i.value) for i in comp.initial_values) ics['regime_'] = 0 # set starting regime to be sub-threshold (PyDSTool will check consistency # with V initial condition) izh.set(pars=pars, ics=ics, tdata=[0, 80], algparams={'init_step': 0.03}) for iSyn in iSyns: izh.set(pars={'iSyn': iSyn}) name = 'iSyn=%.1f' % (float(iSyn)) izh.compute(name, verboselevel=0) pts = izh.sample(name) evs = izh.getTrajEventTimes(name)['spikeOutput'] ISIs = np.diff(evs) print("iSyn ={}:\n Mean ISI = {}, variance = {}" .format(iSyn, np.mean(ISIs), np.var(ISIs))) Vp = izh.query('pars')['Vpeak'] plt.figure(6) plt.plot(pts['t'], pts['V'], label=name) plt.plot(evs, [Vp] * len(evs), 'ko') plt.title('Izhikevich fast spiking model') plt.xlabel('t') plt.ylabel('V') plt.legend() plt.figure(7) plt.plot(pts['t'], pts['U'], label=name) plt.xlabel('t') plt.ylabel('U') plt.legend() plt.title('Izhikevich FS model')
def test_poisson(self, duration=10 * un.s, rate=100 * un.Hz, print_comparisons=False, dt=0.001, simulators=['nest', 'neuron'], build_mode='force', **kwargs): # @UnusedVariable @IgnorePep8 nineml_model = ninemlcatalog.load('input/Poisson', 'Poisson') build_args = {'neuron': {'build_mode': build_mode, 'external_currents': ['iSyn']}, 'nest': {'build_mode': build_mode}} initial_states = {'t_next': 0.0 * un.ms} for sim_name in simulators: meta_class = cell_metaclasses[sim_name] # Build celltype celltype = meta_class( nineml_model, name=nineml_model.name, **build_args[sim_name]) # Initialise simulator if sim_name == 'neuron': # Run NEURON simulation import neuron simulatorNEURON.clear(rng_seed=NEURON_RNG_SEED) neuron.h.dt = dt elif sim_name == 'nest': # Run NEST simulation # import nest # nest.ResetKernel() # nest.ResetNetwork() # nest.SetKernelStatus({'resolution': dt}) simulatorNEST.clear(rng_seed=NEST_RNG_SEED, dt=dt) else: assert False # Create and initialise cell cell = celltype(rate=rate) cell.record('spike_output') cell.set_state(initial_states) # Run simulation if sim_name == 'neuron': simulatorNEURON.run(duration.in_units(un.ms)) elif sim_name == 'nest': simulatorNEST.run(duration.in_units(un.ms)) else: assert False # Get recording spikes = cell.recording('spike_output') # Calculate the rate of the modelled process recorded_rate = pq.Quantity( len(spikes) / (spikes.t_stop - spikes.t_start), 'Hz') ref_rate = pq.Quantity(UnitHandlerNEST.to_pq_quantity(rate), 'Hz') rate_difference = abs(ref_rate - recorded_rate) if print_comparisons: print "Reference rate: {}".format(ref_rate) print "{} recorded rate: {}".format(sim_name, recorded_rate) print "{} difference: {}".format(sim_name, rate_difference) self.assertLess( rate_difference, 1.75 * pq.Hz, ("Recorded rate of {} poisson generator ({}) did not match " "desired ({}) within {}: difference {}".format( sim_name, recorded_rate, ref_rate, 1.75 * pq.Hz, recorded_rate - ref_rate)))
def nineml_document(doc_path): if doc_path.startswith(CATALOG_PREFIX): model = ninemlcatalog.load(doc_path[len(CATALOG_PREFIX):]) else: if (not doc_path.startswith('/') and not doc_path.startswith('./') and not doc_path.startswith('../')): doc_path = './' + doc_path model = nineml.read(doc_path, relative_to=os.getcwd()) return model
def test_poisson(self, duration=100 * un.s, rate=100 * un.Hz, t_next=0.0 * un.ms, print_comparisons=False, dt=0.1, simulators=SIMULATORS_TO_TEST, build_mode=BUILD_MODE_DEFAULT, **kwargs): # @UnusedVariable @IgnorePep8 nineml_model = ninemlcatalog.load('input/Poisson', 'Poisson') build_args = { 'neuron': { 'build_mode': build_mode, 'external_currents': ['iSyn'] }, 'nest': { 'build_mode': build_mode } } for sim_name in simulators: meta_class = cell_metaclasses[sim_name] # Build celltype celltype = meta_class(nineml_model, **build_args[sim_name]) # Initialise simulator if sim_name == 'neuron': # Run NEURON simulation Simulation = NeuronSimulation(dt=dt * un.ms, seed=NEURON_RNG_SEED) elif sim_name == 'nest': Simulation = NESTSimulation(dt=dt * un.ms, seed=NEST_RNG_SEED) else: assert False with Simulation as sim: # Create and initialize cell cell = celltype(rate=rate, t_next=t_next) cell.record('spike_output') sim.run(duration) # Get recording spikes = cell.recording('spike_output') # Calculate the rate of the modelled process recorded_rate = pq.Quantity( len(spikes) / (spikes.t_stop - spikes.t_start), 'Hz') ref_rate = pq.Quantity(UnitHandlerNEST.to_pq_quantity(rate), 'Hz') rate_difference = abs(ref_rate - recorded_rate) if print_comparisons: print("Reference rate: {}".format(ref_rate)) print("{} recorded rate: {}".format(sim_name, recorded_rate)) print("{} difference: {}".format(sim_name, rate_difference)) self.assertLess( rate_difference, 5 * pq.Hz, ("Recorded rate of {} poisson generator ({}) did not match " "desired ({}) within {}: difference {}".format( sim_name, recorded_rate, ref_rate, 2.5 * pq.Hz, recorded_rate - ref_rate)))
def test_build_name_conflict(self): izhi = ninemlcatalog.load('neuron/Izhikevich.xml#Izhikevich') izhi2 = izhi.clone() izhi2.add(StateVariable('Z', dimension=un.dimensionless)) izhi2.regime('subthreshold_regime').add(TimeDerivative('Z', '1 / zp')) izhi2.add(Parameter('zp', dimension=un.time)) izhi_wrap = WithSynapses.wrap(izhi) izhi2_wrap = WithSynapses.wrap(izhi2) CellMetaClass(izhi_wrap) self.assertRaises(Pype9BuildMismatchError, CellMetaClass, izhi2_wrap)
def run(argv): args = argparser().parse_args(argv) # Compile and load cell class HH = CellMetaClass( ninemlcatalog.load('neuron/HodgkinHuxley#PyNNHodgkinHuxley')) # Create and run the simulation with Simulation(dt=0.01 * un.ms) as sim: hh = HH(ninemlcatalog.load( 'neuron/HodgkinHuxley#PyNNHodgkinHuxleyProperties'), v=-65 * un.mV, m=0.0, h=1.0, n=0.0) hh.record('v') sim.run(500 * un.ms) # Plot recordings plot(hh.recordings(), title='Simple Hodgkin-Huxley Example', save=args.save_fig, show=(not args.save_fig))
def test_load_all(self): errors = [] for pth in self.iterate_paths(self.catalog_root): # Just check to see whether all elements of the document load # without error try: _ = list(ninemlcatalog.load(pth).elements) except Exception: errors.append( (pth, traceback.format_exception(*sys.exc_info()))) self.assert_( not errors, "The following failures occured while attempting to load all " "models from the catalog:\n\n{}".format('\n\n'.join( "{}\n---\n{}".format(pth, '\n'.join(trace)) for pth, trace in errors)))
def test_load_all(self): errors = [] for pth in self.iterate_paths(self.catalog_root): # Just check to see whether all elements of the document load # without error try: _ = list(ninemlcatalog.load(pth).elements) except Exception: errors.append( (pth, traceback.format_exception(*sys.exc_info()))) self.assert_( not errors, "The following failures occured while attempting to load all " "models from the catalog:\n\n{}" .format('\n\n'.join("{}\n---\n{}".format(pth, '\n'.join(trace)) for pth, trace in errors)))
def _ref_single_cell(self, simulator, isyn): if simulator == 'neuron': metaclass = CellMetaClassNEURON simulation_controller = simulatorNEURON else: nest.ResetKernel() metaclass = CellMetaClassNEST simulation_controller = simulatorNEST nineml_model = ninemlcatalog.load(self.izhi_path) cell = metaclass(nineml_model.component_class, name='izhikevichAPI')(nineml_model) cell.set_state({'U': Quantity(self.U[0], parse_units(self.U[1])), 'V': Quantity(self.V[0], parse_units(self.V[1]))}) cell.record('V') cell.play('Isyn', isyn) simulation_controller.run(self.t_stop) return cell.recording('V')
def _load_brunel(self, case, order): model = ninemlcatalog.load('network/Brunel2000/' + case).as_network( 'Brunel_{}'.format(case)) # Don't clone so that the url is not reset model = model.clone() scale = order / model.population('Inh').size # rescale populations for pop in model.populations: pop.size = int(numpy.ceil(pop.size * scale)) for proj in (model.projection('Excitation'), model.projection('Inhibition')): props = proj.connectivity.rule_properties number = props.property('number') props.set(Property( number.name, int(numpy.ceil(float(number.value) * scale)) * un.unitless)) return model
def test_poisson(self, duration=100 * un.s, rate=100 * un.Hz, t_next=0.0 * un.ms, print_comparisons=False, dt=0.1, simulators=SIMULATORS_TO_TEST, build_mode=BUILD_MODE_DEFAULT, **kwargs): # @UnusedVariable @IgnorePep8 nineml_model = ninemlcatalog.load('input/Poisson', 'Poisson') build_args = {'neuron': {'build_mode': build_mode, 'external_currents': ['iSyn']}, 'nest': {'build_mode': build_mode}} for sim_name in simulators: meta_class = cell_metaclasses[sim_name] # Build celltype celltype = meta_class(nineml_model, **build_args[sim_name]) # Initialise simulator if sim_name == 'neuron': # Run NEURON simulation Simulation = NeuronSimulation(dt=dt * un.ms, seed=NEURON_RNG_SEED) elif sim_name == 'nest': Simulation = NESTSimulation(dt=dt * un.ms, seed=NEST_RNG_SEED) else: assert False with Simulation as sim: # Create and initialize cell cell = celltype(rate=rate, t_next=t_next) cell.record('spike_output') sim.run(duration) # Get recording spikes = cell.recording('spike_output') # Calculate the rate of the modelled process recorded_rate = pq.Quantity( len(spikes) / (spikes.t_stop - spikes.t_start), 'Hz') ref_rate = pq.Quantity(UnitHandlerNEST.to_pq_quantity(rate), 'Hz') rate_difference = abs(ref_rate - recorded_rate) if print_comparisons: print("Reference rate: {}".format(ref_rate)) print("{} recorded rate: {}".format(sim_name, recorded_rate)) print("{} difference: {}".format(sim_name, rate_difference)) self.assertLess( rate_difference, 5 * pq.Hz, ("Recorded rate of {} poisson generator ({}) did not match " "desired ({}) within {}: difference {}".format( sim_name, recorded_rate, ref_rate, 2.5 * pq.Hz, recorded_rate - ref_rate)))
def setUp(self): self.tmpdir = tempfile.mkdtemp() # Create reduced version of Brunel network model = ninemlcatalog.load(self.brunel_path).as_network( 'Brunel_AI_reduced') scale = self.reduced_brunel_order / model.population('Inh').size # rescale populations reduced_model = model.clone() for pop in reduced_model.populations: pop.size = int(np.ceil(pop.size * scale)) for proj in (reduced_model.projection('Excitation'), reduced_model.projection('Inhibition')): props = proj.connectivity.rule_properties number = props.property('number') props.set(nineml.Property( number.name, int(np.ceil(float(number.value) * scale)) * un.unitless)) self.reduced_brunel_path = os.path.join(self.tmpdir, self.reduced_brunel_fname) reduced_model.write(self.reduced_brunel_path)
def _ref_single_cell(self, simulator, isyn): if simulator == 'neuron': metaclass = NeuronCellMetaClass Simulation = NeuronSimulation else: metaclass = NESTCellMetaClass Simulation = NESTSimulation nineml_model = ninemlcatalog.load(self.izhi_path[len(CATALOG_PREFIX):]) Cell = metaclass(nineml_model.component_class, build_version='API', external_currents=['iSyn']) with Simulation(dt=self.dt * un.ms, min_delay=0.5 * un.ms, device_delay=0.5 * un.ms) as sim: cell = Cell(nineml_model, U=self.U[0] * parse_units(self.U[1]), V=self.V[0] * parse_units(self.V[1]), regime_='subVb') cell.record('V') cell.record_regime() cell.play('iSyn', isyn) sim.run(self.t_stop * un.ms) return (cell.recording('V', t_start=pq.Quantity(self.rec_t_start[0], self.rec_t_start[1])), cell.regime_epochs())
def test_hh(self, plot=PLOT_DEFAULT, print_comparisons=False, simulators=SIMULATORS_TO_TEST, dt=0.001, duration=100.0, build_mode=BUILD_MODE_DEFAULT, **kwargs): # @UnusedVariable # Perform comparison in subprocess comparer = Comparer( nineml_model=ninemlcatalog.load('neuron/HodgkinHuxley', 'PyNNHodgkinHuxley'), state_variable='v', dt=dt, simulators=simulators, initial_states={ 'v': -65.0 * pq.mV, 'm': 0.0, 'h': 1.0, 'n': 0.0 }, properties=ninemlcatalog.load('neuron/HodgkinHuxley', 'PyNNHodgkinHuxleyProperties'), neuron_ref='hh_traub', nest_ref='hh_cond_exp_traub', input_signal=input_step('iExt', 0.5, 50, 100, dt, 10), nest_translations={ 'v': ('V_m', 1), 'm': ('Act_m', 1), 'h': ('Act_h', 1), 'n': ('Inact_n', 1), 'eNa': ('E_Na', 1), 'eK': ('E_K', 1), 'C': ('C_m', 1), 'gLeak': ('g_L', 1), 'eLeak': ('E_L', 1), 'gbarNa': ('g_Na', 1), 'gbarK': ('g_K', 1), 'v_rest': ('V_T', 1), 'v_threshold': (None, 1), 'm_alpha_A': (None, 1), 'm_alpha_V0': (None, 1), 'm_alpha_K': (None, 1), 'm_beta_A': (None, 1), 'm_beta_V0': (None, 1), 'm_beta_K': (None, 1), 'h_alpha_A': (None, 1), 'h_alpha_V0': (None, 1), 'h_alpha_K': (None, 1), 'h_beta_A': (None, 1), 'h_beta_V0': (None, 1), 'h_beta_K': (None, 1), 'n_alpha_A': (None, 1), 'n_alpha_V0': (None, 1), 'n_alpha_K': (None, 1), 'n_beta_A': (None, 1), 'n_beta_V0': (None, 1), 'n_beta_K': (None, 1) }, neuron_translations={ 'eNa': ('ena', 1), 'eK': ('ek', 1), 'C': ('cm', 1), 'gLeak': ('gl', 1), 'eLeak': ('el', 1), 'gbarNa': ('gnabar', 1), 'gbarK': ('gkbar', 1), 'v_rest': ('vT', 1), 'v_threshold': (None, 1), 'm_alpha_A': (None, 1), 'm_alpha_V0': (None, 1), 'm_alpha_K': (None, 1), 'm_beta_A': (None, 1), 'm_beta_V0': (None, 1), 'm_beta_K': (None, 1), 'h_alpha_A': (None, 1), 'h_alpha_V0': (None, 1), 'h_alpha_K': (None, 1), 'h_beta_A': (None, 1), 'h_beta_V0': (None, 1), 'h_beta_K': (None, 1), 'n_alpha_A': (None, 1), 'n_alpha_V0': (None, 1), 'n_alpha_K': (None, 1), 'n_beta_A': (None, 1), 'n_beta_V0': (None, 1), 'n_beta_K': (None, 1) }, # auxiliary_states=['m', 'h', 'n'], neuron_build_args={'build_mode': build_mode}, nest_build_args={'build_mode': build_mode}) comparer.simulate(duration * un.ms, nest_rng_seed=NEST_RNG_SEED, neuron_rng_seed=NEURON_RNG_SEED) comparisons = comparer.compare() if print_comparisons: for (name1, name2), diff in comparisons.items(): print('{} v {}: {}'.format(name1, name2, diff)) if plot: comparer.plot() # FIXME: Need to work out what is happening with the reference NEURON if 'nest' in simulators and 'neuron' in simulators: self.assertLess( comparisons[('9ML-nest', '9ML-neuron')], 0.5 * pq.mV, "HH 9ML NEURON and NEST simulation did not match each other " "within {} ({})".format( 0.5 * pq.mV, comparisons[('9ML-nest', '9ML-neuron')])) if 'neuron' in simulators: self.assertLess( comparisons[('9ML-neuron', 'Ref-neuron')], 0.55 * pq.mV, "HH 9ML NEURON simulation did not match reference built-in " "within {} ({})".format( 0.55 * pq.mV, comparisons[('9ML-neuron', 'Ref-neuron')])) if 'nest' in simulators: self.assertLess( comparisons[('9ML-nest', 'Ref-nest')], 0.0015 * pq.mV, "HH 9ML NEST simulation did not match reference built-in " "within {} ({})".format(0.0015 * pq.mV, comparisons[('9ML-nest', 'Ref-nest')]))
def test_alpha_syn(self, plot=False, print_comparisons=False, simulators=['nest', 'neuron'], dt=0.001, duration=100.0, min_delay=5.0, device_delay=5.0, build_mode='force', **kwargs): # @UnusedVariable # Perform comparison in subprocess iaf = ninemlcatalog.load( 'neuron/LeakyIntegrateAndFire', 'PyNNLeakyIntegrateAndFire') alpha_psr = ninemlcatalog.load( 'postsynapticresponse/Alpha', 'PyNNAlpha') static = ninemlcatalog.load( 'plasticity/Static', 'Static') iaf_alpha = MultiDynamics( name='IafAlpha', sub_components={ 'cell': iaf, 'syn': MultiDynamics( name="IafAlaphSyn", sub_components={'psr': alpha_psr, 'pls': static}, port_connections=[ ('pls', 'fixed_weight', 'psr', 'q')], port_exposures=[('psr', 'i_synaptic'), ('psr', 'spike')])}, port_connections=[ ('syn', 'i_synaptic__psr', 'cell', 'i_synaptic')], port_exposures=[('syn', 'spike__psr', 'spike')]) iaf_alpha_with_syn = MultiDynamicsWithSynapses( 'IafAlpha', iaf_alpha, connection_parameter_sets=[ ConnectionParameterSet( 'spike', [iaf_alpha.parameter('weight__pls__syn')])]) initial_states = {'a__psr__syn': 0.0 * pq.nA, 'b__psr__syn': 0.0 * pq.nA} initial_regime = 'subthreshold___sole_____sole' liaf_properties = ninemlcatalog.load( 'neuron/LeakyIntegrateAndFire/', 'PyNNLeakyIntegrateAndFireProperties') alpha_properties = ninemlcatalog.load( 'postsynapticresponse/Alpha', 'SamplePyNNAlphaProperties') nest_tranlsations = {'tau__psr__syn': ('tau_syn_ex', 1), 'a__psr__syn': (None, 1), 'b__psr__syn': (None, 1), 'spike': ('spike', 1000.0)} neuron_tranlsations = {'tau__psr__syn': ('psr.tau', 1), 'q__psr__syn': ('psr.q', 1), 'spike': ('spike', 1), 'a__psr__syn': (None, 1), 'b__psr__syn': (None, 1)} initial_states.update( (k + '__cell', v) for k, v in self.liaf_initial_states.iteritems()) properties = DynamicsProperties( name='IafAlphaProperties', definition=iaf_alpha, properties=dict( (p.name + '__' + suffix, p.quantity) for p, suffix in chain( zip(liaf_properties.properties, repeat('cell')), zip(alpha_properties.properties, repeat('psr__syn')), [(Property('weight', 10 * un.nA), 'pls__syn')]))) properties_with_syn = DynamicsWithSynapsesProperties( 'IafAlpha_props_with_syn', properties, # @IgnorePep8 connection_property_sets=[ ConnectionPropertySet( 'spike', [properties.property('weight__pls__syn')])]) nest_tranlsations.update( (k + '__cell', v) for k, v in self.liaf_nest_translations.iteritems()) neuron_tranlsations.update( (k + '__cell', v) for k, v in self.liaf_neuron_translations.iteritems()) build_dir = os.path.join(os.path.dirname(iaf.url), '9build') comparer = Comparer( nineml_model=iaf_alpha_with_syn, state_variable='v__cell', dt=dt, simulators=simulators, properties=properties_with_syn, initial_states=initial_states, initial_regime=initial_regime, neuron_ref='ResetRefrac', nest_ref='iaf_psc_alpha', input_train=input_freq('spike', 450 * pq.Hz, duration, weight=[Property('weight__pls__syn', 10 * un.nA)], # 20.680155243 * un.pA offset=duration / 2.0), nest_translations=nest_tranlsations, neuron_translations=neuron_tranlsations, extra_mechanisms=['pas'], extra_point_process='AlphaISyn', neuron_build_args={ 'build_mode': build_mode, 'build_dir': os.path.join(build_dir, 'neuron', 'IaFAlpha')}, nest_build_args={ 'build_mode': build_mode, 'build_dir': os.path.join(build_dir, 'nest', 'IaFAlpha')}, min_delay=min_delay, device_delay=device_delay) comparer.simulate(duration, nest_rng_seed=NEST_RNG_SEED, neuron_rng_seed=NEURON_RNG_SEED) comparisons = comparer.compare() if print_comparisons: for (name1, name2), diff in comparisons.iteritems(): print '{} v {}: {}'.format(name1, name2, diff) if plot: comparer.plot() if 'nest' in simulators and 'neuron' in simulators: self.assertLess( comparisons[('9ML-nest', '9ML-neuron')], 0.015 * pq.mV, "LIaF with Alpha syn NEST 9ML simulation did not match NEURON " "9ML simulation") if 'nest' in simulators: self.assertLess( comparisons[('9ML-nest', 'Ref-nest')], 0.04 * pq.mV, "LIaF with Alpha syn NEST 9ML simulation did not match " "reference built-in") if 'neuron' in simulators: self.assertLess( comparisons[('9ML-neuron', 'Ref-neuron')], 0.03 * pq.mV, "LIaF with Alpha syn NEURON 9ML simulation did not match " "reference PyNN")
def test_hh(self, plot=False, print_comparisons=False, simulators=['nest', 'neuron'], dt=0.001, duration=100.0, build_mode='force', **kwargs): # @UnusedVariable # Perform comparison in subprocess comparer = Comparer( nineml_model=ninemlcatalog.load( 'neuron/HodgkinHuxley', 'PyNNHodgkinHuxley'), state_variable='v', dt=dt, simulators=simulators, initial_states={'v': -65.0 * pq.mV, 'm': 0.0, 'h': 1.0, 'n': 0.0}, properties=ninemlcatalog.load( 'neuron/HodgkinHuxley', 'PyNNHodgkinHuxleyProperties'), neuron_ref='hh_traub', nest_ref='hh_cond_exp_traub', input_signal=input_step('iExt', 0.5, 50, 100, dt), nest_translations={ 'v': ('V_m', 1), 'm': ('Act_m', 1), 'h': ('Act_h', 1), 'n': ('Inact_n', 1), 'eNa': ('E_Na', 1), 'eK': ('E_K', 1), 'C': ('C_m', 1), 'gLeak': ('g_L', 1), 'eLeak': ('E_L', 1), 'gbarNa': ('g_Na', 1), 'gbarK': ('g_K', 1), 'v_rest': ('V_T', 1), 'v_threshold': (None, 1), 'm_alpha_A': (None, 1), 'm_alpha_V0': (None, 1), 'm_alpha_K': (None, 1), 'm_beta_A': (None, 1), 'm_beta_V0': (None, 1), 'm_beta_K': (None, 1), 'h_alpha_A': (None, 1), 'h_alpha_V0': (None, 1), 'h_alpha_K': (None, 1), 'h_beta_A': (None, 1), 'h_beta_V0': (None, 1), 'h_beta_K': (None, 1), 'n_alpha_A': (None, 1), 'n_alpha_V0': (None, 1), 'n_alpha_K': (None, 1), 'n_beta_A': (None, 1), 'n_beta_V0': (None, 1), 'n_beta_K': (None, 1)}, neuron_translations={ 'eNa': ('ena', 1), 'eK': ('ek', 1), 'C': ('cm', 1), 'gLeak': ('gl', 1), 'eLeak': ('el', 1), 'gbarNa': ('gnabar', 1), 'gbarK': ('gkbar', 1), 'v_rest': ('vT', 1), 'v_threshold': (None, 1), 'm_alpha_A': (None, 1), 'm_alpha_V0': (None, 1), 'm_alpha_K': (None, 1), 'm_beta_A': (None, 1), 'm_beta_V0': (None, 1), 'm_beta_K': (None, 1), 'h_alpha_A': (None, 1), 'h_alpha_V0': (None, 1), 'h_alpha_K': (None, 1), 'h_beta_A': (None, 1), 'h_beta_V0': (None, 1), 'h_beta_K': (None, 1), 'n_alpha_A': (None, 1), 'n_alpha_V0': (None, 1), 'n_alpha_K': (None, 1), 'n_beta_A': (None, 1), 'n_beta_V0': (None, 1), 'n_beta_K': (None, 1)}, neuron_build_args={'build_mode': build_mode}, nest_build_args={'build_mode': build_mode}) comparer.simulate(duration, nest_rng_seed=NEST_RNG_SEED, neuron_rng_seed=NEURON_RNG_SEED) comparisons = comparer.compare() if print_comparisons: for (name1, name2), diff in comparisons.iteritems(): print '{} v {}: {}'.format(name1, name2, diff) if plot: comparer.plot() # FIXME: Need to work out what is happening with the reference NEURON if 'nest' in simulators and 'neuron' in simulators: self.assertLess( comparisons[('9ML-nest', '9ML-neuron')], 0.5 * pq.mV, "HH 9ML NEURON and NEST simulation did not match each other") if 'neuron' in simulators: self.assertLess( comparisons[('9ML-neuron', 'Ref-neuron')], 0.55 * pq.mV, "HH 9ML NEURON simulation did not match reference built-in") if 'nest' in simulators: self.assertLess( comparisons[('9ML-nest', 'Ref-nest')], 0.0015 * pq.mV, "HH 9ML NEST simulation did not match reference built-in")
def run(argv): args = argparser().parse_args(argv) delay = args.delay * un.ms # Import of nest needs to be after arguments have been passed as it kills # them before the SLI interpreter tries to read them. if args.simulator == 'nest': from pype9.simulate.nest import CellMetaClass, Simulation # @IgnorePep8 @UnusedImport elif args.simulator == 'neuron': from pype9.simulate.neuron import CellMetaClass, Simulation # @IgnorePep8 @Reimport else: raise Exception("Unrecognised simulator '{}' (can be either 'nest' or " "'neuron')".format(args.simulator)) # Get and combine 9ML models input_model = ninemlcatalog.load('input/ConstantRate', 'ConstantRate') liaf_model = ninemlcatalog.load('neuron/LeakyIntegrateAndFire', 'LeakyIntegrateAndFire') alpha_model = ninemlcatalog.load('postsynapticresponse/Alpha', 'Alpha') weight_model = ninemlcatalog.load('plasticity/Static', 'Static') multi_model = MultiDynamics(name="test_alpha_syn", sub_components={ 'cell': liaf_model, 'psr': alpha_model, 'pls': weight_model }, port_connections=[('psr', 'i_synaptic', 'cell', 'i_synaptic'), ('pls', 'fixed_weight', 'psr', 'weight')], port_exposures=[('psr', 'input_spike'), ('cell', 'spike_output')]) # Add connection weight conn_params = [] if args.connection_weight: conn_params.append( ConnectionParameterSet('input_spike__psr', [multi_model.parameter('weight__pls')])) # Reinterpret the multi-component model as one containing synapses that can # be set by connection weights w_syn_model = WithSynapses.wrap(multi_model, connection_parameter_sets=conn_params) # Generate Pype9 classes Input = CellMetaClass(input_model, build_mode=args.build_mode) Cell = CellMetaClass(w_syn_model, build_mode=args.build_mode) # Create instances rate = args.rate * un.Hz weight = args.weight * un.nA cell_params = { 'tau__cell': args.tau * un.ms, 'R__cell': 1.5 * un.Mohm, 'refractory_period__cell': 2.0 * un.ms, 'v_threshold__cell': args.threshold * un.mV, 'v_reset__cell': 0.0 * un.mV, 'tau__psr': 0.5 * un.ms, 'regime_': 'subthreshold___sole___sole', 'b__psr': 0.0 * un.nA, 'a__psr': 0.0 * un.nA, 'v__cell': 0.0 * un.mV, 'refractory_end__cell': 0.0 * un.ms } # If PSR weight is part of the cell dynamics (as opposed to the connection) if args.connection_weight: conn_properties = [Property('weight__pls', weight)] else: cell_params['weight__pls'] = weight conn_properties = [] with Simulation(args.timestep * un.ms, min_delay=delay) as sim: input = Input(rate=rate, t_next=(1 * un.unitless) / rate) # @ReservedAssignment @IgnorePep8 cell = Cell(**cell_params) # Connect cells together cell.connect(input, 'spike_output', 'input_spike__psr', delay, properties=conn_properties) # Set up recorders cell.record('spike_output__cell') cell.record_regime() cell.record('v__cell') # Run simulation sim.run(args.simtime * un.ms) # Plot recordings plot(cell.recordings(), save=args.save_fig, show=(not args.save_fig), title='Leaky Integrate and Fire with Alpha Synapse') print("Finished simulation.")
def test_load_xml_path(self): liaf_doc = ninemlcatalog.load(LIAF_PATH + '.xml') self.assert_(LIAF_NAME in liaf_doc, "Did not load file with path ending in '.xml'")
def test_alpha_syn(self, plot=PLOT_DEFAULT, print_comparisons=False, simulators=SIMULATORS_TO_TEST, dt=0.001, duration=100.0, min_delay=5.0, device_delay=5.0, build_mode=BUILD_MODE_DEFAULT, **kwargs): # @UnusedVariable @IgnorePep8 # Perform comparison in subprocess iaf = ninemlcatalog.load('neuron/LeakyIntegrateAndFire', 'PyNNLeakyIntegrateAndFire') alpha_psr = ninemlcatalog.load('postsynapticresponse/Alpha', 'PyNNAlpha') static = ninemlcatalog.load('plasticity/Static', 'Static') iaf_alpha = MultiDynamics( name='IafAlpha_sans_synapses', sub_components={ 'cell': iaf, 'syn': MultiDynamics(name="IafAlaphSyn", sub_components={ 'psr': alpha_psr, 'pls': static }, port_connections=[('pls', 'fixed_weight', 'psr', 'q')], port_exposures=[('psr', 'i_synaptic'), ('psr', 'spike')]) }, port_connections=[('syn', 'i_synaptic__psr', 'cell', 'i_synaptic') ], port_exposures=[('syn', 'spike__psr', 'spike')]) iaf_alpha_with_syn = MultiDynamicsWithSynapses( 'IafAlpha', iaf_alpha, connection_parameter_sets=[ ConnectionParameterSet( 'spike', [iaf_alpha.parameter('weight__pls__syn')]) ]) initial_states = { 'a__psr__syn': 0.0 * pq.nA, 'b__psr__syn': 0.0 * pq.nA } initial_regime = 'subthreshold___sole_____sole' liaf_properties = ninemlcatalog.load( 'neuron/LeakyIntegrateAndFire/', 'PyNNLeakyIntegrateAndFireProperties') alpha_properties = ninemlcatalog.load('postsynapticresponse/Alpha', 'SamplePyNNAlphaProperties') nest_tranlsations = { 'tau__psr__syn': ('tau_syn_ex', 1), 'a__psr__syn': (None, 1), 'b__psr__syn': (None, 1), 'spike': ('spike', 1000.0) } neuron_tranlsations = { 'tau__psr__syn': ('psr.tau', 1), 'q__psr__syn': ('psr.q', 1), 'spike': ('spike', 1), 'a__psr__syn': (None, 1), 'b__psr__syn': (None, 1) } initial_states.update( (k + '__cell', v) for k, v in self.liaf_initial_states.items()) properties = DynamicsProperties( name='IafAlphaProperties', definition=iaf_alpha, properties=dict( (p.name + '__' + suffix, p.quantity) for p, suffix in chain( list(zip(liaf_properties.properties, repeat('cell'))), list(zip(alpha_properties.properties, repeat('psr__syn'))), [(Property('weight', 10 * un.nA), 'pls__syn')]))) properties_with_syn = DynamicsWithSynapsesProperties( 'IafAlpha_props_with_syn', properties, # @IgnorePep8 connection_property_sets=[ ConnectionPropertySet( 'spike', [properties.property('weight__pls__syn')]) ]) nest_tranlsations.update( (k + '__cell', v) for k, v in self.liaf_nest_translations.items()) neuron_tranlsations.update( (k + '__cell', v) for k, v in self.liaf_neuron_translations.items()) comparer = Comparer( nineml_model=iaf_alpha_with_syn, state_variable='v__cell', dt=dt, simulators=simulators, properties=properties_with_syn, initial_states=initial_states, initial_regime=initial_regime, neuron_ref='ResetRefrac', nest_ref='iaf_psc_alpha', input_train=input_freq( 'spike', 450 * pq.Hz, duration * pq.ms, weight=[Property('weight__pls__syn', 10 * un.nA)], offset=duration / 2.0), nest_translations=nest_tranlsations, neuron_translations=neuron_tranlsations, extra_mechanisms=['pas'], extra_point_process='AlphaISyn', neuron_build_args={'build_mode': build_mode}, nest_build_args={'build_mode': build_mode}, min_delay=min_delay, # auxiliary_states=['end_refractory__cell'], device_delay=device_delay) comparer.simulate(duration * un.ms, nest_rng_seed=NEST_RNG_SEED, neuron_rng_seed=NEURON_RNG_SEED) comparisons = comparer.compare() if print_comparisons: for (name1, name2), diff in comparisons.items(): print('{} v {}: {}'.format(name1, name2, diff)) if plot: comparer.plot() if 'nest' in simulators and 'neuron' in simulators: self.assertLess( comparisons[('9ML-nest', '9ML-neuron')], 0.015 * pq.mV, "LIaF with Alpha syn NEST 9ML simulation did not match NEURON " "9ML simulation within {} ({})".format( 0.015 * pq.mV, comparisons[('9ML-nest', '9ML-neuron')])) if 'nest' in simulators: self.assertLess( comparisons[('9ML-nest', 'Ref-nest')], 0.04 * pq.mV, "LIaF with Alpha syn NEST 9ML simulation did not match " "reference built-in within {} ({})".format( 0.04 * pq.mV, comparisons[('9ML-nest', 'Ref-nest')])) if 'neuron' in simulators: self.assertLess( comparisons[('9ML-neuron', 'Ref-neuron')], 0.03 * pq.mV, "LIaF with Alpha syn NEURON 9ML simulation did not match " "reference PyNN within {} ({})".format( 0.03 * pq.mV, comparisons[('9ML-neuron', 'Ref-neuron')]))
parser.add_argument('--build_mode', type=str, default='lazy', help=("The build mode to apply when creating the cell " "class")) args = parser.parse_args() # Import of nest needs to be after arguments have been passed as it kills them # before the SLI interpreter tries to read them. from pype9.nest import CellMetaClass, simulation_controller, UnitHandler # @IgnorePep8 build_dir = os.path.join(os.getcwd(), '9build', 'liaf_with_alpha') # Whether weight should be a parameter of the cell or passed as a weight # parameter connection_weight = False # Get and combine 9ML models input_model = ninemlcatalog.load( 'input/ConstantRate', 'ConstantRate') liaf_model = ninemlcatalog.load( 'neuron/LeakyIntegrateAndFire', 'LeakyIntegrateAndFire') alpha_model = ninemlcatalog.load( 'postsynapticresponse/Alpha', 'Alpha') weight_model = ninemlcatalog.load( 'plasticity/Static', 'Static') multi_model = MultiDynamics( name="test_alpha_syn", sub_components={'cell': liaf_model, 'psr': alpha_model, 'pls': weight_model}, port_connections=[('psr', 'i_synaptic', 'cell', 'i_synaptic'), ('pls', 'fixed_weight', 'psr', 'q')], port_exposures=[('psr', 'spike'), ('cell', 'spike_output')]) conn_params = [] if connection_weight:
def create_brunel(g, eta, name=None): """ Build a NineML representation of the Brunel (2000) network model. Arguments: g: relative strength of inhibitory synapses eta: nu_ext / nu_thresh Returns: a nineml user layer Model object """ # Meta-parameters order = 1000 # scales the size of the network Ne = 4 * order # number of excitatory neurons Ni = 1 * order # number of inhibitory neurons epsilon = 0.1 # connection probability Ce = int(epsilon * Ne) # number of excitatory synapses per neuron Ci = int(epsilon * Ni) # number of inhibitory synapses per neuron Cext = Ce # effective number of external synapses per neuron delay = 1.5 # (ms) global delay for all neurons in the group J = 0.1 # (mV) EPSP size Jeff = 24.0 * J # (nA) synaptic weight Je = Jeff # excitatory weights Ji = -g * Je # inhibitory weights Jext = Je # external weights theta = 20.0 # firing thresholds tau = 20.0 # membrane time constant tau_syn = 0.1 # synapse time constant # nu_thresh = theta / (Je * Ce * tau * exp(1.0) * tau_syn) # threshold rate nu_thresh = theta / (J * Ce * tau) nu_ext = eta * nu_thresh # external rate per synapse input_rate = 1000.0 * nu_ext * Cext # mean input spiking rate # Parameters neuron_parameters = dict(tau=tau * ms, v_threshold=theta * mV, refractory_period=2.0 * ms, v_reset=10.0 * mV, R=1.5 * Mohm) # units?? psr_parameters = dict(tau=tau_syn * ms) # Initial Values v_init = RandomDistributionProperties( "uniform_rest_to_threshold", ninemlcatalog.load("randomdistribution/Uniform", 'UniformDistribution'), { 'minimum': (0.0, unitless), 'maximum': (theta, unitless) }) # v_init = 0.0 neuron_initial_values = {"v": (v_init * mV), "refractory_end": (0.0 * ms)} synapse_initial_values = {"a": (0.0 * nA), "b": (0.0 * nA)} tpoisson_init = RandomDistributionProperties( "exponential_beta", ninemlcatalog.load('randomdistribution/Exponential', 'ExponentialDistribution'), {"rate": (1000.0 / input_rate * unitless)}) # tpoisson_init = 5.0 # Dynamics components celltype = DynamicsProperties("nrn", ninemlcatalog.load( 'neuron/LeakyIntegrateAndFire', 'LeakyIntegrateAndFire'), neuron_parameters, initial_values=neuron_initial_values) ext_stim = DynamicsProperties( "stim", ninemlcatalog.load('input/Poisson', 'Poisson'), dict(rate=(input_rate, Hz)), initial_values={"t_next": (tpoisson_init, ms)}) psr = DynamicsProperties("syn", ninemlcatalog.load('postsynapticresponse/Alpha', 'Alpha'), psr_parameters, initial_values=synapse_initial_values) # Connecion rules one_to_one_class = ninemlcatalog.load('/connectionrule/OneToOne', 'OneToOne') random_fan_in_class = ninemlcatalog.load('/connectionrule/RandomFanIn', 'RandomFanIn') # Populations exc_cells = Population("Exc", Ne, celltype, positions=None) inh_cells = Population("Inh", Ni, celltype, positions=None) external = Population("Ext", Ne + Ni, ext_stim, positions=None) # Selections all_cells = Selection("All", Concatenate((exc_cells, inh_cells))) # Projections input_prj = Projection("External", external, all_cells, connection_rule_properties=ConnectionRuleProperties( "OneToOne", one_to_one_class), response=psr, plasticity=DynamicsProperties( "ExternalPlasticity", ninemlcatalog.load("plasticity/Static", 'Static'), properties={"weight": (Jext, nA)}), port_connections=[ EventPortConnection('pre', 'response', 'spike_output', 'spike'), AnalogPortConnection("plasticity", "response", "fixed_weight", "weight"), AnalogPortConnection("response", "destination", "i_synaptic", "i_synaptic") ], delay=(delay, ms)) exc_prj = Projection("Excitation", exc_cells, all_cells, connection_rule_properties=ConnectionRuleProperties( "RandomExc", random_fan_in_class, {"number": (Ce * unitless)}), response=psr, plasticity=DynamicsProperties( "ExcitatoryPlasticity", ninemlcatalog.load("plasticity/Static", 'Static'), properties={"weight": (Je, nA)}), port_connections=[ EventPortConnection('pre', 'response', 'spike_output', 'spike'), AnalogPortConnection("plasticity", "response", "fixed_weight", "weight"), AnalogPortConnection("response", "destination", "i_synaptic", "i_synaptic") ], delay=(delay, ms)) inh_prj = Projection("Inhibition", inh_cells, all_cells, connection_rule_properties=ConnectionRuleProperties( "RandomInh", random_fan_in_class, {"number": (Ci * unitless)}), response=psr, plasticity=DynamicsProperties( "InhibitoryPlasticity", ninemlcatalog.load("plasticity/Static", 'Static'), properties={"weight": (Ji, nA)}), port_connections=[ EventPortConnection('pre', 'response', 'spike_output', 'spike'), AnalogPortConnection("plasticity", "response", "fixed_weight", "weight"), AnalogPortConnection("response", "destination", "i_synaptic", "i_synaptic") ], delay=(delay, ms)) # Save to document in NineML Catalog network = Network(name if name else "BrunelNetwork") network.add(exc_cells, inh_cells, external, all_cells, input_prj, exc_prj, inh_prj) return network
"respectively")) args = parser.parse_args() if args.mode == 'print': document = Document() print(etree.tostring( E.NineML( create_static().to_xml(document), parameterise_static().to_xml(document)), encoding="UTF-8", pretty_print=True, xml_declaration=True)) elif args.mode == 'compare': if ninemlcatalog is None: raise Exception( "NineML catalog is not installed") local_version = create_static() catalog_version = ninemlcatalog.load(catalog_path, local_version.name) mismatch = local_version.find_mismatch(catalog_version) if mismatch: print ("Local version differs from catalog version:\n{}" .format(mismatch)) else: print("Local version matches catalog version") elif args.mode == 'save': if ninemlcatalog is None: raise Exception( "NineML catalog is not installed") dynamics = create_static() ninemlcatalog.save(dynamics, catalog_path, dynamics.name) params = parameterise_static( ninemlcatalog.load(catalog_path, dynamics.name)) ninemlcatalog.save(params, catalog_path, params.name)
"respectively")) args = parser.parse_args() if args.mode == 'print': document = Document() print( etree.tostring(E.NineML(create_static().to_xml(document), parameterise_static().to_xml(document)), encoding="UTF-8", pretty_print=True, xml_declaration=True)) elif args.mode == 'compare': if ninemlcatalog is None: raise Exception("NineML catalog is not installed") local_version = create_static() catalog_version = ninemlcatalog.load(catalog_path, local_version.name) mismatch = local_version.find_mismatch(catalog_version) if mismatch: print("Local version differs from catalog version:\n{}".format( mismatch)) else: print("Local version matches catalog version") elif args.mode == 'save': if ninemlcatalog is None: raise Exception("NineML catalog is not installed") dynamics = create_static() ninemlcatalog.save(dynamics, catalog_path, dynamics.name) params = parameterise_static( ninemlcatalog.load(catalog_path, dynamics.name)) ninemlcatalog.save(params, catalog_path, params.name) print("Saved '{}' and '{}' to catalog".format(dynamics.name,
def run(argv): args = argparser().parse_args(argv) if not args.simulators and not args.reference: raise Exception("No simulations requested " "(see --simulators and --reference options)") if args.save_fig is not None: matplotlib.use('Agg') save_path = os.path.abspath(args.save_fig) if not os.path.exists(save_path) and is_mpi_master(): os.mkdir(save_path) else: save_path = None # Imports matplotlib so needs to be after save_fig is parsed from pype9.utils.testing import ReferenceBrunel2000 # @IgnorePep8 # Needs to be imported after the args.save_fig argument is parsed to # allow the backend to be set from matplotlib import pyplot as plt # @IgnorePep8 simulations = {} pype9_network_classes = {} if 'neuron' in args.simulators: from pype9.simulate.neuron import ( Simulation as SimulationNEURON, Network as NetworkNEURON) # @IgnorePep8 simulations['neuron'] = SimulationNEURON pype9_network_classes['neuron'] = NetworkNEURON if 'nest' in args.simulators or args.reference: from pype9.simulate.nest import ( Simulation as SimulationNEST, Network as NetworkNEST) # @IgnorePep8 simulations['nest'] = SimulationNEST pype9_network_classes['nest'] = NetworkNEST # Get the list of populations to record and plot from pops_to_plot = ['Exc', 'Inh'] if args.plot_input: pops_to_plot.append('Ext') # Set the random seed np.random.seed(args.seed) seeds = np.asarray( np.floor(np.random.random(len(args.simulators)) * 1e5), dtype=int) # Load the Brunel model corresponding to the 'case' argument from the # nineml catalog and scale the model according to the 'order' argument model = ninemlcatalog.load('network/Brunel2000/' + args.case).as_network( 'Brunel_{}'.format(args.case)) scale = args.order / model.population('Inh').size if scale != 1.0: for pop in model.populations: pop.size = int(np.ceil(pop.size * scale)) for proj in (model.projection('Excitation'), model.projection('Inhibition')): props = proj.connectivity.rule_properties number = props.property('number') props.set(Property( number.name, int(np.ceil(float(number.value * scale))) * un.unitless)) if args.input_rate is not None: props = model.population('Ext').cell props.set(Property( 'rate', args.input_rate * un.Hz)) if args.no_init_v: for pop_name in ('Exc', 'Inh'): props = model.population(pop_name).cell props.set(Initial('v', 0.0 * un.V)) # Create the network for each simulator and set recorders networks = {} for simulator, seed in zip(args.simulators, seeds): # Reset the simulator with simulations[simulator](min_delay=ReferenceBrunel2000.min_delay, max_delay=ReferenceBrunel2000.max_delay, dt=args.timestep * un.ms, seed=seed) as sim: # Construct the network print("Constructing the network in {}".format(simulator.upper())) networks[simulator] = pype9_network_classes[simulator]( model, build_mode=args.build_mode) print("Finished constructing the network in {}".format( simulator.upper())) # Record spikes and voltages for pop in networks[simulator].component_arrays: pop[:args.num_record].record('spikes') if args.num_record_v and pop.name != 'Ext': pop[:args.num_record_v].record('v__cell') # Create the reference simulation if required if simulator == 'nest' and args.reference: print("Constructing the reference NEST implementation") if args.no_init_v: init_v = {'Exc': 0.0, 'Inh': 0.0} else: init_v = None ref = ReferenceBrunel2000( args.case, args.order, override_input=args.input_rate, init_v=init_v) ref.record(num_record=args.num_record, num_record_v=args.num_record_v, to_plot=pops_to_plot, timestep=args.timestep) # Run the simulation(s) print("Running the simulation in {}".format(simulator.upper())) if args.progress_bar: kwargs = {'callbacks': [ SimulationProgressBar(args.simtime / 77, args.simtime)]} else: kwargs = {} sim.run(args.simtime * un.ms, **kwargs) if is_mpi_master(): # Plot the results print("Plotting the results") num_subplots = len(args.simulators) + int(args.reference) for pop_name in pops_to_plot: spike_fig, spike_subplots = plt.subplots(num_subplots, 1, figsize=args.figsize) spike_fig.suptitle("{} - {} Spike Times".format(args.case, pop_name), fontsize=14) if args.num_record_v: v_fig, v_subplots = plt.subplots(num_subplots, 1, figsize=args.figsize) v_fig.suptitle("{} - {} Membrane Voltage".format(args.case, pop_name), fontsize=14) for subplot_index, simulator in enumerate(args.simulators): # Get the recordings for the population pop = networks[simulator].component_array(pop_name) block = pop.get_data() segment = block.segments[0] # Plot the spike trains spiketrains = segment.spiketrains spike_times = [] ids = [] for i, spiketrain in enumerate(spiketrains): spike_times.extend(spiketrain) ids.extend([i] * len(spiketrain)) plt.sca(spike_subplots[subplot_index] if num_subplots > 1 else spike_subplots) plt.scatter(spike_times, ids) plt.xlim((args.plot_start, args.simtime)) plt.ylim((-1, len(spiketrains))) plt.xlabel('Times (ms)') plt.ylabel('Cell Indices') plt.title("PyPe9 {}".format(simulator.upper()), fontsize=12) if args.num_record_v and pop_name != 'Ext': traces = segment.analogsignalarrays plt.sca(v_subplots[subplot_index] if num_subplots > 1 else v_subplots) for trace in traces: plt.plot(trace.times, trace) plt.xlim((args.plot_start, args.simtime)) plt.ylim([0.0, 20.0]) plt.xlabel('Time (ms)') plt.ylabel('Membrane Voltage (mV)') plt.title("Pype9 {}".format(simulator.upper()), fontsize=12) if args.reference: events = nest.GetStatus(ref.recorders[pop_name]['spikes'], "events")[0] spike_times = np.asarray(events['times']) senders = np.asarray(events['senders']) inds = np.asarray(spike_times > args.plot_start, dtype=bool) spike_times = spike_times[inds] senders = senders[inds] if len(senders): senders -= senders.min() max_y = senders.max() + 1 else: max_y = args.num_record plt.sca(spike_subplots[-1] if num_subplots > 1 else spike_subplots) plt.scatter(spike_times, senders) plt.xlim((args.plot_start, args.simtime)) plt.ylim((-1, max_y)) plt.xlabel('Times (ms)') plt.ylabel('Cell Indices') plt.title("Ref. NEST", fontsize=12) if args.num_record_v and pop_name != 'Ext': events, = nest.GetStatus(ref.recorders[pop_name]['V_m'], ["events"])[0] sorted_vs = sorted(zip(events['senders'], events['times'], events['V_m']), key=itemgetter(0)) plt.sca(v_subplots[-1] if num_subplots > 1 else v_subplots) for _, group in groupby(sorted_vs, key=itemgetter(0)): _, t, v = list(zip(*group)) t = np.asarray(t) v = np.asarray(v) inds = t > args.plot_start plt.plot(t[inds], v[inds]) plt.xlim((args.plot_start, args.simtime)) plt.ylim([0.0, 20.0]) plt.xlabel('Time (ms)') plt.ylabel('Membrane Voltage (mV)') plt.title("Ref. NEST", fontsize=12) if save_path is not None: spike_fig.savefig(os.path.join(save_path, '{}_spikes'.format(pop_name))) if args.num_record_v: v_fig.savefig(os.path.join(save_path, '{}_v'.format(pop_name))) if save_path is None: plt.show() print("done")
def run(argv): args = argparser().parse_args(argv) delay = args.delay * un.ms # Import of nest needs to be after arguments have been passed as it kills # them before the SLI interpreter tries to read them. if args.simulator == 'nest': from pype9.simulate.nest import CellMetaClass, Simulation # @IgnorePep8 @UnusedImport elif args.simulator == 'neuron': from pype9.simulate.neuron import CellMetaClass, Simulation # @IgnorePep8 @Reimport else: raise Exception("Unrecognised simulator '{}' (can be either 'nest' or " "'neuron')".format(args.simulator)) # Get and combine 9ML models input_model = ninemlcatalog.load( 'input/ConstantRate', 'ConstantRate') liaf_model = ninemlcatalog.load( 'neuron/LeakyIntegrateAndFire', 'LeakyIntegrateAndFire') alpha_model = ninemlcatalog.load( 'postsynapticresponse/Alpha', 'Alpha') weight_model = ninemlcatalog.load( 'plasticity/Static', 'Static') multi_model = MultiDynamics( name="test_alpha_syn", sub_components={'cell': liaf_model, 'psr': alpha_model, 'pls': weight_model}, port_connections=[('psr', 'i_synaptic', 'cell', 'i_synaptic'), ('pls', 'fixed_weight', 'psr', 'weight')], port_exposures=[('psr', 'input_spike'), ('cell', 'spike_output')]) # Add connection weight conn_params = [] if args.connection_weight: conn_params.append(ConnectionParameterSet( 'input_spike__psr', [multi_model.parameter('weight__pls')])) # Reinterpret the multi-component model as one containing synapses that can # be set by connection weights w_syn_model = WithSynapses.wrap(multi_model, connection_parameter_sets=conn_params) # Generate Pype9 classes Input = CellMetaClass(input_model, build_mode=args.build_mode) Cell = CellMetaClass(w_syn_model, build_mode=args.build_mode) # Create instances rate = args.rate * un.Hz weight = args.weight * un.nA cell_params = { 'tau__cell': args.tau * un.ms, 'R__cell': 1.5 * un.Mohm, 'refractory_period__cell': 2.0 * un.ms, 'v_threshold__cell': args.threshold * un.mV, 'v_reset__cell': 0.0 * un.mV, 'tau__psr': 0.5 * un.ms, 'regime_': 'subthreshold___sole___sole', 'b__psr': 0.0 * un.nA, 'a__psr': 0.0 * un.nA, 'v__cell': 0.0 * un.mV, 'refractory_end__cell': 0.0 * un.ms} # If PSR weight is part of the cell dynamics (as opposed to the connection) if args.connection_weight: conn_properties = [Property('weight__pls', weight)] else: cell_params['weight__pls'] = weight conn_properties = [] with Simulation(args.timestep * un.ms, min_delay=delay) as sim: input = Input(rate=rate, t_next=(1 * un.unitless) / rate) # @ReservedAssignment @IgnorePep8 cell = Cell(**cell_params) # Connect cells together cell.connect(input, 'spike_output', 'input_spike__psr', delay, properties=conn_properties) # Set up recorders cell.record('spike_output__cell') cell.record_regime() cell.record('v__cell') # Run simulation sim.run(args.simtime * un.ms) # Plot recordings plot(cell.recordings(), save=args.save_fig, show=(not args.save_fig), title='Leaky Integrate and Fire with Alpha Synapse') print("Finished simulation.")
def run(argv): args = argparser().parse_args(argv) if args.reference and args.fast_spiking: raise Exception( "--reference and --fast_spiking options cannot be used together as" " there is no reference implementation for the fast-spiking model") # Set the random seed np.random.seed(args.seed) seeds = np.asarray(np.floor(np.random.random(len(args.simulators)) * 1e5), dtype=int) # Set of simulators to run simulators_to_run = set(args.simulators) if args.reference: simulators_to_run.add('nest') MetaClasses = {} Simulations = {} if 'neuron' in simulators_to_run: from pype9.simulate.neuron import (CellMetaClass as CellMetaClassNEURON, Simulation as SimulationNEURON) Simulations['neuron'] = SimulationNEURON MetaClasses['neuron'] = CellMetaClassNEURON if 'nest' in simulators_to_run: from pype9.simulate.nest import (CellMetaClass as CellMetaClassNEST, Simulation as SimulationNEST) Simulations['nest'] = SimulationNEST MetaClasses['nest'] = CellMetaClassNEST if args.fast_spiking: model = ninemlcatalog.load('neuron/Izhikevich', 'IzhikevichFastSpiking') properties = ninemlcatalog.load('neuron/Izhikevich', 'SampleIzhikevichFastSpiking') initial_states = { 'U': -1.625 * pq.pA, 'V': -70.0 * pq.mV, 'regime_': 'subthreshold' } input_port_name = 'iSyn' if args.input_amplitude is None: input_amp = 100 * pq.pA else: input_amp = args.input_amplitude * pq.pA # Designate 'iSyn' as an "external" current so that we can play # signals into it. metaclass_kwargs = {'external_currents': ['iSyn']} else: model = ninemlcatalog.load('neuron/Izhikevich', 'Izhikevich') properties = ninemlcatalog.load('neuron/Izhikevich', 'SampleIzhikevich') initial_states = {'U': -14.0 * pq.mV / pq.ms, 'V': -70.0 * pq.mV} input_port_name = 'Isyn' if args.input_amplitude is None: input_amp = 15 * pq.pA else: input_amp = args.input_amplitude * pq.pA metaclass_kwargs = {} # Isyn should be guessed as an external current # Create an input step current # NB: The analog signal needs to be offset > "device delay" (i.e. the # delay from the current source) when playing into NEST cells offset = min_delay + args.timestep num_preceding = int(np.floor((args.input_start - offset) / args.timestep)) num_remaining = int( np.ceil((args.simtime - args.input_start) / args.timestep)) amplitude = float(pq.Quantity(input_amp, 'nA')) input_signal = neo.AnalogSignal(np.concatenate( (np.zeros(num_preceding), np.ones(num_remaining) * amplitude)), sampling_period=args.timestep * pq.ms, units='nA', time_units='ms', t_start=offset * pq.ms) cells = {} for simulator, seed in zip(simulators_to_run, seeds): with Simulations[simulator](min_delay=min_delay * un.ms, max_delay=max_delay * un.ms, dt=args.timestep * un.ms, seed=seed) as sim: # Construct the cells and set up recordings and input plays if simulator in args.simulators: Cell = MetaClasses[simulator](model, **metaclass_kwargs) cells[simulator] = Cell(properties, **initial_states) # Play input current into cell cells[simulator].play(input_port_name, input_signal) # Record voltage cells[simulator].record('V') if args.reference: _, ref_multi, _ = construct_reference(input_signal, args.timestep) sim.run(args.simtime * un.ms) # Plot the results if args.save_fig is not None: import matplotlib matplotlib.use('Agg') # Needs to be imported after the args.save_fig argument is parsed to # allow the backend to be set from matplotlib import pyplot as plt # @IgnorePep8 print("Plotting the results") plt.figure(figsize=args.figsize) if args.fast_spiking: title = "Izhikevich Fast Spiking" else: title = "Izhikevich Original" plt.title(title) legend = [] for simulator in args.simulators: v = cells[simulator].recording('V') v = v.time_slice(args.plot_start * pq.ms, v.t_stop) plt.plot(v.times, v) legend.append(simulator.upper()) if args.reference: events = nest.GetStatus(ref_multi, ["events"])[0] t, v = np.asarray(events['times']), np.asarray(events['V_m']) inds = t > args.plot_start plt.plot(t[inds], v[inds]) legend.append('Ref. NEST') plt.xlabel('Time (ms)') plt.ylabel('Membrane Voltage (mV)') plt.legend(legend) if args.save_fig is not None: plt.savefig(args.save_fig) else: plt.show() print("done")
def test_izhi(self, plot=PLOT_DEFAULT, print_comparisons=False, simulators=SIMULATORS_TO_TEST, dt=0.001, duration=100.0, build_mode=BUILD_MODE_DEFAULT, **kwargs): # @UnusedVariable # Force compilation of code generation # Perform comparison in subprocess comparer = Comparer( nineml_model=ninemlcatalog.load('neuron/Izhikevich', 'Izhikevich'), state_variable='V', dt=dt, simulators=simulators, properties=ninemlcatalog.load('neuron/Izhikevich', 'SampleIzhikevich'), initial_states={ 'U': -14.0 * pq.mV / pq.ms, 'V': -65.0 * pq.mV }, neuron_ref='Izhikevich', nest_ref='izhikevich', # auxiliary_states=['U'], input_signal=input_step('Isyn', 0.02, 50, 100, dt, 30), nest_translations={ 'V': ('V_m', 1), 'U': ('U_m', 1), 'weight': (None, 1), 'C_m': (None, 1), 'theta': ('V_th', 1), 'alpha': (None, 1), 'beta': (None, 1), 'zeta': (None, 1) }, neuron_translations={ 'C_m': (None, 1), 'weight': (None, 1), 'V': ('v', 1), 'U': ('u', 1), 'alpha': (None, 1), 'beta': (None, 1), 'zeta': (None, 1), 'theta': ('vthresh', 1) }, neuron_build_args={ 'build_mode': build_mode, 'build_version': 'TestDyn' }, nest_build_args={ 'build_mode': build_mode, 'build_version': 'TestDyn' }) comparer.simulate(duration * un.ms, nest_rng_seed=NEST_RNG_SEED, neuron_rng_seed=NEURON_RNG_SEED) comparisons = comparer.compare() if print_comparisons: for (name1, name2), diff in comparisons.items(): print('{} v {}: {}'.format(name1, name2, diff)) if plot: comparer.plot() if 'nest' in simulators and 'neuron' in simulators: self.assertLess( comparisons[('9ML-nest', '9ML-neuron')], 0.4 * pq.mV, "Izhikevich NEURON 9ML simulation did not match NEST 9ML " "within {} ({})".format( 0.4 * pq.mV, comparisons[('9ML-nest', '9ML-neuron')])) if 'neuron' in simulators: self.assertLess( comparisons[('9ML-neuron', 'Ref-neuron')], 0.01 * pq.mV, "Izhikevich NEURON 9ML simulation did not match reference " "PyNN within {} ({})".format( 0.01 * pq.mV, comparisons[('9ML-neuron', 'Ref-neuron')])) if 'nest' in simulators: self.assertLess( comparisons[('9ML-nest', 'Ref-nest')], 0.02 * pq.mV, "Izhikevich NEST 9ML simulation did not match reference " "built-in within {} ({})".format( 0.02 * pq.mV, comparisons[('9ML-nest', 'Ref-nest')]))
def run(argv): args = argparser().parse_args(argv) if args.reference and args.fast_spiking: raise Exception( "--reference and --fast_spiking options cannot be used together as" " there is no reference implementation for the fast-spiking model") # Set the random seed np.random.seed(args.seed) seeds = np.asarray( np.floor(np.random.random(len(args.simulators)) * 1e5), dtype=int) # Set of simulators to run simulators_to_run = set(args.simulators) if args.reference: simulators_to_run.add('nest') MetaClasses = {} Simulations = {} if 'neuron' in simulators_to_run: from pype9.simulate.neuron import ( CellMetaClass as CellMetaClassNEURON, Simulation as SimulationNEURON) Simulations['neuron'] = SimulationNEURON MetaClasses['neuron'] = CellMetaClassNEURON if 'nest' in simulators_to_run: from pype9.simulate.nest import ( CellMetaClass as CellMetaClassNEST, Simulation as SimulationNEST) Simulations['nest'] = SimulationNEST MetaClasses['nest'] = CellMetaClassNEST if args.fast_spiking: model = ninemlcatalog.load('neuron/Izhikevich', 'IzhikevichFastSpiking') properties = ninemlcatalog.load('neuron/Izhikevich', 'SampleIzhikevichFastSpiking') initial_states = {'U': -1.625 * pq.pA, 'V': -70.0 * pq.mV, 'regime_': 'subthreshold'} input_port_name = 'iSyn' if args.input_amplitude is None: input_amp = 100 * pq.pA else: input_amp = args.input_amplitude * pq.pA # Designate 'iSyn' as an "external" current so that we can play # signals into it. metaclass_kwargs = {'external_currents': ['iSyn']} else: model = ninemlcatalog.load('neuron/Izhikevich', 'Izhikevich') properties = ninemlcatalog.load('neuron/Izhikevich', 'SampleIzhikevich') initial_states = {'U': -14.0 * pq.mV / pq.ms, 'V': -70.0 * pq.mV} input_port_name = 'Isyn' if args.input_amplitude is None: input_amp = 15 * pq.pA else: input_amp = args.input_amplitude * pq.pA metaclass_kwargs = {} # Isyn should be guessed as an external current # Create an input step current # NB: The analog signal needs to be offset > "device delay" (i.e. the # delay from the current source) when playing into NEST cells offset = min_delay + args.timestep num_preceding = int(np.floor((args.input_start - offset) / args.timestep)) num_remaining = int(np.ceil((args.simtime - args.input_start) / args.timestep)) amplitude = float(pq.Quantity(input_amp, 'nA')) input_signal = neo.AnalogSignal( np.concatenate((np.zeros(num_preceding), np.ones(num_remaining) * amplitude)), sampling_period=args.timestep * pq.ms, units='nA', time_units='ms', t_start=offset * pq.ms) cells = {} for simulator, seed in zip(simulators_to_run, seeds): with Simulations[simulator]( min_delay=min_delay * un.ms, max_delay=max_delay * un.ms, dt=args.timestep * un.ms, seed=seed) as sim: # Construct the cells and set up recordings and input plays if simulator in args.simulators: Cell = MetaClasses[simulator](model, **metaclass_kwargs) cells[simulator] = Cell(properties, **initial_states) # Play input current into cell cells[simulator].play(input_port_name, input_signal) # Record voltage cells[simulator].record('V') if args.reference: _, ref_multi, _ = construct_reference(input_signal, args.timestep) sim.run(args.simtime * un.ms) # Plot the results if args.save_fig is not None: import matplotlib matplotlib.use('Agg') # Needs to be imported after the args.save_fig argument is parsed to # allow the backend to be set from matplotlib import pyplot as plt # @IgnorePep8 print("Plotting the results") plt.figure(figsize=args.figsize) if args.fast_spiking: title = "Izhikevich Fast Spiking" else: title = "Izhikevich Original" plt.title(title) legend = [] for simulator in args.simulators: v = cells[simulator].recording('V') v = v.time_slice(args.plot_start * pq.ms, v.t_stop) plt.plot(v.times, v) legend.append(simulator.upper()) if args.reference: events = nest.GetStatus(ref_multi, ["events"])[0] t, v = np.asarray(events['times']), np.asarray(events['V_m']) inds = t > args.plot_start plt.plot(t[inds], v[inds]) legend.append('Ref. NEST') plt.xlabel('Time (ms)') plt.ylabel('Membrane Voltage (mV)') plt.legend(legend) if args.save_fig is not None: plt.savefig(args.save_fig) else: plt.show() print("done")
pyNN_module['nest'] = pyNN.nest pype9_network_classes['nest'] = pype9.nest.Network # Get the list of populations to record and plot from pops_to_plot = ['Exc', 'Inh'] if args.plot_input: pops_to_plot.append('Ext') # Set the random seed np.random.seed(args.seed) seeds = np.asarray( np.floor(np.random.random(len(args.simulators)) * 1e5), dtype=int) # Load the Brunel model corresponding to the 'case' argument from the # nineml catalog and scale the model according to the 'order' argument model = ninemlcatalog.load('network/Brunel2000/' + args.case).as_network( 'Brunel_{}'.format(args.case)) scale = args.order / model.population('Inh').size if scale != 1.0: for pop in model.populations: pop.size = int(np.ceil(pop.size * scale)) for proj in (model.projection('Excitation'), model.projection('Inhibition')): props = proj.connectivity.rule_properties number = props.property('number') props.set(Property( number.name, int(np.ceil(number.value * scale)) * un.unitless)) if args.input_rate is not None: props = model.population('Ext').cell props.set(Property(