Beispiel #1
0
    def test_spiral_layout(self):

        G = self.Gs

        # a lower value of resolution should result in a more compact layout
        # intuitively, the total distance from the start and end nodes
        # via each node in between (transiting through each) will be less,
        # assuming rescaling does not occur on the computed node positions
        pos_standard = np.array(
            list(nx.spiral_layout(G, resolution=0.35).values()))
        pos_tighter = np.array(
            list(nx.spiral_layout(G, resolution=0.34).values()))
        distances = np.linalg.norm(pos_standard[:-1] - pos_standard[1:],
                                   axis=1)
        distances_tighter = np.linalg.norm(pos_tighter[:-1] - pos_tighter[1:],
                                           axis=1)
        assert sum(distances) > sum(distances_tighter)

        # return near-equidistant points after the first value if set to true
        pos_equidistant = np.array(
            list(nx.spiral_layout(G, equidistant=True).values()))
        distances_equidistant = np.linalg.norm(pos_equidistant[:-1] -
                                               pos_equidistant[1:],
                                               axis=1)
        assert np.allclose(distances_equidistant[1:],
                           distances_equidistant[-1],
                           atol=0.01)
Beispiel #2
0
 def test_smoke_empty_graph(self):
     G = []
     nx.random_layout(G)
     nx.circular_layout(G)
     nx.planar_layout(G)
     nx.spring_layout(G)
     nx.fruchterman_reingold_layout(G)
     nx.spectral_layout(G)
     nx.shell_layout(G)
     nx.bipartite_layout(G, G)
     nx.spiral_layout(G)
     nx.kamada_kawai_layout(G)
Beispiel #3
0
 def test_smoke_string(self):
     G = self.Gs
     nx.random_layout(G)
     nx.circular_layout(G)
     nx.planar_layout(G)
     nx.spring_layout(G)
     nx.fruchterman_reingold_layout(G)
     nx.spectral_layout(G)
     nx.shell_layout(G)
     nx.spiral_layout(G)
     nx.kamada_kawai_layout(G)
     nx.kamada_kawai_layout(G, dim=1)
     nx.kamada_kawai_layout(G, dim=3)
def display_pos(G, layout='shortest'):
    ''' Display Position of the Nodes:
    # spiral

    # 1. general layout that works well for lots of nodes
     # pos = nx.spiral_layout(G)

    # "variable-type":
        multiplartitle_layout using subsets of (output, intermediatory, input). it works well for small number of nodes, but not for a bigger set of nodes


    # "shortest" by default
        multiplartitle_layout using shortest distance to the source.
    '''
    if layout == 'shortest':
        var_id = list(G.nodes)[0]
        shortest_length = single_source_shortest_path_length(G, var_id)

        for node in shortest_length.keys():
            G.nodes[node]['shortest'] = shortest_length[node]

        pos = nx.multipartite_layout(G,
                                     subset_key="shortest",
                                     align='horizontal')

    elif layout == "variable-type":
        for node, varType in G.nodes(data=True):
            if varType['type'] == 'input':
                G.nodes[node]['subset'] = 2
            elif varType['type'] == 'output':
                G.nodes[node]['subset'] = 0
            elif varType['type'] == 'intermediary':
                G.nodes[node]['subset'] = 1
            else:
                G.nodes[node]['subset'] = -1

        pos = nx.multipartite_layout(G,
                                     subset_key="subset",
                                     align='horizontal')
    elif layout == "planar":
        pos = nx.planar_layout(G)
    elif layout == "spring":
        pos = nx.spring_layout(G)
    elif layout == "shell":
        pos = nx.shell_layout(G)
    elif layout == "spiral":
        pos = nx.spiral_layout(G)
    else:
        pos = nx.spiral_layout(G)

    return pos
Beispiel #5
0
    def show(self, labels='type'):
        if labels == 'both' or labels == 'type':
            relabel_mapping = {k: v.node_name() for k, v in self.node_reference.items()}
            computational_graph = nx.relabel_nodes(self.graph, relabel_mapping, )
            options = {'node_size': 2000, 'alpha': 0.7}
            if labels == 'both':
                plt.figure(figsize=(15, 8))
                plt.subplot(121)
                pos = nx.spring_layout(computational_graph, iterations=50)
                nx.draw(computational_graph, pos, with_labels=True, **options)

                plt.subplot(122)
                pos = nx.spiral_layout(self.graph, )
                nx.draw(self.graph, with_labels=True)

            else:
                plt.figure(figsize=(15, 8))
                plt.subplot()
                nx.draw(computational_graph, with_labels=True)

        else:
            plt.figure(figsize=(15, 8))
            plt.subplot()
            nx.draw(self.graph, with_labels=True)

        plt.show()
Beispiel #6
0
def create_graph():
    repo_name = "progit2"
    code_dir = "code"
    dir_path = os.path.join(os.getenv("userprofile"), code_dir, repo_name)
    repo = Repo(dir_path)
    print(dir_path)
    graph = nx.DiGraph()
    for ref in repo.references:
        print(ref.commit, ref)
        if graph.has_node(ref.commit.hexsha) and ('refs' in graph.nodes[ref.commit.hexsha]):
            refs = graph.nodes[ref.commit.hexsha]['refs']
            refs = refs + ", " + ref.name
            graph.nodes[ref.commit.hexsha]['refs'] = refs
        else:
            graph.add_node(ref.commit.hexsha, refs=ref.name)
        add_parent_chain_to_graph(graph, ref.commit)

    print('graph.nodes list', list(graph.nodes))
    pos = nx.spiral_layout(graph)
    options = {
        'node_color': 'orange',
        'node_size': 2,
        'width': 1,
        'arrow_size': 3,
        'with_labels': False,
        'pos': pos
    }
    print('number_of_nodes', graph.number_of_nodes())
    print(list(graph.edges(data=True)))
    print(list(graph.nodes(data=True)))

    nx.draw_networkx(graph, **options)
    nx.write_gexf(graph, '{}.gexf'.format(repo_name))
    plt.show()
Beispiel #7
0
def plot_undirected(reader: MBoxReader,
                    layout: str = 'shell',
                    graphml: bool = False):
    """Plot an undirected social network graph from the entire `mbox`, supplied by `MBoxReader`. 
    `layout` determines the underlying `NetworkX` layout.   

    Usage:
        reader = MboxReader('path-to-mbox.mbox')
        plot_undirected(reader)

    Args:
        reader (MBoxReader): A `MBoxReader` object
        layout (str, optional): Can be one of 'shell', 'spring' or 'spiral'. Defaults to 'shell'.
        graphml (bool, optional): Determines if a .graphml file is exported to the working directory. Defaults to False.
    """

    emails = reader.extract()
    G = nx.Graph(name='Email Social Network')
    plt.figure(figsize=(12, 12))
    counter = Counter()
    for email in emails:
        ng = PeopleCombination(email)

        for combo in ng.combo:
            counter[combo] += 1

    total_combos = sum(counter.values())
    by_freq = {k: v / total_combos for k, v in counter.most_common()}
    for rel in counter.keys():
        G.add_edge(*rel, weight=by_freq[rel], count=counter[rel])

    if graphml:
        fileName = f'network-{str(uuid.uuid4().hex)[:8]}.graphml'
        nx.write_graphml(G, fileName)
        print(f"Graphml exported as {fileName}")

    if layout == 'shell':
        pos = nx.shell_layout(G)
    elif layout == 'spring':
        k = 1 / math.sqrt(G.order()) * 2
        pos = nx.spring_layout(G, k=k)
    else:
        pos = nx.spiral_layout(G)

    deg = [v * 50 for _, v in G.degree()]
    nx.draw_networkx_nodes(G, pos, node_size=deg, linewidths=1.0, alpha=0.60)
    nx.draw_networkx_edges(G,
                           pos,
                           width=1.0,
                           style='dashed',
                           edge_color='cadetblue',
                           alpha=0.6)
    nx.draw_networkx_labels(G,
                            pos, {n: n.split('@')[0]
                                  for n in G.nodes},
                            font_size=8,
                            font_color='darkorchid')

    plt.axis('off')
    plt.show()
Beispiel #8
0
def generateSpectralLayout(layout: Layout):
    positions = nx.spectral_layout(layout.G)
    print(positions)
    nx.draw(layout.G, positions)
    plt.show()

    positions = nx.planar_layout(layout.G)
    print(positions)
    nx.draw(layout.G, positions)
    plt.show()

    positions = nx.circular_layout(layout.G)
    print(positions)
    nx.draw(layout.G, positions)
    plt.show()

    positions = nx.bipartite_layout(layout.G, nx.bipartite.sets(layout.G)[0])
    print(positions)
    nx.draw(layout.G, positions)
    plt.show()

    positions = nx.shell_layout(layout.G)
    print(positions)
    nx.draw(layout.G, positions)
    plt.show()

    positions = nx.random_layout(layout.G)
    print(positions)
    nx.draw(layout.G, positions)
    plt.show()

    positions = nx.spiral_layout(layout.G)
    print(positions)
    nx.draw(layout.G, positions)
    plt.show()
Beispiel #9
0
 def test_smoke_int(self):
     G = self.Gi
     nx.random_layout(G)
     nx.circular_layout(G)
     nx.planar_layout(G)
     nx.spring_layout(G)
     nx.fruchterman_reingold_layout(G)
     nx.fruchterman_reingold_layout(self.bigG)
     nx.spectral_layout(G)
     nx.spectral_layout(G.to_directed())
     nx.spectral_layout(self.bigG)
     nx.spectral_layout(self.bigG.to_directed())
     nx.shell_layout(G)
     nx.spiral_layout(G)
     nx.kamada_kawai_layout(G)
     nx.kamada_kawai_layout(G, dim=1)
     nx.kamada_kawai_layout(G, dim=3)
Beispiel #10
0
def plot_graph(graph, name, dpi=200, width=0.5, layout='spring'):
    plt.figure(figsize=(10, 10))
    pos = nx.spiral_layout(graph)
    if layout == 'spring':
        pos = nx.spring_layout(graph)
    elif layout == 'circular':
        pos = nx.circular_layout(graph)
    nx.draw(graph, pos=pos, node_size=100, width=width)
    plt.savefig('figs/graph_view_{}.png'.format(name),
                dpi=dpi,
                transparent=True)
Beispiel #11
0
def draw_MI(M_orig, ax, layout="spring", pos=None):
    M = copy(M_orig)
    M[np.abs(M) < 1e-5] = 0.0
    M[np.abs(M) < np.median(M)] = 0.0
    G = nx.from_numpy_matrix(M)
    if pos is None:
        if layout == "spring":
            pos = nx.spring_layout(G, k=0.8 / np.sqrt(len(M)), iterations=74)
        elif layout == "bipartite":
            pos = nx.bipartite_layout(G, nodes=range(len(M) // 2))
        elif layout == "circular":
            pos = nx.circular_layout(G)
        elif layout == "spectral":
            pos = nx.spectral_layout(G)
        elif layout == "spiral":
            pos = nx.spiral_layout(G)
        elif layout == "shell":
            pos = nx.shell_layout(G)
        elif layout == "planar":
            pos = nx.planar_layout(G)
        elif layout == "fr":
            pos = nx.fruchterman_reingold_layout(G)
        elif layout == "kk":
            pos = nx.kamada_kawai_layout(G)
        if layout == "grid":
            Ggrid = nx.grid_2d_graph(*M.shape)
            xs = np.linspace(-1, 1, int(np.ceil(np.sqrt(len(M)))))
            pos = {}
            i = 0
            for x in xs:
                for y in xs:
                    if i < len(M):
                        pos[i] = np.array([x, y])
                    i += 1

    edges, weights = zip(*nx.get_edge_attributes(G, "weight").items())
    ws = np.array([w for w in weights])
    mx = max(ws)
    mn = min(ws)
    if mx != mn:
        ws = (ws - mn) / (mx - mn)
    nx.draw(
        G,
        pos,
        ax=ax,
        node_color="k",
        node_size=6,
        alphs=0.5,
        edgelist=edges,
        edge_color="k",
        width=ws,
    )
    ax.set_aspect("equal")
Beispiel #12
0
 def test_default_scale_and_center(self):
     sc = self.check_scale_and_center
     c = (0, 0)
     G = nx.complete_graph(9)
     G.add_node(9)
     sc(nx.random_layout(G), scale=0.5, center=(0.5, 0.5))
     sc(nx.spring_layout(G), scale=1, center=c)
     sc(nx.spectral_layout(G), scale=1, center=c)
     sc(nx.circular_layout(G), scale=1, center=c)
     sc(nx.shell_layout(G), scale=1, center=c)
     sc(nx.spiral_layout(G), scale=1, center=c)
     sc(nx.kamada_kawai_layout(G), scale=1, center=c)
Beispiel #13
0
    def test_spiral_layout(self):

        G = self.Gs

        # a lower value of resolution should result in a more compact layout
        # intuitively, the total distance from the start and end nodes
        # via each node in between (transiting through each) will be less,
        # assuming rescaling does not occur on the computed node positions
        pos_standard = nx.spiral_layout(G, resolution=0.35)
        pos_tighter = nx.spiral_layout(G, resolution=0.34)
        distances = self.collect_node_distances(pos_standard)
        distances_tighter = self.collect_node_distances(pos_tighter)
        assert sum(distances) > sum(distances_tighter)

        # return near-equidistant points after the first value if set to true
        pos_equidistant = nx.spiral_layout(G, equidistant=True)
        distances_equidistant = self.collect_node_distances(pos_equidistant)
        for d in range(1, len(distances_equidistant) - 1):
            # test similarity to two decimal places
            assert almost_equal(distances_equidistant[d],
                                distances_equidistant[d + 1], 2)
Beispiel #14
0
def plot_directed(reader: MBoxReader,
                  layout: str = 'shell',
                  graphml: bool = False) -> None:
    """
    Plot a directed social network graph from the entire `mbox`, supplied by `MBoxReader`. 
    `layout` determines the underlying `NetworkX` layout.   

    Usage:
        reader = MboxReader('path-to-mbox.mbox')
        plot_directed(reader)
    Args:
        reader (MBoxReader): A `MBoxReader` object
        layout (str, optional): Can be one of 'shell', 'spring' or 'spiral'. Defaults to 'shell'.
        graphml (bool, optional): Determines if a .graphml file is exported to the working directory. Defaults to False.
    """

    emails = reader.extract()
    plt.figure(figsize=(12, 12))
    G = nx.MultiDiGraph(name='Email Social Network')
    for email in emails:
        sender = email.sender.name
        source_addr = sender if sender != '' else email.sender.email.split(
            '@')[0]

        all_recipients = [
            em.name if em.name != '' or None else em.email.split('@')[0]
            for em in email.recipients + email.cc
        ]

        for recipient in all_recipients:
            G.add_edge(source_addr, recipient, message=email.subject)

    if graphml:
        fileName = f'network-{str(uuid.uuid4().hex)[:8]}.graphml'
        nx.write_graphml(G, fileName)

    if layout == 'shell':
        pos = nx.shell_layout(G)
    elif layout == 'spring':
        pos = nx.spring_layout(G)
    else:
        pos = nx.spiral_layout(G)
    nx.draw(G,
            pos,
            node_size=0,
            alpha=0.4,
            edge_color='cadetblue',
            font_size=7,
            with_labels=True)
    ax = plt.gca()
    ax.margins(0.08)
    plt.show()
Beispiel #15
0
 def test_scale_and_center_arg(self):
     sc = self.check_scale_and_center
     c = (4, 5)
     G = nx.complete_graph(9)
     G.add_node(9)
     sc(nx.random_layout(G, center=c), scale=0.5, center=(4.5, 5.5))
     # rest can have 2*scale length: [-scale, scale]
     sc(nx.spring_layout(G, scale=2, center=c), scale=2, center=c)
     sc(nx.spectral_layout(G, scale=2, center=c), scale=2, center=c)
     sc(nx.circular_layout(G, scale=2, center=c), scale=2, center=c)
     sc(nx.shell_layout(G, scale=2, center=c), scale=2, center=c)
     sc(nx.spiral_layout(G, scale=2, center=c), scale=2, center=c)
     sc(nx.kamada_kawai_layout(G, scale=2, center=c), scale=2, center=c)
Beispiel #16
0
 def test_smoke_string(self):
     G = self.Gs
     vpos = nx.random_layout(G)
     vpos = nx.circular_layout(G)
     vpos = nx.planar_layout(G)
     vpos = nx.spring_layout(G)
     vpos = nx.fruchterman_reingold_layout(G)
     vpos = nx.spectral_layout(G)
     vpos = nx.shell_layout(G)
     vpos = nx.spiral_layout(G)
     if self.scipy is not None:
         vpos = nx.kamada_kawai_layout(G)
         vpos = nx.kamada_kawai_layout(G, dim=1)
Beispiel #17
0
def demo():
    nodes_dict = {
        'node1': {
            'node2': 1.3,
            'node3': 2
        },
        'node2': {
            'node1': 1.3,
            'node4': 3,
            'node5': 0.5
        },
        'node3': {
            'node2': 1,
            'node4': 2
        }
    }

    cng = create_nx_graph(nodes_dict)

    # if no nodes want to be emphasised, if node_colorlist is None, each node has a random color
    cng.plot(figsize=(8, 8),
             node_sizelist=[1000],
             font_size=20,
             edge_color='blue')
    cng.plot(figsize=(8, 8),
             node_colorlist=['blue'],
             font_size=20,
             edge_color='blue')

    # we want to emphasis node1, we give size and color for it and others
    cng.plot(nodelist=['node1'],
             node_colorlist=['red', 'blue'],
             node_sizelist=[1000, 100],
             figsize=(8, 8),
             font_size=20)

    # we want to emphasis node1 and node2, we give size and color for it and others
    cng.plot(nodelist=['node1', 'node2'],
             node_colorlist=['red', 'blue', 'green'],
             node_sizelist=[1000, 500, 100],
             figsize=(8, 8),
             font_size=20)

    # other layout
    pos = nx.spiral_layout(cng.networkG)
    cng.plot(figsize=(8, 8),
             node_sizelist=[1000],
             font_size=20,
             edge_color='blue',
             pos=pos)
    def layout_network(self, order_by_ip=True, rectangular_grid=False):
        """Determine node locations/coordinates to allow visualization/plotting of the network.

        Parameters
        ----------
        order_by_ip : bool
            Set to true if you want node positions lists ordered by ip address.

        rectangular_grid : bool
            Set to true for a grid placement that is roughly rectangular.
             It will not be exactly rectangular because noise is added to avoid edge line overlap.

        Notes
        -------
        1) Various networkx options are listed in layout_types below.  Pick any compatible layout.
        2) networkx layouts return dictionaries that can't be sorted.
            The order_by_ip option re-orders node locations based on how the layout
            dictionary is iterated, which may or may not improve plot readability.

        See: https://networkx.github.io/documentation/stable/reference/drawing.html"""

        # networkx routines to find node layout
        # Each returns a dictionary of positions keyed by node.  The positions are [x, y].
        layout_types = [
            nx.bipartite_layout, nx.circular_layout, nx.kamada_kawai_layout,
            nx.planar_layout, nx.random_layout, nx.rescale_layout,
            nx.rescale_layout_dict, nx.shell_layout, nx.spring_layout,
            nx.spectral_layout, nx.spiral_layout, nx.multipartite_layout
        ]

        if rectangular_grid:
            # Custom square layout with noise created to best spread network sorted by IP address
            self.node_positions = self.square_layout(self.send_graph,
                                                     noise=0.15)
        else:
            # Choose any of the layout_types for line below
            self.node_positions = nx.spiral_layout(self.send_graph)

        # Sort node locations by ip address if the user requests.
        # It is not clear the order of the nx layouts since they are dictionaries that can't be sorted
        # Re-ordering may/may not improve plot readability, but it won't corrupt the node coordinates
        if order_by_ip:
            # Extract nodes from position dictionary then sort them in a list
            tmp = {}
            node = (i for i in sorted(self.node_positions.keys(),
                                      key=ipaddress.IPv4Address))
            for k, v in self.node_positions.items():
                tmp[next(node)] = v
            self.node_positions = tmp
Beispiel #19
0
 def test_center_parameter(self):
     G = nx.path_graph(1)
     vpos = nx.random_layout(G, center=(1, 1))
     vpos = nx.circular_layout(G, center=(1, 1))
     assert tuple(vpos[0]) == (1, 1)
     vpos = nx.planar_layout(G, center=(1, 1))
     assert tuple(vpos[0]) == (1, 1)
     vpos = nx.spring_layout(G, center=(1, 1))
     assert tuple(vpos[0]) == (1, 1)
     vpos = nx.fruchterman_reingold_layout(G, center=(1, 1))
     assert tuple(vpos[0]) == (1, 1)
     vpos = nx.spectral_layout(G, center=(1, 1))
     assert tuple(vpos[0]) == (1, 1)
     vpos = nx.shell_layout(G, center=(1, 1))
     assert tuple(vpos[0]) == (1, 1)
     vpos = nx.spiral_layout(G, center=(1, 1))
     assert tuple(vpos[0]) == (1, 1)
Beispiel #20
0
 def test_smoke_int(self):
     G = self.Gi
     vpos = nx.random_layout(G)
     vpos = nx.circular_layout(G)
     vpos = nx.planar_layout(G)
     vpos = nx.spring_layout(G)
     vpos = nx.fruchterman_reingold_layout(G)
     vpos = nx.fruchterman_reingold_layout(self.bigG)
     vpos = nx.spectral_layout(G)
     vpos = nx.spectral_layout(G.to_directed())
     vpos = nx.spectral_layout(self.bigG)
     vpos = nx.spectral_layout(self.bigG.to_directed())
     vpos = nx.shell_layout(G)
     vpos = nx.spiral_layout(G)
     if self.scipy is not None:
         vpos = nx.kamada_kawai_layout(G)
         vpos = nx.kamada_kawai_layout(G, dim=1)
Beispiel #21
0
def createLayout(G, layout=None):
    pos = nx.spring_layout(G, seed=36)
    if layout == 'Planar' and nx.check_planarity(G)[0]:
        print(nx.check_planarity(G))
        pos = nx.planar_layout(G)
    elif layout == 'Circular':
        pos = nx.circular_layout(G)
    elif layout == 'Kamada-Kawai':
        pos = nx.kamada_kawai_layout(G)
    elif layout == 'Random':
        pos = nx.random_layout(G)
    elif layout == 'Spectral':
        pos = nx.spectral_layout(G)
    elif layout == 'Spiral':
        pos = nx.spiral_layout(G, resolution=1.0)

    return pos
Beispiel #22
0
def save_graph(G, filename):

	plt.figure(num=None, figsize=(100, 100), dpi=100)
	plt.axis('off')
	fig = plt.figure(1)
	
	pos = nx.spiral_layout(G, center=[0,0])
	pos = nx.spring_layout(G, k=2, iterations=0)
	
	plt.figtext(.5, .85, 'PARKOUR THEORY', fontsize=130, fontweight='bold', ha='center')
	
	nx.draw_networkx_nodes(G, pos, alpha=0.25)
	nx.draw_networkx_edges(G, pos, alpha=0.1)
	nx.draw_networkx_labels(G, pos, font_color='r', font_size=11)

	plt.savefig(filename, bbox_inches="tight")
	pylab.close()
	del fig
Beispiel #23
0
def CreateGraph():
    G = nx.Graph()
    f = open('input.txt')

    titulo = f.readline()  # Título da janela
    plt.gcf().canvas.set_window_title(titulo)

    num = int(f.readline())  # Lê a segunda linha do .txt

    n = int(f.readline())  # n = Número de arestas

    for i in range(n):
        graph_edge_list = f.readline().split(",")

        graph_edge_list[1] = graph_edge_list[1].rstrip('\n')

        #print(graph_edge_list)
        #print("\n\n")
        G.add_edge(graph_edge_list[0], graph_edge_list[1])

    # Define o layout com base no input
    if num == 1:
        layout = nx.circular_layout(G)

    elif num == 2:
        layout = nx.random_layout(G)

    elif num == 3:
        layout = nx.shell_layout(G)

    elif num == 4:
        layout = nx.spring_layout(G)

    elif num == 5:
        layout = nx.spectral_layout(G)

    elif num == 6:
        layout = nx.spiral_layout(G)

    else:
        print(f"{num}")
        layout = nx.circular_layout(G)

    return G, layout
Beispiel #24
0
 def draw_graph(self, node_type='', layout=''):
     if layout == 'spring':
         pos = nx.spring_layout(self.scgraph.code_graph)
     if layout == 'spectral':
         pos = nx.spectral_layout(self.scgraph.code_graph)
     if layout == 'planar':
         pos = nx.planar_layout(self.scgraph.code_graph)
     if layout == 'shell':
         pos = nx.shell_layout(self.scgraph.code_graph)
     if layout == 'circular':
         pos = nx.circular_layout(self.scgraph.code_graph)
     if layout == 'spiral':
         pos = nx.spiral_layout(self.scgraph.code_graph)
     if layout == 'random':
         pos = nx.random_layout(self.scgraph.code_graph)
     if node_type == 'cycles':
         self.scgraph.draw('cycles', layout)
     if node_type == 'dict':
         self.scgraph.draw('dict', layout)
def selectLayout(G, layout_selected):
    if layout_selected == 'circular_layout':
        pos = nx.circular_layout(G)
    if layout_selected == 'spring_layout':
        pos = nx.spring_layout(G)
    if layout_selected == 'kamada_kawai_layout':
        pos = nx.kamada_kawai_layout(G)
    if layout_selected == 'random_layout':
        pos = nx.random_layout(G)
    if layout_selected == 'shell_layout':
        pos = nx.shell_layout(G)
    if layout_selected == 'spectral_layout':
        pos = nx.spectral_layout(G)
    if layout_selected == 'planar_layout':
        pos = nx.planar_layout(G)
    if layout_selected == 'fruchterman_reingold_layout':
        pos = nx.fruchterman_reingold_layout(G)
    if layout_selected == 'spiral_layout':
        pos = nx.spiral_layout(G)
    return pos
Beispiel #26
0
 def test_empty_graph(self):
     G = nx.empty_graph()
     vpos = nx.random_layout(G, center=(1, 1))
     assert vpos == {}
     vpos = nx.circular_layout(G, center=(1, 1))
     assert vpos == {}
     vpos = nx.planar_layout(G, center=(1, 1))
     assert vpos == {}
     vpos = nx.bipartite_layout(G, G)
     assert vpos == {}
     vpos = nx.spring_layout(G, center=(1, 1))
     assert vpos == {}
     vpos = nx.fruchterman_reingold_layout(G, center=(1, 1))
     assert vpos == {}
     vpos = nx.spectral_layout(G, center=(1, 1))
     assert vpos == {}
     vpos = nx.shell_layout(G, center=(1, 1))
     assert vpos == {}
     vpos = nx.spiral_layout(G, center=(1, 1))
     assert vpos == {}
Beispiel #27
0
 def set_nx_layout(self, layout='random', **kwargs):
     """Configura el layout para dibujar el grafo con networkx"""
     g = self.g
     if layout == 'random':
         self.pos = nx.random_layout(g)
     elif layout == 'shell':
         self.pos = nx.shell_layout(g, **kwargs)
     elif layout == 'spring':
         self.pos = nx.spring_layout(g, **kwargs)
     elif layout == 'circular':
         self.pos = nx.circular_layout(g, **kwargs)
     elif layout == 'kamada_kawai':
         self.pos = nx.kamada_kawai_layout(g, **kwargs)
     elif layout == 'bipartite':
         self.pos = nx.bipartite_layout(g, **kwargs)
     elif layout == 'spectral':
         self.pos = nx.spectral_layout(g, **kwargs)
     elif layout == 'spiral':
         self.pos = nx.spiral_layout(g, **kwargs)
     elif layout == 'planar':
         self.pos = nx.planar_layout(g, **kwargs)
Beispiel #28
0
def generateGraph(NG, NH, NR, typeGraph, setScale, layoutMethod):

    nmbOutputs = len(NG)
    nmbOutputs2 = len(NG[0])
    #below function will read through the mat file and try to find how many modules their are

    #using the network functions create a direction graph (nodes with a connection with a direction so connection 1 to 2 has a direction and is not the same as 2 to 1)
    plot = nx.DiGraph()
    plot.add_nodes_from(range(nmbOutputs))

    for x in range(nmbOutputs):
        for y in range(nmbOutputs2):
            if (NG[x][y] == 1):
                plot.add_edge(y, x)

    print("number of nodes: ", plot.number_of_nodes(), " number of edges: ",
          plot.number_of_edges())

    pos = []

    typeGraph = layoutMethod.get()
    #creating coordinates
    #the below functions can be chosen and generate position for the network and return them
    if (typeGraph == "circular"):
        pos = nx.circular_layout(plot, scale=setScale, center=(500, 500))
        print("circular layout")
    if (typeGraph == "kamada_kawai"):
        pos = nx.kamada_kawai_layout(plot, scale=setScale, center=(500, 500))
        print("kamada_kawai layout")
    if (typeGraph == "spring"):
        pos = nx.spring_layout(plot, scale=setScale, center=(500, 500))
        print("spring layout")
    if (typeGraph == "spectral"):
        pos = nx.spectral_layout(plot, scale=setScale, center=(500, 500))
        print("spectral layout")
    if (typeGraph == "spiral"):
        pos = nx.spiral_layout(plot, scale=setScale, center=(500, 500))
        print("spiral layout")
    return pos
Beispiel #29
0
    def plot_graph(
        self,
        save_file: bool = False,
        output_filename: str = f"test.jpg",
        filtered_graph: nx.Graph = None,
    ):
        """

        Args:
            graph_type:
            save_file:
            output_filename:
            filtered_graph:

        Returns:

        """
        graph = filtered_graph if filtered_graph is not None else self.graph
        labels = {}
        for node in list(graph.nodes):
            labels[node] = node.key_name
        node_colors = self.generate_node_color_list(graph)
        # pos = nx.bipartite_layout(graph, graph.nodes, align='horizontal')
        pos = nx.spiral_layout(graph)
        # pos = nx.spring_layout(graph)
        nx.draw(
            graph,
            pos=pos,
            arrowsize=20,
            verticalalignment='bottom',
            labels=labels,
            with_labels=True,
            node_color=node_colors,
        )
        if not save_file:
            plt.show()
        else:
            plt.savefig(output_filename)
def extract_dynamic_ca(str1):
    htap = '/Users/apple/Documents/gs_result/'
    global cur
    global edges
    res = 0
    alters = []
    if str1 == 'ego':
        Chen = 'O6tge4UAAAAJ.parse'
        # addr[8] is the list of co-authors; starting from addr[12] can cal the papers.
        addr = extract_info(htap, Chen)
        ego_papers = []
        set_papers = set()
        print('total papers: ', len(addr) - 12)
        if len(addr) > 8:
            new_dict = literal_eval(addr[8])
            print('total co-authors:', len(new_dict))
            # print(new_dict)
            nodes = [new_dict[key] for key in new_dict]
        if len(addr) > 12:
            # print(addr[12])
            for paper in addr[12:]:
                new_list = literal_eval(paper)
                ego_papers.append(new_list)
                # print(new_list)
                if re.match('\d{4}', new_list[-1]):
                    cur += 1
                    # print(new_list[1], new_list[-1])
                    set_papers.add(new_list[1])
                    # print(new_list)
        print('papers with year:', cur)

        ego = addr[1]
        nodes.append(ego)
        print(ego)
        alters = []
        for key in new_dict:
            # print(key, new_dict[key])
            addr = extract_info(htap, key + '.parse')
            year = find_earliest_year(set_papers, addr)
            if year != 2021:
                res += 1
                # print(ego,'and',new_dict[key], key, "'s co-authorship begin from",year)
                edges.append([ego, new_dict[key], year])
                alters.append(key)

        print('co-author with first year:', res)
        print('co-author with gs_result files:', good)
        print(alters)
    else:
        # filename = 'thu_net.json'
        # with open(filename, 'r') as f:

        alters = preparation.preparation()

    #print(alters)
    for i in range(len(alters)):
        key1 = alters[i]
        addr = extract_info(htap, key1 + '.parse')
        name1 = addr[1]
        alter1_papers = set()
        if len(addr) > 12:
            # print(addr[12])
            for paper in addr[12:]:
                new_list = literal_eval(paper)
                # print(new_list)
                if re.match('\d{4}', new_list[-1]):
                    cur += 1
                    # print(new_list[1], new_list[-1])
                    alter1_papers.add(new_list[1])
        for j in range(i + 1, len(alters)):
            key = alters[j]
            addr = extract_info(htap, key + '.parse')
            name2 = addr[1]
            year = find_earliest_year(alter1_papers, addr)
            if year != 2021:
                res += 1
                # print(new_dict[key1],'and',new_dict[key], key, "'s co-authorship begin from",year)
                edges.append([name1, name2, year])
                # edges.append([new_dict[key1], new_dict[key], year])
    print('# of eges in ego network:', res)
    edges = sorted(edges, key=lambda x: x[2])

    print(len(edges))
    # print(len(nodes))
    # print(nodes)

    for edge in edges:
        print(edge)

    # networkx visualization is a total piece of shit...
    G = nx.Graph()
    graph_cur = 0
    # G.add_nodes_from([(node,{'name': node}) for node in nodes])
    year = edges[0][2]
    for edge in edges:
        cur_year = edge[2]
        if cur_year != year:
            year = cur_year
            edge_labels = nx.get_edge_attributes(G, 'year')
            # edge_labels = nx.get_edge_attributes(G, 'year')
            # nx.write_gexf(G, "test"+str(graph_cur)+".gexf")
            graph_cur += 1
            pos = nx.spiral_layout(G)
            nx.draw(G,
                    pos,
                    node_color='yellow',
                    edge_color='brown',
                    with_labels=True,
                    font_size=8,
                    node_size=10)
            nx.draw_networkx_edge_labels(G,
                                         pos,
                                         edge_labels=edge_labels,
                                         font_size=8)
            plt.show()
        G.add_edge(edge[0], edge[1], year=str(edge[2]))