コード例 #1
0
    def test_multipartite_layout(self):
        sizes = (0, 5, 7, 2, 8)
        G = nx.complete_multipartite_graph(*sizes)

        vpos = nx.multipartite_layout(G)
        assert len(vpos) == len(G)

        start = 0
        for n in sizes:
            end = start + n
            assert all(vpos[start][0] == vpos[i][0]
                       for i in range(start + 1, end))
            start += n

        vpos = nx.multipartite_layout(G,
                                      align="horizontal",
                                      scale=2,
                                      center=(2, 2))
        assert len(vpos) == len(G)

        start = 0
        for n in sizes:
            end = start + n
            assert all(vpos[start][1] == vpos[i][1]
                       for i in range(start + 1, end))
            start += n

        pytest.raises(ValueError, nx.multipartite_layout, G, align="foo")
コード例 #2
0
ファイル: test_layout.py プロジェクト: Rigosebuta/biathlon
 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.multipartite_layout(G)
     nx.kamada_kawai_layout(G)
コード例 #3
0
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
コード例 #4
0
 def print_graph_pretty(self, filename):
     # make a networkx graph and draw it to file
     NG = nx.DiGraph()
     label_dict = {}
     # G.n = maximal number of nodes
     for i in range(self.G.n):
         if i not in NG:
             NG.add_node(i,depth = 0)
             try:
                 label_dict[i]=self.instructions[i]
             except:
                 pass
         depth = NG.nodes[i]['depth']
         # G[i] is a list of the neighbors of the ith node.
         for j in self.G[i]:
             NG.add_node(j,depth = depth+1)
             try:
                 label_dict[j]=self.instructions[j]
             except:
                 pass
                 # print("out of range j=%d, istrutions = %s "%(j,self.instructions))
                 # exit()
             NG.add_edge(i,j)
     nx.draw_networkx(NG,pos = nx.multipartite_layout(NG, subset_key = 'depth', align='horizontal') ,with_labels=True, labels=label_dict)
     plt.savefig(filename)
コード例 #5
0
 def image(self,
           with_labels=True,
           font_weight='bold',
           position_nodes=None,
           input_qubits=[]):
     """
     Produces a matplotlib image of the graph associated to the graph state.
     """
     pos_nodes = position_nodes
     if pos_nodes is None:
         # checks if all nodes have attribute "layer", and, if they do, plot the graph using multilayer_layout
         if all([
                 "layer" in this_node[1]
                 for this_node in self.graph.nodes(data=True)
         ]):
             pos_nodes = nx.multipartite_layout(self.graph,
                                                subset_key="layer")
         else:
             pos_nodes = nx.spring_layout(self.graph)
     color_map = [
         'red' if this_node in input_qubits else 'blue'
         for this_node in self.graph.nodes
     ]
     nx.draw(self.graph,
             pos_nodes,
             node_color=color_map,
             with_labels=with_labels,
             font_weight=font_weight)
コード例 #6
0
def visualize_flow_network(flow_network: np.ndarray, layers: List[list], max_flow: np.ndarray = None):
    """ Visualize flow network with or without max flow in network

    Parameters
    ----------
    flow_network : np.ndarray
        flow network as adjacency matrix
    layers : List[list]
        structure of flow network
    max_flow : np.ndarray
        max flow in flow network as adjacency matrix
    """
    G = nx.from_numpy_array(flow_network, create_using=nx.MultiDiGraph)

    for layer_index, layer in enumerate(layers):
        for node in layer:
            G.nodes(data=True)[node]['layer'] = layer_index

    pos = nx.multipartite_layout(G, subset_key='layer')

    nx.draw(G, pos, with_labels=True, font_weight='bold')
    if max_flow is None:
        edge_labels = dict([((n1, n2), f'{flow_network[n1][n2]}')
                            for n1, n2, d in G.edges])
    else:
        edge_labels = dict([((n1, n2), f'{max_flow[n1][n2]}/{flow_network[n1][n2]}')
                            for n1, n2, d in G.edges])

    nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_size=8, label_pos=0.6)
    plt.show()
コード例 #7
0
 def create_bowtie(self):
     threats_bars = dict(
         zip(self.threats, [bar.split(",") for bar in self.barriers]))
     consequences_mits = dict(
         zip(self.consequences,
             [mit.split(",") for mit in self.mitigations]))
     width = len(sum([bar.split(",") for bar in self.barriers], [])) + len(self.threats) + \
         len(sum([mit.split(",") for mit in self.mitigations], [])) + len(self.consequences)
     hazards_ue = [self.hazard, self.undesired_event, self.bowtie_id]
     Bowtie.connect_nodes(branch=threats_bars,
                          master=hazards_ue,
                          labels=["threat", "barrier"],
                          width=width)
     Bowtie.connect_nodes(branch=consequences_mits,
                          master=hazards_ue,
                          labels=["consequence", "mitigation"],
                          width=width)
     pos = nx.multipartite_layout(Bowtie.graph, subset_key="layer")
     nx.draw_networkx_nodes(Bowtie.graph, pos, node_size=750)
     nx.draw_networkx_edges(Bowtie.graph,
                            pos,
                            edgelist=Bowtie.graph.edges(),
                            edge_color="grey")
     nx.draw_networkx_labels(Bowtie.graph,
                             pos,
                             font_size=12,
                             verticalalignment="top")
     plt.show()
コード例 #8
0
def draw_cell_graph(plot_title, cell_G, from_nodes_cells, to_nodes_cells):
    # not plotting on main graph as we need to show synapses with both electric and chemical together
    G = build_cell_graph_combining_multi_edges(cell_G=cell_G)

    if len(G.nodes()) < 100:
        pos = nx.multipartite_layout(G, subset_key="layer")
    else:
        pos = nx.spring_layout(G)

    node_color_values = color_nodes(G=G,
                                    src_nodes=from_nodes_cells,
                                    target_nodes=to_nodes_cells)

    edge_colors = nx.get_edge_attributes(G, 'color').values()
    edge_weights = nx.get_edge_attributes(G, 'weight').values()

    plotter.figure(plot_title)
    plotter.title(plot_title)

    nx.draw(G,
            pos,
            node_size=1000,
            node_color=node_color_values,
            edge_color=edge_colors,
            with_labels=True)
コード例 #9
0
def draw_class_graph(plot_title, class_G, from_nodes_class, to_nodes_class,
                     cell_pathways_count):
    if len(class_G.nodes()) < 100:
        pos = nx.multipartite_layout(class_G, subset_key="layer")
    else:
        pos = nx.spring_layout(class_G)

    node_color_values = color_nodes(G=class_G,
                                    src_nodes=from_nodes_class,
                                    target_nodes=to_nodes_class)

    edge_attr = nx.get_edge_attributes(class_G, 'attr_dict').values()
    edge_colors = nx.get_edge_attributes(class_G, 'color').values()
    # edge_colors = [edge['color'] for edge in edge_attr]
    # edge_colors = nx.get_edge_attributes(class_G,'color').values()
    # edge_weights = nx.get_edge_attributes(class_G,'weight').values()

    plotter.figure(plot_title)
    plotter.title(plot_title)

    nx.draw(class_G,
            pos,
            node_size=1000,
            node_color=node_color_values,
            edge_color=edge_colors,
            with_labels=True)
    exclude_nodes = []
    exclude_nodes.extend(from_nodes_class)
    exclude_nodes.extend(to_nodes_class)
    interneurons_list, pathways_list = get_graph_details(
        G=class_G, exclude_nodes=exclude_nodes)
    write_plot_legend(G=class_G,
                      pathways_count=cell_pathways_count,
                      interneurons_count=len(interneurons_list))
コード例 #10
0
def display_flow_network(graph: nx.DiGraph, filename: str = ""):
    pos = nx.multipartite_layout(graph, subset_key="layer")
    colors = nx.get_edge_attributes(graph, 'color').values()
    plt.figure(figsize=(8, 8))
    nx.draw(graph, pos, edge_color=colors, with_labels=True)
    plt.axis("equal")
    if filename:
        plt.savefig(filename)
    plt.show()
コード例 #11
0
def test_multipartite_layout_nonnumeric_partition_labels():
    """See gh-5123."""
    G = nx.Graph()
    G.add_node(0, subset="s0")
    G.add_node(1, subset="s0")
    G.add_node(2, subset="s1")
    G.add_node(3, subset="s1")
    G.add_edges_from([(0, 2), (0, 3), (1, 2)])
    pos = nx.multipartite_layout(G)
    assert len(pos) == len(G)
コード例 #12
0
ファイル: NN.py プロジェクト: YA9/AMP
    def print(self):
        """ The print function displays a graphical model of the neural network, representing the neurons as nodes and displaying the weights between the connections. This uses the NetworkX library. """
        G = nx.Graph()
        self.nodes = []

        # connecting the input to the first deep layer
        nodes = []
        for idx, i in enumerate(self.inputs.neurons):
            for j in self.layers_deep[0].neurons:
                G.add_edge(i, j, weight=round(j.prev_weight[idx], 5))
            nodes.append(i)
        self.nodes.append(nodes)

        # connecting the deep layers together
        for i in range(self.n_layers - 1):
            for idx, neuron1 in enumerate(self.layers_deep[i].neurons):
                for neuron2 in self.layers_deep[i + 1].neurons:
                    G.add_edge(neuron1,
                               neuron2,
                               weight=round(neuron2.prev_weight[idx], 5))
        for layer in self.layers_deep:
            nodes = []
            for neuron in layer.neurons:
                nodes.append(neuron)
            self.nodes.append(nodes)

        # connecting the final deep layer to the output layer
        nodes = []
        for idx, neuron in enumerate(self.layers_deep[self.n_layers -
                                                      1].neurons):
            for outputNeuron in self.outputs.neurons:
                G.add_edge(neuron,
                           outputNeuron,
                           weight=round(outputNeuron.prev_weight[idx], 5))
        for outputNeuron in self.outputs.neurons:
            nodes.append(outputNeuron)
        self.nodes.append(nodes)

        # stores the graph inside the object
        self.graph = G

        # defines each layer in the network by a priority number (count). This is to maintain the order of the layers when displaying the graph.
        nx.set_node_attributes(self.graph, 0, "layer")
        count = 0
        for layer in self.nodes:
            count += 1
            for neuron in layer:
                self.graph.nodes[neuron]["layer"] = count

        pos = nx.multipartite_layout(self.graph, subset_key="layer")
        nx.draw(self.graph, pos, with_labels=False)
        labels = nx.get_edge_attributes(self.graph, "weight")
        nx.draw_networkx_edge_labels(self.graph, pos, labels)
コード例 #13
0
ファイル: convertToNX.py プロジェクト: tomek153/SR-zaoczne
def showMultipartite(_df):
    print("Graph generation started...")
    G = nx.MultiGraph()
    relation = mappedRelation(_df)
    listOfNodes1 = [seq[0] for seq in mappedRelation(_df)]
    listOfNodes2 = [seq[1] for seq in mappedRelation(_df)]
    G.add_nodes_from(listOfNodes1, layer=0)
    G.add_nodes_from(listOfNodes2, layer=1)
    G.add_edges_from(relation)
    pos = nx.multipartite_layout(G, subset_key="layer")
    nx.draw(G, pos, with_labels=True, edge_color="grey")
    print("Graph generated.")
    plt.show()
コード例 #14
0
ファイル: DFtoNX.py プロジェクト: AdamskiR/SR
def showMultipartiteProdCat(DFs):
    G = nx.MultiGraph()

    DFsWithoutItems = []
    for x in range(0, 7):
        df = DFs[x][DFs[x].Object != 'item']
        DFsWithoutItems.append(df)

    listOfNodes = []
    for x in range(0, 6):  #predicates
        temp = []
        for y1, y2 in DFs[x].iterrows():
            temp.append(y2[0])
        listOfNodes.append(temp)

    # Don't forget bout the products
    temp = []
    for y1, y2 in DFs[6].iterrows():
        temp.append(y2[2])
    listOfNodes.append(temp)

    print(listOfNodes)

    ## Not possible to add same node few times, so we can do it like this
    for it, x in enumerate(listOfNodes):
        G.add_nodes_from(x, layer=it)

    for x in range(0, 6):
        rels = retMappedRelation(DFsWithoutItems[x])
        G.add_edges_from(rels)

    pos = nx.multipartite_layout(G, subset_key="layer")

    nx.draw(G, pos, with_labels=True, width=0.5, font_size=5, edge_color='r')

    #Relation also here so i could colour them
    rels = retMappedRelation(DFsWithoutItems[6])
    nx.draw_networkx_edges(
        G,
        pos,
        edgelist=rels,
        width=0.5,
        alpha=0.5,
        edge_color="g",
    )
    plt.show()
コード例 #15
0
    def get_tripartite_graph(self, df_party_weights: DataFrame,
                             df_media_weights: DataFrame):
        """
        Creates a tripartite graph fom the term-weight-tuples which were previously calculated.

        :param df_party_weights: The term-weight-tuples dataframe of the parties.
        :param df_media_weights: The term-weight-tuples dataframe of the media.

        :return: The tripartite graph as figure.
        """
        graph = nx.Graph()
        graph.add_nodes_from(df_party_weights["party"], bipartite=0)
        graph.add_nodes_from(df_party_weights["term"], bipartite=1)
        graph.add_nodes_from(df_media_weights["media"], bipartite=2)

        df_party_weights["normalized_weight"] = df_party_weights[
            "weight"].apply(
                lambda row: row / df_party_weights["weight"].max() * 4)

        df_media_weights["normalized_weight"] = df_media_weights[
            "weight"].apply(
                lambda row: row / df_media_weights["weight"].max() * 4)

        graph.add_weighted_edges_from(
            [(row["party"], row["term"], row["normalized_weight"])
             for idx, row in df_party_weights.iterrows()],
            weight="weight",
        )

        graph.add_weighted_edges_from(
            [(row["media"], row["term"], row["normalized_weight"])
             for idx, row in df_media_weights.iterrows()],
            weight="weight",
        )

        plt.close()
        fig = plt.figure(1, figsize=(10, 9))

        nx.draw(
            graph,
            pos=nx.multipartite_layout(graph, subset_key="bipartite"),
            width=list(nx.get_edge_attributes(graph, "weight").values()),
            with_labels=True,
        )

        return fig
コード例 #16
0
def show_Multipartite(df):
    G = nx.MultiGraph()
    nodes = assign_IDs(df)
    relations = make_relation_list(df)

    nodes_layer1 = []  # predicates list
    for n in nodes[0]:
        nodes_layer1.append(n)

    nodes_layer2 = []  # objects list
    for n in nodes[1]:
        nodes_layer2.append(n)

    G.add_nodes_from(nodes_layer1, layer=0)
    G.add_nodes_from(nodes_layer2, layer=1)
    print(nodes_layer2)
    G.add_edges_from(relations)
    pos = nx.multipartite_layout(G, subset_key="layer")
    return nx.draw(G, pos, with_labels=True, edge_color='green')
コード例 #17
0
def main(new):
    global data, bigdata
    num_nodes = len(data)
    print('num of nodes:', num_nodes)
    G = nx.path_graph(num_nodes)
    # networkxでノードに座標を追加
    new.update(nx.multipartite_layout(G, scale=500))
    # 追加した座標をノードデータに書き込み
    for i in range(len(data)):
        try:
            if data[i]['data']['id']:
                data[i]["position"]={ 
                    "x": pos[i][0],
                    "y": pos[i][1]
                }
        except Exception as e:
            raise e
    print("position added")
    for i in range(20000):
        data.append(bigdata[i])
コード例 #18
0
ファイル: DFtoNX.py プロジェクト: AdamskiR/SR
def showUniversalMultipartite(df):
    G = nx.MultiGraph()
    rels = retMappedRelation(df)
    nodes = retIDs(df)

    listOfNodes1 = []
    for x in nodes[0]:  #predicates
        listOfNodes1.append(x)

    listOfNodes2 = []
    for x in nodes[1]:  #objects
        listOfNodes2.append(x)

    G.add_nodes_from(listOfNodes1, layer=0)
    G.add_nodes_from(listOfNodes2, layer=1)
    print(listOfNodes2)

    G.add_edges_from(rels)
    pos = nx.multipartite_layout(G, subset_key="layer")
    nx.draw(G, pos, with_labels=True, edge_color='grey')  #node_color=color,

    plt.show()
コード例 #19
0
def draw_flow_network(graph, title, flow_dict=None):
    plt.figure(num=title)
    positions = nx.multipartite_layout(graph, subset_key='layer')
    nx.draw(graph,
            pos=positions,
            node_color="green",
            node_size=600,
            labels={node: node
                    for node in graph})

    # Draw with flow amounts
    if flow_dict:
        edge_labels = {}
        for tile_id, flow in flow_dict.items():
            for end_edge, flow_amount in flow.items():
                edge_labels[(tile_id, end_edge)] = flow_amount

    # Draw with capacities
    else:
        edge_labels = nx.get_edge_attributes(graph, 'capacity')

    nx.draw_networkx_edge_labels(graph, pos=positions, edge_labels=edge_labels)
コード例 #20
0
ファイル: test_layout.py プロジェクト: Rigosebuta/biathlon
 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 == {}
     vpos = nx.multipartite_layout(G, center=(1, 1))
     assert vpos == {}
     vpos = nx.kamada_kawai_layout(G, center=(1, 1))
     assert vpos == {}
コード例 #21
0
from CommonServerUserPython import *
import networkx as nx
import math

LAYOUT = demisto.args().get('layout')
layout_to_functions = {
    'shell':
    lambda G: nx.shell_layout(G, scale=200),
    'spring':
    lambda G: nx.spring_layout(G, scale=400),
    'kamada_kawai':
    lambda G: nx.kamada_kawai_layout(G, scale=400),
    'circular':
    lambda G: nx.circular_layout(G, scale=600),
    'multipartite':
    lambda G: nx.multipartite_layout(
        G, scale=500, subset_key="layer", align='horizontal')
}


def convert_position(_id, _type, xy_arr):
    return {
        'id': _id,
        'type': _type,
        'position': {
            'x': xy_arr[0],
            'y': xy_arr[1]
        }
    }


def generate_layout(current_incident_id, incident_ids, indicator_ids,
コード例 #22
0

circuit.add_edge(9, 15)
circuit.add_edge(10, 13)
circuit.add_edge(11, 13)
circuit.add_edge(11, 14)
circuit.add_edge(12, 14)

circuit.add_edge(13, 15)

# Convert the circuit to an equivalent formula.
formula = circuit_to_formula(circuit)
print(formula_to_string(formula))

labels = nx.get_node_attributes(circuit, "label")

options = {
    "node_size": 600,
    "alpha": 0.5,
    "node_color": "blue",
    "labels": labels,
    "font_size": 22,
}

plt.figure(figsize=(8, 8))
pos = nx.multipartite_layout(circuit, subset_key="layer")
nx.draw_networkx(circuit, pos, **options)
plt.title(formula_to_string(formula))
plt.axis("equal")
plt.show()
コード例 #23
0
subset_color = [
    "gold",
    "violet",
    "violet",
    "violet",
    "violet",
    "limegreen",
    "limegreen",
    "darkorange",
]


def multilayered_graph(*subset_sizes):
    extents = pairwise(itertools.accumulate((0, ) + subset_sizes))
    layers = [range(start, end) for start, end in extents]
    G = nx.Graph()
    for (i, layer) in enumerate(layers):
        G.add_nodes_from(layer, layer=i)
    for layer1, layer2 in pairwise(layers):
        G.add_edges_from(itertools.product(layer1, layer2))
    return G


G = multilayered_graph(*subset_sizes)
color = [subset_color[data["layer"]] for v, data in G.nodes(data=True)]
pos = nx.multipartite_layout(G, subset_key="layer")
plt.figure(figsize=(8, 8))
nx.draw(G, pos, node_color=color, with_labels=False)
plt.axis("equal")
plt.show()
コード例 #24
0
ファイル: core.py プロジェクト: saurk/depgraph
for k,v in nodesDict.items():
    for node in v:
        G.add_node(node, role=k)

# Cell
for i in nodesDict[0]:
    for j in nodesDict[1]:
        if random() <= 0.25:
            G.add_edge(i,j, relation='tableInput')


for i in nodesDict[1]:
    for j in nodesDict[2]:
        if random() <= 0.4:
            G.add_edge(i,j, relation='modelConsumer')

# Cell
nx.draw_networkx(G, with_labels=True)

# Cell
pos = nx.multipartite_layout(G, subset_key="role")
color = list(itertools.chain(itertools.repeat('gold', len(datasourceNodes)),
                             itertools.repeat('violet', len(modelNodes)),
                             itertools.repeat('limegreen', len(stakeholderNodes)),
                            ))

# Cell
plt.figure(figsize=(8, 8))
nx.draw(G, pos, node_color=color,with_labels=True)
plt.axis("equal")
plt.show()
コード例 #25
0
    def buildGraph(self):
        self.publishers = []
        self.subscribers = []
        pubs_list = []
        subs_list = []
        font_size = 8
        max = 1
        y_offset = 0
        new_nodetoplot = []
        old_nodetoplot = []
        good_chantoplot = []
        old_chantoplot = []
        edgestoplot = []

        self.g.clear()
        size_of_node = 266.66666
        self.g.add_node("Publishers", layer=0)
        self.g.add_node("Channels", layer=1, node_color="white")
        self.g.add_node("Subscribers", layer=2, node_color="white")
        self.g.add_edge("Publishers", "Channels")
        self.g.add_edge("Channels", "Subscribers")

        label_list = {}
        width = self.canvas.width
        height = self.canvas.height

        for chan in self.channels:
            self.g.add_node(str(chan), layer=1)

            for pubs in self.channels[chan]["publishers"]:
                ip_port = "IP:" + str(pubs[0]) + "\nPort:" + str(pubs[1])
                self.g.add_node(str(ip_port), layer=0)
                self.g.add_edge(str(ip_port), str(chan))
                edgestoplot.append([str(ip_port), str(chan)])

                if pubs not in self.g:
                    self.publishers.append(pubs)
                    pubs_list.append(str(ip_port))

            for subs in self.channels[chan]["subscribers"]:
                ip_port = "IP:" + str(subs[0]) + "\nPort:" + str(subs[1])

                self.g.add_node(str(ip_port), layer=2)
                self.g.add_edge(str(chan), str(ip_port))
                edgestoplot.append([str(chan), str(ip_port)])

                if subs not in self.g:
                    self.subscribers.append(subs)
                    subs_list.append(str(ip_port))

        if (len(self.channels) > 1):
            max = len(self.channels)
        if (len(self.subscribers) > max):
            max = len(self.subscribers)
        if (len(self.publishers) > max):
            max = len(self.publishers)

        plt.clf()
        pos = nx.multipartite_layout(self.g, subset_key="layer")
        nx.draw_networkx_nodes(
            self.g,
            pos,
            nodelist=["Publishers", "Channels", "Subscribers"],
            node_color="w")

        if ((1.0 / max) * height * .1) > 8:
            font_size = 8
        else:
            font_size = ((1.0 / max) * height * .1)

        if max < 3:
            y_offset = ((1.0 / 4) / 2)
        else:
            y_offset = ((1.0 / max) / 2)

        for node in pos:
            x, y = pos[node]
            text = str(node)
            if (text != "Publishers" and text != "Channels"
                    and text != "Subscribers"):
                if (text in pubs_list):
                    plt.text(x,
                             y + y_offset,
                             text,
                             horizontalalignment='right',
                             fontsize=font_size)
                    lookup = node.replace("IP:", "")
                    lookup = lookup.replace("\nPort", "")
                    if (self.parent.host.checkPub(lookup)):
                        new_nodetoplot.append(str(node))
                    else:
                        old_nodetoplot.append(str(node))
                if (text in subs_list):
                    plt.text(x,
                             y + y_offset,
                             text,
                             horizontalalignment='left',
                             fontsize=font_size)
                    lookup = node.replace("IP:", "")
                    lookup = lookup.replace("\nPort", "")
                    if (self.parent.host.checkSub(lookup)):
                        new_nodetoplot.append(str(node))
                    else:
                        old_nodetoplot.append(str(node))
                if (text in self.channels):
                    plt.text(x,
                             y + y_offset,
                             text,
                             horizontalalignment='center',
                             fontsize=font_size)
                    if (self.parent.host.checkChan(node)):
                        good_chantoplot.append(str(node))
                    else:
                        old_chantoplot.append(str(node))
            else:
                if (max == 0):
                    plt.text(x,
                             0.0,
                             text,
                             horizontalalignment='center',
                             fontsize=8)
                elif (max == 1):
                    plt.text(x,
                             0.4166666666666666666666,
                             text,
                             horizontalalignment='center',
                             fontsize=8)
                elif (max == 2):
                    plt.text(x,
                             0.7777777777777777777777,
                             text,
                             horizontalalignment='center',
                             fontsize=8)
                else:
                    plt.text(x,
                             1.0,
                             text,
                             horizontalalignment='center',
                             fontsize=8)

        if (((1.0 / max) * height) < size_of_node):
            size_of_node = ((1.0 / max) * height)

        nx.draw_networkx_nodes(self.g,
                               pos,
                               nodelist=new_nodetoplot,
                               node_size=size_of_node)
        nx.draw_networkx_nodes(self.g,
                               pos,
                               nodelist=old_nodetoplot,
                               node_size=size_of_node,
                               node_color="grey")

        nx.draw_networkx_nodes(self.g,
                               pos,
                               nodelist=good_chantoplot,
                               node_size=size_of_node,
                               node_shape='s')
        nx.draw_networkx_nodes(self.g,
                               pos,
                               nodelist=old_chantoplot,
                               node_size=size_of_node,
                               node_shape='s',
                               node_color="grey")

        nx.draw_networkx_edges(self.g,
                               pos,
                               edgelist=edgestoplot,
                               arrowstyle="-")

        plt.axis('off')

        plt.savefig('figure.png')

        image = Image.open('figure.png')

        img_width, img_height = image.size
        rel_width = img_width / width
        rel_height = img_height / height

        image = image.resize(
            (int((rel_width + .4) * width), int((rel_height + .4) * height)),
            Image.ANTIALIAS)  ## The (250, 250) is (height, width)
        img = ImageTk.PhotoImage(image)
        self.parent.one = img
        self.canvas.create_image(width / 2,
                                 height / 2,
                                 anchor='center',
                                 image=img)
        image.close()

        os.remove('figure.png')
コード例 #26
0
def get_feasibility_tree_graph(model, building_element_index):
    G = nx.Graph()

    element = model.building_element_list[building_element_index]
    print(
        f"Considered building element | id: {element.id}, name: {element.name}"
    )
    G.add_node(element.id,
               name=element.name,
               color='lightgray',
               label=element.id,
               subset=0)

    all_activities = element.reference_process.activities
    activities = []
    for activity in all_activities:
        if activity.state == 'IDLE':
            activities.append(activity)

    # Building Element Nodes
    for activity in activities:
        G.add_node(activity.id,
                   name=activity.name,
                   color='bisque',
                   label=remove_prefix(activity.id, element.id),
                   subset=1)
        G.add_edge(element.id, activity.id)

        for capability in activity.capabilities:
            G.add_node(capability.id,
                       name=capability.name,
                       color='bisque',
                       label=remove_prefix(capability.id, activity.id),
                       subset=2)
            G.add_edge(activity.id, capability.id)

            for parameter in capability.parameters:
                G.add_node(
                    (capability.id + "/" + parameter.id),
                    name=parameter.name,
                    color='bisque',
                    label="/" + parameter.id + ": " + str(parameter.value) +
                    " " + str(parameter.dimensionUnit),
                    subset=3)
                G.add_edge(capability.id, (capability.id + "/" + parameter.id))

    #Resources nodes
    for resource in model.resource_list:
        G.add_node(resource.id,
                   name=resource.name,
                   color='lightskyblue',
                   label=resource.id,
                   subset=8)

        for setup in resource.setups:
            G.add_node((resource.id + "/" + setup.name),
                       name=setup.name,
                       color='lightskyblue',
                       label='/' + setup.name,
                       subset=7)
            G.add_edge((resource.id + "/" + setup.name), resource.id)

            for offered_capability in setup.capabilities:
                G.add_node((resource.id + "/" + offered_capability.id),
                           name=offered_capability.name,
                           color='lightskyblue',
                           label=offered_capability.id[4:],
                           subset=6)
                G.add_edge((resource.id + "/" + offered_capability.id),
                           (resource.id + "/" + setup.name))

                for offered_parameter in offered_capability.parameters:
                    try:
                        offered_parameter_label = offered_parameter.id + ": " + str(
                            offered_parameter.value_range) + " " + str(
                                offered_parameter.dimensionUnit)
                    except:
                        offered_parameter_label = offered_parameter.id + ": " + str(
                            offered_parameter.value) + " " + str(
                                offered_parameter.dimensionUnit)
                    G.add_node(resource.id + "/" + offered_capability.id +
                               "/" + offered_parameter.id,
                               name=offered_parameter.name,
                               color='lightskyblue',
                               label=offered_parameter_label,
                               subset=5)
                    G.add_edge((resource.id + "/" + offered_capability.id +
                                "/" + offered_parameter.id),
                               (resource.id + "/" + offered_capability.id))

    # Connections
    for activity in activities:
        for capability in activity.capabilities:
            possible_resources = get_possible_resources_by_capability(
                model.resource_list, capability)

            for needed_parameter in capability.parameters:
                for resource in possible_resources:
                    for offered_parameter in resource[2].parameters:
                        if (resource[0].id + "/" + resource[2].id + "/" +
                                offered_parameter.id) in G:
                            if (offered_parameter.id) == (needed_parameter.id):
                                G.add_edge(
                                    (capability.id + "/" +
                                     needed_parameter.id),
                                    (resource[0].id + "/" + resource[2].id +
                                     "/" + offered_parameter.id))
                        else:
                            print("Node not existing: ")
                            print((resource[0].id + "/" + resource[2].id +
                                   "/" + offered_parameter.id))

    att_labels = nx.get_node_attributes(G, 'label')
    att_colors = list(nx.get_node_attributes(G, 'color').values())

    #pos = hierarchy_pos(G, root=element.id)
    pos = nx.multipartite_layout(G, scale=1.2)
    #pos = nx.kamada_kawai_layout(G)
    nx.draw_networkx(G, pos=pos, with_labels=False, node_color=att_colors)
    text = nx.draw_networkx_labels(G, pos, font_size=8, labels=att_labels)
    for _, t in text.items():
        t.set_rotation(45)
    plt.show()
	def segmentation(self, c0, max_iter = None, visualize=False, show_graphs=False):
		# make graph for image
		self.image_to_graph()
		if(visualize and show_graphs):
			plt.imshow(self.A)
			plt.title("adjacency matrix for graph G")
			plt.show()
			# subset attribute allows for better visualization of graph as grid
			for n in list(self.G.nodes):
				self.G.nodes[n]['subset'] = n % self.m # row number
			nx.draw(self.G, with_labels=True, pos=nx.multipartite_layout(self.G))
			plt.show()
		i = 0
		contour_list = [c0]
		cp = c0
		ci = c0
		while True:
			if(visualize):
				print("ITERATION %d" % i)
			# 1. Dilate current contour ci into its contour neighborhood CN(ci) with an inner contour ICi and an outer contour OCi.
			dilated, contours = self.dilation(cp)
			if(len(contours) == 1):
				ci_image = np.zeros(cp.shape, dtype=np.uint8)
				xs = [x[0][0] for x in contours[0]]
				ys = [x[0][1] for x in contours[0]]
				for j in range(len(xs)):
					ci_image[xs[j], ys[j]] = 1
				if(visualize):
					plt.imshow(ci_image, cmap='gray')
					plt.show()
				return ci_image
			if(visualize):
				plt.subplot(1,2,1)
				plt.imshow(dilated, cmap = 'gray')
				plt.title("dilated contour")
				xs = [x[0][0] for x in contours[0]]
				ys = [x[0][1] for x in contours[0]]
				plt.subplot(1,2,2)
				plt.imshow(dilated, cmap = 'gray')
				plt.plot(xs, ys)
				xs = [x[0][0] for x in contours[1]]
				ys = [x[0][1] for x in contours[1]]
				plt.plot(xs, ys)
				plt.title("inner and outer contour")
				plt.show()
			# 2. Identify all the vertices corresponding to the inner contour as a single source si and identify all the vertices corresponding to the outer contour as a single sink ti to obtain a new graph Gi.
			Gi, Ai = self.vertex_identification(contours[0], contours[1])
			if(visualize and show_graphs):
				plt.imshow(Ai)
				plt.title("adjacency matrix for new graph Gi")
				plt.show()
				# subset attribute allows for better visualization of graph as grid
				for n in list(Gi.nodes):
					if n != 's' and n != 't':
						Gi.nodes[n]['subset'] = n % self.m + 1 # row number
				Gi.nodes['s']['subset'] = int(0)
				Gi.nodes['t']['subset'] = int(self.n+1)
				pos=nx.multipartite_layout(Gi)
				nx.draw(Gi, with_labels=True, pos=pos)
				edge_labels = nx.get_edge_attributes(Gi,'capacity') # key is edge, pls check for your case
				nx.draw_networkx_edge_labels(Gi,pos,edge_labels=edge_labels,font_color='red')
				plt.show()
			# 3. Compute the s–t minimum cut MC(Gi,si,ti) to obtain a new contour ci+1
			ci = self.min_cut(Gi)
			ci_image = np.zeros(cp.shape, dtype=np.uint8)
			# xs = [x[0][0] for x in ci]
			# ys = [x[0][1] for x in ci]
			xs = [x[0] for x in ci]
			ys = [x[1] for x in ci]
			for j in range(len(xs)):
				ci_image[xs[j], ys[j]] = 1
			if(visualize):
				# plt.subplot(1,3,1)
				# plt.imshow(self.image, cmap = 'gray')
				# plt.plot(xs, ys)
				plt.title("new contour")
				plt.subplot(1,2,1)
				plt.imshow(ci_image, cmap='gray')
				plt.title("new contour")
				plt.subplot(1,2,2)
				plt.imshow(cp, cmap='gray')
				plt.title("previous contour")
				plt.show()
			# 4. Terminate the algorithm if a resulting contour reoccurs, otherwise set i=i+1 and return to step 1.
			if np.linalg.norm(cp-ci_image) < 1e-5:
				break
			else:
				contour_list.append(ci_image)
				cp = ci_image
				if max_iter is not None and i >= max_iter:
					break
				i = i + 1
		
		return ci_image
コード例 #28
0
ファイル: GeneralisedWick.py プロジェクト: AGunasekera/DPhil
 def drawGraph(self):
     graph = self.getGraph
     nx.draw(graph, nx.multipartite_layout(graph, "vertex", "horizontal"))
コード例 #29
0
ファイル: plt_network.py プロジェクト: yulkang/constorch
def draw_bipartite(
    weights=None,
    weight_max=None,
):
    # if weights is None:
    #     weights = np.array([[1, 19], [10, 10]])

    n_node = len(weights)
    if weight_max is None:
        weight_max = np.mean(np.sum(weights, 1)) * 2
    # weight_max = 20
    node_sizes = np.concatenate([np.sum(weights, 1), np.sum(weights, 0)])

    G = nx.DiGraph()
    for i in range(n_node):
        G.add_node(i, layer=0, count=node_sizes[i])
        G.add_node(i + n_node, layer=1, count=node_sizes[i + n_node])

    for src in range(n_node):
        for dst in range(n_node):
            G.add_weighted_edges_from([(src, dst + n_node, weights[src, dst])])

    c_max = 255
    cmap = plt.get_cmap('coolwarm', c_max)

    pos = nx.multipartite_layout(G, subset_key="layer")
    # plt.figure(figsize=(3, 3))

    nx.draw_networkx_nodes(G,
                           pos,
                           nodelist=np.arange(n_node**2),
                           node_size=300 * node_sizes / weight_max,
                           node_color=cmap(node_sizes / weight_max),
                           cmap=cmap,
                           alpha=0.5)
    wmax = np.amax(weights)
    for edge, v in G.edges.items():
        w = v['weight']
        nx.draw_networkx_edges(
            G,
            pos,
            edgelist=[edge],
            edge_color=cmap(w / weight_max * n_node),
            width=0,
            arrowstyle=ArrowStyle.Simple(
                head_length=w / weight_max * 2.1,
                head_width=w / weight_max * 1.4,
                tail_width=w / weight_max * 0.5,
            ),
            min_source_margin=wmax / 2 + weight_max * 0.2,
            min_target_margin=wmax / 2 + weight_max * 0.2,
        )
    edge_weights = {k: '%g' % v['weight'] for k, v in G.edges.items()}
    nx.draw_networkx_edge_labels(G,
                                 pos,
                                 edge_labels=edge_weights,
                                 label_pos=0.33)
    node_labels = {k: '%g' % v['count'] for k, v in G.nodes.items()}
    nx.draw_networkx_labels(G, pos, labels=node_labels)

    plt.axis("equal")
    plt.box(False)
    # plt.show()
    # print('--')

    return G, pos
コード例 #30
0
def get_person_relations(externalUid: str):
    if not graph_conn:
        test()
    result = {}
    try:
        relations_query_result = graph_conn.query_data(family_tree_query,
                                                       {'$xuid': externalUid})
    except Exception as e:
        logging.error('At fetching family relations of %s' % extrenalUid)
        logging.error(e)
        if "details" in dir(e):
            details = e.details()
        else:
            details = str(e)
        raise GraphException(details)
    if len(relations_query_result['relations']) == 0:
        raise NotAvailableException("Realtions: " + str(externalUid))

    result['person'] = {
        "name":
        relations_query_result['relations'][0]['name'],
        "link":
        "%s/names/relations?externalUid=%s" %
        (base_URL,
         urllib.parse.quote(
             relations_query_result['relations'][0]['externalUid']))
    }
    result['siblings'] = []
    if "father" in relations_query_result['relations'][0]:
        result['father'] = {
            "name":
            relations_query_result['relations'][0]['father'][0]['name'],
            "link":
            "%s/names/relations?externalUid=%s" %
            (base_URL,
             urllib.parse.quote(relations_query_result['relations'][0]
                                ['father'][0]['externalUid']))
        }
        if 'sibling' in relations_query_result['relations'][0]['father'][0]:
            for sibling in relations_query_result['relations'][0]['father'][0][
                    'sibling']:
                if sibling['externalUid'] != externalUid:
                    result['siblings'].append({
                        "name":
                        sibling['name'],
                        "link":
                        "%s/names/relations?externalUid=%s" %
                        (base_URL, urllib.parse.quote(sibling['externalUid']))
                    })
    elif "sameAs" in relations_query_result['relations'][0]:
        for otherName in relations_query_result['relations'][0]['sameAs']:
            if 'father' in otherName:
                if 'father' not in result:
                    result['father'] = {
                        "name":
                        otherName['father'][0]['name'],
                        "link":
                        "%s/names/relations?externalUid=%s" %
                        (base_URL,
                         urllib.parse.quote(
                             otherName['father'][0]['externalUid']))
                    }
                if 'sibling' in otherName['father'][0]:
                    for sibling in otherName['father'][0]['sibling']:
                        result['siblings'].append({
                            "name":
                            sibling['name'],
                            "link":
                            "%s/names/relations?externalUid=%s" %
                            (base_URL,
                             urllib.parse.quote(sibling['externalUid']))
                        })
                break
    if "mother" in relations_query_result['relations'][0]:
        result['mother'] = {
            "name":
            relations_query_result['relations'][0]['mother'][0]['name'],
            "link":
            "%s/names/relations?externalUid=%s" %
            (base_URL,
             urllib.parse.quote(relations_query_result['relations'][0]
                                ['mother'][0]['externalUid']))
        }
        if 'sibling' in relations_query_result['relations'][0]['mother'][0]:
            for sibling in relations_query_result['relations'][0]['mother'][0][
                    'sibling']:
                sib = {
                    "name":
                    sibling['name'],
                    "link":
                    "%s/names/relations?externalUid=%s" %
                    (base_URL, urllib.parse.quote(sibling['externalUid']))
                }
                if sibling['externalUid'] != externalUid and sib not in result[
                        'siblings']:
                    result['siblings'].append()
    elif "sameAs" in relations_query_result['relations'][0]:
        for otherName in relations_query_result['relations'][0]['sameAs']:
            if 'mother' in otherName:
                if 'mother' not in result:
                    result['mother'] = {
                        "name":
                        otherName['mother'][0]['name'],
                        "link":
                        "%s/names/relations?externalUid=%s" %
                        (base_URL,
                         urllib.parse.quote(
                             otherName['mother'][0]['externalUid']))
                    }
                if 'sibling' in otherName['mother'][0]:
                    for sibling in otherName['mother'][0]['sibling']:
                        sib = {
                            "name":
                            sibling['name'],
                            "link":
                            "%s/names/relations?externalUid=%s" %
                            (base_URL,
                             urllib.parse.quote(sibling['externalUid']))
                        }
                        if sibling[
                                'externalUid'] != externalUid and sib not in result[
                                    'siblings']:
                            result['siblings'].append({
                                "name":
                                sibling['name'],
                                "link":
                                "%s/names/relations?externalUid=%s" %
                                (base_URL,
                                 urllib.parse.quote(sibling['externalUid']))
                            })
                break
    result['spouses'] = []
    if "spouse" in relations_query_result['relations'][0]:
        for spouse in relations_query_result['relations'][0]['spouse']:
            sps = {
                "name":
                spouse['name'],
                "link":
                "%s/names/relations?externalUid=%s" %
                (base_URL, urllib.parse.quote(spouse['externalUid']))
            }
            if sps not in result['spouses']:
                result['spouses'].append(sps)
    elif "sameAs" in relations_query_result['relations'][0]:
        for otherName in relations_query_result['relations'][0]['sameAs']:
            if "spouse" in otherName:
                for spouse in otherName['spouse']:
                    sps = {
                        "name":
                        spouse['name'],
                        "link":
                        "%s/names/relations?externalUid=%s" %
                        (base_URL, urllib.parse.quote(spouse['externalUid']))
                    }
                    if sps not in result['spouses']:
                        result['spouses'].append(sps)

    result['children'] = []
    if "children1" in relations_query_result['relations'][0]:
        for child in relations_query_result['relations'][0]['children1']:
            ch = {
                "name":
                child['name'],
                "link":
                "%s/names/relations?externalUid=%s" %
                (base_URL, urllib.parse.quote(child['externalUid']))
            }
            if ch not in result['children']:
                result['children'].append(ch)
    elif "children2" in relations_query_result['relations'][0]:
        for child in relations_query_result['relations'][0]['children2']:
            ch = {
                "name":
                child['name'],
                "link":
                "%s/names/relations?externalUid=%s" %
                (base_URL, urllib.parse.quote(child['externalUid']))
            }
            if ch not in result['children']:
                result['children'].append(ch)
    elif "sameAs" in relations_query_result['relations'][0]:
        for otherName in relations_query_result['relations'][0]['sameAs']:
            if 'children1' in otherName:
                for child in otherName['children1']:
                    ch = {
                        "name":
                        child['name'],
                        "link":
                        "%s/names/relations?externalUid=%s" %
                        (base_URL, urllib.parse.quote(child['externalUid']))
                    }
                    if ch not in result['children']:
                        result['children'].append(ch)
            elif 'children2' in otherName:
                for child in otherName['children2']:
                    ch = {
                        "name":
                        child['name'],
                        "link":
                        "%s/names/relations?externalUid=%s" %
                        (base_URL, urllib.parse.quote(child['externalUid']))
                    }
                    if ch not in result['children']:
                        result['children'].append(ch)
    if len(result['spouses']) == 0:
        del result['spouses']
    if len(result['siblings']) == 0:
        del result['siblings']
    if len(result['children']) == 0:
        del result['children']

    fig = plt.figure(figsize=(12, 12))
    ax = plt.subplot(111)
    ax.set_title('Graph - Shapes', fontsize=10)
    G = nx.DiGraph()

    G.add_node(result['person']['name'], level=3)
    colour_list = ["blue"]

    if 'father' in result:
        G.add_node(result['father']['name'], level=4)
        G.add_edge(result['person']['name'],
                   result['father']['name'],
                   label='father')
        colour_list.append("green")

    if 'mother' in result:
        G.add_node(result['mother']['name'], level=4)
        G.add_edge(result['person']['name'],
                   result['mother']['name'],
                   label='mother')
        colour_list.append("green")

    if 'siblings' in result:
        for sib in result['siblings']:
            G.add_node(sib['name'], level=2)
            G.add_edge(result['person']['name'], sib['name'], label='sibling')
            colour_list.append("purple")

    if 'spouses' in result:
        for sps in result['spouses']:
            G.add_node(sps['name'], level=2)
            G.add_edge(result['person']['name'], sps['name'], label='spouse')
            colour_list.append("pink")

    if 'children' in result:
        for child in result['children']:
            G.add_node(child['name'], level=1)
            G.add_edge(result['person']['name'], child['name'], label='child')
            colour_list.append("orange")

    pos = nx.multipartite_layout(G, subset_key='level', align='horizontal')
    nx.draw(G,
            pos,
            node_size=5000,
            node_color=colour_list,
            font_size=20,
            font_weight='bold')
    nx.draw_networkx_labels(G, pos)
    nx.draw_networkx_edge_labels(G, pos)
    plt.tight_layout()
    plt.savefig("static/Family-tree.png")

    rels_html = ""
    for key in result:
        if key in ['person', 'mother', 'father']:
            rels_html += '%s:<a href="%s">%s</a><br>' % (
                key.upper(), result[key]['link'], result[key]['name'])
        else:
            items = ", ".join([
                '<a href="%s">%s</a>' % (it['link'], it['name'])
                for it in result[key]
            ])
            # items = ['<a href="%s">%s</a>'%(it['link'], it['name']) for it in result[key]]
            rels_html += '%s:%s <br>' % (key.upper(), str(items))

    html_file = open("Family-tree.html", "w")
    html_content = '''
	<html>
	<body>
	<div style="float:left" width="25%%">
	%s
	</div>
	<div style="float:left" width="75%%">
	<img src="/static/Family-tree.png" height="750px">
	</div>
	</body>
	</html>
	''' % rels_html

    html_file.write(html_content)
    html_file.close()
    return FileResponse("Family-tree.html")