Buncha imports


In [1]:
import numpy as np
import matplotlib.pylab as plt 
%matplotlib inline
import networkx as nx
import SpringRank_tools as sr
import tools as tl
from scipy.optimize import brentq

Some helpers


In [95]:
def eqs39(beta,s,A):
    N = np.shape(A)[0]
    x = 0
    for i in range(N):
        for j in range(N):
            if A[i,j] == 0:
                continue
            else:
                x += (s[i]-s[j]) * ( A[i,j] - (A[i,j]+A[j,i]) / (1+np.exp(-2*beta*(s[i]-s[j]))) )
    return x
def predict(si,sj,beta):
    return 1/(1+np.exp(-2*beta*(si-sj)))

Test Script


In [96]:
# where's the data?
fname = 'test.txt'
# load in the data. NOTE the delimiter here is set to tab but you can set to "," or " "
comparisons = np.loadtxt(fname,delimiter="\t",dtype=int)

# If you are indexing from 1, we're going to shift to 0...
if np.min(comparisons)==1:
    comparisons += -1
# Turn it into a matrix
N = int(np.max(comparisons))
A = np.zeros([N+1,N+1])
for comp in comparisons:
    i = comp[0]
    j = comp[1]
    if len(comp)==3:
        if comp[2] > 0:
            A[i,j] += comp[2]
        else:
            A[i,j] += 1            
    if len(comp)==2:
        A[i,j] += 1
A = np.matrix(A)

In [97]:
# compute the ranks
rank=sr.SpringRank(A,alpha=0,l0=1.,l1=1.)
# cleanup so that min rank is 0
rank=tl.shift_rank(rank)
# compute the inverse temperature tha best describes the system
betahat = brentq(eqs39,1e-3,100,args=(rank,A))


Using faster computation: fixing a rank degree of freedom
Switched to scipy.sparse.linalg.bicgstab(A,B)[0]

In [98]:
# what are the ranks?
print(rank)


[1.25606437 2.29867949 0.5199731  1.65396884 1.82667684 1.29327876
 0.89261694 1.11223627 0.97540207 1.36709949 1.46967984 1.90615726
 0.94777476 0.96012817 0.83033083 1.93896054 1.67724053 1.32137804
 0.32855329 1.77449783 0.72291858 0.29992003 0.49854519 1.11458956
 1.67541454 1.69738929 0.48976898 1.76723697 0.92837535 0.52323965
 0.36226793 1.49753731 1.15832274 0.98410684 0.99882789 1.39938179
 1.76909026 1.08545463 2.0082415  0.84352424 2.28764737 0.9746931
 2.12850186 1.04320278 1.36953237 1.28766285 0.69539578 1.21365733
 1.34632741 1.54158465 0.6413418  2.45977367 1.69266017 0.98176928
 1.2965247  2.09246831 1.20980028 1.45323735 0.53307566 0.87846095
 0.25643821 1.15158167 0.         1.39262563 0.91311926 1.15743811
 0.7263372  1.48418689 1.60037365 1.60494897 1.02844263 0.83085723
 0.09100132 1.24959698 1.19998449 1.19831112 0.84766629 1.13151429
 1.34256662 2.15803065 0.4252917  0.57033886 0.97167454 0.96758249
 1.7946492  0.13769584 1.05641465 0.22952267 1.19998449 1.57436779
 1.03864943 1.45962459 1.16714823 1.233017   1.80059075 1.09779289
 3.4598617  1.17649719 0.8307528  1.13980268]

In [100]:
# try a prediction
# predict(rank_i, rank_j, betahat)
predict(rank[0],rank[41],betahat)


Out[100]:
0.7006371032860206

In [ ]: