def test_external_indegrees(): """ Test settings for external indegrees. """ M0 = create_default_network() K0 = M0.K_matrix conn_params = {'fac_nu_ext_5E': 2., 'fac_nu_ext_6E': 2.} network_params = {'connection_params': conn_params} M = MultiAreaModel(network_params) mask = create_mask(M.structure, target_pops=['5E'], source_pops=[]) assert(np.allclose(M.K_matrix[mask], conn_params['fac_nu_ext_5E'] * K0[mask])) mask = create_mask(M.structure, target_pops=['6E'], source_pops=[]) assert(np.allclose(M.K_matrix[mask], conn_params['fac_nu_ext_6E'] * K0[mask])) conn_params = {'fac_nu_ext_TH': 2.} network_params.update({'connection_params': conn_params}) M = MultiAreaModel(network_params) mask = create_mask(M.structure, target_areas=['TH'], target_pops=['23E', '5E'], source_pops=[]) assert(np.allclose(M.K_matrix[mask], conn_params['fac_nu_ext_TH'] * K0[mask]))
def test_syn_weights(): """ Test different options for synaptic weights. """ M0 = create_default_network() W0 = M0.W_matrix conn_params = {'PSP_e': 0.3, 'PSP_e_23_4': 0.6} network_params = {'connection_params': conn_params} M = MultiAreaModel(network_params) mask = create_mask(M.structure, source_pops=['23E', '4E', '5E', '6E'], external=False) assert(np.allclose(M.W_matrix[mask], conn_params['PSP_e'] / 0.15 * W0[mask])) conn_params = {'cc_weights_factor': 2., 'cc_weights_I_factor': 2.} network_params.update({'connection_params': conn_params}) M = MultiAreaModel(network_params) mask = create_mask(M.structure, source_pops=['23E', '5E', '6E'], target_pops=['23E', '4E', '5E', '6E'], cortico_cortical=True) assert(np.allclose(M.W_matrix[mask], conn_params['cc_weights_factor'] * W0[mask])) mask = create_mask(M.structure, source_pops=['23E', '5E', '6E'], target_pops=['23I', '4I', '5I', '6I'], cortico_cortical=True) assert(np.allclose(M.W_matrix[mask], conn_params['cc_weights_factor'] * conn_params['cc_weights_I_factor'] * W0[mask]))
def test_network_initialization(): """ Tests two different ways to initilize a network: - From a dictionary of custom parameters - From a label string Tests whether the two instances yield identical networks. """ conn_params = { 'replace_non_simulated_areas': 'het_poisson_stat', 'g': -11., 'K_stable': '../K_stable.npy', 'fac_nu_ext_TH': 1.2, 'fac_nu_ext_5E': 1.125, 'fac_nu_ext_6E': 1.41666667, 'av_indegree_V1': 3950. } network_params = { 'N_scaling': 1., 'K_scaling': 1., 'connection_params': conn_params } M = MultiAreaModel(network_params) M2 = MultiAreaModel(M.label) assert (M == M2)
def test_network_scaling(): """ Test the downscaling option of the network. - Test whether indegrees and neuron number are correctly scaled down. - Test whether the resulting mean and variance of the input currents as well as the resulting rates are identical, based on mean-field theory. """ network_params = {} M0 = MultiAreaModel(network_params, theory=True) K0 = M0.K_matrix W0 = M0.W_matrix N0 = M0.N_vec syn0 = M0.syn_matrix p, r0 = M0.theory.integrate_siegert() d = vector_to_dict(r0[:, -1], M0.area_list, M0.structure) with open('mf_rates.json', 'w') as f: json.dump(d, f) network_params = { 'N_scaling': .1, 'K_scaling': .1, 'fullscale_rates': 'mf_rates.json' } theory_params = {'initial_rates': r0[:, -1], 'T': 50.} M = MultiAreaModel(network_params, theory=True, theory_spec=theory_params) K = M.K_matrix W = M.W_matrix N = M.N_vec syn = M.syn_matrix p, r = M.theory.integrate_siegert() assert (np.allclose(K, network_params['K_scaling'] * K0)) assert (np.allclose(N, network_params['N_scaling'] * N0)) assert (np.allclose( syn, network_params['K_scaling'] * network_params['N_scaling'] * syn0)) assert (np.allclose(W, W0 / np.sqrt(network_params['K_scaling']))) r0_extend = np.append(r0[:, -1], M0.params['input_params']['rate_ext']) tau_m = M.params['neuron_params']['single_neuron_dict']['tau_m'] C_m = M.params['neuron_params']['single_neuron_dict']['C_m'] mu0 = (1e-3 * tau_m * np.dot(M0.K_matrix * M0.J_matrix, r0_extend) + tau_m / C_m * M0.add_DC_drive) mu = 1e-3 * tau_m * np.dot(M.K_matrix * M.J_matrix, r0_extend) + tau_m / C_m * M.add_DC_drive sigma0 = np.sqrt(1e-3 * tau_m * np.dot(M0.K_matrix * M0.J_matrix**2, r0_extend)) sigma = np.sqrt(1e-3 * tau_m * np.dot(M.K_matrix * M.J_matrix**2, r0_extend)) assert (np.allclose(mu, mu0)) assert (np.allclose(sigma, sigma0)) assert (np.allclose(r[:, -1], r0[:, -1]))
def create_default_network(): """ Return an instance of the default network. """ network_params = {} M0 = MultiAreaModel(network_params) return M0
def test_hom_poisson_stat_sim(): network_params = {'connection_params': {'replace_non_simulated_areas': 'hom_poisson_stat'}, 'N_scaling': 0.001, 'K_scaling': 0.0001, 'fullscale_rates': 'fullscale_rates.json'} sim_params = {'t_sim': 0.1, 'areas_simulated': ['V1']} M = MultiAreaModel(network_params, simulation=True, sim_spec=sim_params) M.simulation.simulate()
def test_meanfield(): """ Test meanfield calculation of the stationary network state. """ network_params = {} theory_params = {} M0 = MultiAreaModel(network_params, theory=True, theory_spec=theory_params) p, r0 = M0.theory.integrate_siegert()
def test_meanfield(): """ Test stabilization procedure. Since this algorithm is not implemented yet, we here test if this properly raises a NotImplementedError. """ network_params = {'connection_params': {'K_stable': True}} theory_params = {} with pytest.raises(NotImplementedError): MultiAreaModel(network_params, theory=True, theory_spec=theory_params)
def test_analysis(): base_dir = os.getcwd() fn = os.path.join(base_dir, 'fullscale_rates.json') network_params = { 'connection_params': { 'replace_non_simulated_areas': 'het_poisson_stat', 'replace_cc_input_source': fn }, 'N_scaling': 0.001, 'K_scaling': 0.0001, 'fullscale_rates': 'fullscale_rates.json' } sim_params = {'t_sim': 500., 'areas_simulated': ['V1', 'V2']} M = MultiAreaModel(network_params, simulation=True, sim_spec=sim_params) M.simulation.simulate() M = MultiAreaModel(network_params, simulation=True, sim_spec=sim_params, analysis=True) M.analysis.create_pop_rates(t_min=100.) M.analysis.create_pop_rate_dists(t_min=100.) M.analysis.create_synchrony(t_min=100.) M.analysis.create_rate_time_series(t_min=100.) M.analysis.create_synaptic_input(t_min=100.) M.analysis.create_pop_cv_isi(t_min=100.) M.analysis.create_pop_LvR(t_min=100.) M.analysis.save() out = StringIO() sys.stdout = out M.analysis.create_pop_rates(t_min=100.) M.analysis.create_pop_rate_dists(t_min=100.) M.analysis.create_synchrony(t_min=100.) M.analysis.create_rate_time_series(t_min=100.) M.analysis.create_synaptic_input(t_min=100.) M.analysis.create_pop_cv_isi(t_min=100.) M.analysis.create_pop_LvR(t_min=100.) sys.stdout = sys.__stdout__ val = out.getvalue() assert (val.count("Loading data from") == 9)
def test_het_poisson_stat_sim(): base_dir = os.getcwd() fn = os.path.join(base_dir, 'fullscale_rates.json') network_params = {'connection_params': {'replace_non_simulated_areas': 'het_poisson_stat', 'replace_cc_input_source': fn}, 'N_scaling': 0.001, 'K_scaling': 0.0001, 'fullscale_rates': 'fullscale_rates.json'} sim_params = {'t_sim': 0.1, 'areas_simulated': ['V1']} M = MultiAreaModel(network_params, simulation=True, sim_spec=sim_params) M.simulation.simulate()
def test_het_poisson_stat_mf(): network_params = {} theory_params = {} M0 = MultiAreaModel(network_params, theory=True, theory_spec=theory_params) p, r0 = M0.theory.integrate_siegert() rates = vector_to_dict(r0[:, -1], M0.area_list, M0.structure) with open('mf_rates.json', 'w') as f: json.dump(rates, f) network_params = { 'connection_params': { 'replace_cc': 'het_poisson_stat', 'replace_cc_input_source': 'mf_rates.json' } } theory_params = {} M = MultiAreaModel(network_params, theory=True, theory_spec=theory_params) p, r = M.theory.integrate_siegert() assert (np.allclose(r0[:, -1], r[:, -1]))
def test_stabilization(): """ Test stabilization procedure. The stabilized matrix is expected to be stored in a file and the parameter in the dictionary specifies the corresponding name. We here check if the MultiAreaModel class properly throws a TypeError when we try to directly specify the matrix. """ # Create random matrix for indegrees K_stable = np.random.rand(254, 254) np.save('K_stable_test.npy', K_stable) # Trying to directly specify the matrix should throw a TypeError. network_params = {'connection_params': {'K_stable': K_stable}} theory_params = {} with pytest.raises(TypeError): MultiAreaModel(network_params, theory=True, theory_spec=theory_params) # Specifying the file name leads to the correct indegrees being loaded. network_params = {'connection_params': {'K_stable': 'K_stable_test.npy'}} theory_params = {} M = MultiAreaModel(network_params, theory=True, theory_spec=theory_params) assert (np.all(K_stable == M.K_matrix[:, :-1]))
def test_average_indegree(): """ Test different average indegrees. """ for av_indegree in [av_indegree_Cragg, np.mean([av_indegree_Cragg, av_indegree_OKusky]), av_indegree_OKusky]: conn_params = {'av_indegree_V1': av_indegree} network_params = {'connection_params': conn_params} M = MultiAreaModel(network_params) area = 'V1' mask = create_mask(M.structure, target_areas=[area]) x = np.sum(M.syn_matrix[mask].reshape((8, 255))) K_average = x / M.N[area]['total'] print(K_average) assert(np.allclose(K_average, conn_params['av_indegree_V1']))
def test_het_current_non_stat_sim(): curr = np.ones(10) * 10. het_current = {area: {pop: curr for pop in population_list} for area in complete_area_list} _save_dict_to_npy('het_current', het_current) base_dir = os.getcwd() fs = os.path.join(base_dir, 'het_current') network_params = {'connection_params': {'replace_non_simulated_areas': 'het_current_nonstat', 'replace_cc_input_source': fs}, 'N_scaling': 0.001, 'K_scaling': 0.0001, 'fullscale_rates': 'fullscale_rates.json'} sim_params = {'t_sim': 10., 'areas_simulated': ['V1']} M = MultiAreaModel(network_params, simulation=True, sim_spec=sim_params) M.simulation.simulate()
def test_hom_poisson_stat_mf(): network_params = {'connection_params': {'replace_cc': 'hom_poisson_stat'}} theory_params = {} M = MultiAreaModel(network_params, theory=True, theory_spec=theory_params) p, r = M.theory.integrate_siegert() mu, sigma = M.theory.replace_cc_input() # Test for V1 mask = create_mask(M.structure, target_areas=['V1'], cortico_cortical=True, external=False) x = np.sum( (M.J_matrix[mask].reshape((8, -1)) * M.K_matrix[mask].reshape( (8, -1)) * M.params['input_params']['rate_ext'] * M.params['neuron_params']['single_neuron_dict']['tau_m'] * 1e-3), axis=1) assert (np.allclose(x, mu[:8]))
conn_params = { 'g': -16., 'fac_nu_ext_TH': 1.2, 'fac_nu_ext_5E': 1., 'fac_nu_ext_6E': 1., 'av_indegree_V1': 3950. } network_params = { 'N_scaling': 1., 'K_scaling': 1., 'connection_params': conn_params, 'neuron_params': neuron_params, 'input_params': input_params } M_LA = MultiAreaModel(network_params, simulation=True, sim_spec=sim_params, analysis=True) M_LA.analysis.create_pop_rates() """ Simulation with kappa = 1.125 leading to the high-activity fixed point shown in Fig. 4E. """ conn_params = { 'g': -16., 'fac_nu_ext_TH': 1.2, 'fac_nu_ext_5E': 1.125, 'fac_nu_ext_6E': 1.41666667, 'av_indegree_V1': 3950. } network_params = { 'N_scaling': 1.,
'neuron_params': neuron_params } sim_params = { 't_sim': t_sim, 'num_processes': num_processes, 'local_num_threads': 1, 'recording_dict': { 'record_vm': False } } theory_params = {'dt': 0.1} if NEST_version == 2: M = MultiAreaModel(network_params, simulation=True, sim_spec=sim_params, theory=True, theory_spec=theory_params) elif NEST_version == 3: M = MultiAreaModel3(network_params, simulation=True, sim_spec=sim_params, theory=True, theory_spec=theory_params) p, r = M.theory.integrate_siegert() M.simulation.simulate()
else: from network_simulations import init_models from config import data_path models = init_models('Fig2') data_labels = [M.simulation.label for M in models] keys = ['LA', 'HA', 'LA_post'] for key, label in zip(keys, data_labels): fn = os.path.join(data_path, label, 'Analysis/pop_rates.json') with open(fn, 'r') as f: data[key] = json.load(f) """ Create MultiAreaModel instance to have access to data structures """ M = MultiAreaModel({}) labels = ['A', 'B', 'C'] for k, key in enumerate(['LA', 'HA', 'LA_post']): ax = axes[labels[k]] ax2 = axes[labels[k] + '2'] print(k) matrix = np.zeros((len(M.area_list), 8)) for i, area in enumerate(M.area_list): for j, pop in enumerate(M.structure['V1'][::-1]): if pop not in M.structure[area]: rate = np.nan else:
def test_network_params(): net_params = {'x': 3} with pytest.raises(KeyError): MultiAreaModel(net_params)
def test_theory_params(): theory_params = {'x': 3} with pytest.raises(KeyError): MultiAreaModel({}, theory=True, theory_spec=theory_params)
def test_sim_params(): sim_params = {'x': 3} with pytest.raises(KeyError): MultiAreaModel({}, simulation=True, sim_spec=sim_params)
""" Initialization """ conn_params = {'g': -16., 'av_indegree_V1': 3950., 'fac_nu_ext_TH': 1.2} input_params = {'rate_ext': 8.} network_params = {'connection_params': conn_params, 'input_params': input_params} theory_params = {'dt': 0.01, 'T': 30.} time = np.arange(0., theory_params['T'], theory_params['dt']) M_base = MultiAreaModel(network_params, theory=True, theory_spec=theory_params) c_target = copy.deepcopy(conn_params) c_target.update({'fac_nu_ext_5E': 1.2, 'fac_nu_ext_6E': 10/3.*1.2-7/3.}) network_params_target = {'connection_params': c_target, 'input_params': input_params} M_target = MultiAreaModel(network_params_target, theory=True, theory_spec=theory_params) THREADS = 4 load_list = [] # This list defines which of the detected minima of the velocity # vector is identified as the unstable fixed point. It has to be
""" Create instance of MultiAreaModel """ conn_params = {'g': -16., 'av_indegree_V1': 3950., 'fac_nu_ext_TH': 1.2} input_params = {'rate_ext': 8.} network_params = {'connection_params': conn_params, 'input_params': input_params} theory_params = {'dt': 0.01, 'T': 30.} time = np.arange(0., theory_params['T'], theory_params['dt']) M_base = MultiAreaModel(network_params, theory=True, theory_spec=theory_params) """ Plot data """ labels = ['A', 'B'] for ii, label in enumerate(labels): ax = panel_factory.new_panel(ii, 0, '' + labels[ii], label_position='leftleft') ax.yaxis.set_ticks_position('none') ax.xaxis.set_ticks_position('bottom') data = utils.load_iteration(ii + 1) (par_transition, r_low, r_high, minima_low, minima_high) = utils.determine_velocity_minima(time, data) unstable_low = r_low[:, minima_low[1]]
r'\bfseries{}' + 'A', fontdict=fd, transform=axes['A'].transAxes) pl.text(-0.05, 1.0, r'\bfseries{}' + 'G', fontdict=fd, transform=axes['G'].transAxes) """ Load data """ """ Create MultiAreaModel instance to have access to data structures """ M = MultiAreaModel({}) LOAD_ORIGINAL_DATA = True if LOAD_ORIGINAL_DATA: label = '99c0024eacc275d13f719afd59357f7d12f02b77' data_path = original_data_path else: from network_simulations import init_models from config import data_path models = init_models('Fig7') label = models[0].simulation.label rate_time_series = {} for area in M.area_list: fn = os.path.join(data_path, label, 'Analysis', 'rate_time_series_full', 'rate_time_series_full_{}.npy'.format(area))
def init_model(par): return MultiAreaModel(par[0], simulation=True, sim_spec=par[1])
'g': -11., 'K_stable': '../SchueckerSchmidt2017/K_prime_original.npy', 'cc_weights_I_factor': 2., 'cc_weights_factor': 1.9, 'fac_nu_ext_5E': 1.125, 'fac_nu_ext_6E': 1.125 * 10 / 3. - 7 / 3., 'fac_nu_ext_TH': 1.2 }, 'input_params': { 'rate_ext': 10. } } theory_params = {'T': 50., 'dt': 0.1, 'initial_rates': initial_rates} M = MultiAreaModel(par, theory=True, simulation=False, theory_spec=theory_params) # pops, rates_full = M.theory.integrate_siegert() # stationary firing rates: We use stationary rates computed during a # phase where the network state shows low activity (between 3500. and # 3600. ms) fn = os.path.join(data_path, label, 'Analysis', 'pop_rates_LA_state.json') with open(fn, 'r') as f: pop_rates = json.load(f) rates = dict_to_vector(pop_rates, M.area_list, M.structure) # Construct gain matrix with absolute values of synaptic weights mu, sigma = M.theory.mu_sigma(rates) d_nu_d_mu, d_nu_d_sigma = M.theory.d_nu(mu, sigma) d_nu_d_mu_matrix = np.zeros_like(M.K_matrix[:, :-1])
labels = json.load(f) label = labels['simulation_label'] network_label = labels['network_label'] # Load simulation parameters fn = os.path.join(data_path, label, '_'.join(('custom_params', label))) with open(fn, 'r') as f: custom_params = json.load(f) # Copy custom param file for each MPI process for i in range(custom_params['sim_params']['num_processes']): shutil.copy(fn, '_'.join((fn, str(i)))) fn = os.path.join(data_path, label, '_'.join( ('custom_params', label, str(nest.Rank())))) with open(fn, 'r') as f: custom_params = json.load(f) os.remove(fn) if NEST_version == 2: M = MultiAreaModel(network_label, simulation=True, sim_spec=custom_params['sim_params']) elif NEST_version == 3: M = MultiAreaModel3(network_label, simulation=True, sim_spec=custom_params['sim_params']) M.simulation.simulate()
from multiarea_model import MultiAreaModel from multiarea_model.multiarea_helpers import create_mask from plotcolors import myblue rc_file('plotstyle.rc') """ Load data and create MultiAreaModel instance """ with open(os.path.join(datapath, 'viscortex_processed_data.json'), 'r') as f: proc = json.load(f) SLN_completed = proc['SLN_completed'] SLN_Data_FV91 = proc['SLN_Data_FV91'] arch_types = proc['architecture_completed'] par = {'connection_params': {'g': -4.}} M = MultiAreaModel(par, theory=True, simulation=False) gain_matrix = M.K_matrix[:, :-1] * np.absolute(M.J_matrix[:, :-1]) eig = np.linalg.eig(gain_matrix) gain_matrix_rescaled = gain_matrix / np.max(np.real(eig[0])) # Create population-level graph and determine paths and path lengths g = create_networkx_graph(gain_matrix_rescaled, M.structure_vec, relative=False) paths, path_lengths = all_pairs_bellman_ford_path(g, weight='distance') # Treat area MDP which does not receive connections from other areas for area in area_list: for target_pop in area_population_list(M.structure, area): for source_pop in area_population_list(M.structure, 'MDP'):
def test_conn_params(): net_params = {'connection_params': {'x': 3}} with pytest.raises(KeyError): MultiAreaModel(net_params)