Ejemplo n.º 1
0
def get_base_modularity_matrix(network):
    '''
    Obtain the modularity matrix for the whole network.  Assumes any edge weights
    use the key 'weight' in the edge attribute.

    Parameters
    ----------
    network : nx.Graph or nx.DiGraph
        The network of interest

    Returns
    -------
    np.matrix
        The modularity matrix for `network`

    Raises
    ------
    TypeError
        When the input `network` does not fit either nx.Graph or nx.DiGraph
    '''

    if type(network) == nx.Graph:
        if nx.is_weighted(network):
            return sparse.csc_matrix(nx.modularity_matrix(network,weight='weight'))
        return sparse.csc_matrix(nx.modularity_matrix(network))
    elif type(network) == nx.DiGraph:
        if nx.is_weighted(network):
            return sparse.csc_matrix(nx.directed_modularity_matrix(network,weight='weight'))
        return sparse.csc_matrix(nx.directed_modularity_matrix(network))
    else:
        raise TypeError('Graph type not supported. Use either nx.Graph or nx.Digraph')
Ejemplo n.º 2
0
    def test_modularity(self):
        "Modularity matrix"
        B = np.array([[-1.125, 0.25, 0.25, 0.625, 0.],
                      [0.25, -0.5, 0.5, -0.25, 0.],
                      [0.25, 0.5, -0.5, -0.25, 0.],
                      [0.625, -0.25, -0.25, -0.125, 0.], [0., 0., 0., 0., 0.]])

        permutation = [4, 0, 1, 2, 3]
        npt.assert_equal(nx.modularity_matrix(self.G), B)
        npt.assert_equal(nx.modularity_matrix(self.G, nodelist=permutation),
                         B[np.ix_(permutation, permutation)])
Ejemplo n.º 3
0
    def test_modularity(self):
        "Modularity matrix"
        B = numpy.matrix([[-1.125,  0.25 ,  0.25 ,  0.625,  0.  ],
                         [ 0.25 , -0.5  ,  0.5  , -0.25 ,  0.   ],
                         [ 0.25 ,  0.5  , -0.5  , -0.25 ,  0.   ],
                         [ 0.625, -0.25 , -0.25 , -0.125,  0.   ],
                         [ 0.   ,  0.   ,  0.   ,  0.   ,  0.   ]])

        permutation = [4, 0, 1, 2, 3]
        assert_equal(nx.modularity_matrix(self.G), B)
        assert_equal(nx.modularity_matrix(self.G, nodelist=permutation),
                     B[numpy.ix_(permutation, permutation)])
Ejemplo n.º 4
0
    def test_modularity_weight(self):
        "Modularity matrix with weights"
        B = numpy.matrix([[-1.125,  0.25 ,  0.25 ,  0.625,  0.   ],
                         [ 0.25 , -0.5  ,  0.5  , -0.25 ,  0.   ],
                         [ 0.25 ,  0.5  , -0.5  , -0.25 ,  0.   ],
                         [ 0.625, -0.25 , -0.25 , -0.125,  0.   ],
                         [ 0.   ,  0.   ,  0.   ,  0.   ,  0.   ]])

        G_weighted = self.G.copy()
        for n1, n2 in G_weighted.edges():
            G_weighted.edge[n1, n2]["weight"] = 0.5
        # The following test would fail in networkx 1.1
        assert_equal(nx.modularity_matrix(G_weighted), B)
        # The following test that the modularity matrix get rescaled accordingly
        assert_equal(nx.modularity_matrix(G_weighted, weight="weight"), 0.5*B)
Ejemplo n.º 5
0
    def test_modularity_weight(self):
        "Modularity matrix with weights"
        B = numpy.matrix([[-1.125,  0.25 ,  0.25 ,  0.625,  0.   ],
                         [ 0.25 , -0.5  ,  0.5  , -0.25 ,  0.   ],
                         [ 0.25 ,  0.5  , -0.5  , -0.25 ,  0.   ],
                         [ 0.625, -0.25 , -0.25 , -0.125,  0.   ],
                         [ 0.   ,  0.   ,  0.   ,  0.   ,  0.   ]])

        G_weighted = self.G.copy()
        for n1, n2 in G_weighted.edges():
            G_weighted.edge[n1][n2]["weight"] = 0.5
        # The following test would fail in networkx 1.1
        assert_equal(nx.modularity_matrix(G_weighted), B)
        # The following test that the modularity matrix get rescaled accordingly
        assert_equal(nx.modularity_matrix(G_weighted, weight="weight"), 0.5*B)
Ejemplo n.º 6
0
def cluster(G):
    """
    Splits graph G into two communities
    :param G: NetworkX graph to cluster
    :return: solution bitstring
    :rtype: list
    """

    logging.info("Computing coarsening hierarchy...")
    hierarchy = coarsen(G)
    logging.info("Done computing coarsening hierarchy")
    curr_solution = None
    for level, (graph, matching) in zip(
            range(len(hierarchy) - 1, -1, -1), reversed(hierarchy)
    ):  # http://christophe-simonis-at-tiny.blogspot.com/2008/08/python-reverse-enumerate.html
        logging.info("Now at level {}".format(level))
        B = nx.modularity_matrix(graph)
        print(graph.number_of_nodes(), B)
        if curr_solution is None:
            # first level -- initial solution
            _, curr_solution = gm.optimize_modularity(graph.number_of_nodes(),
                                                      B)

        print(curr_solution)
        break
Ejemplo n.º 7
0
def modularity_cluster(g, cap = 200):
    '''
    Cluster the graph based on Newman's algorithm.
    M. E. J. Newman, "Modularity and community structure in networks",
    Proc. Natl. Acad. Sci. USA, vol. 103, pp. 8577-8582, 2006.

    Useful Links:
        - Modularity matrix: https://goo.gl/AQ7ZUC
        - Complex number in Eigenvalue issue: https://goo.gl/APvxRn
        - Benchmark Eigenvalues with Matlab: https://goo.gl/3giVRU
    '''

    if(g.number_of_nodes() < cap):
        return []

    mm = nx.modularity_matrix(g)
    e = eigh(mm, eigvals_only=True)

    pmask = np.array([i > 0 for i in e])
    nmask = np.array(list(map(operator.not_, pmask)))

    indicies = np.array(g.nodes())
    ep = indicies[pmask]
    en = indicies[nmask]

    if(len(ep) < cap or len(en) < cap):
        return [g]

    gpart1 = g.subgraph(ep)
    gpart2 = g.subgraph(en)

    # logging.debug("cluster: (%d, %d) -> (%d, %d) (%d, %d)" % (g.number_of_nodes(), g.number_of_edges(), gpart1.number_of_nodes(), gpart1.number_of_edges(), gpart2.number_of_nodes(), gpart2.number_of_edges()))

    return modularity_cluster(gpart1, cap) + modularity_cluster(gpart2, cap)
Ejemplo n.º 8
0
def graph2dat(graph):
    folder = ""
    mygraphfile = open(folder + "neg_modularity.dat", 'w')
    data_var = {}
    data_var['couplers'] = 'set couplers :=\n'
    data_var['nodes'] = 'set nodes :=\n'
    data_var['bias'] = 'param bias := \n'
    data_var['weight'] = 'param w := \n'

    modularity_mat = nx.modularity_matrix(graph,
                                          nodelist=sorted(graph.nodes()))
    n = nx.number_of_nodes(graph)
    for i in range(n - 1):
        for j in range(i, n):
            w = -modularity_mat.item((i, j))  # neg value
            data_var['couplers'] += ' '.join([str(i), str(j), '\n'])
            data_var['weight'] += ' '.join([str(i), str(j), str(w), '\n'])
    i, j = n - 1, n - 1
    w = -modularity_mat.item((i, j))  # neg value
    data_var['couplers'] += ' '.join([str(i), str(j), '\n'])
    data_var['weight'] += ' '.join([str(i), str(j), str(w), '\n'])
    for i in range(n):
        data_var['nodes'] += str(i) + '\n'
        data_var['bias'] += str(i) + ' 0\n'  # no bias in modularity

    data_var['nodes'] += ';\n'
    data_var['bias'] += ';\n'
    data_var['weight'] += ';\n'
    data_var['couplers'] += ';\n'

    for item in data_var:
        mygraphfile.write(data_var[item])
Ejemplo n.º 9
0
def modularity_spectrum(G):
    """Return eigenvalues of the modularity matrix of G.

    Parameters
    ----------
    G : Graph
       A NetworkX Graph or DiGraph

    Returns
    -------
    evals : NumPy array
      Eigenvalues

    See Also
    --------
    modularity_matrix

    References
    ----------
    .. [1] M. E. J. Newman, "Modularity and community structure in networks",
       Proc. Natl. Acad. Sci. USA, vol. 103, pp. 8577-8582, 2006.
    """
    from scipy.linalg import eigvals
    if G.is_directed():
        return eigvals(nx.directed_modularity_matrix(G))
    else:
        return eigvals(nx.modularity_matrix(G))
Ejemplo n.º 10
0
def modularity_spectrum(G):
    """Return eigenvalues of the modularity matrix of G.

    Parameters
    ----------
    G : Graph
       A NetworkX Graph or DiGraph

    Returns
    -------
    evals : NumPy array
      Eigenvalues

    See Also
    --------
    modularity_matrix

    References
    ----------
    .. [1] M. E. J. Newman, "Modularity and community structure in networks",
       Proc. Natl. Acad. Sci. USA, vol. 103, pp. 8577-8582, 2006.
    """
    from scipy.linalg import eigvals
    if G.is_directed():
        return eigvals(nx.directed_modularity_matrix(G))
    else:
        return eigvals(nx.modularity_matrix(G))
def create_two_clusters(graph):
    nodes = sorted(graph.nodes())
    modularity_matrix = nx.modularity_matrix(graph, nodes)
    eigenvalues, eigenvectors = np.linalg.eigh(modularity_matrix)
    clusters, centroids = clustering.kmeans(eigenvectors[-2:].getT(), 2)
    labels, dist = clustering.vq(eigenvectors[0:2].getT(), clusters)
    return labels
Ejemplo n.º 12
0
def get_sub_mod_matrix(graph, ptn_variables):
    B_matrix = nx.modularity_matrix(graph, nodelist=sorted(graph.nodes()))
    free_var = []
    fixed_var = []
    fixed_vec = []
    free_nodes = []
    fixed_nodes = []
    for node in sorted(ptn_variables):
        if ptn_variables[node] == 'free':
            free_var.append(True)
            fixed_var.append(False)
            free_nodes.append(node)
        else:
            free_var.append(False)
            fixed_var.append(True)
            fixed_vec.append(ptn_variables[node])
            fixed_nodes.append(node)
    free_var = np.array(free_var)
    sub_B_matrix = B_matrix[free_var][:, free_var]
    bias = []
    for node_i in free_nodes:
        bias_i = 0
        for node_j in fixed_nodes:
            s_j = ptn_variables[node_j]
            bias_i += 2 * s_j * B_matrix.item((node_i, node_j))
        bias.append(bias_i)
    fixed_var = np.array(fixed_var)
    C = B_matrix[fixed_var][:, fixed_var]
    n = C.shape[0]
    vec = np.array(fixed_vec).reshape(n, 1)
    constant = vec.transpose() * C * vec
    return sub_B_matrix, bias, constant.item(0)
def get_base_modularity_matrix(network):
    '''
    Obtain the modularity matrix for the whole network

    Parameters
    ----------
    network : nx.Graph or nx.DiGraph
        The network of interest

    Returns
    -------
    np.matrix
        The modularity matrix for `network`

    Raises
    ------
    TypeError
        When the input `network` does not fit either nx.Graph or nx.DiGraph
    '''

    if type(network) == nx.Graph:
        return sparse.csc_matrix(nx.modularity_matrix(network))
    elif type(network) == nx.DiGraph:
        return sparse.csc_matrix(nx.directed_modularity_matrix(network))
    else:
        raise TypeError(
            'Graph type not supported. Use either nx.Graph or nx.Digraph')
Ejemplo n.º 14
0
    def test_modularity_sv(self):
        w = np.array([[0, 1, 1, 0, 0, 0], [1, 0, 1, 0, 0,
                                           0], [1, 1, 0, 1, 0, 0],
                      [0, 0, 1, 0, 1, 1], [0, 0, 0, 1, 0, 1],
                      [0, 0, 0, 1, 1, 0]])
        G = nx.from_numpy_matrix(w)
        B = nx.modularity_matrix(G, nodelist=list(range(6)))
        m = G.number_of_edges()
        mod_obj = partial(modularity_obj, N=1, B=B, m=m)

        varopt = VariationalQuantumOptimizerSequential(
            mod_obj,
            'SequentialOptimizer',
            optimizer_parameters=self.optimizer_parameters,
            varform_description={
                'name': 'RYRZ',
                'num_qubits': 6,
                'depth': 3,
                'entanglement': 'linear'
            },
            backend_description={
                'package': 'qiskit',
                'provider': 'Aer',
                'name': 'statevector_simulator'
            },
            execute_parameters=self.execute_parameters)
        varopt.optimize()
        res = varopt.get_optimal_solution(shots=10000)
        self.assertTrue(
            np.array_equal(res[1], np.array([0, 0, 0, 1, 1, 1]))
            or np.array_equal(res[1], np.array([1, 1, 1, 0, 0, 0])))
Ejemplo n.º 15
0
    def test_modularity_weight(self):
        "Modularity matrix with weights"
        # fmt: off
        B = np.array([[-1.125, 0.25, 0.25, 0.625, 0.],
                      [0.25, -0.5, 0.5, -0.25, 0.],
                      [0.25, 0.5, -0.5, -0.25, 0.],
                      [0.625, -0.25, -0.25, -0.125, 0.], [0., 0., 0., 0., 0.]])
        # fmt: on

        G_weighted = self.G.copy()
        for n1, n2 in G_weighted.edges():
            G_weighted.edges[n1, n2]["weight"] = 0.5
        # The following test would fail in networkx 1.1
        np.testing.assert_equal(nx.modularity_matrix(G_weighted), B)
        # The following test that the modularity matrix get rescaled accordingly
        np.testing.assert_equal(
            nx.modularity_matrix(G_weighted, weight="weight"), 0.5 * B)
Ejemplo n.º 16
0
 def _func(sub_nodes):
     print "Calculating modularity matrix and it's eigs ..."
     mm = nx.modularity_matrix(G.subgraph(sub_nodes))
     vals, vecs = scipy.linalg.eigh(mm)
     count = vecs.shape[1]
     vecs = np.flip(vecs, -1)
     ub = max(min(math.ceil(count / 2.0), 30), 1)
     return vecs[:, :int(ub)]  # our method!
Ejemplo n.º 17
0
def get_data_from(G):
    print "Calculating modularity matrix and it's eigs ..."
    mm = nx.modularity_matrix(G)
    vals, vecs = scipy.linalg.eigh(mm)
    print "Done"
    vecs = np.flip(vecs, -1)
    ub = 10
    return vecs[:, :int(ub)]  # our method!
def get_base_modularity_matrix(network):

    if type(network) == nx.Graph:
        return sparse.csc_matrix(nx.modularity_matrix(network))
    elif type(network) == nx.DiGraph:
        return sparse.csc_matrix(nx.directed_modularity_matrix(network))
    else:
        raise TypeError(
            'Graph type not supported. Use either nx.Graph or nx.Digraph')
Ejemplo n.º 19
0
def get_erdos_renyi_graph(left, right, p=0.7, seed=42, **kwargs):
    right = int(right)
    # kwargs are ignored
    if left != right:
        warnings.warn("Ignoring right parameter")
    print("Generating Erdos-Renyi graph on {} vertices with p={} and seed={}"
          .format(left, p, seed))
    G = nx.erdos_renyi_graph(left, p, seed=seed)
    B = nx.modularity_matrix(G).A
    return G, None
Ejemplo n.º 20
0
def spectral_comunities(G):
    mod_matrix = nx.modularity_matrix(G)
    values, vectors = linalg.eig(mod_matrix)
    max_index = 0
    for x in range(2, len(values)):
        if values[x] > values[max_index]:
            max_index = x
    eigenvector = vectors[max_index].tolist()
    eigenvector = eigenvector[0]
    sList = [1 if val > 0 else -1 for val in eigenvector]
    return sList
Ejemplo n.º 21
0
def get_optimal_modularity_bitstring(G):
    # Guaranteed to return a string of +1 / -1
    B = nx.modularity_matrix(G).A
    _, bitstring = optimize_modularity(G, B)
    if 0 in bitstring:
        # assuming bitstring is of zeros and ones
        bitstring = [
            -1 if x == 0 else 1 if x == 1 else 'Error' for x in bitstring
        ]
    if 'Error' in bitstring or len(bitstring) != G.number_of_nodes():
        raise ValueError("Incorrect bistring returned by nx.erdos_renyi_graph")
    return bitstring
def networkX_modularity(adj_graph,sym,weight='weight'):
    # Compute the modularity matrix using NetworkX built in function.
    #
    # Can take symmetric or directed graphs (sym='sym' or sym='').
    # Can take weighted or unweighted graphs (weight='weight' or weight=None).
    #
    if (sym=='sym'):
        B = nx.modularity_matrix(adj_graph,weight=weight)
    else:
        B = nx.directed_modularity_matrix(adj_graph,weight=weight)

    return B
Ejemplo n.º 23
0
    def fit(self, graph: nx.classes.graph.Graph):
        """
        Fitting a Social Dimensions model.

        Arg types:
            * **graph** *(NetworkX graph)* - The graph to be embedded.
        """
        self._set_seed()
        self._check_graph(graph)
        number_of_nodes = graph.number_of_nodes()
        L_tilde = nx.modularity_matrix(graph, nodelist=range(number_of_nodes))
        _, self._embedding = sps.linalg.eigsh(L_tilde, k=self.dimensions,
                                              which='LM', return_eigenvectors=True)
Ejemplo n.º 24
0
    def test_modularity_obj(self):
        w = np.array([[0, 1, 1, 0, 0, 0], [1, 0, 1, 0, 0,
                                           0], [1, 1, 0, 1, 0, 0],
                      [0, 0, 1, 0, 1, 1], [0, 0, 0, 1, 0, 1],
                      [0, 0, 0, 1, 1, 0]])
        G = nx.from_numpy_matrix(w)
        B = nx.modularity_matrix(G, nodelist=list(range(6)))
        m = G.number_of_edges()

        x = np.array([0, 0, 0, 1, 1, 1])
        N = 1
        y = np.array([0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1])
        M = 2

        self.assertTrue(abs(modularity_obj(x, N, B, m) + 10 / 28) < 1e-5)
        self.assertTrue(abs(modularity_obj(y, M, B, m) + 9 / 98) < 1e-5)
Ejemplo n.º 25
0
def main2():
    """ spectral same part"""
    method = 'pyomo'
    if method == 'dwave':
        solver = start_sapi()
        embedding = get_native_embedding(solver)
        num_reads = 1000
        annealing_time = 200
    #seed = random.randint(1,10000)
    #seed = 8834
    #print seed
    random.seed(seed)
    filename = sys.argv[1]
    graph = data_to_graph(filename)
    #print '%i nodes, %i edges' %(nx.number_of_nodes(graph), nx.number_of_edges(graph))
    mod_matrix = nx.modularity_matrix(graph, nodelist=sorted(graph.nodes()))
    nnodes = nx.number_of_nodes(graph)
    hardware_size = 25
    ptn = [1 - 2 * random.randint(0, 1) for _ in range(nnodes)]
    #init_ptn = [1 for _ in range(nnodes)]
    #init_ptn = [np.sign(i) for i in nx.fiedler_vector(graph).tolist()]
    mod = compute_modularity(graph, mod_matrix, ptn)
    #print 'init modularity:', mod, 0.25*mod/nx.number_of_edges(graph)

    ptn_variables = {}
    for node in sorted(graph.nodes()):
        ptn_variables[node] = ptn[node]
    sp_order = nx.spectral_ordering(graph)
    for mynode in sorted(graph.nodes()):
        free_nodes = spectral_neigh_same_part(mynode, graph, mod_matrix, ptn,
                                              hardware_size, sp_order)
        for node in free_nodes:
            ptn_variables[node] = 'free'
        if method == 'dwave':
            new_ptn = sapi_refine_modularity(graph, solver, hardware_size,
                                             ptn_variables, num_reads,
                                             annealing_time, embedding)
        else:
            new_ptn = pyomo_refine(graph, ptn_variables)
        for node in free_nodes:
            ptn_variables[node] = new_ptn[node]

        mod = compute_modularity(graph, mod_matrix, new_ptn)
Ejemplo n.º 26
0
def get_modularity(graph):
    #graphfile = folder + sys.argv[1]
    #graph = nx.read_graphml(graphfile, node_type=int)
    instance = minimize_ising_model.model.create_instance("neg_modularity.dat")
    solver = SolverFactory("gurobi")
    #solver_manager = SolverManagerFactory('neos') # For Neos server
    # cplex options
    #solver.options['parallel'] = -1
    # gurobi options
    solver.options['threads'] = min(16, multiprocessing.cpu_count())
    #solver.options['timelimit'] = 10

    #results = solver_manager.solve(instance, opt=solver, tee=True) # Neos server
    results = solver.solve(instance, tee=True)
    energy = instance.min_ising()
    solver_modularity = -0.25 * energy / nx.number_of_edges(graph)
    unscaled = -energy
    # Get partition
    varobject = getattr(instance, 'x')
    part0 = []
    part1 = []

    ising_partition = ['unset' for i in graph.nodes()]
    for index in sorted(varobject):
        if varobject[index].value > 0.001:
            part1.append(index)
            ising_partition[index] = 1
        else:
            ising_partition[index] = -1
            part0.append(index)
    #print(ising_partition)
    mod_matrix = nx.modularity_matrix(graph)
    mymod = compute_modularity(graph, mod_matrix, ising_partition)
    res = {
        'unscaled': unscaled,
        'solver_modularity': solver_modularity,
        'from_part': mymod
    }
    print('unscaled:', res['unscaled'])
    print("Solver Modularity:", res['solver_modularity'])
    print("Modularity from part:", res['from_part'])

    return res
Ejemplo n.º 27
0
def get_obj_val(graph_generator_name,
                left,
                right,
                seed=None,
                obj_params='ndarray',
                sign=1,
                backend='IBMQX',
                backend_params={'depth': 3},
                return_x=False):
    # Generate the graph
    G, _ = generate_graph(graph_generator_name, left, right, seed=seed)
    B = nx.modularity_matrix(G).A
    return get_obj(G.number_of_nodes(),
                   B,
                   obj_params=obj_params,
                   sign=sign,
                   backend=backend,
                   backend_params=backend_params,
                   return_x=return_x)
Ejemplo n.º 28
0
G= nx.Graph()

zz_=np.delete(zz,[2],axis=1)

zzTotal_list = zz_.tolist()

#N = G.add_nodes_from(TotalCellsRoi)
E = G.add_edges_from(zzTotal_list)


Nnodos = nx.number_of_nodes(G)
Density = nx.density(G)
Cluster = nx.average_clustering(G)
Assortativity = nx.degree_assortativity_coefficient(G)
ShortPath = nx.average_shortest_path_length(G)   
nx.modularity_matrix(G)
#Attracting = nx.is_attracting_component(G)
plt.style.use('seaborn-whitegrid')

nx.draw(G,node_size=100,node_color='tomato',edge_color='gray')


#%% 

####  AGRUPACION Y COMUNIDADES DE GRAFOS POR METODO gIRVAN

community=[]

def edge_to_remove(G):
    dict1=nx.edge_betweenness_centrality(G)
    list_of_tuples = dict1.items()
Ejemplo n.º 29
0
 def modularity_matrix_calc(self, graph):
     """ This function calculates the modularity matrix"""
     return networkx.modularity_matrix(graph)
Ejemplo n.º 30
0
def test_angles(graph_generator_name,
                left,
                right,
                angles,
                seed=None,
                verbose=0,
                compute_optimal=False,
                backend='IBMQX',
                backend_params={
                    'backend_device': None,
                    'depth': 3
                }):
    # note that compute optimal uses brute force! Not recommended for medium and large problem
    # angles should be a dictionary with fields 'beta' and 'gamma', e.g. {'beta': 2.0541782343349086, 'gamma': 0.34703642333837853}

    rand_seed = seed

    # Generate the graph
    G, _ = generate_graph(graph_generator_name, left, right, seed=seed)
    # Use angles

    # Using NetworkX modularity matrix
    B = nx.modularity_matrix(G).A

    # Compute ideal cost
    if compute_optimal:
        optimal_modularity = gm.compute_modularity(G, B, solution_bitstring)
        print("Optimal solution energy: ", optimal_modularity)
    else:
        optimal_modularity = None

    if backend == 'IBMQX':
        if not isinstance(angles, (np.ndarray, np.generic, list)):
            raise ValueError(
                "Incorrect angles received: {} for backend {}".format(
                    angles, backend))
        var_form = IBMQXVarForm(num_qubits=G.number_of_nodes(),
                                depth=backend_params['depth'])
        resstrs = var_form.run(angles)
    else:
        raise ValueError("Unsupported backend: {}".format(backend))

    if verbose > 1:
        # print distribution
        allstrs = list(product([0, 1], repeat=len(qubits)))
        freq = {}
        for bitstr in allstrs:
            freq[str(list(bitstr))] = 0
        for resstr in resstrs:
            resstr = str(list(resstr))  # for it to be hashable
            if resstr in freq.keys():
                freq[resstr] += 1
            else:
                raise ValueError(
                    "received incorrect string: {}".format(resstr))
        for k, v in freq.items():
            print("{} : {}".format(k, v))

    # Raw results
    modularities = [gm.compute_modularity(G, B, x) for x in resstrs]
    mod_max = max(modularities)
    # Probability of getting best modularity
    if compute_optimal:
        mod_pmax = float(np.sum(np.isclose(
            modularities, optimal_modularity))) / float(len(modularities))
    else:
        mod_pmax = None
    mod_mean = np.mean(modularities)
    if verbose:
        print("Best modularity found:", mod_max)
        print("pmax: ", mod_pmax)
        print("mean: ", mod_mean)
    return {
        'max': mod_max,
        'mean': mod_mean,
        'pmax': mod_pmax,
        'optimal': optimal_modularity,
        'x': angles
    }
Ejemplo n.º 31
0
    def test_mpo_objective_modularity_k_way(self):
        import logging
        logging.disable(logging.CRITICAL)
        import matlab
        G = nx.OrderedGraph()
        elist = [(0, 2), (0, 3), (0, 11), (1, 2), (1, 3), (2, 3), (3, 4),
                 (4, 6), (4, 7), (5, 6), (5, 7), (6, 7), (7, 8), (8, 10),
                 (8, 11), (9, 10), (9, 11), (10, 11)]
        G.add_edges_from(elist)
        nnodes = G.number_of_nodes()
        N = 2
        nqubits = nnodes * N  # N variables per node -- up to 2**N communities

        node_list = list(range(nnodes))
        B = matlab.double(nx.modularity_matrix(G, nodelist=node_list).tolist())

        obj = partial(modularity_energy,
                      N=N,
                      B=nx.modularity_matrix(G, nodelist=node_list).getA(),
                      m=G.number_of_edges(),
                      deg_list=[G.degree[i] for i in node_list])

        precomputed_good_params = np.array([
            4.15610651, 1.31952566, 5.39528713, 0.03165722, 0.29017244,
            1.13614827, -2.07509482, 2.29757058, 0.41243041, 5.76625946,
            -4.32125694, -2.21142374, -2.95591283, -0.44569759, 5.00991472,
            -2.38284874, 4.08231081, 1.55265289, -5.20439166, -2.62705216,
            0.26832527, -4.12101477, -4.27473955, 4.58479753, -1.56014587,
            -0.52379135, -2.78755743, 6.35824237, 6.16095312, -4.80030703,
            -0.84348438, -2.9339378, -3.13894666, 3.30636124, -3.2208338,
            -4.00239323, 1.91003078, 5.73582487, 1.4899889, 5.80934756,
            3.10322086, 1.60227976, 4.74931798, 2.32907816, 4.38702652,
            -4.80603026, -0.82120823, -3.2610527, -3.64614703, 5.99653502,
            4.94231979, 3.73974001, -2.34897493, -4.71583219, 1.48330405,
            6.04077852, 2.84132271, 0.01466078, -3.61453391, -5.68864954,
            6.08686394, 5.46570721, 5.44826073, -5.26395504, -0.93564532,
            1.89588868, -5.21973893, 3.01863335, 2.51588271, -3.97664614,
            7.58394176, -3.59918101, 0.96797456, -0.74624669, -4.83039533,
            -4.03002175, 0.70923642, -3.75009256, 4.82231404, -4.22920321,
            -3.52680223, 0.31700832, 6.75879683, 3.50625919, -5.1009759,
            3.0347534, -4.09756222, -3.42942231, 2.83041522, -3.9895508,
            -2.8693705, 2.12212776, 0.39196109, 7.48359308, -3.69241341,
            -3.46325887, -2.33739302, -5.40617378, 3.54184289, 4.31628083,
            0.29044417, 4.18564356, 2.30074315, 2.57942552, -3.10036929,
            -4.30000567, -1.62644728, 5.24134547, -1.74320921, 3.27039832,
            4.08539243, 4.56899165, 5.74862203, -2.40435231, 3.44914951,
            -5.03919062, 2.84952808, -1.13341506, 5.00855887, -5.66899901,
            0.28431306, -4.32562784, 2.91942835, 5.01386366, 0.36082722,
            7.66761106, 4.13723874, -4.45246101, 0.13413378, 5.94874616,
            5.92336011, 6.59555163, -3.31464691, 2.2468367, -4.56588791,
            1.01536706, 0.34020607, 3.74764888, 1.65250476, -4.72223208,
            2.38389989, -6.36721914, -2.80402566, -4.48821116, 0.28952596,
            -4.51485203, 3.08119184, -0.60249566, 6.10183681, 5.66230155,
            0.30292948, 2.08435297, 2.48144112, -0.4033077, 3.18158093,
            4.38631354, -1.37507408, -0.72594662, -3.35534963, -0.09028156,
            -5.56034943, 3.40867727, 2.51204148, -3.50149819, 3.21263761,
            1.39083258, -0.3292894, -2.45686952, -4.17826603, -3.08442966,
            -2.04319878, 1.13819382, -2.12785284, -0.62048513, -3.67792066,
            5.43649767, -3.14400277, 3.01728892, -0.62765206, -1.6561974,
            4.61813977, 5.65717505, 2.8793227, 0.67725344, 3.29505459,
            0.33112227, 3.07787261, -2.43315426, -1.11027068, 3.18688124,
            2.95611302, -1.09703103
        ])

        varopt = VariationalQuantumOptimizerSequential(
            obj,
            'COBYLA',
            optimizer_parameters={'maxiter': 5},
            initial_point=precomputed_good_params,
            varform_description={
                'package': 'mpsbackend',
                'name': 'RYRZ',
                'num_qubits': nqubits,
                'depth': 3,
                'entanglement_gate': 'cz'
            },
            backend_description=self.backend_description,
            objective_parameters={
                'use_mpo_energy': True,
                'hamiltonian_constructor':
                'construct_k_way_modularity_Hamiltonian',
                'hamiltonian_constructor_parameters': [B, N]
            },
            execute_parameters={})
        optres = varopt.optimize()
        self.assertTrue(optres['min_val'] < -19)
        logging.disable(logging.NOTSET)
def load_dataset(name):
    dolphin_path = 'Datasets/dolphins.gml'
    adjnoun_path = "Datasets/adjnoun.gml"
    football_path = 'Datasets/football.gml'
    polbooks_path = 'Datasets/polbooks.gml'
    email_edges = 'Datasets/email-Eu-core.txt'
    email_labels = 'Datasets/email-Eu-core-department-labels.txt'

    # # Polblogs
    # if(name=='polblogs'):
    #     G_data = nx.read_gml(polblogs_path)
    #     G_data = G_data.to_undirected()
    #     G_data = nx.Graph(G_data)
    #     B_data = nx.modularity_matrix(G_data)

    # Karate
    if(name == 'karate'):
        G_data = nx.karate_club_graph()
        B_data = nx.modularity_matrix(G_data)

    # Football
    elif(name == 'football'):
        G_data = nx.read_gml(football_path)
        B_data = nx.modularity_matrix(G_data)

    # Polbooks
    elif(name == 'polbooks'):
        G_data = nx.read_gml(polbooks_path)
        B_data = nx.modularity_matrix(G_data)

    # Dolphin
    elif(name == 'dolphin'):
        G_data = nx.read_gml(dolphin_path)
        B_data = nx.modularity_matrix(G_data)

    # lfr 0.1
    elif(name == 'lfr 0.1'):
        G_data = nx.Graph()
        data, labels = load_data(0.1)

        for index, item in enumerate(labels):
            G_data.add_node(index+1, value=item)
        for item in data:
            G_data.add_edge(*item)
        B_data = nx.modularity_matrix(G_data)

    # lfr 0.3
    elif(name == 'lfr 0.3'):
        G_data = nx.Graph()
        data, labels = load_data(0.3)

        for index, item in enumerate(labels):
            G_data.add_node(index+1, value=item)
        for item in data:
            G_data.add_edge(*item)
        B_data = nx.modularity_matrix(G_data)

    # lfr 0.5
    elif(name == 'lfr 0.5'):
        G_data = nx.Graph()
        data, labels = load_data(0.5)

        for index, item in enumerate(labels):
            G_data.add_node(index+1, value=item)
        for item in data:
            G_data.add_edge(*item)
        B_data = nx.modularity_matrix(G_data)

    elif(name == 'email'):
        G_data=nx.Graph()

        with open(email_edges) as f:
            for line in f:
                if(len(line)>0):
                    x=(line.split())
                    G_data.add_edge(int(x[0]),int(x[1]))

        G_data.remove_nodes_from([658,653,648,798,731,772,670,691,675,684,660,711,744,808,746,580,633,732,703])
        B_data = nx.modularity_matrix(G_data)

    return G_data, B_data
        ajModList.append([])
        for xj in range(len(clusterL[xi])):
            for xk in range(len(clusterL[xi])):
                if clusterL[xi][xj] != clusterL[xi][xk]:
                    ajModList.append((clusterL[xi][xj], clusterL[xi][xk]))
                    adjac_matrix[clusterL[xi][xj]][clusterL[xi][xk]] = 1

    # adjac matrix #2
    # combine every node like shown on graph
    adjac_matrix2 = np.zeros((len(Data) + len(Z), len(Data) + len(Z)),
                             dtype=int)
    for nodex in az:
        adjac_matrix2[nodex] = 1

    G1 = nx.from_numpy_matrix(adjac_matrix)
    B1 = nx.modularity_matrix(G1)

    G2 = nx.from_numpy_matrix(adjac_matrix2)
    B2 = nx.modularity_matrix(G2)

    ajModScore = []
    for am in range(len(ajModList)):
        if ajModList[am] == []:
            continue
        ajModScore.append(ajModList[am])

        # Creating adjac matrix
    adjac_matrix3 = np.zeros((len(Data) + len(Z), len(Data) + len(Z)),
                             dtype=int)

    # adjac matrix #1