def run_hnn_core(backend=None, n_jobs=1): """Test to check if hnn-core does not break.""" # small snippet of data on data branch for now. To be deleted # later. Data branch should have only commit so it does not # pollute the history. data_url = ('https://raw.githubusercontent.com/jonescompneurolab/' 'hnn-core/test_data/dpl.txt') if not op.exists('dpl.txt'): _fetch_file(data_url, 'dpl.txt') dpl_master = loadtxt('dpl.txt') hnn_core_root = op.dirname(hnn_core.__file__) # default params params_fname = op.join(hnn_core_root, 'param', 'default.json') params = read_params(params_fname) # run the simulation net = Network(params) if backend == 'mpi': with MPIBackend(n_procs=2, mpi_cmd='mpiexec'): dpl = simulate_dipole(net)[0] elif backend == 'joblib': with JoblibBackend(n_jobs=n_jobs): dpl = simulate_dipole(net)[0] else: dpl = simulate_dipole(net)[0] # write the dipole to a file and compare fname = './dpl2.txt' dpl.write(fname) dpl_pr = loadtxt(fname) assert_array_equal(dpl_pr[:, 2], dpl_master[:, 2]) # L2 assert_array_equal(dpl_pr[:, 3], dpl_master[:, 3]) # L5 # Test spike type counts spiketype_counts = {} for spikegid in net.spikes.gids[0]: if net.gid_to_type(spikegid) not in spiketype_counts: spiketype_counts[net.gid_to_type(spikegid)] = 0 else: spiketype_counts[net.gid_to_type(spikegid)] += 1 assert 'common' not in spiketype_counts assert 'exgauss' not in spiketype_counts assert 'extpois' not in spiketype_counts assert spiketype_counts == { 'evprox1': 269, 'L2_basket': 54, 'L2_pyramidal': 113, 'L5_pyramidal': 395, 'L5_basket': 85, 'evdist1': 234, 'evprox2': 269 }
def _run_hnn_core_fixture(backend=None, n_procs=None, n_jobs=1, reduced=False, record_vsoma=False, record_isoma=False, postproc=True): hnn_core_root = op.dirname(hnn_core.__file__) # default params params_fname = op.join(hnn_core_root, 'param', 'default.json') params = read_params(params_fname) if reduced: params.update({ 'N_pyr_x': 3, 'N_pyr_y': 3, 'tstop': 25, 't_evprox_1': 5, 't_evdist_1': 10, 't_evprox_2': 20, 'N_trials': 2 }) net = Network(params) # number of trials simulated assert all( len(src_feed_times) == params['N_trials'] for src_type, src_feed_times in net.feed_times.items() if src_type != 'tonic') if backend == 'mpi': with MPIBackend(n_procs=n_procs, mpi_cmd='mpiexec'): dpls = simulate_dipole(net, record_vsoma=record_isoma, record_isoma=record_vsoma, postproc=postproc) elif backend == 'joblib': with JoblibBackend(n_jobs=n_jobs): dpls = simulate_dipole(net, record_vsoma=record_isoma, record_isoma=record_vsoma, postproc=postproc) else: dpls = simulate_dipole(net, record_vsoma=record_isoma, record_isoma=record_vsoma, postproc=postproc) return dpls, net
def _run_hnn_core_fixture(backend=None, n_procs=None, n_jobs=1, reduced=False, record_vsoma=False, record_isoma=False, postproc=True): hnn_core_root = op.dirname(hnn_core.__file__) # default params params_fname = op.join(hnn_core_root, 'param', 'default.json') params = read_params(params_fname) if reduced: params.update({ 'N_pyr_x': 3, 'N_pyr_y': 3, 'tstop': 40, 't_evprox_1': 5, 't_evdist_1': 10, 't_evprox_2': 20, 'N_trials': 2 }) net = Network(params, add_drives_from_params=True) # number of trials simulated for drive in net.external_drives.values(): assert len(drive['events']) == params['N_trials'] if backend == 'mpi': with MPIBackend(n_procs=n_procs, mpi_cmd='mpiexec'): dpls = simulate_dipole(net, record_vsoma=record_isoma, record_isoma=record_vsoma, postproc=postproc) elif backend == 'joblib': with JoblibBackend(n_jobs=n_jobs): dpls = simulate_dipole(net, record_vsoma=record_isoma, record_isoma=record_vsoma, postproc=postproc) else: dpls = simulate_dipole(net, record_vsoma=record_isoma, record_isoma=record_vsoma, postproc=postproc) return dpls, net
def simulate(net): """Start the simulation with hnn_core.simulate Parameters ---------- net : Network object The constructed Network object from hnn-core """ sim_data = {} # run the simulation with MPIBackend for faster completion time record_vsoma = bool(net.params['record_vsoma']) numspikes_params = net.params['numspikes_*'] # optimization can feed in floats for numspikes for param_name, spikes in numspikes_params.items(): net.params[param_name] = round(spikes) sim_data['raw_dpls'] = simulate_dipole(net, net.params['N_trials'], postproc=False, record_vsoma=record_vsoma) # hnn-core changes this to bool, change back to int if isinstance(net.params['record_vsoma'], bool): net.params['record_vsoma'] = int(record_vsoma) sim_data['gid_ranges'] = net.gid_ranges sim_data['spikes'] = net.cell_response sim_data['vsoma'] = net.cell_response.vsoma return sim_data
def test_hnn_core(): """Test to check if MNE neuron does not break.""" # small snippet of data on data branch for now. To be deleted # later. Data branch should have only commit so it does not # pollute the history. data_url = ('https://raw.githubusercontent.com/hnnsolver/' 'hnn-core/test_data/dpl.txt') if not op.exists('dpl.txt'): _fetch_file(data_url, 'dpl.txt') dpl_master = loadtxt('dpl.txt') hnn_core_root = op.join(op.dirname(hnn_core.__file__), '..') params_fname = op.join(hnn_core_root, 'param', 'default.json') params = Params(params_fname) net = Network(params, n_jobs=1) dpl = simulate_dipole(net)[0] fname = './dpl2.txt' dpl.write(fname) dpl_pr = loadtxt(fname) assert_array_equal(dpl_pr[:, 2], dpl_master[:, 2]) # L2 assert_array_equal(dpl_pr[:, 3], dpl_master[:, 3]) # L5
def _run_hnn_core_fixture(backend=None, n_procs=None, n_jobs=1, reduced=False, record_vsoma=False, record_isoma=False, postproc=False, electrode_array=None): hnn_core_root = op.dirname(hnn_core.__file__) # default params params_fname = op.join(hnn_core_root, 'param', 'default.json') params = read_params(params_fname) tstop = 170. if reduced: params.update({'N_pyr_x': 3, 'N_pyr_y': 3, 't_evprox_1': 5, 't_evdist_1': 10, 't_evprox_2': 20, 'N_trials': 2}) tstop = 40. net = jones_2009_model(params, add_drives_from_params=True) if electrode_array is not None: for name, positions in electrode_array.items(): net.add_electrode_array(name, positions) if backend == 'mpi': with MPIBackend(n_procs=n_procs, mpi_cmd='mpiexec'): dpls = simulate_dipole(net, record_vsoma=record_isoma, record_isoma=record_vsoma, postproc=postproc, tstop=tstop) elif backend == 'joblib': with JoblibBackend(n_jobs=n_jobs): dpls = simulate_dipole(net, record_vsoma=record_isoma, record_isoma=record_vsoma, postproc=postproc, tstop=tstop) else: dpls = simulate_dipole(net, record_vsoma=record_isoma, record_isoma=record_vsoma, postproc=postproc, tstop=tstop) # check that the network object is picklable after the simulation pickle.dumps(net) # number of trials simulated for drive in net.external_drives.values(): assert len(drive['events']) == params['N_trials'] return dpls, net
def test_rec_array_calculation(): """Test LFP calculation.""" hnn_core_root = op.dirname(hnn_core.__file__) params_fname = op.join(hnn_core_root, 'param', 'default.json') params = read_params(params_fname) params.update({'N_pyr_x': 3, 'N_pyr_y': 3, 't_evprox_1': 7, 't_evdist_1': 17}) net = jones_2009_model(params, add_drives_from_params=True) # one electrode inside, one above the active elements of the network electrode_pos = [(1.5, 1.5, 1000), (1.5, 1.5, 3000)] net.add_electrode_array('arr1', electrode_pos) _ = simulate_dipole(net, tstop=5, n_trials=1) # test accessing simulated voltages assert (len(net.rec_arrays['arr1']) == len(net.rec_arrays['arr1'].voltages) == 1) # n_trials assert len(net.rec_arrays['arr1'].voltages[0]) == 2 # n_contacts assert (len(net.rec_arrays['arr1'].voltages[0][0]) == len(net.rec_arrays['arr1'].times)) # ensure copy drops data (but retains electrode position information etc.) net_copy = net.copy() assert isinstance(net_copy.rec_arrays['arr1'], ExtracellularArray) assert len(net_copy.rec_arrays['arr1'].voltages) == 0 assert isinstance(net.rec_arrays['arr1'].voltages, np.ndarray) assert isinstance(net.rec_arrays['arr1'].times, np.ndarray) # using the same electrode positions, but a different method: LSA net.add_electrode_array('arr2', electrode_pos, method='lsa') # make sure no sinister segfaults are triggered when running mult. trials n_trials = 5 # NB 5 trials! _ = simulate_dipole(net, tstop=5, n_trials=n_trials) # simulate_dipole is run twice above, first 1 then 5 trials. # Make sure that previous results are discarded on each run assert len(net.rec_arrays['arr1']._data) == n_trials for trial_idx in range(n_trials): # LSA and PSA should agree far away (second electrode) assert_allclose(net.rec_arrays['arr1']._data[trial_idx][1], net.rec_arrays['arr2']._data[trial_idx][1], rtol=1e-3, atol=1e-3)
def adjust_param_and_simulate_dipole(thisParams, paramsOfInterest, paramValue, outDir): for paramOfInterest in paramsOfInterest: thisParams.update({paramOfInterest: paramValue}) net = Network(thisParams) dpl = simulate_dipole(net) return dpl
def __call__(self, new_param_values): new_params = dict( zip(self.param_names, new_param_values.detach().cpu().numpy())) self.params.update(new_params) net = Network(self.params) with JoblibBackend(n_jobs=1): dpl = simulate_dipole(net, n_trials=1) summstats = torch.as_tensor(dpl[0].data['agg']) return summstats
def adjust_param_and_simulate_dipole_mp(paramValue): for paramOfInterest in paramsOfInterest: params.update({paramOfInterest: paramValue}) net = Network(params) dpl = simulate_dipole(net) out_fname = op.join(dplPath, "{0:.5e}.txt".format(paramValue)) dpl[0].write(out_fname) return dpl
def test_tonic_inputs(): """Test tonic inputs.""" hnn_core_root = op.dirname(hnn_core.__file__) # default params params_fname = op.join(hnn_core_root, 'param', 'default.json') params = read_params(params_fname) net = hnn_core.Network(params) with pytest.raises(ValueError, match='Duration of tonic input cannot be' ' negative'): net.add_tonic_input('L2Pyr', amplitude=1.0, t0=5.0, T=4.0) with pytest.raises(ValueError, match='End time of tonic input cannot be' ' negative'): net.add_tonic_input('L2Pyr', amplitude=1.0, t0=5.0, T=-1.) with pytest.raises(ValueError, match='parameter may be missing'): params['Itonic_T_L2Pyr_soma'] = 5.0 net = hnn_core.Network(params) params.update({ 'N_pyr_x': 3, 'N_pyr_y': 3, 'tstop': 25, 'N_trials': 1, 't_evprox_1': 5, 't_evdist_1': 10, 't_evprox_2': 20, # tonic inputs 'Itonic_A_L2Pyr_soma': 1.0, 'Itonic_t0_L2Pyr_soma': 5.0, 'Itonic_T_L2Pyr_soma': 15.0 }) net = hnn_core.Network(params) # smoke test for tonic inputs hnn_core.simulate_dipole(net)
def __call__(self, new_param_values): new_params = dict( zip(self.param_names, new_param_values.detach().cpu().numpy())) self.params.update(new_params) net = Network(self.params) with JoblibBackend(n_jobs=1): dpl = simulate_dipole(net, n_trials=1) summstats = dpl[0].data['agg'] spike_times = net.cell_response.spike_times spike_gids = net.cell_response.spike_gids spike_types = net.cell_response.spike_types return summstats, spike_times, spike_gids, spike_types
def test_transmembrane_currents(): """Test that net transmembrane current is zero at all times.""" params.update({'N_pyr_x': 3, 'N_pyr_y': 3, 't_evprox_1': 5, 't_evdist_1': 10, 't_evprox_2': 20, 'N_trials': 1}) net = jones_2009_model(params, add_drives_from_params=True) electrode_pos = (0, 0, 0) # irrelevant where electrode is # all transfer resistances set to unity net.add_electrode_array('net_Im', electrode_pos, method=None) _ = simulate_dipole(net, tstop=40.) assert_allclose(net.rec_arrays['net_Im'].voltages, 0, rtol=1e-10, atol=1e-10)
def test_hnn_core(): """Test to check if MNE neuron does not break.""" # small snippet of data on data branch for now. To be deleted # later. Data branch should have only commit so it does not # pollute the history. data_url = ('https://raw.githubusercontent.com/jonescompneurolab/' 'hnn-core/test_data/dpl.txt') if not op.exists('dpl.txt'): _fetch_file(data_url, 'dpl.txt') dpl_master = loadtxt('dpl.txt') hnn_core_root = op.join(op.dirname(hnn_core.__file__), '..') params_fname = op.join(hnn_core_root, 'param', 'default.json') params = read_params(params_fname) net = Network(params, n_jobs=1) dpl = simulate_dipole(net)[0] fname = './dpl2.txt' dpl.write(fname) dpl_pr = loadtxt(fname) assert_array_equal(dpl_pr[:, 2], dpl_master[:, 2]) # L2 assert_array_equal(dpl_pr[:, 3], dpl_master[:, 3]) # L5 # Test spike type counts spiketype_counts = {} for spikegid in net.spikegids[0]: if net.gid_to_type(spikegid) not in spiketype_counts: spiketype_counts[net.gid_to_type(spikegid)] = 0 else: spiketype_counts[net.gid_to_type(spikegid)] += 1 assert 'extinput' not in spiketype_counts assert 'exgauss' not in spiketype_counts assert 'extpois' not in spiketype_counts assert spiketype_counts == { 'evprox1': 269, 'L2_basket': 54, 'L2_pyramidal': 113, 'L5_pyramidal': 395, 'L5_basket': 85, 'evdist1': 234, 'evprox2': 269 }
numspikes=1, weights_ampa=weights_ampa_p2, location='proximal', synaptic_delays=synaptic_delays_prox, event_seed=814) ############################################################################### # Now let's simulate the dipole, running 2 trials with the # :class:`~hnn_core.parallel_backends.Joblib` backend. # To run them in parallel we could set ``n_jobs`` to equal the number of # trials. The ``Joblib`` backend allows running the simulations in parallel # across trials. from hnn_core import JoblibBackend with JoblibBackend(n_jobs=2): dpls = simulate_dipole(net, tstop=170., n_trials=2) ############################################################################### # Rather than reading smoothing and scaling parameters from file, we recommend # explicit use of the :meth:`~hnn_core.dipole.Dipole.smooth` and # :meth:`~hnn_core.dipole.Dipole.scale` methods instead. Note that both methods # operate in-place, i.e., the objects are modified. window_len, scaling_factor = 30, 3000 for dpl in dpls: dpl.smooth(window_len).scale(scaling_factor) ############################################################################### # Plot the amplitudes of the simulated aggregate dipole moments over time import matplotlib.pyplot as plt fig, axes = plt.subplots(2, 1,
# ``simulate_dipole`` is ``n_trials=params['N_trials']``). net = jones_2009_model(params) weights_ampa = {'L2_pyramidal': 0.0008, 'L5_pyramidal': 0.0075} synaptic_delays = {'L2_pyramidal': 0.1, 'L5_pyramidal': 1.0} rate_constant = {'L2_pyramidal': 140.0, 'L5_pyramidal': 40.0} net.add_poisson_drive('poisson', rate_constant=rate_constant, weights_ampa=weights_ampa, location='proximal', synaptic_delays=synaptic_delays, event_seed=1079) ############################################################################### dpls = simulate_dipole(net, tstop=250.) scaling_factor = 30000 dpls = [dpl.scale(scaling_factor) for dpl in dpls] # scale in place ############################################################################### # Take a look at how different cell types respond to the exogenous drive. Note # the periodic firing pattern of all cell types. While the basket cells fire # relatively synchronously, the pyramidal cell populations display a more # varied pattern, in which only a fraction of cells reach firing threshold. net.cell_response.plot_spikes_raster() ############################################################################### # To confirm that the periodicity observed in the firing patterns correspond to # a population oscillation in the gamma-range, we can plot the time-frequency # representation together with the signal. Note that the network requires some # time to reach steady state. Hence, we omit the first 50 ms in our analysis.
# 1) beta event only, 2) ERP only, and 3) beta event + ERP. beta_start, stimulus_start = 50.0, 125.0 net_beta = net.copy() net_beta = add_beta_drives(net_beta, beta_start) net_erp = net.copy() net_erp = add_erp_drives(net_erp, stimulus_start) net_beta_erp = net_beta.copy() net_beta_erp = add_erp_drives(net_beta_erp, stimulus_start) ############################################################################### # And finally we simulate. Note that the default simulation time has been # increased to 400 ms to observe the long time course over which beta events # can influence sensory input to the cortical column. dpls_beta = simulate_dipole(net_beta, tstop=400) dpls_erp = simulate_dipole(net_erp, tstop=400) dpls_beta_erp = simulate_dipole(net_beta_erp, tstop=400) ############################################################################### # By inspecting the activity during the beta event, we can see that spiking # occurs exclusively at 50 ms, the peak of the gaussian distributed proximal # and distal inputs. This spiking activity leads to sustained GABAb mediated # inhibition of the L2 and L5 pyrmaidal cells. One effect of this inhibition # is an assymetric beta event with a long positive tail. import matplotlib.pyplot as plt import numpy as np fig, axes = plt.subplots(4, 1, sharex=True, figsize=(7, 7),
syn_delays_p = {'L2_pyramidal': 0.1, 'L5_pyramidal': 1.} net.add_bursty_drive('alpha_prox', tstart=50., burst_rate=10, burst_std=burst_std, numspikes=2, spike_isi=10, repeats=10, location=location, weights_ampa=weights_ampa_p, synaptic_delays=syn_delays_p, seedcore=14) # simulate the dipole, but do not automatically scale or smooth the result dpl = simulate_dipole(net, n_trials=1, postproc=False) trial_idx = 0 # single trial simulated, choose the first index # to emulate a larger patch of cortex, we can apply a simple scaling factor dpl[trial_idx].scale(3000) ############################################################################### # Prior to plotting, we can choose to smooth the dipole waveform (note that the # :meth:`~hnn_core.dipole.smooth`-method operates in-place, *i.e.*, it alters # the data inside the ``Dipole`` object). Smoothing approximates the effect of # signal summation from a larger number and greater volume of neurons than are # included in our biophysical model. We can confirm that what we simulate is # indeed 10 Hz activity by plotting the power spectral density (PSD). import matplotlib.pyplot as plt from hnn_core.viz import plot_dipole, plot_psd
from hnn_core import simulate_dipole, read_params, Network hnn_core_root = op.join(op.dirname(hnn_core.__file__), '..') ############################################################################### # Then we read the parameters file params_fname = op.join(hnn_core_root, 'param', 'gamma_L5weak_L2weak.json') params = read_params(params_fname) print(params) ############################################################################### # Now let's simulate the dipole # You can simulate multiple trials in parallel by using n_jobs > 1 net = Network(params) dpls = simulate_dipole(net, n_jobs=1, n_trials=1) ############################################################################### # We can plot the time-frequency response using MNE import numpy as np import matplotlib.pyplot as plt from mne.time_frequency import tfr_array_multitaper fig, axes = plt.subplots(2, 1, sharex=True, figsize=(6, 6)) dpls[0].plot(ax=axes[0], layer='agg') sfreq = 1000. / params['dt'] time_bandwidth = 4.0 freqs = np.arange(20., 100., 1.) n_cycles = freqs / 4.
depths = list(range(-325, 2150, 100)) electrode_pos = [(135, 135, dep) for dep in depths] net.add_electrode_array('shank1', electrode_pos) ############################################################################### # The electrode arrays are stored under ``Network.rec_arrays`` as a dictionary # of :class:`hnn_core.extracellular.ElectrodeArray` objects that are now # attached to the network and will be recorded during the simulation. Note that # calculating the extracellular potentials requires additional computational # resources and will thus slightly slow down the simulation. # :ref:`Using MPI <sphx_glr_auto_examples_plot_simulate_mpi_backend.py>` will # speed up computation considerably. print(net.rec_arrays) net.plot_cells() dpl = simulate_dipole(net, tstop=170) ############################################################################### # For plotting both aggregate dipole moment and LFP traces, we'll use a 10 ms # smoothing window, after which both data can be decimated by a factor of 20 # from 40 to 2 kHz sampling rates (note that decimation is applied in two # steps). Decimation speeds up plotting significantly. trial_idx = 0 window_len = 10 # ms decimate = [5, 4] # from 40k to 8k to 2k fig, axs = plt.subplots(3, 1, sharex=True, figsize=(6, 8), gridspec_kw={'height_ratios': [1, 3, 2]})
width=Inches(10) prs = Presentation() title_slide_layout = prs.slide_layouts[0] slide = prs.slides.add_slide(title_slide_layout) title = slide.shapes.title subtitle = slide.placeholders[1] title.text = "NEW (r) fits" subtitle.text = "plot_from_hnn.py" #------------------------------------- # get default #------------------------------------- dict_param=m.get_dict_param(my_param_out_dir,'default_Sarah') default_params=Params(dict_param) net_default = Network(default_params) dpls_default = simulate_dipole(net_default, n_trials=1) # time delay delays=[0,2,4,6,8,10,15,20,30,40,50,60,70,80,100,120,140,160,180,200,220,240,250,300,400,500,600]#[50, 100, 150, 200, 300, 400, 500, 600] delayed_input_type=['default_Sarah']#,'Supra_ERPYesSupraT']# also try triple later? ## pick a param file and tripple those inputs param_files=['default_Sarah']#,'Supra_ERPYesSupraT'] add10=False triple_pulse=False keep_dpls=[] for p in param_files: for delayed_p in delayed_input_type:
# parameters using unix-style wildcard characters print(params['L2Pyr_soma*']) ############################################################################### # Let us first create our network from the params file and visualize the cells # inside it. net = Network(params) net.plot_cells() ############################################################################### # Now let's simulate the dipole, running 2 trials with the Joblib backend. # To run them in parallel we could set n_jobs to equal the number of trials. from hnn_core import JoblibBackend with JoblibBackend(n_jobs=1): dpls = simulate_dipole(net, n_trials=2) ############################################################################### # and then plot it import matplotlib.pyplot as plt fig, axes = plt.subplots(2, 1, sharex=True, figsize=(6, 6)) plot_dipole(dpls, ax=axes[0], layer='agg', show=False) net.plot_input(ax=axes[1]) ############################################################################### # Also, we can plot the spikes and write them to txt files. # Note that we can use formatting syntax to specify the filename pattern # with which each trial will be written. To read spikes back in, we can use # wildcard expressions. net.spikes.plot() with tempfile.TemporaryDirectory() as tmp_dir_name:
############################################################################### # Let's first simulate the dipole with some initial parameters. The parameter # definitions also contain the drives. Even though we could add drives # explicitly through our API # (see :ref:`sphx_glr_auto_examples_workflows_plot_simulate_evoked.py`), # for conciseness, # we add them automatically from the parameter files scale_factor = 3000. smooth_window_len = 30. tstop = exp_dpl.times[-1] net = jones_2009_model(params=params, add_drives_from_params=True) with MPIBackend(n_procs=n_procs): print("Running simulation with initial parameters") initial_dpl = simulate_dipole(net, tstop=tstop, n_trials=1)[0] initial_dpl = initial_dpl.scale(scale_factor).smooth(smooth_window_len) ############################################################################### # Now we start the optimization! from hnn_core.optimization import optimize_evoked with MPIBackend(n_procs=n_procs): net_opt = optimize_evoked(net, tstop=tstop, n_trials=1, target_dpl=exp_dpl, initial_dpl=initial_dpl, scale_factor=scale_factor, smooth_window_len=smooth_window_len)
plt.figure() plt.plot(1e3 * stc.times, stc.data[pick_vertex, :].T * 1e9, 'ro-') plt.xlabel('time (ms)') plt.ylabel('%s value (nAM)' % method) plt.xlim((0, 150)) plt.axhline(0) plt.show() ############################################################################### # Now, let us try to simulate the same with MNE-neuron import os.path as op import hnn_core from hnn_core import simulate_dipole, read_params, Network hnn_core_root = op.dirname(hnn_core.__file__) params_fname = op.join(hnn_core_root, 'param', 'N20.json') params = read_params(params_fname) net = Network(params) dpl = simulate_dipole(net, n_trials=1) import matplotlib.pyplot as plt fig, axes = plt.subplots(2, 1, sharex=True, figsize=(6, 6)) dpl[0].plot(ax=axes[0], show=False) net.plot_input(ax=axes[1]) net.spikes.plot()
params.update({ 'dipole_scalefctr': 150000.0, 'dipole_smooth_win': 0, 'tstop': 310.0, 't0_input_dist': 50.0, 'tstop_input_dist': 1001.0, 'input_dist_A_weight_L2Pyr_ampa': 5.4e-5, 'input_dist_A_weight_L5Pyr_ampa': 5.4e-5, 'sync_evinput': 1, "prng_seedcore_input_dist": 3 }) ############################################################################### # Now let's simulate the dipole and plot it net = Network(params) dpl = simulate_dipole(net) dpl[0].plot() ############################################################################### # We can confirm that what we simulate is indeed 10 Hz activity. import matplotlib.pyplot as plt from scipy.signal import spectrogram import numpy as np sfreq = 1000. / params['dt'] n_fft = 1024 * 8 freqs, _, psds = spectrogram(dpl[0].data['agg'], sfreq, window='hamming', nfft=n_fft, nperseg=n_fft, noverlap=0)
# The occurrence of each burst is jittered by a random, normally distributed # amount (20 ms standard deviation). We repeat the burst train 10 times, each # time with unique randomization. net = jones_2009_model() weights_ampa = {'L2_pyramidal': 5.4e-5, 'L5_pyramidal': 5.4e-5} net.add_bursty_drive('bursty', tstart=50., burst_rate=10, burst_std=20., numspikes=2, spike_isi=10, n_drive_cells=10, location='distal', weights_ampa=weights_ampa, event_seed=8) ############################################################################### # Finally, to simulate we use the # :class:`~hnn_core.parallel_backends.MPIBackend` class. This will # start the simulation across the number of processors (cores) specified by # ``n_procs`` using MPI. The ``'mpiexec'`` launcher is used from # ``openmpi``, which must be installed on the system from hnn_core import MPIBackend with MPIBackend(n_procs=2, mpi_cmd='mpiexec'): dpls = simulate_dipole(net, tstop=310., n_trials=1) trial_idx = 0 dpls[trial_idx].plot()
'L2_basket': 0.000003, 'L2_pyramidal': 1.438840, 'L5_basket': 0.008958, 'L5_pyramidal': 0.684013 } # all NMDA weights are zero; omit weights_nmda (defaults to None) net.add_evoked_drive('evprox2', mu=137.12, sigma=8.33, numspikes=1, weights_ampa=weights_ampa_p2, location='proximal', synaptic_delays=synaptic_delays_prox, event_seed=814) dpls = simulate_dipole(net, tstop=170., record_vsoma=True) ############################################################################### # Here, we explain more details about the data structures and how they can # be used to better interpret the data. The cell IDs (gids) uniquely define # neurons in the network and are stored in the :class:`~hnn_core.Network` # object as a dictionary gid_ranges = net.gid_ranges print(net.gid_ranges) ############################################################################### # Simulated voltage in the soma is stored in :class:`~hnn_core.CellResponse` # as a dictionary. The CellResponse object stores data produced by individual # cells including spikes, somatic voltages and currents. trial_idx = 0 vsoma = net.cell_response.vsoma[trial_idx]
target_gids='L5_pyramidal', loc='soma', receptor='gabaa') conn_idx = conn_indices[0] print(net_erp.connectivity[conn_idx]) plot_connectivity_matrix(net_erp, conn_idx) gid_idx = 11 src_gid = net_erp.connectivity[conn_idx]['src_gids'][gid_idx] fig = plot_cell_connectivity(net_erp, conn_idx, src_gid) ############################################################################### # Data recorded during simulations are stored under # :class:`~hnn_core.Cell_Response`. Spiking activity can be visualized after # a simulation is using :meth:`~hnn_core.Cell_Response.plot_spikes_raster` dpl_erp = simulate_dipole(net_erp, tstop=170., n_trials=1) net_erp.cell_response.plot_spikes_raster() ############################################################################### # We can also define our own connections to test the effect of different # connectivity patterns. To start, ``net.clear_connectivity()`` can be used # to clear all cell-to-cell connections. By default, previously defined drives # to the network are retained, but can be removed with ``net.clear_drives()``. # ``net.add_connection`` is then used to create a custom network. Let us first # create an all-to-all connectivity pattern between the L5 pyramidal cells, # and L2 basket cells. :meth:`hnn_core.Network.add_connection` allows # connections to be specified with either cell names, or the cell IDs (gids) # directly. def get_network(probability=1.0): net = jones_2009_model(params, add_drives_from_params=True)
location='distal', n_drive_cells=1, cell_specific=False, weights_ampa=weights_ampa_d, weights_nmda=weights_nmda_d, synaptic_delays=synaptic_delays_d, event_seed=2) ############################################################################### # Now we run the simulation over 2 trials so that we can plot the average # aggregate dipole. For a better match to the empirical waveform, set # ``n_trials`` to be >=25. n_trials = 2 # n_trials = 25 with JoblibBackend(n_jobs=2): dpls = simulate_dipole(net, tstop=170., n_trials=n_trials) ############################################################################### # Since the model is a reduced representation of the larger network # contributing to the response, the model response is noisier than it would be # in the net activity from a larger network where these effects are averaged # out, and the dipole amplitude is smaller than the recorded data. The # post-processing steps of smoothing and scaling the simulated dipole response # allow us to more accurately approximate the true signal responsible for the # recorded macroscopic evoked response [1]_, [2]_. dpl_smooth_win = 20 dpl_scalefctr = 12 for dpl in dpls: dpl.smooth(dpl_smooth_win) dpl.scale(dpl_scalefctr)
net = Network(params, add_drives_from_params=True) ############################################################################### # Instantiating the network comes with a predefined set of connections that # reflect the canonical neocortical microcircuit. ``net.connectivity`` # is a list of dictionaries which detail every cell-cell, and drive-cell # connection. print(len(net.connectivity)) print(net.connectivity[0:2]) ############################################################################### # Data recorded during simulations are stored under # :class:`~hnn_core.Cell_Response`. To test multiple network structures, we can # create a copy of the original network. The copied network is then simulated. net_erp = net.copy() dpl_erp = simulate_dipole(net_erp, n_trials=1) net_erp.cell_response.plot_spikes_raster() ############################################################################### # We can modify the connectivity list to test the effect of different # connectivity patterns. For example, we can remove all layer 2 inhibitory # connections. In the default network, the src_gids of each connection are # all the same cell type.. Connections are stored under ``conn['gid_pairs']`` # as a dictionary indexed by src_gid: # ``{src_gid1: [target_gid1, target_gid2], ...]``. Each src_gid indexes a # list with its target gids new_connectivity = [ conn for conn in net.connectivity if conn['src_type'] != 'L2_basket' ] net.connectivity = new_connectivity