27
Content-Disposition: inline; filename="
1ff3
Last-Modified: Tue, 04 Aug 2026 16:40:10 GMT
Expires: Fri, 01 Aug 2036 16:40:10 GMT
ETag: "7482877c5518028b2a6d04ad934ec2994f15c882"

import sys
import math 
import numpy as np
from scipy.sparse import csr_matrix, eye
from scipy.linalg import eigh, eig
import copy
from scipy.cluster.hierarchy import linkage, dendrogram

has_matplotlib = False

try:
    import matplotlib
    has_matplotlib = True

except ImportError:
    has_matplotlib = False


class XLogx_fit:
    def __init__(self, degree, npoints= 100, xmax=1):
        if xmax > 1:
            xmax = 1
        self.degree = degree
        x = np.linspace(0, xmax, npoints)
        y = [i * math.log(i) for i in x[1:]]
        y.insert(0, 0)
        self.fit = np.polyfit(x, y, degree)

    def __getitem__ (self, index):
        if index <= self.degree:
            return self.fit[index]
        else:
            print "Error!!! Index %d is larger than the degree of the fitting polynomial (%d)" \
                % (index, degree)
            sys.exit(-1)


class layer:
    def __init__ (self, layerfile= None, matrix=None):
        self.N = 0
        self.num_layer = -1
        self.fname = layerfile
        self.adj_matr = None
        self.laplacian = None
        self.resc_laplacian = None
        self.entropy = None
        self.entropy_approx = None
        self._ii = []
        self._jj = []
        self._ww = []
        self._matrix_called = False
        if layerfile != None:
            try:
                min_N = 10e10
                with open(layerfile, "r") as lines:
                    for l in lines:
                        if l[0] == '#':
                            continue
                        elems = l.strip(" \n").split(" ")
                        s = int(elems[0])
                        d = int(elems[1])
                        self._ii.append(s)
                        self._jj.append(d)
                        if s > self.N:
                            self.N = s
                        if d > self.N:
                            self.N = d
                        if s < min_N:
                            min_N = s
                        if  d < min_N:
                            min_N = d
                        if len(elems) >2 : ## A weight is specified 
                            val = [float(x) if "e" in x or "." in x else int(x) for x in [elems[2]]][0]
                            self._ww.append(float(val))
                        else:
                            self._ww.append(int(1))
                    
            except (IOError):
                print "Unable to find/open file %s -- Exiting!!!" % layerfile
                exit(-2)
        elif matrix != None:
            self.adj_matr = copy.copy(matrix)
            self.N, _x = matrix.shape 
            K = np.multiply(self.adj_matr.sum(0), np.ones((self.N,self.N)))
            D = np.diag(np.diag(K))
            self.laplacian = csr_matrix(D - self.adj_matr)
            K = self.laplacian.diagonal().sum()
            self.resc_laplacian = csr_matrix(self.laplacian / K)
            self._matrix_called = True
        else:
            print "The given matrix is BLANK"
    def make_matrices(self, N):
        self.N = N 
        self.adj_matr = csr_matrix((self._ww, (self._ii, self._jj)), shape=(self.N, self.N))
        self.adj_matr = self.adj_matr + self.adj_matr.transpose()
        K = np.multiply(self.adj_matr.sum(0), np.ones((self.N,self.N)))
        D = np.diag(np.diag(K))
        self.laplacian = csr_matrix(D - self.adj_matr)
        K = self.laplacian.diagonal().sum()
        self.resc_laplacian = csr_matrix(self.laplacian / K)
        self._matrix_called = True
    
    def dump_info(self):
        N, M = self.adj_matr.shape
        K = self.adj_matr.nnz
        sys.stderr.write("Layer File: %s\nNodes: %d Edges: %d\nEntropy: %g Approx. Entropy: %g\n" % \
                             (self.fname, N, K, self.entropy, self.entropy_approx) )

    def compute_VN_entropy(self):
        eigvals = eigh(self.resc_laplacian.todense())

        self.entropy = 0
        for l_i in eigvals[0]:
            if (l_i > 10e-20):
                self.entropy -= l_i * math.log (l_i)


    def compute_VN_entropy_approx(self, poly):
        p = poly.degree
        h = - poly[p] * self.N
        M = csr_matrix(np.eye(self.N))
        for i in range(p-1, -1, -1):
            M = M *  self.resc_laplacian
            h += - poly[i] * sum(M.diagonal())
        self.entropy_approx = h

    def aggregate(self, other_layer):
        if self.adj_matr != None:
            self.adj_matr = self.adj_matr + other_layer.adj_matr
        else:
            self.adj_matr = copy.copy(other_layer.adj_matr)
        K = np.multiply(self.adj_matr.sum(0), np.ones((self.N,self.N)))
        D = np.diag(np.diag(K))
        self.laplacian = csr_matrix(D - self.adj_matr)
        K = self.laplacian.diagonal().sum()
        self.resc_laplacian = csr_matrix(self.laplacian / K)
        self._matrix_called = True

        

class multiplex_red:
    
    def __init__ (self, multiplexfile, directed = None, fit_degree=10, verbose=False):
        self.layers = []
        self.N = 0
        self.M = 0
        self.entropy = 0
        self.entropy_approx = 0
        self.JSD = None
        self.JSD_approx = None
        self.Z = None
        self.Z_approx = None
        self.aggr = None
        self.q_vals = None
        self.q_vals_approx = None
        self.fit_degree = fit_degree
        self.poly = XLogx_fit(self.fit_degree)
        self.verb = verbose
        self.cuts = None
        self.cuts_approx = None
        try:
            with open(multiplexfile, "r") as lines:
                for l in lines:
                    if (self.verb):
                        sys.stderr.write("Loading layer %d from file %s" % (len(self.layers), l))
                    A = layer(l.strip(" \n"))
                    if A.N > self.N:
                        self.N = A.N+1
                    self.layers.append(A)
                    n = 0
                    for l in self.layers:
                        l.make_matrices(self.N)
                        l.num_layer = n
                        n += 1
                    self.M = len(self.layers)
        except ( IOError):
            print "Unable to find/open file %s -- Exiting!!!" % layer_file
            exit(-2)

    def dump_info(self):
        i = 0
        for l in self.layers:
            sys.stderr.write("--------\nLayer: %d\n" % i)
            l.dump_info()
            i += 1


    def compute_aggregated(self):
        self.aggr = copy.copy(self.layers[0])
        self.aggr.entropy = 0
        self.aggr.entropy_approx = 0
        for l in self.layers[1:]:
            self.aggr.aggregate(l)

    def compute_layer_entropies(self):
        for l in self.layers:
            l.compute_VN_entropy()

    def compute_layer_entropies_approx(self):
        for l in self.layers:
            l.compute_VN_entropy_approx(self.poly)


    def compute_multiplex_entropy(self, force_compute=False):
        ### The entropy of a multiplex is defined as the sum of the entropies of its layers
        for l in self.layers:
            if l.entropy == None:
                l.compute_VN_entropy()
                self.entropy += l.entropy

    def compute_multiplex_entropy_approx(self, force_compute=False):
        ### The entropy of a multiplex is defined as the sum of the entropies of its layers
        for l in self.layers:
            if l.entropy_approx == None:
                l.compute_VN_entropy_approx(self.poly)
            self.entropy_approx += l.entropy_approx

    def compute_JSD_matrix(self):
        if (self.verb):
            sys.stderr.write("Computing JSD matrix\n")
        self.JSD = np.zeros((self.M, self.M))
        for i in range(len(self.layers)):
            for j in range(i+1, len(self.layers)):
                li = self.layers[i]
                lj = self.layers[j]
                if not li.entropy:
                    li.compute_VN_entropy()
                if not lj.entropy:
                    lj.compute_VN_entropy()
                # m_sigma = (li.resc_laplacian + lj.resc_laplacian)/2.0
   
HTTP/1.0 500 Internal Server Error
Date: Tue, 04 Aug 2026 16:40:11 GMT
Server: OpenBSD httpd
Connection: close
Content-Type: text/html
Content-Length: 518

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>500 Internal Server Error</title>
<style type="text/css"><!--
body { background-color: white; color: black; font-family: 'Comic Sans MS', 'Chalkboard SE', 'Comic Neue', sans-serif; }
hr { border: 0; border-bottom: 1px dashed; }
@media (prefers-color-scheme: dark) {
body { background-color: #1E1F21; color: #EEEFF1; }
a { color: #BAD7FF; }
}
--></style>
</head>
<body>
<h1>500 Internal Server Error</h1>
<hr>
<address>OpenBSD httpd</address>
</body>
</html>
