Пример #1
0
def graph_coloring_qubo(graph, k):
    """
    the QUBO for k-coloring a graph A is as follows:

    variables:
    x_{v,c} = 1 if vertex v of A gets color c; x_{v,c} = 0 otherwise

    constraints:
    1)  each v in A gets exactly one color.
       This constraint is enforced by including the term (\sum_c x_{v,c} - 1)^2 in the QUBO,
       which is minimized when \sum_c x_{v,c} = 1.

    2) If u and v in A are adjacent, then they get different colors.
       This constraint is enforced by including terms x_{v,c} x_{u,c} in the QUBO,
       which is minimzed when at most one of u and v get color c.

    Total QUBO:
    Q(x) = \sum_v (\sum_c x_{v,c} - 1)^2  + \sum_{u ~ v} \sum_c x_{v,c} x_{u,c}

    The graph of interactions for this QUBO consists of cliques of size k (with vertices {x_{v,c} for c = 0,...,k-1})
    plus k disjoint copies of the graph A (one for each color).

    """

    K = nx.complete_graph(k)
    g1 = nx.cartesian_product(nx.create_empty_copy(graph), K)
    g2 = nx.cartesian_product(graph, nx.create_empty_copy(K))
    return nx.compose(g1, g2)
Пример #2
0
def cartesian_product(graphs):
    """Performs a cartesian product between a list of networkx graphs."""
    G = nx.cartesian_product(graphs[0], graphs[1])
    for i in range(2, len(graphs)):
        G = nx.cartesian_product(G, graphs[i])
    mapping = {}
    for node in G.nodes():
        mapping[node] = tuple(flatten(node))
    return nx.relabel_nodes(G, mapping)
Пример #3
0
def test_cartesian_product_classic():
    # test some classic product graphs
    P2 = nx.path_graph(2)
    P3 = nx.path_graph(3)
    # cube = 2-path X 2-path
    G=cartesian_product(P2,P2)
    G=cartesian_product(P2,G)
    assert_true(nx.is_isomorphic(G,nx.cubical_graph()))

    # 3x3 grid
    G=cartesian_product(P3,P3)
    assert_true(nx.is_isomorphic(G,nx.grid_2d_graph(3,3)))
Пример #4
0
def test_cartesian_product_classic():
    # test some classic product graphs
    P2 = nx.path_graph(2)
    P3 = nx.path_graph(3)
    # cube = 2-path X 2-path
    G = nx.cartesian_product(P2, P2)
    G = nx.cartesian_product(P2, G)
    assert_true(nx.is_isomorphic(G, nx.cubical_graph()))

    # 3x3 grid
    G = nx.cartesian_product(P3, P3)
    assert_true(nx.is_isomorphic(G, nx.grid_2d_graph(3, 3)))
Пример #5
0
def test_cartesian_product_size():
    # order(GXH)=order(G)*order(H)
    K5 = nx.complete_graph(5)
    P5 = nx.path_graph(5)
    K3 = nx.complete_graph(3)
    G = nx.cartesian_product(P5, K3)
    assert nx.number_of_nodes(G) == 5 * 3
    assert nx.number_of_edges(
        G) == nx.number_of_edges(P5) * nx.number_of_nodes(
            K3) + nx.number_of_edges(K3) * nx.number_of_nodes(P5)
    G = nx.cartesian_product(K3, K5)
    assert nx.number_of_nodes(G) == 3 * 5
    assert nx.number_of_edges(
        G) == nx.number_of_edges(K5) * nx.number_of_nodes(
            K3) + nx.number_of_edges(K3) * nx.number_of_nodes(K5)
Пример #6
0
def test_cartesian_product_size():
    # order(GXH)=order(G)*order(H)
    K5=nx.complete_graph(5)
    P5=nx.path_graph(5)
    K3=nx.complete_graph(3)
    G=cartesian_product(P5,K3)
    assert_equal(nx.number_of_nodes(G),5*3)
    assert_equal(nx.number_of_edges(G),
                 nx.number_of_edges(P5)*nx.number_of_nodes(K3)+
                 nx.number_of_edges(K3)*nx.number_of_nodes(P5))
    G=cartesian_product(K3,K5)
    assert_equal(nx.number_of_nodes(G),3*5)
    assert_equal(nx.number_of_edges(G),
                 nx.number_of_edges(K5)*nx.number_of_nodes(K3)+
                 nx.number_of_edges(K3)*nx.number_of_nodes(K5))
def generate_hamming_graph(
    d: int, q: int, v_as_string: bool = False
) -> Tuple[Set[Tuple[str, str]], Text]:
    """Returns edges for hamming graph (caretesian product of complete graphs).

    See also http://mathworld.wolfram.com/HammingGraph.html

    Arguments:
        d: Dimension of graph (number of copies).
        q: Number of nodes for complete graph used in cartesian product.
        v_as_string: Convert vertices to strings of format "v10v11v12...".
    """
    kq = nx.complete_graph(q)
    graph = kq
    for _ in range(d - 1):
        graph = nx.cartesian_product(graph, kq)

    edges = set((_v2str(v1), _v2str(v2)) for v1, v2 in graph.edges)

    if not v_as_string:
        nodes = dict()
        n_nodes = 0
        int_edges = set()
        for v1, v2 in edges:
            if v1 not in nodes:
                nodes[v1] = n_nodes
                n_nodes += 1
            if v2 not in nodes:
                nodes[v2] = n_nodes
                n_nodes += 1

            int_edges.add((nodes[v1], nodes[v2]))
        edges = int_edges

    return edges, f"Hamming({d},{q})"
Пример #8
0
 def rooks_generator(self, size):
     m = n = int(math.sqrt(size))
     G = nx.complete_graph(n)
     H = nx.complete_graph(m)
     F = nx.cartesian_product(G, H)
     print(len(F))
     F.name = 'rooks'
     return F
def hypercube_graph(m):
    path = nx.path_graph(2)
    G = nx.Graph()
    G.add_node(1)
    for i in range(m):
        G = nx.cartesian_product(G, path)
    G = nx.convert_node_labels_to_integers(G)
    return G
Пример #10
0
def __test_cartesian_try_01__():

   # You'll also find a product-type fcn. in networkx.

   dir_graph, node_first, node_final = __test_get_graph_01__()

   graphed = networkx.cartesian_product(dir_graph, dir_graph)
   log.debug('test_cartesian:  once: cnt. graphed.nodes: %d' % (len(graphed),))

   graphed = networkx.cartesian_product(dir_graph, graphed)
   log.debug('test_cartesian: twice: cnt. graphed.nodes: %d' % (len(graphed),))

   graphed = networkx.cartesian_product(dir_graph, graphed)
   log.debug('test_cartesian: thrice: cnt graphed.nodes: %d' % (len(graphed),))

   graphed = networkx.cartesian_product(dir_graph, graphed)
   log.debug('test_cartesian: fource: cnt graphed.nodes: %d' % (len(graphed),))
Пример #11
0
    def cartesian_product(self, other_kg):
        """ Returns the cartesian product of the knowledge graph and other_kg

        :param other_kg: The other knowledge graph
        :type other_kg: :class:`.KnowledgeGraph`
        """
        # Returns a KnowledgeGraph of the Cartesian product of self and other_kg
        return KnowledgeGraph(nx.cartesian_product(self.net, other_kg.net))
Пример #12
0
def rooks_graph(n, m=None):
    if m is None:
        m = n
    G = nx.complete_graph(n)
    H = nx.complete_graph(m)
    F = nx.cartesian_product(G, H)
    F.name = 'rooks'
    F.graph['pos'] = {v: list(v) for v in F}
    return F
Пример #13
0
	def __init__(self,L):
		#compute vertices, edges and faces
		torus = nx.cartesian_product(nx.generators.classic.cycle_graph(L), nx.generators.classic.cycle_graph(L))
		rlabels = dict(enumerate(torus.nodes()))
		labels = dict(zip(rlabels.values(),rlabels.keys()))
		torus = nx.relabel_nodes(torus,labels)
		faces = [ [[labels[v,u], labels[(v+1)%L,u]], [labels[v,u], labels[v,(u+1)%L]], [labels[(v+1)%L,u], labels[(v+1)%L,(u+1)%L]], [labels[v,(u+1)%L], labels[(v+1)%L,(u+1)%L]]] for v in range(L) for u in range(L) ]
		#initialize TwoComplex
		super(ToricLattice,self).__init__(torus.nodes(),torus.edges(),faces,L)
Пример #14
0
def test_cartesian_product_random():
    G = nx.erdos_renyi_graph(10,2/10.)
    H = nx.erdos_renyi_graph(10,2/10.)
    GH = cartesian_product(G,H)

    for (u_G,u_H) in GH.nodes_iter():
        for (v_G,v_H) in GH.nodes_iter():
            if (u_G==v_G and H.has_edge(u_H,v_H)) or \
               (u_H==v_H and G.has_edge(u_G,v_G)):
                assert_true(GH.has_edge((u_G,u_H),(v_G,v_H)))
            else:
                assert_true(not GH.has_edge((u_G,u_H),(v_G,v_H)))
Пример #15
0
def test_cartesian_product_random():
    G = nx.erdos_renyi_graph(10, 2 / 10.)
    H = nx.erdos_renyi_graph(10, 2 / 10.)
    GH = nx.cartesian_product(G, H)

    for (u_G, u_H) in GH.nodes():
        for (v_G, v_H) in GH.nodes():
            if (u_G == v_G and H.has_edge(u_H, v_H)) or \
               (u_H == v_H and G.has_edge(u_G, v_G)):
                assert_true(GH.has_edge((u_G, u_H), (v_G, v_H)))
            else:
                assert_true(not GH.has_edge((u_G, u_H), (v_G, v_H)))
Пример #16
0
def test_cartesian_product_multigraph():
    G=nx.MultiGraph()
    G.add_edge(1,2,key=0)
    G.add_edge(1,2,key=1)
    H=nx.MultiGraph()
    H.add_edge(3,4,key=0)
    H.add_edge(3,4,key=1)
    GH=cartesian_product(G,H)
    assert_equal( set(GH) , set([(1, 3), (2, 3), (2, 4), (1, 4)]))
    assert_equal( set(GH.edges(keys=True)) ,
                  set([((1, 3), (2, 3), 0), ((1, 3), (2, 3), 1), 
                       ((1, 3), (1, 4), 0), ((1, 3), (1, 4), 1), 
                       ((2, 3), (2, 4), 0), ((2, 3), (2, 4), 1), 
                       ((2, 4), (1, 4), 0), ((2, 4), (1, 4), 1)]))    
Пример #17
0
    def modular_product(self, matching_b):
        """Function that creates modular graph product out of two matching objects and returns it.
        """
        graph_product = nx.Graph()
        if self.network.is_directed() == matching_b.network.is_directed():
            graph_product.add_nodes_from(nx.cartesian_product(self.network, matching_b.network).nodes(True))
            for i in range(len(graph_product.nodes)):
                for j in range(i + 1, len(graph_product.nodes)):
                    # Check whether a node would map to itself
                    if list(graph_product.nodes)[i][0] != list(graph_product.nodes)[j][0] and \
                            list(graph_product.nodes)[i][1] != list(graph_product.nodes)[j][1]:
                        # check whether nodes are connected in the same way in the original graph
                        if self.is_connected_how(list(graph_product.nodes)[i][0], list(graph_product.nodes)[j][0],
                                                 self.network) == \
                                self.is_connected_how(list(graph_product.nodes)[i][1], list(graph_product.nodes)[j][1],
                                                      matching_b.network):
                            label = []
                            # add edge labels to edges in the modular graph product
                            for edge in self.network.edges(data=True):
                                if Matching.edgecompare(edge, [list(graph_product.nodes)[i][0],
                                                               list(graph_product.nodes)[j][0]]):
                                    attributes = self.network.get_edge_data(edge[0], edge[1])
                                    if 'Label' in attributes:
                                        label_1 = attributes['Label']
                                    else:
                                        label_1 = None
                                    label.append(label_1)
                                    break
                            else:
                                label.append(None)
                            for edge in matching_b.network.edges(data=True):
                                if Matching.edgecompare(edge, [list(graph_product.nodes)[i][1],
                                                               list(graph_product.nodes)[j][1]]):
                                    attributes = matching_b.network.get_edge_data(edge[0], edge[1])
                                    if 'Label' in attributes:
                                        label_2 = attributes['Label']
                                    else:
                                        label_2 = None
                                    label.append(label_2)
                                    break
                            else:
                                label.append(None)
                            graph_product.add_edge(list(graph_product.nodes)[i], list(graph_product.nodes)[j],
                                                   Label=label)

            return graph_product

        else:
            return -1
Пример #18
0
def test_cartesian_product_multigraph():
    G = nx.MultiGraph()
    G.add_edge(1, 2, key=0)
    G.add_edge(1, 2, key=1)
    H = nx.MultiGraph()
    H.add_edge(3, 4, key=0)
    H.add_edge(3, 4, key=1)
    GH = nx.cartesian_product(G, H)
    assert_equal(set(GH), {(1, 3), (2, 3), (2, 4), (1, 4)})
    assert_equal({(frozenset([u, v]), k) for u, v, k in GH.edges(keys=True)},
                 {(frozenset([u, v]), k) for u, v, k in
                  [((1, 3), (2, 3), 0), ((1, 3), (2, 3), 1),
                   ((1, 3), (1, 4), 0), ((1, 3), (1, 4), 1),
                   ((2, 3), (2, 4), 0), ((2, 3), (2, 4), 1),
                   ((2, 4), (1, 4), 0), ((2, 4), (1, 4), 1)]})
Пример #19
0
def test_cartesian_product_multigraph():
    G = nx.MultiGraph()
    G.add_edge(1, 2, key=0)
    G.add_edge(1, 2, key=1)
    H = nx.MultiGraph()
    H.add_edge(3, 4, key=0)
    H.add_edge(3, 4, key=1)
    GH = cartesian_product(G, H)
    assert_equal(set(GH), {(1, 3), (2, 3), (2, 4), (1, 4)})
    assert_equal({(frozenset([u, v]), k) for u, v, k in GH.edges(keys=True)},
                 {(frozenset([u, v]), k) for u, v, k in
                  [((1, 3), (2, 3), 0), ((1, 3), (2, 3), 1),
                   ((1, 3), (1, 4), 0), ((1, 3), (1, 4), 1),
                   ((2, 3), (2, 4), 0), ((2, 3), (2, 4), 1),
                   ((2, 4), (1, 4), 0), ((2, 4), (1, 4), 1)]})
Пример #20
0
def random_walk_kernel(g1, g2, parameter_lambda, node_attribute='label'):
    """ Compute the random walk kernel of two graphs as described by Neuhaus
        and Bunke in the chapter 5.9 of "Bridging the Gap Between Graph Edit
        Distance and Kernel Machines (2007)"
    """
    p = nx.cartesian_product(g1, g2)
    M = nx.attr_sparse_matrix(p, node_attr=node_attribute)
    A = M[0]
    L = A.shape[0]
    k = 0
    A_exp = A
    for n in range(L):
        k += (parameter_lambda**n) * long(A_exp.sum())
        if n < L:
            A_exp = A_exp * A

    return k
Пример #21
0
def random_walk_kernel(g1, g2, parameter_lambda, node_attribute="label"):
    """ Compute the random walk kernel of two graphs as described by Neuhaus
        and Bunke in the chapter 5.9 of "Bridging the Gap Between Graph Edit
        Distance and Kernel Machines (2007)"
    """
    p = nx.cartesian_product(g1, g2)
    M = nx.attr_sparse_matrix(p, node_attr=node_attribute)
    A = M[0]
    L = A.shape[0]
    k = 0
    A_exp = A
    for n in xrange(L):
        k += (parameter_lambda ** n) * long(A_exp.sum())
        if n < L:
            A_exp = A_exp * A

    return k
Пример #22
0
def grid_graph(dim, periodic=False, create_using=None):
    """ Return the n-dimensional grid graph.

    The dimension is the length of the list 'dim' and the
    size in each dimension is the value of the list element.

    E.g. G=grid_graph(dim=[2,3]) produces a 2x3 grid graph.

    If periodic=True then join grid edges with periodic boundary conditions.

    """
    from networkx.utils import is_list_of_ints

    if create_using is not None and create_using.is_directed():
        raise nx.NetworkXError("Directed Graph not supported")
    dlabel = "%s" % dim
    if dim == []:
        G = empty_graph(0, create_using)
        G.name = "grid_graph(%s)" % dim
        return G
    if not is_list_of_ints(dim):
        raise nx.NetworkXError("dim is not a list of integers")
    if min(dim) <= 0:
        raise nx.NetworkXError("dim is not a list of strictly positive integers")
    if periodic:
        func = cycle_graph
    else:
        func = path_graph

    current_dim = dim.pop()
    G = func(current_dim, create_using)
    while len(dim) > 0:
        current_dim = dim.pop()
        # order matters: copy before it is cleared during the creation of Gnew
        Gold = G.copy()
        Gnew = func(current_dim, create_using)
        # explicit: create_using=None
        # This is so that we get a new graph of Gnew's class.
        G = nx.cartesian_product(Gnew, Gold, create_using=None)
    # graph G is done but has labels of the form (1,(2,(3,1)))
    # so relabel
    H = nx.relabel_nodes(G, utils.flatten)
    H.name = "grid_graph(%s)" % dlabel
    return H
Пример #23
0
def grid_graph(dim, periodic=False, create_using=None):
    """ Return the n-dimensional grid graph.

    The dimension is the length of the list 'dim' and the
    size in each dimension is the value of the list element.

    E.g. G=grid_graph(dim=[2,3]) produces a 2x3 grid graph.

    If periodic=True then join grid edges with periodic boundary conditions.

    """
    if create_using is not None and create_using.is_directed():
        raise nx.NetworkXError("Directed Graph not supported")
    dlabel = "%s" % dim
    if dim == []:
        G = empty_graph(0, create_using)
        G.name = "grid_graph(%s)" % dim
        return G
    if not is_list_of_ints(dim):
        raise nx.NetworkXError("dim is not a list of integers")
    if min(dim) <= 0:
        raise nx.NetworkXError(\
              "dim is not a list of strictly positive integers")
    if periodic:
        func = cycle_graph
    else:
        func = path_graph

    current_dim = dim.pop()
    G = func(current_dim, create_using)
    while len(dim) > 0:
        current_dim = dim.pop()
        # order matters: copy before it is cleared during the creation of Gnew
        Gold = G.copy()
        Gnew = func(current_dim, create_using)
        # explicit: create_using=None
        # This is so that we get a new graph of Gnew's class.
        G = nx.cartesian_product(Gnew, Gold, create_using=None)
    # graph G is done but has labels of the form (1,(2,(3,1)))
    # so relabel
    H = nx.relabel_nodes(G, flatten)
    H.name = "grid_graph(%s)" % dlabel
    return H
Пример #24
0
def generate_product_graph():
    """Generates k cuts for cartesian product of a path and a double tree"""
    k = int(input("k for product of tree & path:"))
    trials = int(input("number of trials:"))
    prodfname = input("output file:")
    prodfname = "hard_instances/" + prodfname
    prodfile = open(prodfname, "wb", 0)
    h = int(input("height of the tree: "))
    H1 = nx.balanced_tree(2, h)
    H2 = nx.balanced_tree(2, h)
    H = nx.disjoint_union(H1, H2)
    n = H.number_of_nodes()
    p = math.pow(2, h + 1) - 1
    H.add_edge(0, p)
    n = 4 * math.sqrt(n)
    n = math.floor(n)
    print("Length of path graph: " + str(n))
    G = nx.path_graph(n)
    tmpL = nx.normalized_laplacian_matrix(G).toarray()
    T = nx.cartesian_product(G, H)
    A = nx.adjacency_matrix(T).toarray()
    L = nx.normalized_laplacian_matrix(T).toarray()
    (tmpw, tmpv) = la.eigh(L)
    tmp = 2 * math.sqrt(tmpw[1])
    print("cheeger upperbound:" + str(tmp))
    (w, v) = spectral_projection(L, k)
    lambda_k = w[k - 1]
    tmp_str = "Cartesian product of balanced tree of height " + str(h)
    tmp_str += " and path of length " + str(n - 1) + "\n"
    tmp_str += "k = " + str(k) + ", "
    tmp_str += "trials = " + str(trials) + "\n\n\n"
    tmp_str = tmp_str.encode("utf-8")
    prodfile.write(tmp_str)
    k_cuts_list = lrtv(A, v, k, lambda_k, trials, prodfile)
    plotname = prodfname + "plot"
    plot(k_cuts_list, plotname)
    for i in range(len(k_cuts_list)):
        k_cuts = k_cuts_list[i]
        tmp_str = list(map(str, k_cuts))
        tmp_str = " ".join(tmp_str)
        tmp_str += "\n\n"
        tmp_str = tmp_str.encode("utf-8")
        prodfile.write(tmp_str)
Пример #25
0
    def test_weighted_graph(self):

        m = 4
        n = 3
        g = nx.cartesian_product(nx.cycle_graph(m), nx.cycle_graph(n))

        nx.set_edge_attributes(g, 1, 'weight')

        for i in range(m):
            for j in range(n):
                if i % 2 == 0:
                    if j < (n - 1):
                        g[(i, j)][(i, j + 1)]['weight'] = 100
                    else:
                        if i < (m - 1):
                            g[(i, j)][(i + 1, j)]['weight'] = 100
                        else:
                            g[(i, j)][(0, j)]['weight'] = 100
                else:
                    if j > 0:
                        g[(i, j)][(i, j - 1)]['weight'] = 100
                    else:
                        if i < (m - 1):
                            g[(i, j)][(i + 1, j)]['weight'] = 100
                        else:
                            g[(i, j)][(0, j)]['weight'] = 100

        g = nx.convert_node_labels_to_integers(g)
        cbs_lb = n * m * 100
        cbs_ub = cbs_lb + (n * m)**2 / 2

        # shuffle labels
        random_labeling = generate_random_labeling(g)
        g = nx.relabel_nodes(g, random_labeling)

        assert cyclic_bandwidth_sum(g, weight_attr='weight') >= cbs_lb

        # relabel graph according to cbs
        mach_labeling = get_mach_labeling(g, weight_attr='weight')
        g = nx.relabel_nodes(g, mach_labeling)

        assert cyclic_bandwidth_sum(g, weight_attr='weight') >= cbs_lb
        assert cyclic_bandwidth_sum(g, weight_attr='weight') <= cbs_ub
Пример #26
0
def cartesian_product(request):
    """Function for calculating a cartesian product of 2 graphs

    This function is getting 2 graphs and return their cartesian
    product
    """
    raw_data = request.GET.dict()
    first_graph = raw_data["first_graph"]
    sec_graph_data = Graph.objects.get(id=int(raw_data["second_graph"]))
    with open(sec_graph_data.path_to_graph) as file:
        second_graph = json.load(file)
    second_graph = json.loads(second_graph["graph"])
    first_graph = json.loads(first_graph)
    first_matrix = np.matrix(cn.to_matrix(first_graph))
    second_matrix = np.matrix(cn.to_matrix(second_graph))
    first_graph_nx = create_graph(first_matrix, first_graph)
    second_graph_nx = create_graph(second_matrix, second_graph)
    product = nx.cartesian_product(first_graph_nx, second_graph_nx)
    data = cn.to_json(nx.to_numpy_matrix(product).tolist(), first_graph)
    return JsonResponse(data)
Пример #27
0
def merge_graph(g1, g2, merge_type):  # 聚合图
    """
    :param g1: 第一个图对象
    :param g2:  第二个图对象
    :param merge_type:  聚合方式("subgraph","union","dis_union", "cartesian", "compose")
    :return:
    """
    if merge_type == "subgraph":
        new_g = nx.subgraph(g1, g2)  # g2为 list,
    elif merge_type == "union":  # 不相交的拼接
        new_g = nx.union(g1, g2)
    elif merge_type == "dis_union":  # 所有节点都不同的不相交拼接
        new_g = nx.disjoint_union(g1, g2)
    elif merge_type == "cartesian":  # 笛卡尔乘积图
        new_g = nx.cartesian_product(g1, g2)
    elif merge_type == "compose":
        new_g = nx.compose(g1, g2)  # 与g1 一样新的图
    else:
        raise ValueError("error merge_type")
    return new_g
Пример #28
0
def product_graph_2(g1: nx.MultiDiGraph,
                    g2: nx.MultiDiGraph) -> nx.MultiDiGraph:
    cp = nx.cartesian_product(g1, g2)
    prod = nx.MultiDiGraph()

    for edge in cp.edges(data=True):
        s_tup, d_tup, data = edge
        prod.add_edge(
            reduce(lambda acc, n: acc.union(n), s_tup),
            reduce(lambda acc, n: acc.union(n), d_tup),
            computers=data["computers"],
        )

    # the cartesian product can also contain nodes that
    # are not connected.
    for cart_node in cp.nodes:
        prod_node = reduce(lambda acc, n: acc.union(n), cart_node)

        prod.add_node(prod_node)

    return prod
Пример #29
0
def grid_graph(dim, periodic=False):
    """ Return the n-dimensional grid graph.

    'dim' is a list with the size in each dimension or an
    iterable of nodes for each dimension. The dimension of
    the grid_graph is the length of the list 'dim'.

    E.g. G=grid_graph(dim=[2, 3]) produces a 2x3 grid graph.

    E.g. G=grid_graph(dim=[range(7, 9), range(3, 6)]) produces a 2x3 grid graph.

    If periodic=True then join grid edges with periodic boundary conditions.

    """
    dlabel = "%s" % dim
    if dim == []:
        G = empty_graph(0)
        G.name = "grid_graph(%s)" % dim
        return G
    if periodic:
        func = cycle_graph
    else:
        func = path_graph

    dim = list(dim)
    current_dim = dim.pop()
    G = func(current_dim)
    while len(dim) > 0:
        current_dim = dim.pop()
        # order matters: copy before it is cleared during the creation of Gnew
        Gold = G.copy()
        Gnew = func(current_dim)
        # explicit: create_using=None
        # This is so that we get a new graph of Gnew's class.
        G = nx.cartesian_product(Gnew, Gold)
    # graph G is done but has labels of the form (1, (2, (3, 1)))
    # so relabel
    H = nx.relabel_nodes(G, flatten)
    H.name = "grid_graph(%s)" % dlabel
    return H
Пример #30
0
    def make_ConformationalNetwork(self):

        neigh = NearestNeighbors(radius=1, metric='chebyshev')
        neigh.fit(self.ijk_centers)
        net_centers = nx.from_scipy_sparse_matrix(
            neigh.radius_neighbors_graph())
        del (neigh)

        net_rotations = nx.Graph()
        net_rotations.add_nodes_from(range(self.num_rotations))
        for ii in range(self.num_rotations):
            neighs = hp.get_all_neighbours(self.nside, ii, nest=False)
            neighs[neighs == -1] = 0
            net_rotations.add_edges_from(
                zip(np.full(neighs.shape[0], ii), neighs))
        del (neighs)

        net = nx.cartesian_product(net_centers, net_rotations)

        del (net_rotations, net_centers)

        return net
def get_N(cartesian1, cartesian2, remove1, remove2):
    product_graph = nx.cartesian_product(cartesian1, cartesian2)
    product_graph.remove_nodes_from(remove1.edges())
    product_graph.remove_nodes_from(remove2.edges())

    return product_graph
Пример #32
0
def test_cartesian_product_null():
    null = nx.null_graph()
    empty10 = nx.empty_graph(10)
    K3 = nx.complete_graph(3)
    K10 = nx.complete_graph(10)
    P3 = nx.path_graph(3)
    P10 = nx.path_graph(10)
    # null graph
    G = nx.cartesian_product(null, null)
    assert_true(nx.is_isomorphic(G, null))
    # null_graph X anything = null_graph and v.v.
    G = nx.cartesian_product(null, empty10)
    assert_true(nx.is_isomorphic(G, null))
    G = nx.cartesian_product(null, K3)
    assert_true(nx.is_isomorphic(G, null))
    G = nx.cartesian_product(null, K10)
    assert_true(nx.is_isomorphic(G, null))
    G = nx.cartesian_product(null, P3)
    assert_true(nx.is_isomorphic(G, null))
    G = nx.cartesian_product(null, P10)
    assert_true(nx.is_isomorphic(G, null))
    G = nx.cartesian_product(empty10, null)
    assert_true(nx.is_isomorphic(G, null))
    G = nx.cartesian_product(K3, null)
    assert_true(nx.is_isomorphic(G, null))
    G = nx.cartesian_product(K10, null)
    assert_true(nx.is_isomorphic(G, null))
    G = nx.cartesian_product(P3, null)
    assert_true(nx.is_isomorphic(G, null))
    G = nx.cartesian_product(P10, null)
    assert_true(nx.is_isomorphic(G, null))
Пример #33
0
def test_cartesian_product_raises():
    P = nx.cartesian_product(nx.DiGraph(), nx.Graph())
    'hypercube': nx.hypercube_graph
}


pyramid = gen.pyramid_prism(4, 0)


pwff = []
acff = []
classes = []
for graph_type, generator in GRAPHS.items():
    pwrow = [graph_type]
    acrow = [graph_type]
    crow = [graph_type]
    for i in range(MIN, MAX_1):
        graph = nx.cartesian_product(pyramid, generator(i))
        w_obj = polygraph.walk_classes(graph)
        w = w_obj['eig_matrix']
        pwrow.append(polygraph.pair_wise_flip_flopping(w))
        acrow.append(polygraph.average_condition_flip_flopping(w))
        crow.append(w_obj['num_classes'])
    pwff.append(pwrow)
    acff.append(acrow)
    classes.append(crow)

print('Number of Walk Classes')
print(tabulate(
    classes,
    tablefmt='grid',
    headers=['Graph', *[i for i in range(MIN, MAX_1)]]
))
def create_torus(n):
    C = nx.cycle_graph(n)
    torus = nx.cartesian_product(C,C)
    torus.graph["size"] = n
    return torus
""" Union disjointe de graphes """
#Change les labels en entiers
GH1=nx.disjoint_union(G,H)
GH1.nodes()
GH1.edges()

""" Composition de graphes """
GH2=nx.compose(G,H)
GH2.nodes()
#['a', 1, 'c', 'b', 4, 'd', 2, 3]
GH2.edges()
#[('a', 'b'), (1, 2), ('c', 'b'), ('c', 'd'), (4, 3), (2, 3)]

""" Produit cartesien """
GH3=nx.cartesian_product(G,H)
GH3.nodes()
#[(1, 'c'), (3, 'c'), (1, 'b'), (3, 'b'), (2, 'a'), (3, 'a'), (4, 'd'), (1, 'd'), (2, 'b'), (4, 'b'), (2, 'c'), (4, 'c'), (1, 'a'), (4, 'a'), (2, 'd'), (3, 'd')]
GH3.edges()
#[((1, 'c'), (1, 'd')), ((1, 'c'), (1, 'b')), ((1, 'c'), (2, 'c')), ((3, 'c'), (4, 'c')), ((3, 'c'), (2, 'c')), ((3, 'c'), (3, 'b')), ((3, 'c'), (3, 'd')), ((1,'b'), (1, 'a')), ((1, 'b'), (2, 'b')), ((3, 'b'), (3, 'a')), ((3, 'b'), (2, 'b')), ((3, 'b'), (4, 'b')), ((2, 'a'), (3, 'a')), ((2, 'a'), (1, 'a')), ((2, 'a'),(2, 'b')), ((3, 'a'), (4, 'a')), ((4, 'd'), (4, 'c')), ((4, 'd'), (3, 'd')), ((1, 'd'), (2, 'd')), ((2, 'b'), (2, 'c')), ((4, 'b'), (4, 'c')), ((4, 'b'), (4, 'a')), ((2, 'c'), (2, 'd')), ((2, 'd'), (3, 'd'))]

""" Complement """
#Graphe complementaire
G1=nx.complement(G)
G1.nodes()
G1.edges()

""" Intersection de graphes """
# Les noeuds de H et G doivent etre les memes
H.clear()
H.add_nodes_from([1,2,3,4])
Пример #37
0
def test_cartesian_product_null():
    null=nx.null_graph()
    empty10=nx.empty_graph(10)
    K3=nx.complete_graph(3)
    K10=nx.complete_graph(10)
    P3=nx.path_graph(3)
    P10=nx.path_graph(10)
    # null graph
    G=cartesian_product(null,null)
    assert_true(nx.is_isomorphic(G,null))
    # null_graph X anything = null_graph and v.v.
    G=cartesian_product(null,empty10)
    assert_true(nx.is_isomorphic(G,null))
    G=cartesian_product(null,K3)
    assert_true(nx.is_isomorphic(G,null))
    G=cartesian_product(null,K10)
    assert_true(nx.is_isomorphic(G,null))
    G=cartesian_product(null,P3)
    assert_true(nx.is_isomorphic(G,null))
    G=cartesian_product(null,P10)
    assert_true(nx.is_isomorphic(G,null))
    G=cartesian_product(empty10,null)
    assert_true(nx.is_isomorphic(G,null))
    G=cartesian_product(K3,null)
    assert_true(nx.is_isomorphic(G,null))
    G=cartesian_product(K10,null)
    assert_true(nx.is_isomorphic(G,null))
    G=cartesian_product(P3,null)
    assert_true(nx.is_isomorphic(G,null))
    G=cartesian_product(P10,null)
    assert_true(nx.is_isomorphic(G,null))
Пример #38
0
def test_cartesian_product_raises():
    P = cartesian_product(nx.DiGraph(), nx.Graph())
def compute_random_walk_kernel(G1, G2):
    pdg = nx.cartesian_product(G1, G2)
    lbda = -0.1
    adj_matrix = np.array(nx.adjacency_matrix(pdg).todense())
    return rwk_f(lbda, pdg, adj_matrix)
Пример #40
0
'''
Theorem 3 of

Mahadevan, S., & Maggioni, M. (2007). Proto-value functions: A Laplacian
framework for learning representation and control in Markov decision
processes. Journal of Machine Learning Research, 8

states that the eigenvalues of the Laplacian of graph G that is the cartesian
product of two graphs G1 and G2, are the sums of all the combination of the
eigenvalues of G1 and G2.

This program illustrates this by generating a grid as the cartesian product of
two paths.
'''

from itertools import product
import networkx as nx

n = 5
P = nx.path_graph(n)
G = nx.cartesian_product(P, P)

ev_P = nx.laplacian_spectrum(P)
ev_G = nx.laplacian_spectrum(G).real

ev = []
for i,j in product(range(n), repeat=2):
    ev.append(ev_P[i] + ev_P[j])


Пример #41
0
    return kovalev_code(G, G)

if __name__ == "__main__":
    pl.close("all")
    d = 7

    # gridded torus
    pl.figure()
    pl.title("%i-by-%i regular paving of the torus" % (d, d))
    nx.draw_graphviz(tanner_graph(tanner_cartesian_power(tanner_cycle(d), 2)),
                     node_size=30, with_labels=False)

    # Tillich-Zemor hypergraph-product constructions
    s1 = s2 = tanner_cycle(d)
    s = tanner_cartesian_product(s1, s2, split=True)
    t = nx.cartesian_product(tanner_graph(s1), tanner_graph(s2))
    pl.figure()
    pl.suptitle("Sum decomposition of Tanner graph products")
    for j, support in enumerate([s1, s2]):
        ax = pl.subplot("32%i" % (j + 1))
        ax.set_title("t%i = tanner(%s)" % (j + 1, support))
        tj = tanner_graph(support)
        nx.draw_graphviz(tj, with_labels=0, node_size=30)
    ax = pl.subplot("312")
    ax.set_title("t1 x t2 =: t =: t1' + t2'")
    nx.draw_graphviz(t, with_labels=0, node_size=30)
    for j, sj in enumerate(s):
        ax = pl.subplot("32%i" % (4 + j + 1))
        ax.set_title("t%i'" % (j + 1))
        tj = tanner_graph(sj)
        nx.draw_graphviz(tj, with_labels=0, node_size=30)
Пример #42
0
                    break
                if ch != '\n':
                    word.append(ch)
            if word in vocab:
                word_vecs[word] = np.fromstring(f.read(binary_len), dtype='float32')
            else:
                f.read(binary_len)
    return word_vecs


G = nx.complete_graph(3)
nx.set_node_attributes(G, name='label', values=G.degree())
H = nx.balanced_tree(2, 2)
nx.set_node_attributes(H, name='label', values=H.degree())

Gp = nx.cartesian_product(G, H)


# nx.draw(G, with_labels=True)
# plt.show()
# nx.draw(H, with_labels=True)
# plt.show()


# nx.draw(Gp, with_labels=True)
# plt.show()


def _dict_product(d1, d2):
    return dict((k, (d1.get(k), d2.get(k))) for k in set(d1) | set(d2))