예제 #1
0
def set_node_attributes(G, values, name=None):
    if G.is_multigraph():
        # multigraph forward NetworkX
        func.set_node_attributes(G, values, name)
        return

    # Set node attributes based on type of `values`
    if name is not None:  # `values` must not be a dict of dict
        try:  # `values` is a dict
            for n, v in values.items():
                if n in G:
                    dd = get_node_data(G, n)
                    dd[name] = values[n]
                    G.set_node_data(n, dd)
        except AttributeError:  # `values` is a constant
            for n in G:
                dd = get_node_data(G, n)
                dd[name] = values
                G.set_node_data(n, dd)
    else:  # `values` must be dict of dict
        for n, d in values.items():
            if n in G:
                dd = get_node_data(G, n)
                dd.update(d)
                G.set_node_data(n, dd)
예제 #2
0
def build_graph_from_dict_nx(graph_dict):
    import networkx as nx
    import networkx.classes.function as fn

    # currently only undirected graph, with no feature stored
    # TODO: option for directed graph
    # TODO(DONE): see features

    # graph attributes
    g = nx.Graph()
    g.graph['num_evils'] = graph_dict['num_evils']
    g.graph['num_evil_edges'] = graph_dict['num_evil_edges']

    # node attributes
    g.add_nodes_from(range(graph_dict['num_nodes']))
    node_attr = {i: is_bot for i, is_bot in enumerate(graph_dict['y'])}
    fn.set_node_attributes(G=g, values=node_attr, name='is_bot')

    # edge attributes
    g.add_edges_from(
        zip(graph_dict['edge_index'][0], graph_dict['edge_index'][1]))
    edges = zip(graph_dict['edge_index'][0], graph_dict['edge_index'][1])
    edge_attr = {e: bot for e, bot in zip(edges, graph_dict['edge_y'])}
    fn.set_edge_attributes(G=g, values=edge_attr, name='is_bot_connection')

    return g
예제 #3
0
    def agnn_representation(self) -> DiGraph:
        """
        Basic graph representation with an empty node input and target variable
        """
        graph = self.base_representation
        set_node_attributes(graph, 0, "node_y")

        # add opposing edge for each existing edge
        set_edge_attributes(graph, 1, 'edge_exists')
        for u, v in graph.edges:
            if not graph.has_edge(v, u) and v != u:
                graph.add_edge(v, u, edge_exists=0)

        # add feature (exist or none exist) of the opposite edge
        set_edge_attributes(graph, None, "edge_opposite")
        for u, v in graph.edges:
            graph.edges[u, v]["edge_opposite"] = graph.edges[v,
                                                             u]["edge_exists"]

        # self attacks
        set_edge_attributes(graph, 0, "edge_self")
        for n in graph.nodes:
            if graph.has_edge(n, n):
                graph.edges[n, n]["edge_self"] = 1

        return graph
예제 #4
0
 def gcn_representation(self) -> DiGraph:
     """
     Graph representation suitable for a graph convolutional network
     """
     graph = self.agnn_representation
     set_node_attributes(graph, 0, "node_y")
     set_node_attributes(graph, float(1), "node_x")
     return graph
예제 #5
0
 def value_unserved_demand(self, VoLL):
     if isinstance(VoLL, dict) and len(VoLL.values()) == len(self.nodes):
         set_node_attributes(self, VoLL, name="VoLL")
         self._VoLL_init = True
     else:
         raise IOError(
             "Check input object type is float and has value greater than 0."
         )
예제 #6
0
 def minimum_pressure_bounds(self, p_min):
     if isinstance(p_min, dict) and len(p_min.values()) == len(self.nodes):
         set_node_attributes(self, p_min, name="p_min")
         self._p_min_init = True
     else:
         raise IOError(
             "Check input object type is dict and has as many values as there are edges."
         )
     return None
예제 #7
0
 def nodal_demands(self, d):
     if isinstance(d, dict) and len(d.values()) == len(self.nodes):
         set_node_attributes(self, d, name="d")
         self._d_init = True
     else:
         raise IOError(
             "Check input object type is dict and has as many values as there are edges."
         )
     return None
예제 #8
0
 def maximum_nodal_injections(self, s_max):
     if isinstance(s_max, dict) and len(s_max.values()) == len(self.nodes):
         set_node_attributes(self, s_max, name="s_max")
         self._s_max_init = True
     else:
         raise IOError(
             "Check input object type is dict and has as many values as there are edges."
         )
     return None
예제 #9
0
 def fm2_representation(self) -> DiGraph:
     """
     Graph representation Used by Kuhlmann & Thimm (2019)
     each node gets a feature denoting the incoming and outgoing attacks
     """
     graph = self.agnn_representation
     set_node_attributes(graph, 0, "node_y")
     for node in graph.nodes:
         graph.nodes[node]["node_x_in"] = float(graph.in_degree(node))
         graph.nodes[node]["node_x_out"] = float(graph.out_degree(node))
     return graph
예제 #10
0
 def add_downvote(self, arg, agent):
     upvotes = self.nodes[arg]["upvotes"]
     downvotes = self.nodes[arg]["downvotes"]
     up_list = self.nodes[arg]["up_list"]
     down_list = self.nodes[arg]["down_list"]
     set_node_attributes(
         self, {
             arg: {
                 "upvotes": upvotes,
                 "up_list": up_list,
                 "downvotes": downvotes + 1,
                 "down_list": down_list + [agent]
             }
         })
예제 #11
0
def readResourceStructure(structureFilename, resourceAttributesFilename):
    resourceStructure = networkx.read_adjlist(structureFilename, create_using = networkx.DiGraph())    
    log('Resources: ' + ', '.join(resourceStructure.nodes()))
    
    with open(resourceAttributesFilename) as f:
        resAttrsStr = f.readlines()
    resAttrsStr = [x.strip() for x in resAttrsStr]
    
    for resAttrs in resAttrsStr:
        resAttrMap = {}
        attrName = resAttrs.split('|')[0]
        attrPairs = resAttrs.split('|')[1]
        for attrPair in attrPairs.split(','):
            resId = attrPair.split(':')[0]
            attrVal = attrPair.split(':')[1]            
            resAttrMap[resId] = attrVal
        set_node_attributes(resourceStructure, attrName, resAttrMap)
    resAttrMap = {}
    for n in resourceStructure.nodes():
        resAttrMap[n] = n
    set_node_attributes(resourceStructure, 'room_id', resAttrMap)
    return resourceStructure
예제 #12
0
            if (e[::-1] in G.edges()) and (e[0] != e[1])
        ])).drop_duplicates().reset_index(drop=True),
    how="right",
    left_on=["from", "to"],
    right_on=[0, 1],
).drop([0, 1], axis=1).reset_index(drop=True))

G_undir = nx.Graph()

G_undir.add_nodes_from(poll_data.reset_index()["ID"].unique())

G_undir.add_edges_from(edges_df[["from", "to"]].values)

set_node_attributes(G_undir,
                    {n: {
                        "size": G_undir.degree(n)
                    }
                     for n in G_undir.nodes()})

### plusz feature-ök

#### beszédtémák megoszlása

topics = [c for c in poll_data.columns if "téma" in c]

edges_df = (edges_df.merge(
    poll_data[["ID"] + topics],
    how="left",
    left_on="from",
    right_on="ID",
).rename(
예제 #13
0
 def base_representation(self) -> DiGraph:
     graph = copy.deepcopy(self.graph)
     set_node_attributes(graph, 0, "node_input")
     return graph