コード例 #1
0
    def test_is_semieulerian(self):
        # Test graphs with Eulerian paths but no cycles return True.
        assert nx.is_semieulerian(nx.path_graph(4))
        G = nx.path_graph(6, create_using=nx.DiGraph)
        assert nx.is_semieulerian(G)

        # Test graphs with Eulerian cycles return False.
        assert not nx.is_semieulerian(nx.complete_graph(5))
        assert not nx.is_semieulerian(nx.complete_graph(7))
        assert not nx.is_semieulerian(nx.hypercube_graph(4))
        assert not nx.is_semieulerian(nx.hypercube_graph(6))
コード例 #2
0
ファイル: test_euler.py プロジェクト: 4c656554/networkx
    def test_is_eulerian(self):
        assert_true(is_eulerian(nx.complete_graph(5)))
        assert_true(is_eulerian(nx.complete_graph(7)))
        assert_true(is_eulerian(nx.hypercube_graph(4)))
        assert_true(is_eulerian(nx.hypercube_graph(6)))

        assert_false(is_eulerian(nx.complete_graph(4)))
        assert_false(is_eulerian(nx.complete_graph(6)))
        assert_false(is_eulerian(nx.hypercube_graph(3)))
        assert_false(is_eulerian(nx.hypercube_graph(5)))

        assert_false(is_eulerian(nx.petersen_graph()))
        assert_false(is_eulerian(nx.path_graph(4)))
コード例 #3
0
    def test_is_eulerian(self):
        assert nx.is_eulerian(nx.complete_graph(5))
        assert nx.is_eulerian(nx.complete_graph(7))
        assert nx.is_eulerian(nx.hypercube_graph(4))
        assert nx.is_eulerian(nx.hypercube_graph(6))

        assert not nx.is_eulerian(nx.complete_graph(4))
        assert not nx.is_eulerian(nx.complete_graph(6))
        assert not nx.is_eulerian(nx.hypercube_graph(3))
        assert not nx.is_eulerian(nx.hypercube_graph(5))

        assert not nx.is_eulerian(nx.petersen_graph())
        assert not nx.is_eulerian(nx.path_graph(4))
コード例 #4
0
def _hypercube(n):
    """Hypercube's nodes are cube coordinates, which isn't so nice"""
    G = nx.hypercube_graph(int(np.log2(n) + .1))
    G = nx.relabel_nodes(
        G, {n: int('0b' + ''.join(str(i) for i in n), 2)
            for n in G.node})
    return G
コード例 #5
0
def hypercubegraph(n):
    '''
    n-dimensional hypercube
    '''
    g = BaseGraph()
    g.load_from_nx(nx.hypercube_graph(n))
    return g
コード例 #6
0
def construct_H_cube():
    G = nx.hypercube_graph(3)

    # convert node labels to ints
    G = nx.relabel_nodes(G, lambda v: to_int(v))

    N = 2**G.order()
    # H = np.zeros( (N, N) )

    H = construct_Hv(G, 0)
    # for v in G.nodes():
    for v in range(1, G.order()):
        # print(v)
        Hv = construct_Hv(G, v)
        # H = and_hams(H, Hv)
        H = H + Hv

    # nx.draw_networkx(G)
    # plt.show()
    # print(DataFrame(H))
    # print(np.matrix(H))
    # Hm = np.matrix(H)
    diag = np.diagonal(H)
    for idx, d in enumerate(diag):
        cut = format(idx, '#010b')[2:]
        print(idx, d, cut)
コード例 #7
0
def generateNonGreedyGray(bits=5):
    assert bits >= 3, "ngg only exists for l >= 3"
    g = nx.hypercube_graph(bits)
    l = bits - 3
    zero = tuple([0] * l) + (0, 0, 0)
    one = tuple([0] * l) + (0, 0, 1)
    two = tuple([0] * l) + (0, 1, 1)
    three = tuple([0] * l) + (1, 1, 1)
    g.remove_node(zero)
    g.remove_node(one)
    g.remove_node(two)
    g.remove_node(three)
    cycle = [zero, one, two, three] + hamilton(g, tuple([0] * l) + (1, 0, 1))

    stringifiedCycle = []

    for node in cycle:
        string = ''
        for coord in node:
            string += str(coord)
        stringifiedCycle.append(string)

    repfn = {stringifiedCycle[i]: i for i in range(len(stringifiedCycle))}
    nongreedy = rp.Representation(repfn,
                                  "Non Greedy Gray " + str(bits) + "-bits")
    return nongreedy
コード例 #8
0
	def __init__(self, N):
		self.name = 'Hypercube graph HyperCube_%i' % N
		self.N = N
		self.G = nx.hypercube_graph(N)

		self.params = dict()
		self.state = None
コード例 #9
0
ファイル: minigc.py プロジェクト: zhaojiayuX/dgl
 def _gen_hypercube(self, n):
     for _ in range(n):
         num_v = np.random.randint(self.min_num_v, self.max_num_v)
         g = nx.hypercube_graph(int(math.log(num_v, 2)))
         g = nx.convert_node_labels_to_integers(g)
         self.graphs.append(g)
         self.labels.append(4)
コード例 #10
0
 def createHypercube(self, algorithm, dimension=10):
     # type: (Union[AlgorithmCtorFactory,collections.abc.Sequence,Callable[[],pg.algorithm]], int) -> Topology
     '''
     Creates a hypercube topology.
     '''
     return self._processTopology(nx.hypercube_graph(dimension), algorithm,
                                  Topology)
コード例 #11
0
ファイル: Main.py プロジェクト: naushad-rahman/rysim
def generate_connection_graph(graph_type, params, count):
    lower_type = graph_type.lower()
    if lower_type == 'complete':
        assert (len(params) == 0)
        return networkx.complete_graph(count)
    elif lower_type == 'complete-bipartite':
        assert (len(params) == 2)
        assert (int(params[0]) > 0.0)
        assert (int(params[1]) > 0.0)
        n1 = int(round(count * float(params[0]) / float(params[1])))
        n2 = int(round(count * float(params[1]) / float(params[0])))
        n1 = 1 if n1 < 1 else n1
        n2 = 1 if n2 < 1 else n2
        return networkx.complete_bipartite_graph(n1, n2)
    elif lower_type == 'circular-ladder':
        assert (len(params) == 0)
        return networkx.circular_ladder_graph(count)
    elif lower_type == 'cycle':
        assert (len(params) == 0)
        return networkx.cycle_graph(count)
    elif lower_type == 'periodic-2grid':
        assert (len(params) == 2)
        assert (int(params[0]) > 0.0)
        assert (int(params[1]) > 0.0)
        width = int(round(math.sqrt(count * float(params[0]) / float(params[1]))))
        height = int(round(math.sqrt(count * float(params[1]) / float(params[0]))))
        width = 1 if width < 1 else width
        height = 1 if height < 1 else height
        return networkx.grid_2d_graph(width, height, True)
    elif lower_type == 'nonperiodic-2grid':
        assert (len(params) == 2)
        assert (int(params[0]) > 0.0)
        assert (int(params[1]) > 0.0)
        width = int(round(math.sqrt(count * float(params[0]) / float(params[1]))))
        height = int(round(math.sqrt(count * float(params[1]) / float(params[0]))))
        width = 1 if width < 1 else width
        height = 1 if height < 1 else height
        return networkx.grid_2d_graph(width, height, False)
    elif lower_type == 'hypercube':
        assert (len(params) == 0)
        return networkx.hypercube_graph(int(round(math.log(count, 2))))
    elif lower_type == 'star':
        assert (len(params) == 0)
        return networkx.star_graph(count - 1)
    elif lower_type == 'wheel':
        assert (len(params) == 0)
        return networkx.wheel_graph(count)
    elif lower_type == 'erdos-reyni':
        assert (len(params) == 1)
        return networkx.erdos_renyi_graph(count, float(params[0]))
    elif lower_type == 'watts-strogatz':
        assert (len(params) == 2)
        if int(params[0]) >= count / 2:
            k = int(count / 2 - 1)
        else:
            k = int(params[0])
        return networkx.connected_watts_strogatz_graph(count, k, int(params[1]))
    else:
        print "Unknown graph type {}".format(lower_type)
        assert False
コード例 #12
0
ファイル: Landscapes.py プロジェクト: adrianapaza/NBA-NKC
def sorted_from_NK(landscape):
    df = landscape.sort_values(by="Fitness")
    fitnesses = list(df.Fitness)

    N = len(df.iloc[0]["Location"])
    hypercube = nx.hypercube_graph(N)
    chosen_peak = tuple((np.random.rand(N) > 0.5).astype(int))

    node_dict = nx.shortest_path_length(hypercube, chosen_peak)
    distance_dict = defaultdict(list)
    max_dist = 0
    for key, dist in node_dict.items():
        distance_dict[dist].append(key)
        if dist > max_dist:
            max_dist = dist

    sorted_landscape = {}
    sorted_landscape["".join([str(i) for i in chosen_peak
                              ])] = (fitnesses.pop(), chosen_peak)

    for dist in range(1,
                      max_dist + 1):  # node_dict has zero key...so weird IMHO
        for location in distance_dict[dist]:
            sorted_landscape["".join([str(i) for i in location
                                      ])] = (fitnesses.pop(), location)

    return pd.DataFrame.from_dict(sorted_landscape,
                                  orient="index",
                                  columns=["Fitness", "Location"])
コード例 #13
0
ファイル: Landscapes.py プロジェクト: adrianapaza/NBA-NKC
def landscape_as_digraph(df):

    N = len(df.iloc[0].name)
    hypercube = nx.hypercube_graph(N)

    digraph = nx.DiGraph()
    digraph.add_nodes_from(hypercube.nodes())

    fitness_diff_dict = {}
    fitness_dict = {}
    for focal_row in df.itertuples():
        source_fit = focal_row.Fitness
        Neighbors = df[df['Location'].apply(lambda row: sum(
            abs(np.array(row) - np.array(focal_row.Location))) == 1)]
        fitness_dict[focal_row.Location] = source_fit
        for neighbor in Neighbors.itertuples():
            fitness_diff_dict[(
                focal_row.Location,
                neighbor.Location)] = 1 + source_fit - neighbor.Fitness
            fitness_diff_dict[(
                neighbor.Location,
                focal_row.Location)] = 1 + neighbor.Fitness - source_fit

    nx.set_node_attributes(digraph, fitness_dict, "fitness")
    nx.set_edge_attributes(digraph, fitness_diff_dict, "fitness_difference")

    return digraph
コード例 #14
0
 def test_loader(self):
     graph = networkx.hypercube_graph(3)
     nb_graph = networkx_loader.load_graph(graph)
     expected = {'edges':
                 [{'id': 0, 'target': '(0, 1, 0)', 'source': '(0, 1, 1)'},
                  {'id': 1, 'target': '(0, 0, 1)', 'source': '(0, 1, 1)'},
                  {'id': 2, 'target': '(1, 1, 1)', 'source': '(0, 1, 1)'},
                  {'id': 3, 'target': '(1, 0, 0)', 'source': '(0, 0, 0)'},
                  {'id': 4, 'target': '(0, 1, 0)', 'source': '(0, 0, 0)'},
                  {'id': 5, 'target': '(0, 0, 1)', 'source': '(0, 0, 0)'},
                  {'id': 6, 'target': '(1, 0, 0)', 'source': '(1, 1, 0)'},
                  {'id': 7, 'target': '(0, 1, 0)', 'source': '(1, 1, 0)'},
                  {'id': 8, 'target': '(1, 1, 1)', 'source': '(1, 1, 0)'},
                  {'id': 9, 'target': '(1, 0, 1)', 'source': '(1, 0, 0)'},
                  {'id': 10, 'target': '(1, 0, 1)', 'source': '(0, 0, 1)'},
                  {'id': 11, 'target': '(1, 0, 1)', 'source': '(1, 1, 1)'}],
                 'nodes': [
                     {'id': '(0, 1, 1)', 'label': '(0, 1, 1)'},
                     {'id': '(1, 0, 0)', 'label': '(1, 0, 0)'},
                     {'id': '(0, 0, 1)', 'label': '(0, 0, 1)'},
                     {'id': '(1, 0, 1)', 'label': '(1, 0, 1)'},
                     {'id': '(0, 0, 0)', 'label': '(0, 0, 0)'},
                     {'id': '(1, 1, 1)', 'label': '(1, 1, 1)'},
                     {'id': '(1, 1, 0)', 'label': '(1, 1, 0)'},
                     {'id': '(0, 1, 0)', 'label': '(0, 1, 0)'}]}
     self.assertEqual(nb_graph.as_dict(), expected)
コード例 #15
0
def classic_graphs():
    print("Balanced Tree")
    BG = nx.balanced_tree(3, 2)
    draw_graph(BG)
    print("Barbell Graph")
    BBG = nx.barbell_graph(3, 2)
    draw_graph(BBG)
    print("Complete Graph")
    CG = nx.complete_graph(10)
    draw_graph(CG)
    print("Complete Multipartite Graph")
    CMG = nx.complete_multipartite_graph(1, 2, 10)
    print([CMG.node[u]['block'] for u in CMG])
    print(CMG.edges(0))
    print(CMG.edges(2))
    print(CMG.edges(4))
    draw_graph(CMG)
    print("Circular Ladder Graph")
    CLG = nx.circular_ladder_graph(5)
    draw_graph(CLG)
    print("Dorogovtsev Goltsev Mendes Graph")
    DGMG = nx.dorogovtsev_goltsev_mendes_graph(3)
    draw_graph(DGMG)
    print("Empty Graph")
    EG = nx.empty_graph(5, create_using=nx.DiGraph())
    draw_graph(EG)
    print("Grid 2D Graph")
    G2DG = nx.grid_2d_graph(5, 6)
    draw_graph(G2DG)
    print("Grid Graph")
    GDG = nx.grid_graph(dim=[5, 2])
    draw_graph(GDG)
    print("Hypercube Graph")
    HG = nx.hypercube_graph(3)
    draw_graph(HG)
    print("Ladder Graph")
    LG = nx.ladder_graph(8)
    draw_graph(LG)
    print("Ladder Graph")
    LG = nx.ladder_graph(8)
    draw_graph(LG)
    print("Lollipop Graph")
    LPG = nx.lollipop_graph(n=6, m=4)
    draw_graph(LPG)
    print("Null Graph")
    NG = nx.null_graph()
    draw_graph(NG)
    print("Path Graph")
    PG = nx.path_graph(16)
    draw_graph(PG)
    print("Star Graph")
    SG = nx.star_graph(16)
    draw_graph(SG)
    print("Trivial Graph")
    TG = nx.trivial_graph()
    draw_graph(TG)
    print("Wheel Graph")
    WG = nx.wheel_graph(n=18)
    draw_graph(WG)
コード例 #16
0
def Graph():
    # Diameter = n
    # kmax = 2
    # DFS = Should traverse in order until b reached
    # BFS = 
    G = nx.hypercube_graph(3)

    return G
def test_centralised_spanning_tree():
    graph = nx.hypercube_graph(4)  # 4 dimensional
    sm = Simulation(embedding_graph=graph,
                    process_type=CentralisedSpanningTreeProcess,
                    channel_type=DelayedChannel)
    list(sm.node_map.keys())[1].is_initiator = True

    sm.run(quit_after=4.0)
コード例 #18
0
def test_token_ring():
    graph = nx.hypercube_graph(4)  # 4 dimensional
    sm = Simulation(embedding_graph=graph,
                    process_type=TokenRingProcess,
                    channel_type=DelayedChannel)
    list(sm.node_map.keys())[1].is_initiator = True

    sm.run(quit_after=4.0)
コード例 #19
0
def test_basic_depth_first_traversal():
    graph = nx.hypercube_graph(4)  # 4 dimensional
    sm = Simulation(embedding_graph=graph,
                    process_types=[BasicDepthFirstTraversalProcess],
                    channel_type=DelayedChannel)
    list(sm.node_map.keys())[1].is_initiator = True

    sm.run(quit_after=12.0)
コード例 #20
0
def test_synchronizer_alpha():
    graph = nx.hypercube_graph(4)  # 4 dimensional
    sm = Simulation(embedding_graph=graph,
                    process_types=[SynchronizerAlphaProcess],
                    channel_type=DelayedChannel)
    list(sm.node_map.keys())[1].is_initiator = True

    sm.run(quit_after=4.0)
コード例 #21
0
def hypercube_graph(n=None, dim=None):
    if n is None and dim is None:
        return nx.empty_graph()
    if dim is None:
        dim = round(math.log(n, 2))
    G = nx.hypercube_graph(dim)
    G.name = 'hypercube'
    return G
コード例 #22
0
def test_echo():
    graph = nx.hypercube_graph(4)  # 4 dimensional
    sm = Simulation(embedding_graph=graph,
                    process_types=[EchoProcess, TerminatingEchoProcess],
                    channel_type=DelayedChannel)
    list(sm.node_map.keys())[1].is_initiator = True

    sm.run(quit_after=4.0)
コード例 #23
0
 def test_special_cases(self):
     for n, H in [
         (0, nx.null_graph()),
         (1, nx.path_graph(2)),
         (2, nx.cycle_graph(4)),
         (3, nx.cubical_graph()),
     ]:
         G = nx.hypercube_graph(n)
         assert nx.could_be_isomorphic(G, H)
コード例 #24
0
def test_echo():
    graph = nx.hypercube_graph(4)  # 4 dimensional
    sm = Simulation(embedding_graph=graph,
                    process_type=TerminatingEchoProcess,
                    channel_type=DelayedChannel)
    for a in sm.node_map:
        a.is_initiator = True
        break

    sm.run(quit_after=4.0)
コード例 #25
0
def test_spanning_tree():
    graph = nx.hypercube_graph(4)  # 4 dimensional
    sm = Simulation(embedding_graph=graph,
                    process_types=[SpanningTreeProcess],
                    channel_type=DelayedChannel)
    list(sm.node_map.keys())[0].is_initiator = True
    #for a in sm.node_map:
    #    a.is_initiator = True
    #    break

    sm.run(quit_after=4.0)
コード例 #26
0
def test_networkx_graphs():
	G = nx.path_graph(10)
	mc_srw = mkm.nx_graph_srw(G)
	mc_lswr = mkm.nx_graph_lazy_srw(G)

	G = nx.hypercube_graph(10)
	print nx.number_of_nodes(G)
	mkm.nx_graph_lazy_srw(G)

	G = nx.complete_graph(50)
	print mkm.nx_graph_nbrw(G).get_n()
コード例 #27
0
def test_networkx_graphs():
    G = nx.path_graph(10)
    mc_srw = mkm.nx_graph_srw(G)
    mc_lswr = mkm.nx_graph_lazy_srw(G)

    G = nx.hypercube_graph(10)
    print nx.number_of_nodes(G)
    mkm.nx_graph_lazy_srw(G)

    G = nx.complete_graph(50)
    print mkm.nx_graph_nbrw(G).get_n()
コード例 #28
0
    def test_ladder_graph(self):
        for i, G in [(0, nx.empty_graph(0)), (1, nx.path_graph(2)),
                     (2, nx.hypercube_graph(2)), (10, nx.grid_graph([2, 10]))]:
            assert is_isomorphic(nx.ladder_graph(i), G)

        pytest.raises(nx.NetworkXError,
                      nx.ladder_graph,
                      2,
                      create_using=nx.DiGraph)

        g = nx.ladder_graph(2)
        mg = nx.ladder_graph(2, create_using=nx.MultiGraph)
        assert_edges_equal(mg.edges(), g.edges())
コード例 #29
0
def compare_times(gtype, n_max, n_min=2, chords=0):
    """
    Compare computational times between the Deletion-Contraction algorithm, and its optimized version
    :param gtype: <GType> graph type (enum object)
    :param n_max: maximum number of nodes
    :param n_min: minimum number of nodes (2 by default)
    :param chords: number of chords (only in the case of random hamiltonian graphs), 0 by default
    :return: dictionary with all the times where <key=nodes, value = both times (pair object)
    """
    print("----------------------------------------------", gtype.name,
          "------------------------------------------------")
    times = dict()
    for n in range(n_min, n_max + 1):
        print("\n-----------> n =", n)
        if gtype == GType.Hypercube:
            g = nx.hypercube_graph(n)
        elif gtype == GType.Grid:
            g = nx.grid_graph([n, n])
        elif gtype == GType.CircularLadder:
            g = nx.circular_ladder_graph(n)
        elif gtype == GType.Complete:
            g = nx.complete_graph(n)
        elif gtype == GType.RandomHamiltonian:
            g = GraphTools.gen_random_hamiltonian(n, chords)

        start1 = time.time()
        poly = GraphRel.relpoly_binary_basic(g)
        end1 = time.time()
        t1 = end1 - start1
        print(Utilities.polynomial2binomial(poly))
        print("Basic - ", gtype.name, " ", n, ":", t1)

        start2 = time.time()
        poly = GraphRel.relpoly_binary_improved(g)
        end2 = time.time()
        t2 = end2 - start2
        print(Utilities.polynomial2binomial(poly))
        print("Advanced - ", gtype.name, " ", n, ":", t2)

        times[n] = (t1, t2)
        try:
            print("SP efficientcy compared to basic: ",
                  round(t1 * 100 / t2, 3), "%")

        except (ZeroDivisionError):
            print("SP efficientcy compared to basic: ", round(t1 * 100, 3),
                  "%")
    print(
        "-------------------------------------------------------------------------------------------------------"
    )
    return times
コード例 #30
0
def main():
    #G = nx.drawing.nx_agraph.read_dot('input.dot')
    #G = nx.erdos_renyi_graph(50,0.5)
    G = nx.hypercube_graph(3)
    P = nx.all_pairs_shortest_path_length(G)
    for i in P:
        print(i)
    d = np.asarray(all_pairs_shortest_path(G)) / 1
    print(d)

    #all_three(d)
    Y = MDS(d, geometry='euclidean')
    Y.solve(1000)
    print(Y.calc_stress())
    output_euclidean(G, Y.X)
コード例 #31
0
def generate_index(message_type='ba',
                   n=16,
                   sparsity=0.5,
                   p=0.2,
                   directed=False,
                   seed=123):
    degree = n * sparsity
    known_names = [
        'mcwhole', 'mcwholeraw', 'mcvisual', 'mcvisualraw', 'cat', 'catraw'
    ]
    if message_type == 'er':
        graph = nx.gnm_random_graph(n=n, m=n * degree // 2, seed=seed)
    elif message_type == 'random':
        edge_num = int(n * n * sparsity)
        edge_id = np.random.choice(n * n, edge_num, replace=False)
        edge_index = np.zeros((edge_num, 2), dtype=int)
        for i in range(edge_num):
            edge_index[i, 0] = edge_id[i] // n
            edge_index[i, 1] = edge_id[i] % n
    elif message_type == 'ws':
        graph = connected_ws_graph(n=n, k=degree, p=p, seed=seed)
    elif message_type == 'ba':
        graph = nx.barabasi_albert_graph(n=n, m=degree // 2, seed=seed)
    elif message_type == 'hypercube':
        graph = nx.hypercube_graph(n=int(np.log2(n)))
    elif message_type == 'grid':
        m = degree
        n = n // degree
        graph = nx.grid_2d_graph(m=m, n=n)
    elif message_type == 'cycle':
        graph = nx.cycle_graph(n=n)
    elif message_type == 'tree':
        graph = nx.random_tree(n=n, seed=seed)
    elif message_type == 'regular':
        graph = nx.connected_watts_strogatz_graph(n=n,
                                                  k=degree,
                                                  p=0,
                                                  seed=seed)
    elif message_type in known_names:
        graph = load_graph(message_type)
        edge_index = nx_to_edge(graph, directed=True, seed=seed)
    else:
        raise NotImplementedError
    if message_type != 'random' and message_type not in known_names:
        edge_index = nx_to_edge(graph, directed=directed, seed=seed)
    return edge_index
コード例 #32
0
def large_graph_tests():
    if not total_coloring_test("Complete graph on 7 vertices",
                               networkx.complete_graph(7), 7):
        return False
    if not total_coloring_test("Cycle of length 100",
                               networkx.cycle_graph(100), 4):
        return False
    if not total_coloring_test("Star graph on 200 vertices",
                               networkx.star_graph(200), 201):
        return False
    if not total_coloring_test("Complete bipartite graph on 4+4 vertices",
                               networkx.complete_multipartite_graph(4, 4), 6):
        return False
    if not total_coloring_test("Hypercube of dimension 5",
                               networkx.hypercube_graph(5), 6):
        return False
    return True
コード例 #33
0
def _hypercube(n):
    """Hypercube's nodes are cube coordinates, which isn't so nice"""
    G = nx.hypercube_graph(int(np.log2(n) + .1))
    G = nx.relabel_nodes(G, {n: int('0b' + ''.join(str(i) for i in n), 2)
                             for n in G.node})
    return G
コード例 #34
0
 def test_line_inverse_line_hypercube(self):
     G = nx.hypercube_graph(5)
     H = nx.line_graph(G)
     J = nx.inverse_line_graph(H)
     assert_true(nx.is_isomorphic(G, J))
コード例 #35
0
ファイル: lrtv.py プロジェクト: ionux/k-sparse-cuts
def hypercube():
    """Generates a hypercube"""
    n = int(input("Number of dimensions: "))
    G = nx.hypercube_graph(n)
    return G
コード例 #36
0
 def test092_hypercube_graph(self):
     """ Larger hypercube graph. """
     g = nx.hypercube_graph(13)
     mate1 = mv.max_cardinality_matching( g )
     mate2 = nx.max_weight_matching( g, True )
     self.assertEqual( len(mate1), len(mate2) )
if not os.path.exists(args.output):
    os.makedirs(args.output)

with open(args.output + '/output.csv', 'w') as output:
	helper(output, nx.balanced_tree(2, 5), "balanced_tree") # branching factor, height
	helper(output, nx.barbell_graph(50, 50), "barbell_graph")
	helper(output, nx.complete_graph(50), "complete_graph")
	helper(output, nx.complete_bipartite_graph(50, 50), "complete_bipartite_graph")
	helper(output, nx.circular_ladder_graph(50), "circular_ladder_graph")
	helper(output, nx.cycle_graph(50), "cycle_graph")
	helper(output, nx.dorogovtsev_goltsev_mendes_graph(5), "dorogovtsev_goltsev_mendes_graph")
	helper(output, nx.empty_graph(50), "empty_graph")
	helper(output, nx.grid_2d_graph(5, 20), "grid_2d_graph")
	helper(output, nx.grid_graph([2, 3]), "grid_graph")
	helper(output, nx.hypercube_graph(3), "hypercube_graph")
	helper(output, nx.ladder_graph(50), "ladder_graph")
	helper(output, nx.lollipop_graph(5, 20), "lollipop_graph")
	helper(output, nx.path_graph(50), "path_graph")
	helper(output, nx.star_graph(50), "star_graph")
	helper(output, nx.trivial_graph(), "trivial_graph")
	helper(output, nx.wheel_graph(50), "wheel_graph")
	
	helper(output, nx.random_regular_graph(1, 50, 678995), "random_regular_graph_1")
	helper(output, nx.random_regular_graph(3, 50, 683559), "random_regular_graph_3")
	helper(output, nx.random_regular_graph(5, 50, 515871), "random_regular_graph_5")
	helper(output, nx.random_regular_graph(8, 50, 243579), "random_regular_graph_8")
	helper(output, nx.random_regular_graph(13, 50, 568324), "random_regular_graph_13")
	
	
	helper(output, nx.diamond_graph(), "diamond_graph")
コード例 #38
0
script, filename1, filename2 = argv
print("usage: python adiabaticv2.py info_file distribution_file")
infofile = open(filename1, 'w') # writing file
infofile.truncate()
distfile = open(filename2, 'w')  # writing file
distfile.truncate()
##################### Parameters
T=10
deltaT=0.01
timesteps=int(T/deltaT) # number of steps
n=10 # dimension of hypercube
if (deltaT > (1/float(3*n))): print("Warning: time-step deltaT is very large") # NOTE this condition depends on the dynamics
vertexnumber=2**n # for hypercube
initialwalkernum=4*n # initial number of walkers should be logarithmic in the number of vertices
##################### Use NetworkX to generate a hypercube; generate various dictionaries with the output
hyper=nx.hypercube_graph(n) # generate hypercube using NetworkX
vertexlist=hyper.nodes()
edgelist=hyper.edges()
adjlist=hyper.adjacency_list()
incidencedict=dict() # adjacency dictionary
hammingdist=dict() # hamming weight dictionary
layerdict=dict() # dictionary of vertices organized according to hamming weights
#eg for n=3 layerdict[2]={(1,1,0),(1,0,1),(0,1,1)}
for dist in range((2**n)+1):
	layerdict[dist]=list()
for v in range(vertexnumber):
	vert=vertexlist[v]
	adj=adjlist[v]
	incidencedict[vert]=adj
	weight=0 # variable for hamming weight of v
	for ind in range(n):
コード例 #39
0
ファイル: test_lattice.py プロジェクト: jklaise/networkx
 def test_degree_distribution(self):
     for n in range(1, 10):
         G = nx.hypercube_graph(n)
         expected_histogram = [0] * n + [2 ** n]
         assert_equal(nx.degree_histogram(G), expected_histogram)
コード例 #40
0
ファイル: test_lattice.py プロジェクト: jklaise/networkx
 def test_special_cases(self):
     for n, H in [(0, nx.null_graph()), (1, nx.path_graph(2)),
                  (2, nx.cycle_graph(4)), (3, nx.cubical_graph())]:
         G = nx.hypercube_graph(n)
         assert_true(nx.could_be_isomorphic(G, H))
コード例 #41
0
n = 6
hypercube_n = 4
m = 6
r = 2
h = 3
dim = [2, 3]

# left out dorogovtsev_goltsev_mendes_graph and null_graph

graphs = [
    ("balanced_tree", nx.balanced_tree(r, h)),
    ("barbell_graph", nx.barbell_graph(n, m)),
    ("complete_graph", nx.complete_graph(n)),
    ("complete_bipartite_graph", nx.complete_bipartite_graph(n, m)),
    ("circular_ladder_graph", nx.circular_ladder_graph(n)),
    ("cycle_graph", nx.cycle_graph(n)),
    ("empty_graph", nx.empty_graph(n)),
    ("grid_2d_graph", nx.grid_2d_graph(m, n)),
    ("grid_graph", nx.grid_graph(dim)),
    ("hypercube_graph", nx.hypercube_graph(hypercube_n)),
    ("ladder_graph", nx.ladder_graph(n)),
    ("lollipop_graph", nx.lollipop_graph(m, n)),
    ("path_graph", nx.path_graph(n)),
    ("star_graph", nx.star_graph(n)),
    ("trivial_graph", nx.trivial_graph()),
    ("wheel_graph", nx.wheel_graph(n)),
]

plot_multigraph(graphs, 4, 4, node_size=50)
plt.savefig("graphs/classic.png")