def evolution(network_type, N, d, weight_list, seed, dynamics, arguments, attractor_value): """TODO: Docstring for evolution. :network_type: TODO :N: TODO :d: TODO :weight: TODO :dynamics: TODO :arguments: TODO :: TODO :returns: TODO """ if network_type == 'SBM_ER': A, A_interaction, index_i, index_j, cum_index = SBM_ER(N, d, 1, seed) else: A, A_interaction, index_i, index_j, cum_index = network_generate( network_type, N, 1, 0, seed, d) G = nx.from_numpy_array(A) core_number = np.array(list(nx.core_number(G).values())) N_actual = len(A) k = np.sum(A > 0, 0) t = np.arange(0, 1000, 0.01) initial_condition = np.ones(N_actual) * attractor_value dynamics_multi = globals()[dynamics + '_multi'] xs_multi_list = np.zeros((len(weight_list), N_actual)) for i, weight in enumerate(weight_list): if network_type == 'SBM_ER': A, A_interaction, index_i, index_j, cum_index = SBM_ER( N, d, weight, seed) else: A, A_interaction, index_i, index_j, cum_index = network_generate( network_type, N, weight, 0, seed, d) net_arguments = (index_i, index_j, A_interaction, cum_index) xs_multi = odeint(dynamics_multi, initial_condition, t, args=(arguments, net_arguments))[-1] xs_multi_list[i] = xs_multi des = '../data/' + dynamics + '/' + network_type + f'/xs_multi/' if not os.path.exists(des): os.makedirs(des) des_file = des + f'N={N}_d=' + str(d) + f'_seed={seed}.csv' data = np.vstack((np.hstack((0, k)), np.hstack((0, core_number)), np.hstack((weight_list.reshape(len(weight_list), 1), xs_multi_list)))) df = pd.DataFrame(data) df.to_csv(des_file, index=None, header=None, mode='a') return data
def data_load(self, m, space): """TODO: Docstring for data_multi. :arg1: TODO :returns: TODO """ N, d, seed = self.N, self.d, self.seed if m == N : xs_des = self.des + 'xs_multi/' xs_file = xs_des + f'N={N}_d={d}_seed={seed}.csv' self.data = np.array(pd.read_csv(xs_file, header=None)) self.group_node_number = np.array( np.ones(self.data.shape[-1]-1), int) self.group_index = [[i] for i in range(N)] else: xs_des = self.des + f'degree_kmeans_space={space}/' xs_file = xs_des + f'N={N}_d={d}_number_groups={m}_seed={seed}.csv' A_unit, A_interaction, index_i, index_j, cum_index = network_generate(network_type, N, 1, 0, seed, d) """ file_A = '../data/A_matrix/' + network_type + '/' + f'N={N}_d={d}_seed={seed}_A.npz' A_unit = scipy.sparse.load_npz(file_A).toarray() """ G = nx.from_numpy_array(A_unit) feature = feature_from_network_topology(A_unit, G, space, tradeoff_para=0.5, method='degree') group_index = group_index_from_feature_Kmeans(feature, m) self.group_index = group_index self.group_node_number = np.array([len(i) for i in group_index]) self.data = np.array(pd.read_csv(xs_file, header=None))
def evolution(network_type, N, beta, seed, arguments, d1, d2, d3, d=None): """TODO: Docstring for evolution. :arg1: TODO :returns: TODO """ A, A_interaction, index_i, index_j, cum_index = network_generate( network_type, N, beta, seed, d) g = lambda t: np.ones(N) * 5 t = np.arange(0, 1000, 0.01) #dyn_all = ddeint(mutual_multi_delay_original, g, t, fargs=(d1, d2, d3, N, index_i, index_j, A_interaction, cum_index, arguments)) t1 = time.time() dyn_all = ddeint_Cheng( mutual_multi_delay, np.ones(N) * 5, t, *(d1, d2, d3, N, index_i, index_j, A_interaction, cum_index, arguments)) t2 = time.time() print(t2 - t1) plt.plot(t, np.mean(dyn_all, 1), alpha=alpha) #plt.plot(t, dyn_all, alpha = alpha) plt.subplots_adjust(left=0.18, right=0.98, wspace=0.25, hspace=0.25, bottom=0.18, top=0.98) plt.xticks(fontsize=ticksize) plt.yticks(fontsize=ticksize) plt.xlabel('$t$', fontsize=fs) plt.ylabel('$\\langle x \\rangle$', fontsize=fs) plt.show() return dyn_all
def coeff_K(arguments, beta, low=0.1, high=10): """TODO: Docstring for coeff_interaction. :R: TODO :alpha: TODO :beta: TODO :returns: TODO """ network_type = '2D' seed = 0 d = 0 N = 9 A, A_interaction, index_i, index_j, cum_index = network_generate( network_type, N, beta, seed, d) beta_eff, _ = betaspace(A, [0]) weight = beta / beta_eff A = A * weight B, C, D, E, H, K = arguments xs_low, xs_high = stable_state(A, A_interaction, index_i, index_j, cum_index, low, high, arguments) xs = xs_high[0] P = (beta * E * xs * xs) / (D + E * xs + H * xs)**2 - (beta * xs) / ( D + E * xs + H * xs) + (beta * H * xs * xs) / ( D + E * xs + H * xs)**2 - (beta * xs) / (D + E * xs + H * xs) - ( 1 - xs / K) * (2 * xs / C - 1) Q = xs / K * (xs / C - 1) tau1 = np.arccos(-P / Q) / Q / np.sin(np.arccos(-P / Q)) f = lambda x: Q * np.exp(1 + P * x) * x - 1 initial_condition = np.array([0.1]) tau2 = fsolve(f, initial_condition) return P, Q, tau1, tau2
def xs_group_partition_bifurcation(network_type, N, seed, d, weight, m, attractor_low, initial_high, space, tradeoff_para, method): """TODO: Docstring for random_partition. :arg1: TODO :returns: TODO """ A_unit, A_interaction, index_i, index_j, cum_index = network_generate( network_type, N, 1, 0, seed, d) G = nx.from_numpy_array(A_unit) N_actual = len(A_unit) k = np.sum(A_unit > 0, 0) t = np.arange(0, 1000, 0.01) dynamics_multi = globals()[dynamics + '_multi'] A = A_unit * weight net_arguments = (index_i, index_j, weight * A_interaction, cum_index) feature = feature_from_network_topology(A, G, space, tradeoff_para, method) group_index = group_index_from_feature_Kmeans(feature, m) A_reduction_deg_part, net_arguments_reduction_deg_part, _ = reducednet_effstate( A, np.zeros(N_actual), group_index) initial_low = np.ones(len(A_reduction_deg_part)) * attractor_low initial_high = np.ones(len(A_reduction_deg_part)) * attractor_high xs_low = odeint(dynamics_multi, initial_low, t, args=(arguments, net_arguments_reduction_deg_part)) xs_high = odeint(dynamics_multi, initial_high, t, args=(arguments, net_arguments_reduction_deg_part)) return xs_low[::100], xs_high[::100]
def delay_evolution(network_type, N, seed, d, weight, dynamics, arguments, attractor_value, delay): """TODO: Docstring for tau_evolution. :network_type: TODO :N: TODO :beta: TODO :seed: TODO :d: TODO :returns: TODO """ A, A_interaction, index_i, index_j, cum_index = network_generate( network_type, N, weight, 0, seed, d) net_arguments = (index_i, index_j, A_interaction, cum_index) N_actual = np.size(A, 0) initial_condition = np.ones(N_actual) * attractor_value t = np.arange(0, 1000, 0.01) dynamics_multi = globals()[dynamics + '_multi'] xs_multi = odeint(dynamics_multi, initial_condition, t, args=(arguments, net_arguments))[-1] initial_condition = xs_multi - 0.01 t = np.arange(0, 200, 0.001) dyn_all = ddeint_Cheng(mutual_multi_delay, initial_condition, t, *(delay, arguments, net_arguments))[::100] df = pd.DataFrame(np.hstack((t[::100].reshape(len(t[::100]), 1), dyn_all))) des = '../data/' + 'tau_compare/' des_file = des + dynamics + '_' + network_type + f'_N={N}_d={d}_seed={seed}_weight={weight}_delay={delay}_evolution.csv' df.to_csv(des_file, header=None, index=None) df = pd.DataFrame(xs_multi.reshape(len(xs_multi), 1)) xs_file = des + dynamics + '_' + network_type + f'_N={N}_d={d}_seed={seed}_weight={weight}_xs.csv' df.to_csv(xs_file, header=None, index=None) return None
def xs_multi_bifurcation(network_type, N, seed, d, weight, attractor_low, attractor_high): """TODO: Docstring for random_partition. :arg1: TODO :returns: TODO """ A_unit, A_interaction, index_i, index_j, cum_index = network_generate( network_type, N, 1, 0, seed, d) G = nx.from_numpy_array(A_unit) N_actual = len(A_unit) k = np.sum(A_unit > 0, 0) t = np.arange(0, 1000, 0.01) initial_low = np.ones(N_actual) * attractor_low initial_high = np.ones(N_actual) * attractor_high dynamics_multi = globals()[dynamics + '_multi'] A = A_unit * weight net_arguments = (index_i, index_j, weight * A_interaction, cum_index) xs_low = odeint(dynamics_multi, initial_low, t, args=(arguments, net_arguments)) xs_high = odeint(dynamics_multi, initial_high, t, args=(arguments, net_arguments)) return xs_low[::100], xs_high[::100]
def sensitivity_connection(network_type, dynamics, seed_list, d, weight_list): """TODO: Docstring for sensitivity_connection. :network_type: TODO :dynamics: TODO :seed: TODO :d: TODO :weight_list: TODO :returns: TODO """ des = '../data/' + dynamics + '/' + network_type + '/xs_bifurcation/xs_multi/' for seed in seed_list: des_file = des + f'N={N}_d={d}_seed={seed}.csv' data = np.array(pd.read_csv(des_file, header=None)) A_unit, A_interaction, index_i, index_j, cum_index = network_generate( network_type, N, 1, 0, seed, d) index = [ np.where(np.abs(w - data[:, 0]) < 1e-8)[0][0] for w in weight_list ] xs_multi = data[index, 1:] y_multi = betaspace(A_unit, xs_multi)[-1] plt.plot(weight_list, y_multi, label=f'seed={seed[1]}') plt.legend() plt.show() return None
def xs_multi_bifurcation(dynamics, arguments, network_type, N, seed, d, weight_list, attractor_value, des_save): """TODO: Docstring for random_partition. :arg1: TODO :returns: TODO """ A_unit, A_interaction, index_i, index_j, cum_index = network_generate( network_type, N, 1, 0, seed, d) G = nx.from_numpy_array(A_unit) N_actual = len(A_unit) k = np.sum(A_unit > 0, 0) t = np.arange(0, 1000, 0.01) initial_condition = np.ones(N_actual) * attractor_value dynamics_multi = globals()[dynamics + '_multi'] for i, weight in enumerate(weight_list): A = A_unit * weight net_arguments = (index_i, index_j, weight * A_interaction, cum_index) xs_multi = odeint(dynamics_multi, initial_condition, t, args=(arguments, net_arguments))[-1] des_file = des_save + f'N={N}_d=' + str(d) + f'_seed={seed}.csv' data = np.hstack((weight, xs_multi)) df = pd.DataFrame(data.reshape(1, len(data))) df.to_csv(des_file, index=None, header=None, mode='a') return None
def eigenvalue_Matrix(network_type, arguments, N, beta, seed, d, nu_set, tau_set, low=0.1, high=10): B, C, D, E, H, K = arguments A, A_interaction, index_i, index_j, cum_index = network_generate( network_type, N, beta, seed, d) Degree = np.sum(A, 0) xs_low, xs_high = stable_state(A, A_interaction, index_i, index_j, cum_index, arguments, d) xs = xs_high fx = (1 - xs / K) * (2 * xs / C - 1) fxt = -xs / K * (xs / C - 1) gx_i = xs / (D + E * xs + H * xs) - E * xs**2 / (D + E * xs + H * xs)**2 gx_j = xs / (D + E * xs + H * xs) - H * xs**2 / (D + E * xs + H * xs)**2 eigenvalue_set = np.zeros((np.size(tau_set), np.size(nu_set))) for tau, i in zip(tau_set, range(np.size(tau_set))): for nu, j in zip(nu_set, range(np.size(nu_set))): M = np.diagflat(nu * imag - fx - fxt * np.exp(-nu * tau * imag) - Degree * gx_i) - A * gx_j eigenvalue, eigenvector = np.linalg.eig(M) eigenvalue_set[i, j] = np.min(np.abs(eigenvalue)) #print(np.sort(np.real(eigenvalue)), np.sort(np.imag(eigenvalue))) sns.heatmap(eigenvalue_set, vmin=np.min(eigenvalue_set), vmax=np.max(eigenvalue_set)) return eigenvalue_set
def tau_multi_critical(network_type, N, arguments, beta_set, seed, d=None, nu_set=None, tau_set=None, low=0.1, high=10): """TODO: Docstring for tau_critical. :arg1: TODO :returns: TODO """ tau_critical = np.zeros(np.size(beta_set)) for beta, i in zip(beta_set, range(np.size(beta_set))): t1 = time.time() tau_sol = np.ravel( tau_eigenvalue(network_type, N, beta, nu_set, tau_set, arguments, seed, d=d)) tau_critical[i] = np.min(tau_sol[tau_sol > 0]) t2 = time.time() print(i, t2 - t1, tau_critical) A, A_interaction, index_i, index_j, cum_inde = network_generate( network_type, N, beta, seed, d) A = np.heaviside(A, 0) degree = np.sum(A, 0) hetero = np.sum((degree - np.mean(degree))**2) / N data = np.hstack((seed, np.mean(degree), hetero, tau_critical)) data = pd.DataFrame(data.reshape(1, np.size(data))) data.to_csv('../report/report101920/' + network_type + f'_N={N}_d=' + str(d).replace('.', '') + '_logistic.csv', header=None, index=None, mode='a') plt.plot(beta_set, tau_critical, linewidth=lw, alpha=alpha) plt.subplots_adjust(left=0.18, right=0.98, wspace=0.25, hspace=0.25, bottom=0.18, top=0.98) plt.xticks(fontsize=ticksize) plt.yticks(fontsize=ticksize) plt.xlabel('$\\beta_{eff}$', fontsize=fs) plt.ylabel('$\\tau_c$', fontsize=fs) #plt.show() return tau_critical
def KNN_kcore_regroup_partition(network_type, N, d, weight, seed, dynamics, arguments, attractor_value, regroup): """TODO: Docstring for degree_partition. :arg1: TODO :returns: TODO """ if regroup == 'None': des = '../data/' + dynamics + '/' + network_type + f'/xs_KNN_kcore/' else: des = '../data/' + dynamics + '/' + network_type + f'/xs_KNN_kcore_regroup/' if not os.path.exists(des): os.makedirs(des) "the original network" if network_type == 'SBM_ER': A, A_interaction, index_i, index_j, cum_index = SBM_ER( N, d, weight, seed) else: A, A_interaction, index_i, index_j, cum_index = network_generate( network_type, N, weight, 0, seed, d) N_actual = len(A) net_arguments = (index_i, index_j, A_interaction, cum_index) t = np.arange(0, 1000, 0.01) initial_condition = np.ones(N_actual) * attractor_value dynamics_multi = globals()[dynamics + '_multi'] xs_multi = odeint(dynamics_multi, initial_condition, t, args=(arguments, net_arguments))[-1] "the reduced system by KNN partition" G = nx.from_numpy_array(A) core_group = find_core_group(G) #core_group = np.arange(N_group[0]) w = np.sum(A, 0) A_reduction, net_arguments_reduction, x_eff = neighbors_shell( G, A, core_group, xs_multi, regroup) initial_condition_reduction = np.ones(len(A_reduction)) * attractor_value xs_reduction = odeint(dynamics_multi, initial_condition_reduction, t, args=(arguments, net_arguments_reduction))[-1] "save data" data = np.hstack((weight, np.ravel(A_reduction), x_eff, xs_reduction)) if regroup == 'None': des_file = des + f'N={N}_d=' + str(d) + f'_seed={seed}.csv' else: des_file = des + f'N={N}_d=' + str( d) + f'_seed={seed}_regroup={regroup}.csv' df = pd.DataFrame(data.reshape(1, len(data))) df.to_csv(des_file, index=None, header=None, mode='a') return None
def partition_linear_expansion(network_type, N, d, weight, seed, dynamics, arguments, attractor_value, number_groups, space, degree_interval, method): """TODO: Docstring for degree_partition. :arg1: TODO :returns: TODO """ if method == 'degree': des = '../data/' + dynamics + '/' + network_type + f'/linear_expansion_degree_group_decouple_' + space + '/' des_file = des + f'N={N}_d=' + str( d) + f'_group_num={number_groups}_seed={seed}.csv' elif method == 'kcore': des = '../data/' + dynamics + '/' + network_type + f'/linear_expansion_kcore/' des_file = des + f'N={N}_d=' + str(d) + f'_seed={seed}.csv' elif method == 'kcore_degree': des = '../data/' + dynamics + '/' + network_type + f'/linear_expansion_kcore_degree_' + space + f'={degree_interval}/' des_file = des + f'N={N}_d=' + str(d) + f'_seed={seed}.csv' elif method == 'kcore_KNN_degree': des = '../data/' + dynamics + '/' + network_type + f'/linear_expansion_kcore_KNN_degree_' + space + f'={degree_interval}/' des_file = des + f'N={N}_d=' + str(d) + f'_seed={seed}.csv' if not os.path.exists(des): os.makedirs(des) "the original network" A, A_interaction, index_i, index_j, cum_index = network_generate( network_type, N, weight, 0, seed, d) N_actual = len(A) net_arguments = (index_i, index_j, A_interaction, cum_index) t = np.arange(0, 1000, 0.01) initial_condition = np.ones(N_actual) * attractor_value dynamics_multi = globals()[dynamics + '_multi'] dynamics_linear_expansion = globals()[dynamics + '_linear_expansion'] xs_multi = odeint(dynamics_multi, initial_condition, t, args=(arguments, net_arguments))[-1] "the reduced system by partition, calculated by linear expansion" beta_kl, alpha_k, gamma_kl, x_eff_deg_part = linear_expansion_coeff( network_type, N, d, weight, seed, dynamics, method, number_groups, space, degree_interval, xs_multi) net_arguments_reduction_deg_part = (beta_kl, alpha_k, gamma_kl) initial_condition_reduction_deg_part = np.ones( len(beta_kl)) * attractor_value xs_reduction_deg_part = odeint(dynamics_linear_expansion, initial_condition_reduction_deg_part, t, args=(arguments, net_arguments_reduction_deg_part))[-1] "save data" data = np.hstack( (weight, np.ravel(beta_kl), x_eff_deg_part, xs_reduction_deg_part)) df = pd.DataFrame(data.reshape(1, len(data))) df.to_csv(des_file, index=None, header=None, mode='a') return None
def tau_decouple(network_type, N, d, beta, betaeffect, arguments, seed_list): """TODO: Docstring for tau_kmax. :network_type: TODO :N: TODO :beta: TODO :betaeffect: TODO :returns: TODO """ B, C, D, E, H, K = arguments des = '../data/' if not os.path.exists(des): os.makedirs(des) if betaeffect: des_file = des + network_type + f'_N={N}_d=' + str( d) + '_decouple_beta=' + str(beta) + '_logistic.csv' else: des_file = des + network_type + f'_N={N}_d=' + str( d) + '_decouple_wt=' + str(beta) + '_logistic.csv' for seed in seed_list: A, A_interaction, index_i, index_j, cum_index = network_generate( network_type, N, beta, betaeffect, seed, d) xs_low, xs_high = stable_state(A, A_interaction, index_i, index_j, cum_index, arguments) degree = np.sum(A > 0, 0) x_fix = np.mean(xs_high) index_list = np.argsort(degree)[-10:] tau = [] for index in index_list: w = np.sum(A[index]) xs = ddeint_Cheng(one_single_delay, np.ones(1) * 5, np.arange(0, 100, 0.01), *(0, 0, 0, w, x_fix, arguments))[-1] #xs = fsolve(one_kmax, np.ones(1) * 10, args=(w, x_fix, arguments)) P = -(w * x_fix) / (D + E * xs + H * x_fix) + ( w * E * xs * x_fix) / (D + E * xs + H * x_fix)**2 - ( 1 - xs / K) * (2 * xs / C - 1) Q = xs / K * (xs / C - 1) if abs(P / Q) <= 1: tau.append(np.arccos(-P / Q) / Q / np.sin(np.arccos(-P / Q))) tau = np.min(tau) data = np.hstack((seed, degree.max(), tau)) column_name = [f'seed{i}' for i in range(np.size(seed))] column_name.extend(['kmax', str(beta)]) if not os.path.exists(des_file): df = pd.DataFrame(data.reshape(1, np.size(data)), columns=column_name) df.to_csv(des_file, index=None, mode='a') else: df = pd.DataFrame(data.reshape(1, np.size(data))) df.to_csv(des_file, index=None, header=None, mode='a') print(seed, tau) return None
def A_feature(network_type, N, seed, d, weight, space, tradeoff_para, method): A_unit, A_interaction, index_i, index_j, cum_index = network_generate( network_type, N, 1, 0, seed, d) G = nx.from_numpy_array(A_unit) N_actual = len(A_unit) A = A_unit * weight feature = feature_from_network_topology(A, G, space, tradeoff_para, method) net_arguments = (index_i, index_j, weight * A_interaction, cum_index) return A, feature, net_arguments
def ER_SBM_partition(arg1): """TODO: Docstring for ER_SBM_partition. :arg1: TODO :returns: TODO """ network_type = 'SBM_ER' N = [30, 30, 30] beta = 1 betaeffect = 0 seed = 2 d = [[0.9, 0.01, 0.01], [0.01, 0.5, 0.01], [0.01, 0.01, 0.1]] A, A_interaction, index_i, index_j, cum_index = network_generate( network_type, N, beta, betaeffect, seed, d) G = nx.from_numpy_matrix(A) k = np.sum(A, 0) space = 'linear' tradeoff_para = 0.5 method = 'degree' feature = feature_from_network_topology(A, G, space, tradeoff_para, method) number_groups = 3 group_index = group_index_from_feature_Kmeans(feature, number_groups) val_map = dict() color_val = ['tab:red', 'tab:green', 'tab:blue'] color_val = ['#1b9e77', '#d95f02', '#7570b3'] for i, group_i in enumerate(group_index): for j in group_i: val_map[j] = color_val[i] node_color = [val_map.get(node) for node in range(sum(N))] pos = nx.nx_agraph.graphviz_layout(G, prog='neato') pos_map = dict() pos_group = [[0, 0], [100, 100], [100, -100]] for i, group_i in enumerate(group_index): for j in group_i: pos_map[j] = (np.random.random(2) * 70 + pos_group[i]) node_size = [v * 15 for v in k] nx.draw(G, pos=pos_map, node_color=node_color, node_size=node_size, edgecolors='k') plt.savefig('../manuscript/dimension_reduction_v1_111021/figure/network_' + network_type + '_' + method + '_space=' + space + f'_N={N}_d={d}_group_num={number_groups}_seed={seed}' + '.svg', format="svg") # nodes options = {"edgecolors": "tab:gray", "node_size": 800, "alpha": 0.9} plt.show()
def linear_expansion_coeff(network_type, N, d, weight, seed, dynamics, method, number_groups, space, degree_interval, xs_multi): """TODO: Docstring for eigenvalue_A. :network_type: TODO :N: TODO :d: TODO :weight: TODO :seed: TODO :dynamics: TODO :: TODO :returns: TODO """ A, A_interaction, index_i, index_j, cum_index = network_generate( network_type, N, weight, 0, seed, d) w = np.sum(A, 0) G = nx.from_numpy_array(A) N_actual = len(A) if method == 'degree': group_index, rearange_index = group_partition_degree( w, number_groups, N_actual, space) elif method == 'kcore_degree': _, _, _, group_index = kcore_degree(G, A, xs_multi, space, degree_interval) elif method == 'kcore': _, _, _, group_index = kcore_shell(G, A, xs_multi, 'None') elif method == 'kcore_KNN_degree': core_group = find_core_group(G) _, _, _, group_index = kcore_KNN_degree(G, A, core_group, xs_multi, 'None', space, degree_interval, 'None') gamma_kl = np.zeros((len(group_index), len(group_index))) beta_kl = np.zeros((len(group_index), len(group_index))) alpha_k = np.zeros((len(group_index))) x_eff = np.zeros((len(group_index))) for k, group_k in enumerate(group_index): s_k = w[group_k] a_k = s_k / sum(s_k) for l, group_l in enumerate(group_index): A_lk = A[group_l][:, group_k] a_l = w[group_l] / sum(w[group_l]) s_kl = np.sum(A_lk, 0) t1 = A_lk.dot(a_k) t2 = a_l * (s_kl * a_k).sum() if abs(sum(t2)) < 1e-10: gamma_kl[k, l] = 1 else: gamma_kl[k, l] = sum(t1 * t2) / sum(t2**2) beta_kl[k, l] = t1.sum() t3 = a_k * s_k t4 = (a_k * s_k).sum() * a_k alpha_k[k] = sum(t3 * t4) / sum(t4**2) x_eff[k] = (xs_multi[group_k] * a_k).sum() return beta_kl, alpha_k, gamma_kl, x_eff
def x_feature(network_type, beta, d, N, seed_list): """TODO: Docstring for x_feature. :network_type: TODO :d_list: TODO :N_list: TODO :seed_list: TODO :feature: TODO :returns: TODO """ for seed, i in zip(seed_list, range(len(seed_list))): print(i) A, _, _, _, _ = network_generate(network_type, N, beta, seed, d) L = np.copy(A) N_gcc = np.size(A, 0) degree = np.sum(np.heaviside(A, 0), 0) degree_sort = np.hstack((np.sort(degree)[::-1], np.zeros(N - N_gcc))) k_ave = np.mean(degree) degree_max = np.max(degree) degree_min = np.min(degree) heterogeneity_gao = np.mean((degree - k_ave)**2) / k_ave heterogeneity_barabasi = np.sum( np.abs(degree - degree.reshape(degree.size, 1))) / N_gcc**2 / k_ave lambda_adj = np.max(np.real(LA.eig(A)[0])) np.fill_diagonal(L, degree) lambda_lap = np.max(np.real(LA.eig(L)[0])) y, x = np.histogram(degree, np.arange(degree_min, degree_max, 1)) index = np.where(y > 10)[0][-1] gamma = -np.polyfit(np.log(x[:index]), np.log(y[:index]), 1)[0] data = np.hstack((seed, N_gcc, degree_max, degree_min, k_ave, heterogeneity_gao, heterogeneity_barabasi, lambda_adj, lambda_lap, gamma, degree_sort)) des_file = '../data/' + network_type + f'_N={N}_d=' + str( d) + '_network.csv' if not os.path.exists(des_file): column_name = [f'seed{j}' for j in range(np.size(seed))] column_name.extend([ 'N_actual', 'degree_max', 'degree_min', 'degree_ave', 'heterogeneity_gao', 'heterogeneity_barabasi', 'lambda_adj', 'lambda_lap', 'gamma' ]) column_name.extend( [i + j for i, j in zip(['k'] * N, np.arange(N).astype(str))]) df = pd.DataFrame(data.reshape(1, np.size(data)), columns=column_name) df.to_csv(des_file, index=None, mode='a') else: df = pd.DataFrame(data.reshape(1, np.size(data))) df.to_csv(des_file, index=None, header=None, mode='a') return None
def plot_xs_onenet(network_type, N, d, seed, dynamics, m_list, space, weight_list): """TODO: Docstring for plot_P_w. :weight_list: TODO :returns: TODO """ fig, axes = plt.subplots(len(seed_list), len(weight_list) + 1, sharex=False, sharey=True, figsize=(3*(len(weight_list) +1), 3*len(seed_list)) ) markers = ['o', '^', 's', 'p', 'P', 'h'] linestyles = [(i, j) for i in [3, 6, 9] for j in [1, 5, 9, 13]] colors=sns.color_palette('hls', 11) alphas = [np.log(min(m_list)+1) / np.log(m+1) for m in m_list] sizes = [np.log(min(m_list)+1) / np.log(m+1) for m in m_list] s = StateDistribution(network_type, N, d, seed, dynamics) A_unit, A_interaction, index_i, index_j, cum_index = network_generate(network_type, N, 1, 0, seed, d) data_m = dict() data_all_m = dict() groups_node_nums = dict() for m in m_list: s.data_load(m, space) data = np.abs(s.data ) data_all_m[m] = data weights = data[:, :1] index = [np.where(np.abs(weights - weight) < 1e-02 )[0][0] for weight in weight_list] xs = data[index, 1:] data_m[m] = xs groups_node_nums[m] = s.group_node_number for j, weight in enumerate(weight_list): ax = axes[i][j] simpleaxis(ax) sizes = np.ravel(np.tile( (s.group_node_number / np.sum(s.group_node_number) + 0.01) * 100, (1, len(weight_list)) )) for k, m in enumerate(m_list): y = data_m[m][j] ax.scatter(x=np.ones(len(y)) * m, y=y, s= (groups_node_nums[m] / np.sum(groups_node_nums[m]) + 0.05) * 100, alpha=np.log(min(m_list)+0.5) / np.log(m+0.5), color=colors[k]) ax.set(xscale='log', yscale='log') if i == 0: title_name = 'group ' + f'$w={weight}$' ax.set_title(title_name, size=labelsize*0.5) ax = axes[i][j+1] simpleaxis(ax) for i_m, m in enumerate(m_list): data = data_all_m[m] weights = data[:, 0] weight_unique = np.arange(0.01, 0.6, 0.01) index_plot = [np.where(abs(weights - w_i) < 1e-5)[0][0] for w_i in weight_unique] y = data[index_plot, 1:] xs = np.repeat(y, groups_node_nums[m], axis=1) y_gl = betaspace(A_unit, xs)[-1] ax.plot(weight_unique, y_gl, linewidth=1, color=colors[i_m], label=f'$m={m}$', linestyle=(0, linestyles[i_m]) ) if i == 0: title_name = f'global' ax.set_title(title_name, size=labelsize*0.5) ax.legend(fontsize=legendsize*0.5, ncol=2, loc='lower right', frameon=False, )
def tau_evolution(network_type, N, seed, d, weight, dynamics, arguments, attractor_value, delay1, delay2, criteria_delay, criteria_dyn): """TODO: Docstring for tau_evolution. :network_type: TODO :N: TODO :beta: TODO :seed: TODO :d: TODO :returns: TODO """ A, A_interaction, index_i, index_j, cum_index = network_generate( network_type, N, weight, 0, seed, d) net_arguments = (index_i, index_j, A_interaction, cum_index) N_actual = np.size(A, 0) initial_condition = np.ones(N_actual) * attractor_value t = np.arange(0, 1000, 0.01) dynamics_multi = globals()[dynamics + '_multi'] xs_multi = odeint(dynamics_multi, initial_condition, t, args=(arguments, net_arguments))[-1] initial_condition = xs_multi - 0.01 t = np.arange(0, 200, 0.001) dyn_dif = 1 delta_delay = delay2 - delay1 result = dict() while delta_delay > criteria_delay: if delay1 not in result: dyn_all1 = ddeint_Cheng(mutual_multi_delay, initial_condition, t, *(delay1, arguments, net_arguments))[-1000:] diff1 = np.max(np.max(dyn_all1, 0) - np.min(dyn_all1, 0)) result[delay1] = diff1 if delay2 not in result: dyn_all2 = ddeint_Cheng(mutual_multi_delay, initial_condition, t, *(delay2, arguments, net_arguments))[-1000:] diff2 = np.max(np.max(dyn_all2, 0) - np.min(dyn_all2, 0)) result[delay2] = diff2 if result[delay1] < criteria_dyn and (result[delay2] > criteria_dyn or np.isnan(result[delay2])): delay1 = np.round(delay1 + delta_delay / 2, 10) elif result[delay1] > criteria_dyn or np.isnan(result[delay1]): delay2 = np.round(delay1, 10) delay1 = np.round(delay1 - delta_delay, 10) delta_delay = delay2 - delay1 df = pd.DataFrame([[delay1]]) des = '../data/' + 'tau_compare/' des_file = des + dynamics + '_' + network_type + f'_N={N}_d={d}_seed={seed}_weight={weight}_evolution.csv' df.to_csv(des_file, header=None, index=None, mode='a') return delay1
def many_trial(network_type, N, beta, betaeffect, seed, d, number_groups, T0, T_num, T_decay, N_trial): """TODO: Docstring for network_info. :arg1: TODO :returns: TODO """ A, A_interaction, index_i, index_j, cum_index = network_generate( network_type, N, beta, betaeffect, seed, d) T_list = np.array([T_decay**i for i in range(T_num)]) * T0 w = np.sum(A, 0) N_actual = np.size(A, 0) each_number_groups = int(np.sum([N]) / number_groups) group_index = [ np.arange(each_number_groups * i, each_number_groups * (i + 1)) for i in range(number_groups) ] """ G = nx.from_numpy_array(A) method = 'degree' if network_type == 'SF': space = 'log' else: space = 'linear' feature = feature_from_network_topology(A, G, space, 0.5, method) group_index = group_index_from_feature_Kmeans(feature, number_groups) """ h1_list, h2_list = objective_function(A, w, group_index) change_list = [] for T in T_list: print(T) node_move_list = np.random.choice(N_actual, N_trial) R_list = np.random.uniform(size=N_trial) for node_move, R in zip(node_move_list, R_list): group_length = len(group_index) moveout_group, movein_group = random_move(group_index, node_move) t1 = time.time() group_index, h1_list, h2_list, change = one_trial( A, w, N, group_index, movein_group, moveout_group, node_move, h1_list, h2_list, T, R) change_list.append(change) t2 = time.time() "write to .txt file" des_file = '../data/network_partition/' + network_type + '/' if not os.path.exists(des_file): os.makedirs(des_file) file_name = des_file + f'N={N}_d={d}_seed={seed}_number_groups={number_groups}_trial={N_trial}_T=[{T0}, {T_num}, {T_decay}].txt' with open(file_name, 'w') as output: for i in range(group_length): output.write(','.join(map(str, group_index[i])) + '\n') return group_index, change_list
def verify1(network_type, N, beta, seed=0): A, A_interaction, index_i, index_j, cum_index = network_generate( network_type, N, beta, seed) det = lambda a: np.linalg.det(a * np.identity(N) + A) initial_condition = np.arange(-10, 1, 0.01) solution_set = [] for i in initial_condition: solution = fsolve(det, i) if abs(det(solution)) < 1e-10: solution_set.append(solution) solution_set = np.unique(solution_set) return solution_set
def many_trial(network_type, N, beta, betaeffect, seed, d, group_num, r, T0, T_num, T_decay, N_trial): """TODO: Docstring for network_info. :arg1: TODO :returns: TODO """ A, A_interaction, index_i, index_j, cum_index = network_generate( network_type, N, beta, betaeffect, seed, d) T_list = np.array([T_decay**i for i in range(T_num)]) * T0 w = np.sum(A, 0) N_actual = np.size(A, 0) l = np.sum(A) / 2 if network_type == 'SF': space = 'log' elif network_type == 'ER': space = 'linear' group_index, rearange_index = group_partition_degree( w, group_num, N_actual, space) delta_S_list = [] delta_Q_list = [] delta_H_list = [] for T in T_list: node_move_list = np.random.choice(N_actual, N_trial) R_list = np.random.uniform(size=N_trial) for node_move, R in zip(node_move_list, R_list): group_length = len(group_index) moveout_group, movein_group = random_move(group_index, node_move) group_in = group_index[movein_group] group_out = group_index[moveout_group] group_in, group_out, delta_H, delta_Q, delta_S = one_trial( A, w, l, group_in, group_out, node_move, group_length, r, T, R) group_index[movein_group] = group_in group_index[moveout_group] = group_out delta_S_list.append(delta_S) delta_H_list.append(delta_H) delta_Q_list.append(delta_Q) H = np.cumsum(delta_H_list) Q = np.cumsum(delta_Q_list) S = np.cumsum(delta_S_list) "write to .txt file" des_file = '../data/network_partition/' + network_type + '/' if not os.path.exists(des_file): os.makedirs(des_file) file_name = des_file + f'N={N}_d={d}_seed={seed}_group_num={group_num}_trial={N_trial}_r={r}_T=[{T0}, {T_num}, {T_decay}].txt' with open(file_name, 'w') as output: for i in range(group_length): output.write(','.join(map(str, group_index[i])) + '\n') return group_index, H, Q, S
def evolution_multi(network_type, arguments, N, beta, betaeffect, d, seed, delay, initial_value): """TODO: Docstring for evolution_compare. :network_type: TODO :dynamics: TODO :arguments: TODO :N: TODO :beta: TODO :betaeffect: TODO :d: TODO :returns: TODO """ A, A_interaction, index_i, index_j, cum_index = network_generate(network_type, N, beta, betaeffect, seed, d) N_actual = np.size(A, 0) net_arguments = (index_i, index_j, A_interaction, cum_index) dyn_multi = np.ones((N_actual)) * initial_value t = np.arange(0, 500, 0.01) xs = odeint(mutual_multi, dyn_multi, t, args=(arguments, net_arguments))[-1] iteration = 1 deviation1 = np.abs(dyn_multi - xs) while 0 < iteration < 50: dyn_multi = ddeint_Cheng(mutual_multi_delay, dyn_multi, t, *(delay, arguments, net_arguments))[-1] deviation2 = np.abs(dyn_multi-xs) if np.max(deviation2)< 1e-2: iteration = 0 elif np.sum(deviation2) < np.sum(deviation1): iteration += 1 deviation1 = deviation2 else: iteration = 0 dyn_beta = betaspace(A, dyn_multi)[-1] if np.max(deviation2) < 1e-2: x = dyn_beta else: x = -1 data = np.hstack((seed, x)) des = f'../data/mutual/' + network_type + '/xs/' if not os.path.exists(des): os.makedirs(des) if betaeffect == 0: des_file = des + f'N={N}_d={d}_wt={beta}_delay={delay}_x0={initial_value}.csv' else: des_file = des + f'N={N}_d={d}_beta={beta}_delay={delay}_x0={initial_value}.csv' df = pd.DataFrame(data.reshape(1, len(data))) df.to_csv(des_file, mode='a', index=None, header=None) #dyn_multi = ddeint_Cheng(mutual_multi_delay, xs-1e-3, t, *(delay, arguments, net_arguments)) #dyn_decouple = ddeint_Cheng(mutual_decouple_two_delay, xs_decouple - 1e-3, t, *(delay, w, beta, arguments)) #print(x, np.max(deviation2)) return None
def degree_partition(network_type, N, d, weight, seed, dynamics, arguments, attractor_value, number_groups_list, space): """TODO: Docstring for degree_partition. :arg1: TODO :returns: TODO """ des = '../data/' + dynamics + '/' + network_type + f'/bifurcation_group_decouple_' + space + '/' if not os.path.exists(des): os.makedirs(des) "the original network" if network_type == 'SBM_ER': A, A_interaction, index_i, index_j, cum_index = SBM_ER( N, d, weight, seed) else: A, A_interaction, index_i, index_j, cum_index = network_generate( network_type, N, weight, 0, seed, d) N_actual = len(A) net_arguments = (index_i, index_j, A_interaction, cum_index) t = np.arange(0, 1000, 0.01) initial_condition = np.ones(N_actual) * attractor_value dynamics_multi = globals()[dynamics + '_multi'] xs_multi = odeint(dynamics_multi, initial_condition, t, args=(arguments, net_arguments))[-1] "the reduced system by degree partition" for number_groups in number_groups_list: A_reduction_deg_part, net_arguments_reduction_deg_part, x_eff_deg_part = reduced_network_group_partition_degree( A, xs_multi, number_groups, space) initial_condition_reduction_deg_part = np.ones( len(A_reduction_deg_part)) * attractor_value xs_reduction_deg_part = odeint( dynamics_multi, initial_condition_reduction_deg_part, t, args=(arguments, net_arguments_reduction_deg_part))[-1] "save data" data = np.hstack((weight, np.ravel(A_reduction_deg_part), x_eff_deg_part, xs_reduction_deg_part)) des_file = des + f'N={N}_d=' + str( d) + f'_group_num={number_groups}_seed={seed}.csv' df = pd.DataFrame(data.reshape(1, len(data))) df.to_csv(des_file, index=None, header=None, mode='a') return None
def tau_eigenvalue(network_type, N, beta, nu_set, tau_set, arguments, seed, d=None): """TODO: Docstring for character_multi. :x: TODO :tau: TODO :returns: TODO """ B, C, D, E, H, K = arguments A, A_interaction, index_i, index_j, cum_index = network_generate( network_type, N, beta, seed, d) Degree_weighted = np.sum(A, 0) xs_low, xs_high = stable_state(A, A_interaction, index_i, index_j, cum_index, arguments, d=d) xs = xs_high fx = (1 - xs / K) * (2 * xs / C - 1) fxt = -xs / K * (xs / C - 1) gx_i = xs / (D + E * xs + H * xs) - E * xs**2 / (D + E * xs + H * xs)**2 gx_j = xs / (D + E * xs + H * xs) - H * xs**2 / (D + E * xs + H * xs)**2 tau_sol = np.ones((np.size(tau_set), np.size(nu_set))) * 10 for tau, i in zip(tau_set, range(np.size(tau_set))): for nu, j in zip(nu_set, range(np.size(nu_set))): t1 = time.time() initial_condition = np.array([tau, nu]) tau_solution, nu_solution = fsolve(eigenvalue_zero, initial_condition, args=(A, fx, fxt, Degree_weighted, gx_i, gx_j)) eigen_real, eigen_imag = eigenvalue_zero( np.array([tau_solution, nu_solution]), A, fx, fxt, Degree_weighted, gx_i, gx_j) if abs(eigen_real) < 1e-5 and abs(eigen_imag) < 1e-5: tau_sol[i, j] = tau_solution t2 = time.time() # print(tau, nu, t2-t1, tau_solution) return tau_sol
def evolution_analysis(network_type, N, beta, betaeffect, seed, d, delay): """TODO: Docstring for evolution_oscillation. :arg1: TODO :returns: TODO """ A, A_interaction, index_i, index_j, cum_index = network_generate( network_type, N, beta, betaeffect, seed, d) xs_low, xs_high = stable_state(A, A_interaction, index_i, index_j, cum_index, arguments) beta_eff, _ = betaspace(A, [0]) degree = np.sum(A > 0, 0) N = np.size(A, 0) initial_condition = np.ones(N) * 5 initial_condition = xs_high - 0.0001 t = np.arange(0, 50, 0.001) #dyn_all = ddeint_Cheng(mutual_multi_delay, initial_condition, t, *(delay, 0, 0, N, index_i, index_j, A_interaction, cum_index, arguments)) dyn_all = ddeint_Cheng( mutual_single_delay, initial_condition, t, *(delay, 0, 0, N, [np.argmax(degree)], index_i, index_j, A_interaction, cum_index, arguments)) w = np.sum(A[np.argmax(degree)]) initial_condition = np.array([xs_high.max()]) xs_eff = fsolve(mutual_1D, initial_condition, args=(0, beta_eff, arguments)) xs_eff = np.mean(xs_high) print(xs_eff) #dyn_all = ddeint_Cheng(one_single_delay, initial_condition, t, *(delay, 0, 0, w, xs_eff, arguments)) #xs_high = ddeint_Cheng(one_single_delay, initial_condition, t, *(0, 0, 0, w, xs_eff, arguments))[-1] diff = dyn_all - xs_high peaks = [] peaks_index = [] for i in diff.transpose(): peak_index, _ = list(find_peaks(i)) peak = i[peak_index] positive_index = np.where(peak > 0)[0] peak_positive = peak[positive_index] peak_index_positive = peak_index[positive_index] peaks.append(peak_positive) peaks_index.append(peak_index_positive) #plt.loglog(degree, peaks_last, 'o') plt.semilogy(peak_index_positive, peak_positive, '.', color='r') return degree, w, dyn_all, diff, peaks, peaks_index
def evolution_single(network_type, N, beta, betaeffect, seed, arguments, d1, d2, d3, d): """TODO: Docstring for evolution. :arg1: TODO :returns: TODO """ A, A_interaction, index_i, index_j, cum_index = network_generate( network_type, N, beta, betaeffect, seed, d) xs_low, xs_high = stable_state(A, A_interaction, index_i, index_j, cum_index, arguments) x_fix = np.mean(xs_high) initial_condition = np.ones(1) * 5 t = np.arange(0, 500, 0.001) t1 = time.time() degree = np.sum(A > 0, 0) index = np.argmax(degree) w = np.sum(A[index]) initial_condition = np.array([xs_high[index]]) dyn_all = ddeint_Cheng(one_single_delay, initial_condition, t, *(d1, d2, d3, w, x_fix, arguments)) xs = ddeint_Cheng(one_single_delay, initial_condition, t, *(0, 0, 0, w, x_fix, arguments))[-1] B, C, D, E, H, K = arguments P = -(w * x_fix) / (D + E * xs + H * x_fix) + (w * E * xs * x_fix) / ( D + E * xs + H * x_fix)**2 - (1 - xs / K) * (2 * xs / C - 1) Q = xs / K * (xs / C - 1) tau = np.arccos(-P / Q) / Q / np.sin(np.arccos(-P / Q)) t2 = time.time() print(t2 - t1) plt.plot(t, dyn_all, alpha=alpha) #plt.plot(t, dyn_all, alpha = alpha) plt.subplots_adjust(left=0.18, right=0.98, wspace=0.25, hspace=0.25, bottom=0.18, top=0.98) plt.xticks(fontsize=ticksize) plt.yticks(fontsize=ticksize) plt.xlabel('$t$', fontsize=fs) plt.ylabel('$ x $', fontsize=fs) #plt.show() return dyn_all, tau
def save_ygl(network_type, N, d, seed, dynamics, m, space): """TODO: Docstring for error_ygl. :network_type: TODO :N: TODO :d: TODO :seed_list: TODO :dynamics: TODO :returns: TODO """ A_unit, A_interaction, index_i, index_j, cum_index = network_generate( network_type, N, 1, 0, seed, d) """ file_A = '../data/A_matrix/' + network_type + '/' + f'N={N}_d={d}_seed={seed}_A.npz' A_unit = scipy.sparse.load_npz(file_A).toarray() """ des = '../data/' + dynamics + '/' + network_type + '/xs_bifurcation/' beta_cal = betaspace(A_unit, [0])[0] if m == N: des_multi = des + 'xs_multi_beta/' file_multi = des_multi + f'N={N}_d={d}_seed={seed}.csv' data_multi = np.array(pd.read_csv(file_multi, header=None)) weight = data_multi[:, 0] xs = data_multi[:, 1:] save_file = des + 'y_multi_beta/' + f'N={N}_d={d}_seed={seed}.csv' else: des_group = des + f'degree_kmeans_space={space}_beta/' file_group = des_group + f'N={N}_d={d}_number_groups={m}_seed={seed}.csv' data_group = np.array(pd.read_csv(file_group, header=None)) G = nx.from_numpy_array(A_unit) feature = feature_from_network_topology(A_unit, G, space, tradeoff_para=0.5, method='degree') group_index = group_index_from_feature_Kmeans(feature, m) y_group = data_group[:, 1:] xs_group = np.zeros((len(data_group), N)) for i, group_i in enumerate(group_index): xs_group[:, group_i] = y_group[:, i:i + 1] xs = xs_group weight = data_group[:, 0] save_file = des + 'y_group_beta/' + f'N={N}_d={d}_number_groups={m}_seed={seed}.csv' y_gl = betaspace(A_unit, xs)[-1] beta_list = beta_cal * weight data_save = np.vstack((weight, beta_list, y_gl)) df = pd.DataFrame(data_save.transpose()) df.to_csv(save_file, index=None, header=None, mode='w') return None
def save_A(network_type, N, d, seed, save_des): """TODO: Docstring for A_to_save. :network_type: TODO :N: TODO :d: TODO :seed: TODO :returns: TODO """ save_file = save_des + f'N={N}_d={d}_seed={seed}_A.npz' if not os.path.exists(save_file): A, A_interaction, index_i, index_j, cum_index = network_generate(network_type, N, 1, 0, seed, d) scipy.sparse.save_npz(save_file, scipy.sparse.csr_matrix(A) ) return None