Beispiel #1
0
    def keywords(self, text, n=10):
        tokens = self.pos_tagging(text)

        tokens = [t for s in tokens for w in s[1] for t in w]
        nodes = [
            k for t in tokens for k in t[1]
            if (k[1][0] in ['N', 'V']) & (len(k[0]) > 1)
        ]
        tokens = [k for t in tokens for k in t[1]]

        def connect(nodes, tokens):
            window_size = 5  # coocurrence를 판단하기 위한 window 사이즈 설정

            edges = []
            for window_start in range(0, (len(tokens) - window_size + 1)):
                window = tokens[window_start:window_start + window_size]
                #edges.append([(window[i], window[j]) for i in range(window_size) for j in range(window_size) if ( (i > j) & (window[i] in nodes) & (window[j] in nodes))])

                for i in range(window_size):
                    for j in range(window_size):
                        if (i > j) & (window[i] in nodes) & (window[j]
                                                             in nodes):
                            edges.append((window[i], window[j]))
            return edges

        graph = nx.diamond_graph()
        graph.clear()  #처음 생성시 graph에 garbage node가 남아있어 삭제
        graph.add_nodes_from(list(set(nodes)))  #node 등록
        graph.add_edges_from(connect(nodes, tokens))  #edge 연결
        scores = nx.pagerank(graph)  #pagerank 계산
        rank = sorted(scores.items(), key=lambda x: x[1],
                      reverse=True)  #score 역순 정렬
        return rank[:n]
Beispiel #2
0
    def __init__(self,
                 pos_tagger_name='mecab',
                 mecab_path='',
                 exceptional_stop_pos=[],
                 lang='ko',
                 stopwords=[]):
        self.stop_pos = STOP_POS[lang]
        # print(self.stop_pos)

        if pos_tagger_name == 'mecab':
            from konlpy.tag import Mecab
            self.pos_tagger = Mecab(mecab_path)
        elif pos_tagger_name == 'komoran':
            from konlpy.tag import Komoran
            self.pos_tagger = Komoran()
        elif pos_tagger_name == 'nltk':
            self.pos_tagger = None
        else:
            from konlpy.tag import Okt
            self.pos_tagger = Okt()

        if not exceptional_stop_pos:
            self.stop_pos = [
                x for x in self.stop_pos if x not in exceptional_stop_pos
            ]

        self.stopwords = []
        if stopwords:
            self.stopwords = stopwords

        self.graph = nx.diamond_graph()
        self.graph.clear()  # 처음 생성시 graph에 garbage node가 남아있어 삭제

        self.tokens = []
Beispiel #3
0
def DiamondGraph():
    """
    Returns a diamond graph with 4 nodes.

    A diamond graph is a square with one pair of diagonal nodes
    connected.

    This constructor depends on NetworkX numeric labeling.

    PLOTTING: Upon construction, the position dictionary is filled to
    override the spring-layout algorithm. By convention, the diamond
    graph is drawn as a diamond, with the first node on top, second on
    the left, third on the right, and fourth on the bottom; with the
    second and third node connected.

    EXAMPLES: Construct and show a diamond graph

    ::

        sage: g = graphs.DiamondGraph()
        sage: g.show() # long time
    """
    pos_dict = {0:(0,1),1:(-1,0),2:(1,0),3:(0,-1)}
    import networkx
    G = networkx.diamond_graph()
    return graph.Graph(G, pos=pos_dict, name="Diamond Graph")
Beispiel #4
0
def DiamondGraph():
    """
    Returns a diamond graph with 4 nodes.

    A diamond graph is a square with one pair of diagonal nodes
    connected.

    This constructor depends on NetworkX numeric labeling.

    PLOTTING: Upon construction, the position dictionary is filled to
    override the spring-layout algorithm. By convention, the diamond
    graph is drawn as a diamond, with the first node on top, second on
    the left, third on the right, and fourth on the bottom; with the
    second and third node connected.

    EXAMPLES: Construct and show a diamond graph

    ::

        sage: g = graphs.DiamondGraph()
        sage: g.show() # long time
    """
    pos_dict = {0: (0, 1), 1: (-1, 0), 2: (1, 0), 3: (0, -1)}
    import networkx
    G = networkx.diamond_graph()
    return graph.Graph(G, pos=pos_dict, name="Diamond Graph")
    def testLimit(self):
        '''Test we can limit the number of instances generated.'''
        g = networkx.diamond_graph()
        gen = FixedNetwork(g, limit=10)

        n = 0
        for _ in gen:
            n += 1
        self.assertEqual(n, 10)
    def testFixedNetworkGenerator(self):
        '''Test that adding a network creates the right generator.'''
        g = networkx.diamond_graph()
        p = Process()
        dyn = Dynamics(p)

        dyn.setNetworkGenerator(g)
        self.assertIsInstance(dyn.networkGenerator(), FixedNetwork)
        self.assertGraphsEqual(g, dyn.networkGenerator().generate())
Beispiel #7
0
    def __init__(self,STOPWORD=None, STOPPOS=pos, MECABPATH=None):
        from konlpy.tag import Mecab

        self.stopwords = STOPWORD
        self.stoppos = STOPPOS
        self.mecabpath = MECABPATH
        self.pos_tag = Mecab(self.mecabpath)
        self.graph = {}
        self.graph_treform =nx.diamond_graph()
        self.graph_treform.clear()
    def testFixedNetwork(self):
        '''Test we always return a fixed network.'''
        g = networkx.diamond_graph(
        )  # doesn't matter what it as, as long as it's fixed
        gen = FixedNetwork(g)

        self.assertGraphsEqual(g, gen.generate())

        for _ in range(5):  # make sure the iterator is stable
            gp = gen.__next__()
            self.assertGraphsEqual(g, gp)
Beispiel #9
0
def instance4():
    lst = []
    for _ in range(25):
        lst.append(nx.diamond_graph())

    L = nx.Graph()
    for i in lst:
        L = nx.disjoint_union(L, i)

    r = 0
    while (r <= 92):
        L.add_edge(r + 3, r + 4)
        r += 4
    L.add_edge(0, 99)

    return L
Beispiel #10
0
    def summarize(self, text, n=3):
        tokens = self.pos_tagging(text)

        #자카드 유사도 계산
        def jaccard_similarity(query, document):
            intersection = set(query).intersection(set(document))
            union = set(query).union(set(document))
            return len(intersection) / len(union)

        # 문장간 유사도 측정 (BoW를 활용 코사인 유사도 측정)
        def sentence_similarity(sentence1, sentence2):

            sentence1 = self.tokenizer.morphs(
                sentence1[0]
            )  #[t[0] for s in sentence1[1][0] for t in s[1] if t[1][0] in ['N','V'] ]
            sentence2 = self.tokenizer.morphs(
                sentence2[0]
            )  #.split()#[t[0] for s in sentence2[1][0] for t in s[1] if t[1][0] in ['N','V'] ]
            #print(sentence1)
            return jaccard_similarity(sentence1, sentence2)

        def sentences(doc):
            return [s[0].strip() for s in doc]

        def connect(doc):
            return [(start[0].strip(), end[0].strip(),
                     sentence_similarity(start, end)) for start in doc
                    for end in doc if start is not end]

        graph = nx.diamond_graph()
        graph.clear()  #처음 생성시 graph에 garbage node가 남아있어 삭제
        graph.add_nodes_from(sentences(tokens))  #node 등록
        graph.add_weighted_edges_from(connect(tokens))  #edge 연결
        scores = nx.pagerank(graph)  #pagerank 계산
        #print(scores)
        rank = sorted(scores.items(), key=lambda x: x[1],
                      reverse=True)  #score 역순 정렬
        ssum = rank[:n]
        ranks = []
        for s in ssum:
            ranks.append(s[0])
        return ' '.join(ranks)
Beispiel #11
0
    def keywords(self, text, n=10, window_size=WINDOW_SIZE):
        if self.pos_tagger is None:
            import nltk
            _tokens = nltk.word_tokenize(text)
            tokenized = nltk.pos_tag(_tokens)
        else:
            tokenized = self.pos_tagger.pos(text)
        # print(tokenized)

        nodes = []
        tokens = []
        for token in tokenized:
            if (len(token[0]) > 1) & (str(token[0]) not in self.stopwords) & (
                    token[1][:3] not in self.stop_pos) & (
                        token[0] !=
                        token[1]):  # nltk는 특수문자는 품사가 태깅이 안되고 토큰이 그대로 품사에 나옴
                nodes.append(token)
            tokens.append(token)

        def connect(nodes, tokens):
            edges = []
            for window_start in range(0, (len(tokens) - window_size + 1)):
                window = tokens[window_start:window_start + window_size]

                for i in range(window_size):
                    for j in range(window_size):
                        if (i > j) & (window[i] in nodes) & (window[j]
                                                             in nodes):
                            edges.append((window[i], window[j]))
            return edges

        graph = nx.diamond_graph()
        graph.clear()  # 처음 생성시 graph에 garbage node가 남아있어 삭제
        graph.add_nodes_from(list(set(nodes)))  # node 등록
        graph.add_edges_from(connect(nodes, tokens))  # edge 연결
        scores = nx.pagerank(graph)  # pagerank 계산
        rank = sorted(scores.items(), key=lambda x: x[1],
                      reverse=True)  # score 역순 정렬
        return rank[:n]
Beispiel #12
0
    def summarize(self, text, max=3):
        # 자카드 유사도 계산
        def jaccard_similarity(query, document):
            intersection = set(query).intersection(set(document))
            union = set(query).union(set(document))
            return len(intersection) / len(union)

        # 문장간 유사도 측정 (BoW를 활용 코사인 유사도 측정)
        def sentence_similarity(sentence1, sentence2):
            sentence1 = [
                t[0] for t in self.pos_tagger.pos(sentence1)
                if t[1][:3] not in self.stop_pos
            ]  # 개선 필요
            sentence2 = [
                t[0] for t in self.pos_tagger.pos(sentence2)
                if t[1][:3] not in self.stop_pos
            ]  # 개선 필요
            # print(sentence1)
            return jaccard_similarity(sentence1, sentence2)

        def sentences(doc):
            return sent_tokenize(doc)  # [s[0].strip() for s in doc]

        def connect(doc):
            return [(start, end, sentence_similarity(start, end))
                    for start in doc for end in doc if start is not end]

        # tokens = self.pos_tagger(text)
        sentence_li = sentences(text)
        graph = nx.diamond_graph()
        graph.clear()  # 처음 생성시 graph에 garbage node가 남아있어 삭제
        graph.add_nodes_from(sentence_li)  # node 등록
        graph.add_weighted_edges_from(connect(sentence_li))  # edge 연결
        scores = nx.pagerank(graph)  # pagerank 계산

        rank = sorted(scores.items(), key=lambda x: x[1],
                      reverse=True)  # score 역순 정렬
        return rank[:max]
def diamond():
    return nx.diamond_graph()
Beispiel #14
0
from monosat import *
from networkx.relabel import convert_node_labels_to_integers

print("begin encode")

seed = random.randint(1, 100000)

random.seed(seed)
print("RandomSeed=" + str(seed))

size = 6

#Monosat().newSolver("-decide-graph-bv -no-decide-theories -no-decide-graph-rnd   -lazy-maxflow-decisions -conflict-min-cut -conflict-min-cut-maxflow -reach-underapprox-cnf ")

graphs = [
    nx.diamond_graph(),
    nx.complete_graph(2),
    nx.complete_graph(3),
    nx.complete_graph(4),
    nx.cycle_graph(5),
    nx.grid_2d_graph(4, 4),
    nx.grid_2d_graph(4, 4, True),
    nx.dense_gnm_random_graph(4, 8, 123),
    nx.dense_gnm_random_graph(4, 8, 124),
    nx.dense_gnm_random_graph(4, 16, 125)
]
#Directed graphs:
graphs += [
    nx.gnp_random_graph(4, 8, 123, True),
    nx.gnp_random_graph(4, 8, 124, True),
    nx.gnp_random_graph(4, 8, 125, True),
Beispiel #15
0
def small_graphs():
    print("Make small graph")
    G = nx.make_small_graph(
        ["adjacencylist", "C_4", 4, [[2, 4], [1, 3], [2, 4], [1, 3]]])
    draw_graph(G)
    G = nx.make_small_graph(
        ["adjacencylist", "C_4", 4, [[2, 4], [3], [4], []]])
    draw_graph(G)
    G = nx.make_small_graph(
        ["edgelist", "C_4", 4, [[1, 2], [3, 4], [2, 3], [4, 1]]])
    draw_graph(G)
    print("LCF graph")
    G = nx.LCF_graph(6, [3, -3], 3)
    draw_graph(G)
    G = nx.LCF_graph(14, [5, -5], 7)
    draw_graph(G)
    print("Bull graph")
    G = nx.bull_graph()
    draw_graph(G)
    print("Chvátal graph")
    G = nx.chvatal_graph()
    draw_graph(G)
    print("Cubical graph")
    G = nx.cubical_graph()
    draw_graph(G)
    print("Desargues graph")
    G = nx.desargues_graph()
    draw_graph(G)
    print("Diamond graph")
    G = nx.diamond_graph()
    draw_graph(G)
    print("Dodechaedral graph")
    G = nx.dodecahedral_graph()
    draw_graph(G)
    print("Frucht graph")
    G = nx.frucht_graph()
    draw_graph(G)
    print("Heawood graph")
    G = nx.heawood_graph()
    draw_graph(G)
    print("House graph")
    G = nx.house_graph()
    draw_graph(G)
    print("House X graph")
    G = nx.house_x_graph()
    draw_graph(G)
    print("Icosahedral graph")
    G = nx.icosahedral_graph()
    draw_graph(G)
    print("Krackhardt kite graph")
    G = nx.krackhardt_kite_graph()
    draw_graph(G)
    print("Moebius kantor graph")
    G = nx.moebius_kantor_graph()
    draw_graph(G)
    print("Octahedral graph")
    G = nx.octahedral_graph()
    draw_graph(G)
    print("Pappus graph")
    G = nx.pappus_graph()
    draw_graph(G)
    print("Petersen graph")
    G = nx.petersen_graph()
    draw_graph(G)
    print("Sedgewick maze graph")
    G = nx.sedgewick_maze_graph()
    draw_graph(G)
    print("Tetrahedral graph")
    G = nx.tetrahedral_graph()
    draw_graph(G)
    print("Truncated cube graph")
    G = nx.truncated_cube_graph()
    draw_graph(G)
    print("Truncated tetrahedron graph")
    G = nx.truncated_tetrahedron_graph()
    draw_graph(G)
    print("Tutte graph")
    G = nx.tutte_graph()
    draw_graph(G)
import networkx as nx
import matplotlib.pylab as plt
from plot_multigraph import plot_multigraph

graphs = [
    ("bull", nx.bull_graph()),
    ("chvatal", nx.chvatal_graph()),
    ("cubical", nx.cubical_graph()),
    ("desargues", nx.desargues_graph()),
    ("diamond", nx.diamond_graph()),
    ("dodecahedral", nx.dodecahedral_graph()),
    ("frucht", nx.frucht_graph()),
    ("heawood", nx.heawood_graph()),
    ("house", nx.house_graph()),
    ("house_x", nx.house_x_graph()),
    ("icosahedral", nx.icosahedral_graph()),
    ("krackhardt_kite", nx.krackhardt_kite_graph()),
    ("moebius_kantor", nx.moebius_kantor_graph()),
    ("octahedral", nx.octahedral_graph()),
    ("pappus", nx.pappus_graph()),
    ("petersen", nx.petersen_graph()),
    ("sedgewick_maze", nx.sedgewick_maze_graph()),
    ("tetrahedral", nx.tetrahedral_graph()),
    ("truncated_cube", nx.truncated_cube_graph()),
    ("truncated_tetrahedron", nx.truncated_tetrahedron_graph()),
]

plot_multigraph(graphs, 4, 5, node_size=50)
plt.savefig('graphs/small.png')
Beispiel #17
0
seed = random.randint(1,100000)

random.seed(seed)
print("RandomSeed=" + str(seed))

size =6
filename="/tmp/test.gnf"
#Monosat().init("-decide-graph-bv -no-decide-theories -no-decide-graph-rnd   -lazy-maxflow-decisions -conflict-min-cut -conflict-min-cut-maxflow -reach-underapprox-cnf ")
Monosat().setOutputFile(open(filename,'w'))
print("Writing file to " + filename)




graphs = [nx.diamond_graph(), nx.complete_graph(2), nx.complete_graph(3), nx.complete_graph(4), nx.cycle_graph(5),
          nx.grid_2d_graph(4,4),nx.grid_2d_graph(4,4,True),
          nx.dense_gnm_random_graph(4,8,123),
          nx.dense_gnm_random_graph(4,8,124),
          nx.dense_gnm_random_graph(4,16,125)
          ]
            #Directed graphs:
graphs+=[nx.gnp_random_graph(4,8,123,True),nx.gnp_random_graph(4,8,124,True),nx.gnp_random_graph(4,8,125,True),nx.gnp_random_graph(4,8,126,True),
         nx.gnp_random_graph(4,16,127,True),
          nx.gnp_random_graph(4,32,128,True),
          nx.gnp_random_graph(9,16,127,True),
         
         ]
for i,nxg in enumerate(graphs):

    nxg = convert_node_labels_to_integers(nxg)
Beispiel #18
0
def test_get_cliques_of_size():
    networkx_graph_with_cliques = nx.diamond_graph()
    nose.tools.assert_equal(
        len(
            networkx_graph_from_array._get_cliques_of_size(
                networkx_graph_with_cliques, 3)), 2)
Beispiel #19
0
def test_remove_clique_edges():
    networkx_graph_with_cliques = nx.diamond_graph()
    edges_before = networkx_graph_with_cliques.number_of_edges()
    networkx_graph_from_array._remove_clique_edges(networkx_graph_with_cliques)
    nose.tools.assert_equal(networkx_graph_with_cliques.number_of_edges(),
                            edges_before)
 def test_diamond(self):
     expected = True
     actual = is_planar(nx.diamond_graph())
     self.assertEqual(expected, actual)
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")
def process_arguments(args):

    extract_id_fn = subgraph_counts2ids

    ###### choose the function that computes the automorphism group and the orbits #######
    if args['edge_automorphism'] == 'induced':
        automorphism_fn = induced_edge_automorphism_orbits if args[
            'id_scope'] == 'local' else automorphism_orbits
    elif args['edge_automorphism'] == 'line_graph':
        automorphism_fn = edge_automorphism_orbits if args[
            'id_scope'] == 'local' else automorphism_orbits
    else:
        raise NotImplementedError

    ###### choose the function that computes the subgraph isomorphisms #######
    count_fn = subgraph_isomorphism_edge_counts if args[
        'id_scope'] == 'local' else subgraph_isomorphism_vertex_counts

    ###### choose the substructures: usually loaded from networkx,
    ###### except for 'all_simple_graphs' where they need to be precomputed,
    ###### or when a custom edge list is provided in the input by the user
    if args['id_type'] in [
            'cycle_graph', 'path_graph', 'complete_graph', 'binomial_tree',
            'star_graph', 'nonisomorphic_trees'
    ]:
        args['k'] = args['k'][0]
        k_max = args['k']
        k_min = 2 if args['id_type'] == 'star_graph' else 3
        args['custom_edge_list'] = get_custom_edge_list(
            list(range(k_min, k_max + 1)), args['id_type'])

    elif args['id_type'] in [
            'cycle_graph_chosen_k', 'path_graph_chosen_k',
            'complete_graph_chosen_k', 'binomial_tree_chosen_k',
            'star_graph_chosen_k', 'nonisomorphic_trees_chosen_k'
    ]:
        args['custom_edge_list'] = get_custom_edge_list(
            args['k'], args['id_type'].replace('_chosen_k', ''))

    elif args['id_type'] in ['all_simple_graphs']:
        args['k'] = args['k'][0]
        k_max = args['k']
        k_min = 3
        filename = os.path.join(args['root_folder'], 'all_simple_graphs')
        args['custom_edge_list'] = get_custom_edge_list(list(
            range(k_min, k_max + 1)),
                                                        filename=filename)

    elif args['id_type'] in ['all_simple_graphs_chosen_k']:
        filename = os.path.join(args['root_folder'], 'all_simple_graphs')
        args['custom_edge_list'] = get_custom_edge_list(args['k'],
                                                        filename=filename)

    elif args['id_type'] in ['diamond_graph']:
        args['k'] = None
        graph_nx = nx.diamond_graph()
        args['custom_edge_list'] = [list(graph_nx.edges)]

    elif args['id_type'] == 'custom':
        assert args[
            'custom_edge_list'] is not None, "Custom edge list must be provided."

    else:
        raise NotImplementedError(
            "Identifiers {} are not currently supported.".format(
                args['id_type']))

    # define if degree is going to be used as a feature and when (for each layer or only at initialization)
    if args['inject_degrees']:
        args['degree_as_tag'] = [
            args['degree_as_tag'] for _ in range(args['num_layers'])
        ]
    else:
        args['degree_as_tag'] = [args['degree_as_tag']] + [
            False for _ in range(args['num_layers'] - 1)
        ]

    # define if existing features are going to be retained when the degree is used as a feature
    args['retain_features'] = [args['retain_features']] + [
        True for _ in range(args['num_layers'] - 1)
    ]

    # replicate d_out dimensions if the rest are not defined (msg function, mlp hidden dimension, encoders, etc.)
    # and repeat hyperparams for every layer
    if args['d_msg'] == -1:
        args['d_msg'] = [None for _ in range(args['num_layers'])]
    elif args['d_msg'] is None:
        args['d_msg'] = [args['d_out'] for _ in range(args['num_layers'])]
    else:
        args['d_msg'] = [args['d_msg'] for _ in range(args['num_layers'])]

    if args['d_h'] is None:
        args['d_h'] = [[args['d_out']] * (args['num_mlp_layers'] - 1)
                       for _ in range(args['num_layers'])]
    else:
        args['d_h'] = [[args['d_h']] * (args['num_mlp_layers'] - 1)
                       for _ in range(args['num_layers'])]

    if args['d_out_edge_encoder'] is None:
        args['d_out_edge_encoder'] = [
            args['d_out'] for _ in range(args['num_layers'])
        ]
    else:
        args['d_out_edge_encoder'] = [
            args['d_out_edge_encoder'] for _ in range(args['num_layers'])
        ]

    if args['d_out_node_encoder'] is None:
        args['d_out_node_encoder'] = args['d_out']
    else:
        pass

    if args['d_out_id_embedding'] is None:
        args['d_out_id_embedding'] = args['d_out']
    else:
        pass

    if args['d_out_degree_embedding'] is None:
        args['d_out_degree_embedding'] = args['d_out']
    else:
        pass

    # virtual node configuration for ogb datasets
    if args['vn']:

        if args['d_out_vn_encoder'] is None:
            args['d_out_vn_encoder'] = args['d_out']
        else:
            pass

        if args['d_out_vn'] is None:
            args['d_out_vn'] = [
                args['d_out'] for _ in range(args['num_layers'] - 1)
            ]
        else:
            args['d_out_vn'] = [
                args['d_out_vn'] for _ in range(args['num_layers'] - 1)
            ]
    else:
        pass

    # repeat hyperparams for every layer
    args['d_out'] = [args['d_out'] for _ in range(args['num_layers'])]

    args['train_eps'] = [args['train_eps'] for _ in range(args['num_layers'])]

    if len(args['final_projection']) == 1:
        args['final_projection'] = [
            args['final_projection'][0] for _ in range(args['num_layers'])
        ] + [True]

    args['bn'] = [args['bn'] for _ in range(args['num_layers'])]
    args['dropout_features'] = [
        args['dropout_features'] for _ in range(args['num_layers'])
    ] + [args['dropout_features']]

    # loss function & metrics
    if args['loss_fn'] == 'CrossEntropyLoss':
        assert args[
            'regression'] is False, "Can't use Cross-Entropy loss in regression."
        loss_fn = nn.CrossEntropyLoss()
    elif args['loss_fn'] == 'BCEWithLogitsLoss':
        assert args[
            'regression'] is False, "Can't use binary Cross-Entropy loss in regression."
        loss_fn = nn.BCEWithLogitsLoss()
    elif args['loss_fn'] == 'MSELoss':
        loss_fn = nn.MSELoss()
    elif args['loss_fn'] == 'L1Loss':
        loss_fn = nn.L1Loss()
    else:
        raise NotImplementedError

    if args['prediction_fn'] == 'multi_class_accuracy':
        assert args[
            'regression'] is False, "Can't use Classification Accuracy metric in regression."
        prediction_fn = multi_class_accuracy
    elif args['prediction_fn'] == 'MSELoss':
        prediction_fn = nn.MSELoss(reduction='sum')
    elif args['prediction_fn'] == 'L1Loss':
        prediction_fn = nn.L1Loss(reduction='sum')
    elif args['prediction_fn'] == 'None':
        prediction_fn = None
    else:
        raise NotImplementedError

    if args['regression']:
        perf_opt = np.argmin
    else:
        perf_opt = np.argmax

    return args, extract_id_fn, count_fn, automorphism_fn, loss_fn, prediction_fn, perf_opt
import networkx as nx
import matplotlib.pylab as plt
from plot_multigraph import plot_multigraph

graphs = [
  ("bull", nx.bull_graph()),
  ("chvatal", nx.chvatal_graph()),
  ("cubical", nx.cubical_graph()),
  ("desargues", nx.desargues_graph()),
  ("diamond", nx.diamond_graph()),
  ("dodecahedral", nx.dodecahedral_graph()),
  ("frucht", nx.frucht_graph()),
  ("heawood", nx.heawood_graph()),
  ("house", nx.house_graph()),
  ("house_x", nx.house_x_graph()),
  ("icosahedral", nx.icosahedral_graph()),
  ("krackhardt_kite", nx.krackhardt_kite_graph()),
  ("moebius_kantor", nx.moebius_kantor_graph()),
  ("octahedral", nx.octahedral_graph()),
  ("pappus", nx.pappus_graph()),
  ("petersen", nx.petersen_graph()),
  ("sedgewick_maze", nx.sedgewick_maze_graph()),
  ("tetrahedral", nx.tetrahedral_graph()),
  ("truncated_cube", nx.truncated_cube_graph()),
  ("truncated_tetrahedron", nx.truncated_tetrahedron_graph()),
]

plot_multigraph(graphs, 4, 5, node_size=50)
plt.savefig('graphs/small.png')

    def test_properties_named_small_graphs(self):
        G = nx.bull_graph()
        assert G.number_of_nodes() == 5
        assert G.number_of_edges() == 5
        assert sorted(d for n, d in G.degree()) == [1, 1, 2, 3, 3]
        assert nx.diameter(G) == 3
        assert nx.radius(G) == 2

        G = nx.chvatal_graph()
        assert G.number_of_nodes() == 12
        assert G.number_of_edges() == 24
        assert list(d for n, d in G.degree()) == 12 * [4]
        assert nx.diameter(G) == 2
        assert nx.radius(G) == 2

        G = nx.cubical_graph()
        assert G.number_of_nodes() == 8
        assert G.number_of_edges() == 12
        assert list(d for n, d in G.degree()) == 8 * [3]
        assert nx.diameter(G) == 3
        assert nx.radius(G) == 3

        G = nx.desargues_graph()
        assert G.number_of_nodes() == 20
        assert G.number_of_edges() == 30
        assert list(d for n, d in G.degree()) == 20 * [3]

        G = nx.diamond_graph()
        assert G.number_of_nodes() == 4
        assert sorted(d for n, d in G.degree()) == [2, 2, 3, 3]
        assert nx.diameter(G) == 2
        assert nx.radius(G) == 1

        G = nx.dodecahedral_graph()
        assert G.number_of_nodes() == 20
        assert G.number_of_edges() == 30
        assert list(d for n, d in G.degree()) == 20 * [3]
        assert nx.diameter(G) == 5
        assert nx.radius(G) == 5

        G = nx.frucht_graph()
        assert G.number_of_nodes() == 12
        assert G.number_of_edges() == 18
        assert list(d for n, d in G.degree()) == 12 * [3]
        assert nx.diameter(G) == 4
        assert nx.radius(G) == 3

        G = nx.heawood_graph()
        assert G.number_of_nodes() == 14
        assert G.number_of_edges() == 21
        assert list(d for n, d in G.degree()) == 14 * [3]
        assert nx.diameter(G) == 3
        assert nx.radius(G) == 3

        G = nx.hoffman_singleton_graph()
        assert G.number_of_nodes() == 50
        assert G.number_of_edges() == 175
        assert list(d for n, d in G.degree()) == 50 * [7]
        assert nx.diameter(G) == 2
        assert nx.radius(G) == 2

        G = nx.house_graph()
        assert G.number_of_nodes() == 5
        assert G.number_of_edges() == 6
        assert sorted(d for n, d in G.degree()) == [2, 2, 2, 3, 3]
        assert nx.diameter(G) == 2
        assert nx.radius(G) == 2

        G = nx.house_x_graph()
        assert G.number_of_nodes() == 5
        assert G.number_of_edges() == 8
        assert sorted(d for n, d in G.degree()) == [2, 3, 3, 4, 4]
        assert nx.diameter(G) == 2
        assert nx.radius(G) == 1

        G = nx.icosahedral_graph()
        assert G.number_of_nodes() == 12
        assert G.number_of_edges() == 30
        assert (list(
            d for n, d in G.degree()) == [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5])
        assert nx.diameter(G) == 3
        assert nx.radius(G) == 3

        G = nx.krackhardt_kite_graph()
        assert G.number_of_nodes() == 10
        assert G.number_of_edges() == 18
        assert (sorted(
            d for n, d in G.degree()) == [1, 2, 3, 3, 3, 4, 4, 5, 5, 6])

        G = nx.moebius_kantor_graph()
        assert G.number_of_nodes() == 16
        assert G.number_of_edges() == 24
        assert list(d for n, d in G.degree()) == 16 * [3]
        assert nx.diameter(G) == 4

        G = nx.octahedral_graph()
        assert G.number_of_nodes() == 6
        assert G.number_of_edges() == 12
        assert list(d for n, d in G.degree()) == 6 * [4]
        assert nx.diameter(G) == 2
        assert nx.radius(G) == 2

        G = nx.pappus_graph()
        assert G.number_of_nodes() == 18
        assert G.number_of_edges() == 27
        assert list(d for n, d in G.degree()) == 18 * [3]
        assert nx.diameter(G) == 4

        G = nx.petersen_graph()
        assert G.number_of_nodes() == 10
        assert G.number_of_edges() == 15
        assert list(d for n, d in G.degree()) == 10 * [3]
        assert nx.diameter(G) == 2
        assert nx.radius(G) == 2

        G = nx.sedgewick_maze_graph()
        assert G.number_of_nodes() == 8
        assert G.number_of_edges() == 10
        assert sorted(d for n, d in G.degree()) == [1, 2, 2, 2, 3, 3, 3, 4]

        G = nx.tetrahedral_graph()
        assert G.number_of_nodes() == 4
        assert G.number_of_edges() == 6
        assert list(d for n, d in G.degree()) == [3, 3, 3, 3]
        assert nx.diameter(G) == 1
        assert nx.radius(G) == 1

        G = nx.truncated_cube_graph()
        assert G.number_of_nodes() == 24
        assert G.number_of_edges() == 36
        assert list(d for n, d in G.degree()) == 24 * [3]

        G = nx.truncated_tetrahedron_graph()
        assert G.number_of_nodes() == 12
        assert G.number_of_edges() == 18
        assert list(d for n, d in G.degree()) == 12 * [3]

        G = nx.tutte_graph()
        assert G.number_of_nodes() == 46
        assert G.number_of_edges() == 69
        assert list(d for n, d in G.degree()) == 46 * [3]

        # Test create_using with directed or multigraphs on small graphs
        pytest.raises(nx.NetworkXError,
                      nx.tutte_graph,
                      create_using=nx.DiGraph)
        MG = nx.tutte_graph(create_using=nx.MultiGraph)
        assert sorted(MG.edges()) == sorted(G.edges())
Beispiel #25
0
 def test_diamond(self):
     print '\ndiamond:',
     self.g = nx.diamond_graph()
     a = programming_for_tree_decomposition(self.g, True)
     self.t = a.tree_decomposition()
     self.assertTrue(self.__test_all_conditions())
Beispiel #26
0
def clean_attributes(g):
    for v in g.nodes():
        if 'visited' in g.node[v]:
            del g.node[v]['visited']
    for u, v in g.edges():
        if 'visited' in g[u][v]:
            del g[u][v]['visited']


if __name__ == '__main__':
    targets = {
        'bull': nx.bull_graph(),  # 1-connected planar
        'chvatal': nx.chvatal_graph(),  # 4-connected non-planar
        'cubical': nx.cubical_graph(),  # 3-connected planar
        'desargues': nx.desargues_graph(),  # 3-connected non-planar
        'diamond': nx.diamond_graph(),  # 2-connected planar
        'dodecahedral': nx.dodecahedral_graph(),  # 3-connected planar
        'frucht': nx.frucht_graph(),  # 3-connected planar
        'heawood': nx.heawood_graph(),  # 3-connected non-planar
        'house': nx.house_graph(),  # 2-connected planar
        'house_x': nx.house_x_graph(),  # 2-connected planar
        'icosahedral': nx.icosahedral_graph(),  # 5-connected planar
        'krackhardt': nx.krackhardt_kite_graph(),  # 1-connected planar
        'moebius': nx.moebius_kantor_graph(),  # non-planar
        'octahedral': nx.octahedral_graph(),  # 4-connected planar
        'pappus': nx.pappus_graph(),  # 3-connected non-planar
        'petersen': nx.petersen_graph(),  # 3-connected non-planar
        'sedgewick': nx.sedgewick_maze_graph(),  # 1-connected planar
        'tetrahedral': nx.tetrahedral_graph(),  # 3-connected planar
        'truncated_cube': nx.truncated_cube_graph(),  # 3-conn. planar
        'truncated_tetrahedron': nx.truncated_tetrahedron_graph(),
Beispiel #27
0
def rank(nodes, edges):
    '''Return a dicitionary containing the scores for each vertex.'''
    graph = nx.diamond_graph()
    graph.add_nodes_from(nodes)
    graph.add_weighted_edges_from(edges)
    return nx.pagerank(graph)
Beispiel #28
0
print("begin encode");

seed = random.randint(1,100000)

random.seed(seed)
print("RandomSeed=" + str(seed))

size =6
filename="/tmp/test.gnf"
#Monosat().init("-decide-graph-bv -no-decide-theories -no-decide-graph-rnd   -lazy-maxflow-decisions -conflict-min-cut -conflict-min-cut-maxflow -reach-underapprox-cnf ")




graphs = [nx.diamond_graph(), nx.complete_graph(2), nx.complete_graph(3), nx.complete_graph(4), nx.cycle_graph(5),
          nx.grid_2d_graph(4,4),nx.grid_2d_graph(4,4,True),
          nx.dense_gnm_random_graph(4,8,123),
          nx.dense_gnm_random_graph(4,8,124),
          nx.dense_gnm_random_graph(4,16,125)
          ]
            #Directed graphs:
graphs+=[nx.gnp_random_graph(4,8,123,True),nx.gnp_random_graph(4,8,124,True),nx.gnp_random_graph(4,8,125,True),nx.gnp_random_graph(4,8,126,True),
         nx.gnp_random_graph(4,16,127,True),
          nx.gnp_random_graph(4,32,128,True),
          nx.gnp_random_graph(9,16,127,True),
         
         ]
for i,nxg in enumerate(graphs):

    nxg = convert_node_labels_to_integers(nxg)