def plotjson(fn):
    """
    plotjson: make plots from json output of fiedler.py

    fn: the filename of the json file
    """

    fo=open(fn)
    data=json.load(fo)
    fo.close()
    if "adj" in data:
        (A,adj,Npts) = fiedler.adj_mat(data["adj"])


        #A = (A.T - A)/2

        A=A.tocoo()
        pos=A.data!=0
        skew = numpy.column_stack((A.row[pos],A.col[pos],A.data[pos])).tolist()
        
      
        # method from ranking driver.py
    
        asc = abstract_simplicial_complex([numpy.column_stack((A.row[pos],A.col[pos])).tolist()])
        B1 = asc.chain_complex()[1] # boundary matrix
        rank = lsqr(B1.T, A.data[pos])[0] # solve least squares problem
        # sc = simplicial_complex(([[el] for el in range(0,A.shape[0])],numpy.column_stack((A.row[pos],A.col[pos])).tolist()))
        # omega = sc.get_cochain(1)
        # omega.v[:] = A.data[pos]
        # p = omega.k
        # alpha = sc.get_cochain(p - 1)
        #
        # alpha.v = rank
        # v = A.data[pos]-d(alpha).v
        #
        # cyclic_adj_list=numpy.column_stack((A.row[pos],A.col[pos],v)).tolist()
        # div_adj_list=numpy.column_stack((A.row[pos],A.col[pos],d(alpha).v)).tolist()

        data["hodge"]=list(rank)
        data["hodgerank"]=list(numpy.argsort(numpy.argsort(rank)))
        print "Adding hodge results to %s"%(os.path.abspath(fn))
        fo = open(fn,"w")
        json.dump(data,fo, indent=2)
        fo.close()
示例#2
0
文件: ratings.py 项目: ilvrvltn/ncaa
    def rate(self, mutate=True):
        '''Least squares ranking on graphs. This method is adapted from the
        example given by Hirani et al. Set mutate to False to prevent the
        calculation from being saved on each Squad instance. No commits
        are performed.
        See also
            * A. N. Hirani, K. Kalyanaraman, S. Watts
            arXiv:1011.1716v1 [cs.NA] on http://arxiv.org/abs/1011.1716'''
        data = self.distances
        
        # Find edges
        edges = data[:, :2]

        # Create abstract simplicial complex from edges
        asc = abstract_simplicial_complex([edges])

        # Pairwise comparisons
        omega = data[:, -1]

        # Find boundary matrix of abs. simplicial complex
        B = asc.chain_complex()[1]

        # Solve least squares problem
        alpha = lsqr(B.T, omega)[0]

        # Normalize minimum
        alpha = alpha - alpha.min()

        # Convert enumerated IDs back into SIDs
        ret = {}
        for eid, aval in enumerate(alpha):
            ret[self._squadmap['eid2sid'][eid]] = aval
        
        if mutate:
            for squad in self.squads:
                squad.lsalpha = ret[squad.id]

        return ret
示例#3
0
Least Squares Ranking on Graphs, Hodge Laplacians, Time Optimality,
and Iterative Methods
A. N. Hirani, K. Kalyanaraman, S. Watts
See arXiv:1011.1716v1 [cs.NA] on http://arxiv.org/abs/1011.1716

"""
from numpy import loadtxt
from pydec import abstract_simplicial_complex
from scipy.sparse.linalg import lsqr

# Load graph and edge values
data = loadtxt('data.txt').astype(int)
edges = data[:,:2]

# Create abstract simplicial complex from edges
asc = abstract_simplicial_complex([edges])

omega = data[:,-1] # pairwise comparisons
B1 = asc.chain_complex()[1] # boundary matrix
alpha = lsqr(B1.T, omega)[0] # solve least squares problem

# Set the minimum to 0
alpha = alpha - alpha.min()

print alpha





示例#4
0
文件: driver.py 项目: msebaa/pydec
Least Squares Ranking on Graphs, Hodge Laplacians, Time Optimality,
and Iterative Methods
A. N. Hirani, K. Kalyanaraman, S. Watts
See arXiv:1011.1716v1 [cs.NA] on http://arxiv.org/abs/1011.1716

"""
from numpy import loadtxt
from pydec import abstract_simplicial_complex
from scipy.sparse.linalg import lsqr

# Load graph and edge values
data = loadtxt('data.txt').astype(int)
edges = data[:,:2]

# Create abstract simplicial complex from edges
asc = abstract_simplicial_complex([edges])

omega = data[:,-1] # pairwise comparisons
B1 = asc.chain_complex()[1] # boundary matrix
alpha = lsqr(B1.T, omega)[0] # solve least squares problem

# Set the minimum to 0
alpha = alpha - alpha.min()

print(alpha)





def plotjson(fn):
    """
    plotjson: make plots from json output of fiedler.py

    fn: the filename of the json file
    """

    fo=open(fn)
    data=json.load(fo)
    fo.close()
    if "adj" in data:
        (A,adj,Npts) = fiedler.adj_mat(data["adj"])
        #scew symetricise

        A = (A.T - A)/2

        A=A.tocoo()
        pos=A.data>0
        skew = numpy.column_stack((A.row[pos],A.col[pos],A.data[pos])).tolist()
        
        # #method from hodge decomposition driver.py
        # sc = simplicial_complex(([[el] for el in range(0,A.shape[0])],numpy.column_stack((A.row[pos],A.col[pos])).tolist()))
        # omega = sc.get_cochain(1)
        # omega.v[:] = A.data[pos]
        # p = omega.k
        # alpha = sc.get_cochain(p - 1)
        # #beta  = sc.get_cochain(p + 1)    

        # # Solve for alpha
        # A2 = delta(d(sc.get_cochain_basis(p - 1))).v
        # b = delta(omega).v
        # rank=cg( A2, b, tol=1e-8 )[0]

        # method from ranking driver.py

        asc = abstract_simplicial_complex([numpy.column_stack((A.row[pos],A.col[pos])).tolist()])
        B1 = asc.chain_complex()[1] # boundary matrix
        rank = lsqr(B1.T, A.data[pos])[0] # solve least squares problem
        
        sc = simplicial_complex(([[el] for el in range(0,A.shape[0])],numpy.column_stack((A.row[pos],A.col[pos])).tolist()))
        omega = sc.get_cochain(1)
        omega.v[:] = A.data[pos]
        p = omega.k
        alpha = sc.get_cochain(p - 1)
        
        alpha.v = rank
        v = A.data[pos]-d(alpha).v
        
        cyclic_adj_list=numpy.column_stack((A.row[pos],A.col[pos],v)).tolist()
        div_adj_list=numpy.column_stack((A.row[pos],A.col[pos],d(alpha).v)).tolist()

        data["hodge"]=list(rank)
        data["hodgerank"]=list(numpy.argsort(numpy.argsort(rank)))
        fo = open(fn,"w")
        json.dump(data,fo, indent=2)
        fo.close()

        fn=fn+".abstract"
        #fiedler.doPlots(numpy.array(data["f1"]),numpy.array(data["f2"]),numpy.array(data["d"]),cyclic_adj_list,fn+".decomp.cyclic.",widths=[6],vsdeg=False,nByi=data["nByi"],directed=True)
        #fiedler.doPlots(numpy.array(data["f1"]),numpy.array(data["f2"]),numpy.array(data["d"]),div_adj_list,fn+".decomp.acyclic.",widths=[6],vsdeg=False,nByi=data["nByi"],directed=True)
        #fiedler.doPlots(numpy.array(data["f1"]),numpy.array(data["f2"]),numpy.array(data["d"]),data["adj"],fn+".decomp.acyclic.over.all.",widths=[6],vsdeg=False,nByi=data["nByi"],adj_list2=div_adj_list,directed=True)
        #fiedler.doPlots(numpy.array(data["f1"]),-1*numpy.array(rank),numpy.array(data["d"]),cyclic_adj_list,fn+".decomp.harmonic.v.grad.",widths=[6],heights=[2],vsdeg=False,nByi=data["nByi"],directed=True)
        #fiedler.doPlots(numpy.array(data["f1"]),-1*numpy.array(rank),numpy.array(data["d"]),skew,fn+".decomp.skew.v.grad.",widths=[6],heights=[2],vsdeg=False,nByi=data["nByi"],directed=True)
        #fiedler.doPlots(numpy.array(data["f1"]),-1*numpy.array(rank),numpy.array(data["d"]),data["adj"],fn+".decomp.acyclic.over.all.v.grad.",widths=[6],heights=[2],vsdeg=False,nByi=data["nByi"],adj_list2=div_adj_list,directed=True)
        fiedler.doPlots(numpy.array(data["f1"]),-1*numpy.array(rank),numpy.array(data["d"]),data["adj"],fn+".all.v.grad.",widths=[24],heights=[6],vsdeg=False,nByi=data["nByi"],directed=False)
    col_span = list(remainder(
        range(block_location[1], (block_location[1] + block_size[1])),
        matrix_size))
    for r, c in product(row_span, col_span):
        M[r, c] = 1
Mcsr = csr_matrix(M); Mcsc = csc_matrix(M)

# The complex formation is ugly for readability but IMHO elegant for
# getting the job done !
row_complex = map(list, list(set(filter(None, [tuple(
    Mcsr.indices[Mcsr.indptr[i]:Mcsr.indptr[i + 1]]
    ) for i in range(len(Mcsr.indptr) - 1)]))))
## row_complex += [[vertex] for vertex in list(set(list(chain(*row_complex))))]
row_vertex_set = [vertex for vertex in list(set(list(chain(*row_complex))))]
row_complex += [[v] for v in row_vertex_set]
row_complex = abstract_simplicial_complex(row_complex)

col_complex = map(list, list(set(filter(None, [tuple(
    Mcsc.indices[Mcsc.indptr[i]:Mcsc.indptr[i + 1]]
    ) for i in range(len(Mcsc.indptr) - 1)]))))
## col_complex += [[vertex] for vertex in list(set(list(chain(*col_complex))))]
col_vertex_set = [vertex for vertex in list(set(list(chain(*col_complex))))]
col_complex += [[v] for v in col_vertex_set]
col_complex = abstract_simplicial_complex(col_complex)

evals_row_complex = []; evals_col_complex = []
for p in range(row_complex.complex_dimension()):
    B_p = row_complex.chain_complex()[p]
    B_pplus1 = row_complex.chain_complex()[p + 1]
    laplacian_p = (B_p.T * B_p + B_pplus1 * B_pplus1.T)
    evals_row_complex.append(eigvalsh(laplacian_p.todense()))
# Define the tolerance for determining when an eigenvale is "zero enough."
tol = 1e-7

# Now that we have the master data matrix assembled, we filter it, and at 
# each level construct the user- and movie-complex, upon which we compute
# dim(ker(Laplacian_k)) for k ranging from 0 through top dimension.
print "Filtering data and computing Betti numbers..."
M_0 = 1*(M > 0) # used to filter out the non-rated films
for stars in [1,2,3,4,5]:
    print stars

    # Filter M and create filtered complexes.
    M_filt = 1*(M <= stars) * M_0
    user_tuple, movie_tuple = get_complexes(M_filt)
    user_complex = abstract_simplicial_complex(user_tuple)
    movie_complex = abstract_simplicial_complex(movie_tuple)

    # Perform calculations on user complex Lalacians.
    for k in range(user_complex.complex_dimension()):
        b_low = user_complex.chain_complex()[k]
        b_high = user_complex.chain_complex()[k+1]
        Laplacian_k = (b_low.T * b_low + b_high * b_high.T).todense()
        betti_k = get_dim_ker(Laplacian_k, tol)
        user_results[k, stars-1] = betti_k
    k = user_complex.complex_dimension()
    b_low = user_complex.chain_complex()[k]
    Laplacian_k = (b_low.T * b_low).todense()
    betti_k = get_dim_ker(Laplacian_k, tol)
    user_results[k, stars-1] = betti_k