打印計(jì)數(shù)器
def flushPrint(variable):
sys.stdout.write('\r')
sys.stdout.write('%s' % variable)
sys.stdout.flush()
單變量最小二乘(OLS)回歸擬合
def OLSRegressFit(x,y):
xx = sm.add_constant(x, prepend=True)
res = sm.OLS(y,xx).fit()
constant, beta = res.params
r2 = res.rsquared
return [constant, beta, r2]
雙對(duì)數(shù)坐標(biāo)系下線(xiàn)性回歸擬合畫(huà)圖(冪律函數(shù))
def alloPlot(x,y,col,lab):
lx = np.log(x+1)
ly = np.log(y+1)
xx = sm.add_constant(lx, prepend=True)
res = sm.OLS(ly,xx).fit()
constant, beta = res.params
plt.plot(x,y, "o",color=col)
plt.plot(x,np.exp(constant)*x**beta,color=col,label=lab+' '+str(np.round(beta,2)))
縱軸對(duì)數(shù)坐標(biāo)下線(xiàn)性回歸擬合(指數(shù)函數(shù))
def semilogPlot(x,y,col,lab):
ly = np.log(y)
xx = sm.add_constant(x, prepend=True)
res = sm.OLS(ly,xx).fit()
constant, beta = res.params
plt.plot(x,y, "o",color=col)
plt.plot(x,np.exp(constant+x*beta),color=col,label=lab+' '+str(np.round(beta,2)))
計(jì)算一個(gè)平衡過(guò)的流網(wǎng)絡(luò)從源到各節(jié)點(diǎn)的流距離
def flowDistanceFromSource(G): #input a balanced nx graph
R = G.reverse()
mapping = {'source':'sink','sink':'source'}
H = nx.relabel_nodes(R,mapping)
#---------initialize flow distance dict------
L = dict((i,1) for i in G.nodes())
#---------prepare weighted out-degree dict------
T = G.out_degree(weight='weight')
#---------iterate until converge------------
ls = np.array(L.values())
delta = len(L)*0.001 + 1
k=0
while delta > len(L)*0.001:
k+=1
if k>20:
break
for i in L:
l=1
for m,n in H.edges(i):
l+=L[n]*H[m][n].values()[0]/float(T[m])
L[i]=l
delta = sum(np.abs(np.array(L.values()) - ls))
ls = np.array(L.values())
#---------clean the result-------
del L['sink']
for i in L:
L[i]-=1
L['sink'] = L.pop('source')
L['source'] = 0
return L
計(jì)算一個(gè)平衡過(guò)的流網(wǎng)絡(luò)從各節(jié)點(diǎn)到匯的流距離
def flowDistanceToSink(G): #input a balanced nx graph
#---------initialize flow distance dict------
L = dict((i,1) for i in G.nodes())
#---------prepare weighted out-degree dict------
T = G.out_degree(weight='weight')
#---------iterate until converge------------
ls = np.array(L.values())
delta = len(L)*0.001 + 1
k=0
while delta > len(L)*0.001:
k+=1
if k>20:
break
for i in L:
l=1
for m,n in G.edges(i):
l+=L[n]*G[m][n].values()[0]/float(T[m])
L[i]=l
delta = sum(np.abs(np.array(L.values()) - ls))
ls = np.array(L.values())
for i in L:
L[i]-=1
return L