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 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 test_external_common_feeds(): """Test external common feeds to proximal and distal dendrites.""" 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) # default parameters have no common inputs (distal or proximal), params.update({'input_dist_A_weight_L2Pyr_ampa': 5.4e-5, 'input_dist_A_weight_L5Pyr_ampa': 5.4e-5, 't0_input_dist': 50, 'input_prox_A_weight_L2Pyr_ampa': 5.4e-5, 'input_prox_A_weight_L5Pyr_ampa': 5.4e-5, 't0_input_prox': 50}) with Network(deepcopy(params)) as net: net._create_all_spike_sources() assert len(net.common_feeds) == 2 # (distal & proximal) for ei in net.common_feeds: assert ei.feed_type == 'common' assert ei.cell_type is None # artificial cell assert hasattr(ei, 'nrn_eventvec') assert hasattr(ei, 'nrn_vecstim') assert ei.nrn_eventvec.hname().startswith('Vector') assert hasattr(ei.nrn_vecstim, 'play') # parameters should lead to > 0 input spikes assert len(ei.nrn_eventvec.as_numpy()) > 0 # check that ei.p_ext matches params loc = ei.params['loc'][:4] # loc=prox or dist for layer in ['L2', 'L5']: key = 'input_{}_A_weight_{}Pyr_ampa'.format(loc, layer) assert ei.params[layer + 'Pyr_ampa'][0] == params[key]
def run(self, params): """Run MPI simulation(s) and write results to stderr""" from hnn_core import Network from hnn_core.parallel_backends import _clone_and_simulate net = Network(params) sim_data = [] for trial_idx in range(params['N_trials']): single_sim_data = _clone_and_simulate(net, trial_idx) # go ahead and append trial data for each rank, though # only rank 0 has data that should be sent back to MPIBackend sim_data.append(single_sim_data) # flush output buffers from all ranks (any errors or status mesages) sys.stdout.flush() sys.stderr.flush() if self.rank == 0: # the parent process is waiting for "end_of_sim" to signal that # the following stderr will only contain sim_data sys.stdout.write('end_of_sim') sys.stdout.flush() # flush to ensure signal is not buffered return sim_data
def test_str_to_net(): """Test reading the network via a string""" hnn_core_root = op.dirname(hnn_core.__file__) # prepare network params_fname = op.join(hnn_core_root, 'param', 'default.json') params = read_params(params_fname) net = Network(params, add_drives_from_params=True) pickled_net = _pickle_data(net) input_str = '@start_of_net@' + pickled_net.decode() + \ '@end_of_net:%d@\n' % (len(pickled_net)) received_net = _str_to_net(input_str) assert isinstance(received_net, Network) # muck with the data size in the signal input_str = '@start_of_net@' + pickled_net.decode() + \ '@end_of_net:%d@\n' % (len(pickled_net) + 1) expected_string = "Got incorrect network size: %d bytes " % \ len(pickled_net) + "expected length: %d" % \ (len(pickled_net) + 1) # process input from queue with pytest.raises(ValueError, match=expected_string): _str_to_net(input_str)
def test_dipole_visualization(): """Test dipole visualisations.""" 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, 'tstop': 100.}) net = Network(params) weights_ampa_p = {'L2_pyramidal': 5.4e-5, 'L5_pyramidal': 5.4e-5} syn_delays_p = {'L2_pyramidal': 0.1, 'L5_pyramidal': 1.} net.add_bursty_drive( 'beta_prox', tstart=0., burst_rate=25, burst_std=5, numspikes=1, spike_isi=0, repeats=11, location='proximal', weights_ampa=weights_ampa_p, synaptic_delays=syn_delays_p, seedcore=14) dpls = simulate_dipole(net, n_trials=2, postproc=False) fig = dpls[0].plot() # plot the first dipole alone axes = fig.get_axes()[0] dpls[0].copy().smooth(window_len=10).plot(ax=axes) # add smoothed versions dpls[0].copy().savgol_filter(h_freq=30).plot(ax=axes) # on top # test decimation options plot_dipole(dpls[0], decim=2) for dec in [-1, [2, 2.]]: with pytest.raises(ValueError, match='each decimation factor must be a positive'): plot_dipole(dpls[0], decim=dec) # test plotting multiple dipoles as overlay fig = plot_dipole(dpls) # multiple TFRs get averaged fig = plot_tfr_morlet(dpls, freqs=np.arange(23, 26, 1.), n_cycles=3) with pytest.raises(RuntimeError, match="All dipoles must be scaled equally!"): plot_dipole([dpls[0].copy().scale(10), dpls[1].copy().scale(20)]) with pytest.raises(RuntimeError, match="All dipoles must be scaled equally!"): plot_psd([dpls[0].copy().scale(10), dpls[1].copy().scale(20)]) with pytest.raises(RuntimeError, match="All dipoles must be sampled equally!"): dpl_sfreq = dpls[0].copy() dpl_sfreq.sfreq /= 10 plot_psd([dpls[0], dpl_sfreq])
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 }
def test_network_visualization(): """Test network visualisations.""" 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}) net = Network(params) plot_cells(net)
def test_dipole(): """Test params object.""" 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) with Network(params) as net: net.build() net.cells[0].plot_voltage()
def test_cell(): """Test cells object.""" hnn_core_root = op.dirname(hnn_core.__file__) params_fname = op.join(hnn_core_root, 'param', 'default.json') params = read_params(params_fname) net = Network(params) with NeuronNetwork(net) as neuron_net: neuron_net.cells[0].plot_voltage()
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 test_network(): """Test network object.""" 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(deepcopy(params)) for p in params: assert params[p] == net.params[p] assert len(params) == len(net.params) print(net) print(net.cells[:2])
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_network_visualization(): """Test network visualisations.""" 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}) net = Network(params) plot_cells(net) with pytest.raises(ValueError, match='Unrecognized cell type'): plot_cell_morphology(cell_types='blah') axes = plot_cell_morphology(cell_types='L2Pyr') assert len(axes) == 1 assert len(axes[0].lines) == 8
def _run(self, banner=True, sim_length=None): with self.killed_lock: self.killed = False # make copy of params dict in Params object before # modifying tstop sim_params = hnn_core_compat_params(self.params) if sim_length is not None: sim_params['tstop'] = round(sim_length, 8) while True: if self.ncore == 0: raise RuntimeError("No cores available for simulation") try: sim_log = self._log_sim_status(parent=self) with redirect_stdout(sim_log): # create the network from the parameter file # Note: NEURON objects haven't been created yet net = Network(sim_params, add_drives_from_params=True) with MPIBackend(n_procs=self.ncore, mpi_cmd='mpiexec') as backend: self.backend = backend with self.killed_lock: if self.killed: raise RuntimeError("Terminated") sim_data = simulate(net) self.backend = None break except RuntimeError as e: if self.ncore == 1: # can't reduce ncore any more print(str(e)) self._updatewaitsimwin(str(e)) raise RuntimeError("Simulation failed to start") # check if proc was killed before retrying with fewer cores with self.killed_lock: if self.killed: raise RuntimeError("Terminated") self.ncore = ceil(self.ncore / 2) txt = "INFO: Failed starting simulation, retrying with %d cores" \ % self.ncore print(txt) self._updatewaitsimwin(txt) # put sim_data into the val attribute of a ResultObj self.result_signal.sig.emit(ResultObj(sim_data, self.params))
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 test_dipole_simulation(): """Test data produced from simulate_dipole() call.""" 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, 'tstop': 25, 'dipole_smooth_win': 5, 't_evprox_1': 5, 't_evdist_1': 10, 't_evprox_2': 20 }) net = Network(params, add_drives_from_params=True) with pytest.raises(ValueError, match="Invalid number of simulations: 0"): simulate_dipole(net, n_trials=0) with pytest.raises(TypeError, match="record_vsoma must be bool, got int"): simulate_dipole(net, n_trials=1, record_vsoma=0) with pytest.raises(TypeError, match="record_isoma must be bool, got int"): simulate_dipole(net, n_trials=1, record_vsoma=False, record_isoma=0) # test Network.copy() returns 'bare' network after simulating dpl = simulate_dipole(net, n_trials=1)[0] net_copy = net.copy() assert len(net_copy.external_drives['evprox1']['events']) == 0 assert len(net_copy.cell_response.vsoma) == 0 # test that Dipole.copy() returns the expected exact copy assert_allclose(dpl.data['agg'], dpl.copy().data['agg']) # Test raster plot with no spikes params['tstop'] = 0.1 net = Network(params) simulate_dipole(net, n_trials=1, postproc=False) net.cell_response.plot_spikes_raster()
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 _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 test_child_run(): """Test running the child process without MPI""" hnn_core_root = op.dirname(hnn_core.__file__) # prepare params params_fname = op.join(hnn_core_root, 'param', 'default.json') params = read_params(params_fname) params_reduced = params.copy() params_reduced.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_reduced = Network(params_reduced, add_drives_from_params=True) with MPISimulation(skip_mpi_import=True) as mpi_sim: with io.StringIO() as buf, redirect_stdout(buf): sim_data = mpi_sim.run(net_reduced) stdout = buf.getvalue() assert "Simulation time:" in stdout with io.StringIO() as buf_err, redirect_stderr(buf_err): mpi_sim._write_data_stderr(sim_data) stderr_str = buf_err.getvalue() assert "@start_of_data@" in stderr_str assert "@end_of_data:" in stderr_str # write data to queue err_q = Queue() err_q.put(stderr_str) # use _read_stderr to get data_len (but not the data this time) data_len, data = _get_data_from_child_err(err_q) sim_data = _process_child_data(data, data_len) n_trials = 1 postproc = False dpls = _gather_trial_data(sim_data, net_reduced, n_trials, postproc) assert len(dpls) == 1
def test_network(): """Test network object.""" hnn_core_root = op.dirname(hnn_core.__file__) params_fname = op.join(hnn_core_root, 'param', 'default.json') params = read_params(params_fname) # add rhythmic inputs (i.e., a type of common input) params.update({'input_dist_A_weight_L2Pyr_ampa': 5.4e-5, 'input_dist_A_weight_L5Pyr_ampa': 5.4e-5, 't0_input_dist': 50, 'input_prox_A_weight_L2Pyr_ampa': 5.4e-5, 'input_prox_A_weight_L5Pyr_ampa': 5.4e-5, 't0_input_prox': 50}) net = Network(deepcopy(params)) neuron_network = NeuronNetwork(net) # needed to populate net.cells # Assert that params are conserved across Network initialization for p in params: assert params[p] == net.params[p] assert len(params) == len(net.params) print(neuron_network) print(neuron_network.cells[:2]) # Assert that proper number of gids are created for Network inputs assert len(net.gid_dict['common']) == 2 assert len(net.gid_dict['extgauss']) == net.n_cells assert len(net.gid_dict['extpois']) == net.n_cells for ev_input in params['t_ev*']: type_key = ev_input[2: -2] + ev_input[-1] assert len(net.gid_dict[type_key]) == net.n_cells # Assert that an empty Spikes object is created as an attribute assert net.spikes == Spikes() # Assert that all external feeds are initialized n_evoked_sources = 270 * 3 n_pois_sources = 270 n_gaus_sources = 270 n_common_sources = 2 assert len(neuron_network._feed_cells) == (n_evoked_sources + n_pois_sources + n_gaus_sources + n_common_sources)
def test_run_mpibackend_oversubscribed(self, run_hnn_core_fixture): """Test running MPIBackend with oversubscribed number of procs""" 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, '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) oversubscribed = round(cpu_count() * 1.5) with MPIBackend(n_procs=oversubscribed) as backend: assert backend.n_procs == oversubscribed simulate_dipole(net)
def test_dipole_simulation(): """Test data produced from simulate_dipole() call.""" 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, 'tstop': 25, 't_evprox_1': 5, 't_evdist_1': 10, 't_evprox_2': 20 }) net = Network(params) with pytest.raises(ValueError, match="Invalid number of simulations: 0"): simulate_dipole(net, n_trials=0) with pytest.raises(TypeError, match="record_vsoma must be bool, got int"): simulate_dipole(net, n_trials=1, record_vsoma=0) with pytest.raises(TypeError, match="record_isoma must be bool, got int"): simulate_dipole(net, n_trials=1, record_vsoma=False, record_isoma=0)
def test_network(): """Test network object.""" 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(deepcopy(params)) # Assert that params are conserved across Network initialization for p in params: assert params[p] == net.params[p] assert len(params) == len(net.params) print(net) print(net.cells[:2]) # Assert that proper number of gids are created for Network inputs assert len(net.gid_dict['extinput']) == 2 assert len(net.gid_dict['extgauss']) == net.N_cells assert len(net.gid_dict['extpois']) == net.N_cells for ev_input in params['t_ev*']: type_key = ev_input[2:-2] + ev_input[-1] assert len(net.gid_dict[type_key]) == net.N_cells
def test_cell(): """Test cells object.""" hnn_core_root = op.dirname(hnn_core.__file__) params_fname = op.join(hnn_core_root, 'param', 'default.json') params = read_params(params_fname) net = Network(params) with NetworkBuilder(net) as neuron_net: neuron_net.cells[0].plot_voltage() # test that ExpSyn always takes nrn.Segment, not float soma_props = { "L": 22.1, "diam": 23.4, "cm": 0.6195, "Ra": 200.0, "pos": (0., 0., 0.), 'name': 'test_cell' } cell = _Cell(gid=1, soma_props=soma_props) with pytest.raises(TypeError, match='secloc must be instance of'): cell.syn_create(0.5, e=0., tau1=0.5, tau2=5.)
def test_terminate_mpibackend(self, run_hnn_core_fixture): """Test terminating MPIBackend from thread""" 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, '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) with MPIBackend() as backend: event = Event() # start background thread that will kill all MPIBackends # until event.set() kill_t = Thread(target=_terminate_mpibackend, args=(event, backend)) # make thread a daemon in case we throw an exception # and don't run event.set() so that py.test will # not hang before exiting kill_t.daemon = True kill_t.start() with pytest.warns(UserWarning) as record: with pytest.raises( RuntimeError, match="MPI simulation failed. Return code: 1"): simulate_dipole(net) event.set() expected_string = "Child process failed unexpectedly" assert expected_string in record[0].message.args[0]
height = Inches(7) 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:
import hnn_core 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.
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()