def plot_log_degree_distribution(self, degrees): # degrees is an array of degrees or a dict containing multiple degree arrays if len(degrees) == self.numberOfNodes: # i.e. one degree list logDataX, logDataY, _ = logbin(degrees, 1.1, zeros=False) plt.figure() plt.loglog(logDataX, logDataY, c='b', label='Data') #plt.plot(logDataX,np.log(random),c='r',label='Theoretical fit $p_{\infty}(k)$') plt.xlabel('log k') plt.ylabel('p(k)') plt.legend() else: plt.figure() markers = ['.', 'o', '^'] colorvals = np.linspace(0, 0.6, len(degrees)) labels = list(degrees.keys()) for idx, degList in enumerate(degrees.values()): logDataX, logDataY, _ = logbin(degList, 1.1, zeros=False) plt.loglog(logDataX, logDataY, '.', c=str(colorvals[idx]), label='mu: ' + str(labels[idx]), marker=markers[idx]) plt.xlabel('$k$') plt.ylabel('$P(k)$') plt.legend()
def plot_theory(): m = [1,2,3,4,5,6] for m_val in m: y_theory = [] val = pickle.load(open("m=%d,init=20,add=100000,repeat5.txt"%(m_val), "rb")) x, y = lb.logbin(np.array(val), scale=1.25, zeros=False) x_un, y_un = lb.logbin(np.array(val), scale=1, zeros=False) x_theory = np.logspace(min(x),max(x),200) for i in x: y_theory.append(p_k(m_val,i)) D, p_val = stats.ks_2samp(y_theory, y) print(D,p_val) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.set_aspect(aspect=0.2) plt.loglog(x_un, y_un, '.', label='Unbinned data, m = %d' % (m_val)) plt.loglog(x, y, '--', label='Binned data, m = %d' % (m_val)) plt.loglog(x, y_theory, '-', label=r'Theoretical plot'+'\n'+r'$D$ = %.4f, $p-value$ = %.4g'%(D,p_val)) plt.xlabel('Degree k', fontsize=13) plt.ylabel('Probability of degree P(k)', fontsize=13) plt.legend() plt.show()
def Prob_vs_s(): fig = pl.figure() ax = fig.add_subplot(1, 1, 1) for item in range(len(length)): avasize = avalanche_size[item] reqsize = avasize[t_c[item]:] # Log-bin the data bincentre_bin, hist_bin = lb.logbin(reqsize, scale=1.5) print(bincentre_bin) print(hist_bin) ax.loglog(bincentre_bin, hist_bin, '-', label=r"$L = %d$" % (length[item])) x = bincentre_bin[:25] y = hist_bin[:25] para, var = np.polyfit(np.log(np.array(x)) / np.log(10), np.log(y) / np.log(10), 1, cov=True) error = np.sqrt(np.diag(var)) x1 = range(1, 200000, 100) y1 = 10**(para[0] * (np.log(x1) / np.log(10))) ax.loglog(x1, y1, 'k--', label=r'Slop = %.3f $\pm$ %.3f' % (para[0], error[0])) pl.grid(True) pl.legend() pl.xlabel(r"Avalanche size $s$") pl.ylabel(r"Probability of $s$ $P(s; L)$") pl.show()
def plot_figure_binned(): # plot binned figure m = [1,2,3,4,5,6] fig = plt.figure() ax = fig.add_subplot(1, 1, 1) for m_val in m: val = pickle.load(open("m=%d,init=20,add=100000,repeat5.txt"%(m_val), "rb")) print(len(val)) x, y = lb.logbin(np.array(val), scale=1.25, zeros=False) x_un, y_un = lb.logbin(np.array(val), scale=1, zeros=False) plt.loglog(x, y,'-', label='m = %d'%(m_val)) x1 = np.linspace(1,max(x),500) y1 = 1/x1**3 plt.loglog(x1, y1, '--',label=r'$p(k)\propto k^{-3}$') plt.legend() plt.xlabel('Degree k', fontsize=13) plt.ylabel('Probability of degree P(k)', fontsize=13) plt.show()
def plot_figure_unbinned(): # plot unbinned figure m = [1, 2, 3, 4, 5, 6] fig = plt.figure() ax = fig.add_subplot(1, 1, 1) for m_val in m: val = pickle.load(open("m=%d,init=20,add=100000,repeat5.txt" % (m_val), "rb")) x_un, y_un = lb.logbin(np.array(val), scale=1, zeros=False) plt.loglog(x_un, y_un, '.', label='m = %d' % (m_val)) plt.legend() plt.xlabel('Degree k', fontsize=13) plt.ylabel('Probability of degree P(k)', fontsize=13) plt.show()
def tau_s(): avasize = avalanche_size[-1] reqsize = avasize[t_c[-1]:] bincentre_bin, hist_bin = lb.logbin(reqsize, scale=1.5) x = bincentre_bin[:25] y = hist_bin[:25] para, var = np.polyfit(np.log(np.array(x)) / np.log(10), np.log(y) / np.log(10), 1, cov=True) error = np.sqrt(np.diag(var)) return -para[0], error[0]
def ranetsimulator(m, N, smooth=100, logbinning=False, scale=1.3): b = ranet(m) numbers = [] for j in tqdm(range(smooth)): for i in range(N): b.add_node() n = b.probabilitydist() for i in n: numbers.append(i) numbers.sort() if logbinning == True: x, y = logbin.logbin(numbers, scale=scale) else: prob = collections.Counter(numbers) x, y = zip(*prob.items()) y = y / np.sum(y) return x, y
def single_plot(): for i in [2, 3, 4, 5, 6]: if i != 6: reqsize = avasize[t_c[-1]:t_c[-1] + 10**i] else: reqsize = avasize[t_c[-1]:] bins = np.arange(min(reqsize), max(reqsize), 1) bincentre = bins[:-1] hist, bin_edges = np.histogram( reqsize, bins=bins, density=True) # density = True returns probability density # Log-bin the data bincentre_bin, hist_bin = lb.logbin(reqsize, scale=1.5) fig = pl.figure() ax = fig.add_subplot(1, 1, 1) if i != 6: ax.loglog(bincentre, hist, 'o', label=r"Unbinned, $N = 10^%d$" % (i)) ax.loglog(bincentre_bin, hist_bin, 'r-', label=r"Binned, $N = 10^%d$" % (i)) else: ax.loglog(bincentre, hist, 'o', label=r"Unbinned, $N = %.1g$" % (1e6 - t_c[-1])) ax.loglog(bincentre_bin, hist_bin, 'r-', label=r"Binned, $N = %.1g$" % (1e6 - t_c[-1])) pl.legend() pl.grid() pl.xlim(1, 10**6) pl.ylim(10**-13, 1) pl.xlabel('System size L') pl.ylabel(r'$\sigma_h$') pl.show() # single_plot()
def d_value(): s_max = [] for i in range( len(length)): # neglect largest L since it is used for comparison avasize = avalanche_size[i] reqsize = avasize[t_c[i]:] bincentre_bin, hist_bin = lb.logbin(reqsize, scale=1.5) #scaling y axis hist_bin = np.array(hist_bin) * np.array(bincentre_bin)**tau - b index, value = max(enumerate(hist_bin), key=operator.itemgetter(1)) s_max.append(bincentre_bin[index]) para1, var1 = np.polyfit(np.log(np.array(length)) / np.log(10), np.log(s_max) / np.log(10), 1, cov=True) error = np.sqrt(np.diag(var1)) return para1, error
def plot_k6(): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) for i in range(4): l = [100,1000,10000,100000] k = pickle.load(open("m=6,init=16,add=%d,k8,Ldiff.txt" %(l[i]), "rb"))[0] x, y = lb.logbin(np.array(k), scale=1.19, zeros=False) yl = (2*6*7)/(np.array(x)*(np.array(x)+1)*(np.array(x)+2)) y_new = np.array(y)/yl x_new = np.array(x)/k_mean_list[i] ax.plot(x,y,'o',label='N = %d'%(l[i])) ax.plot(x, y, '-', label='N = %d' % (l[i])) # ax.plot(x_new,y_new,label='N = %d'%(l[i])) ax.set_xlabel(r'Degree $k$',fontsize=13) ax.set_ylabel(r'Probability of degree $p(k)$',fontsize=13 ) ax.set_xscale('log') ax.set_yscale('log') plt.legend() plt.show()
def Plot_collapse_data(): fig = pl.figure() ax = fig.add_subplot(1, 1, 1) for item in range(len(length)): avasize = avalanche_size[item] reqsize = avasize[t_c[item]:] # Log-bin the data bincentre_bin, hist_bin = lb.logbin(reqsize, scale=1.5) hist_bin = np.array(hist_bin) * np.array(bincentre_bin)**tau bincentre_bin = bincentre_bin / (np.array(length)[item]**D) ax.loglog(bincentre_bin, hist_bin, '-', label=r"$L = %d$" % (length[item])) pl.grid(True) pl.legend() pl.xlabel(r"Avalanche size $s/L^D$") pl.ylabel(r"Probability $s^\tau P(s; L)$") pl.show()
def avalanche(L, N, tc, comparison=False, zeros=False): """ Performs the data-binning on the steady state data that has been pre calculated. Input: runs = No. realisations to average over N = iterations, L = system size, comparison = compares data-binning, zeros = includes s = 0 if True Returns: Data-binned avalanche size s and frequency (P^tilda) """ model = om.OsloModel(L, N).load() ind = np.where(model.tm == tc)[0][0] model.s_arr = np.array(model.s_arr[ind:], dtype=int) s, freq = logbin.logbin(model.s_arr, scale=1.3, zeros=zeros) if comparison == True: fig, ax = plt.subplots(figsize=(8, 4.5)) maxs = int(max(model.s_arr)) probs = [P_s(s, model.s_arr, N - tc) for s in range(maxs + 1)] ax.plot(np.arange(maxs + 1), probs, 'o', markersize=2, label=(r'$Raw \, P_{N}(s;L)$')) ax.plot(s, freq, '-o', markersize=2.5, label=(r'$Data-binned \, \tilde{P}_{N}(s^{j};L)$')) ax.set_xlabel('s') ax.set_ylabel(r'${P}(s;512)$') ax.set_xscale('log') ax.set_yscale('log') ax.legend() fig.tight_layout() return s, freq
# -*- coding: utf-8 -*- """ Created on Wed Feb 12 11:06:56 2020 @author: Ching Hoe Lee """ from logbin230119 import logbin import scipy as sp import numpy as np import matplotlib.pyplot as plt a_size_list = np.loadtxt('avalanche_size.txt', delimiter=',') L = np.array([4, 8, 16, 32, 64, 128, 256]) i = 0 while i <= 6: x_3a, y_3a = logbin(np.asarray(a_size_list[i], dtype=np.int64), scale=1.5) y = y_3a * x_3a**(1.55) x = x_3a / L[i]**(2.25) plt.plot(x, y, label=f'L={L[i]}') plt.loglog() i += 1 plt.xlabel('s/L^(D)') plt.ylabel('Probability') plt.legend() plt.savefig('task3b.png') plt.show()
""" from logbin230119 import logbin import scipy as sp import numpy as np import matplotlib.pyplot as plt import complexity as com L=np.array([4,8,16,32,64,128,256]) attractor_t=np.array([40,70,300,1000,4000,15000,60000]) num=10000 a=0 a_size_list=[] list_x_3a=[] list_y_3a=[] while a <=6: model_3a=com.oslo(L[a]) model_3a.iteration(attractor_t[a]) a_size=model_3a.avalanche_size(num) a_size_list.append(a_size) x_3a,y_3a=logbin(a_size, scale=1.5) list_x_3a.append(x_3a) list_x_3a.append(y_3a) plt.plot(x_3a,y_3a,label=f'L={L[a]}') a+=1 plt.loglog() plt.xlabel('avalanche size') plt.ylabel('probability') plt.legend() plt.savefig('task3a.png') plt.show() np.savetxt('avalanche_size.txt',a_size_list,delimiter=',')
# -*- coding: utf-8 -*- """ Created on Tue Feb 11 16:20:27 2020 @author: Ching Hoe Lee """ from logbin230119 import logbin import scipy as sp import numpy as np import matplotlib.pyplot as plt a_size_list = np.loadtxt('avalanche_size.txt', delimiter=',') L = np.array([4, 8, 16, 32, 64, 128, 256]) a = 0 for i in a_size_list: x_3a, y_3a = logbin(np.asarray(i, dtype=np.int64), scale=1.5) plt.plot(x_3a, y_3a, label=f'L={L[a]}') plt.loglog() a += 1 plt.xlabel('avalanche size') plt.ylabel('probability') plt.legend() plt.show()
repeats = 10 m_starting = 5 m_add = 5 times = [1, 10, 100, 1000, 10000, 100000] degrees_all = [] k_maxes_random = [] for i in range(len(times)): print("Calulating time t = ", times[i]) degrees_total = [] k_maxes_random.append([]) for N in range(repeats): print("--Repeat ", N) Ba_1 = Barabasi_Albert(time_limit=times[i], m=m_add, m_start=m_starting) df = Ba_1.drive_random() degrees_total.extend(df.Degrees.values) k_maxes_random[i].append(max(df.Degrees.values)) x, y = logbin(degrees_total, scale=1.2) plt.title("Degree Distribution, (m = {}, m0 = {})".format( m_add, m_starting)) plt.xlabel("Number of Degrees (k)") plt.ylabel("Probability of degree $p(k)$") plt.loglog(x, y, label="t = {}".format(times[i])) degrees_all.append(degrees_total) plt.legend() # fit_log(x,y,label = r"$p_{\infty}(k)\propto k^{-3}$") # expected_values = fit_master_EQ(m=2,k=x) # plt.legend()