Exemplo n.º 1
0
 def decode_attr_elements(self, gexf_keys, obj_xml):
     # Use the key information to decode the attr XML
     attr = {}
     # look for outer '<attvalues>' element
     attr_element = obj_xml.find(f"{{{self.NS_GEXF}}}attvalues")
     if attr_element is not None:
         # loop over <attvalue> elements
         for a in attr_element.findall(f"{{{self.NS_GEXF}}}attvalue"):
             key = a.get("for")  # for is required
             try:  # should be in our gexf_keys dictionary
                 title = gexf_keys[key]["title"]
             except KeyError as err:
                 raise eg.EasyGraphError(
                     f"No attribute defined for={key}.") from err
             atype = gexf_keys[key]["type"]
             value = a.get("value")
             if atype == "boolean":
                 value = self.convert_bool[value]
             else:
                 value = self.python_type[atype](value)
             if gexf_keys[key]["mode"] == "dynamic":
                 # for dynamic graphs use list of three-tuples
                 # [(value1,start1,end1), (value2,start2,end2), etc]
                 ttype = self.timeformat
                 start = self.python_type[ttype](a.get("start"))
                 end = self.python_type[ttype](a.get("end"))
                 if title in attr:
                     attr[title].append((value, start, end))
                 else:
                     attr[title] = [(value, start, end)]
             else:
                 # for static graphs just assign the value
                 attr[title] = value
     return attr
Exemplo n.º 2
0
 def find_graphml_keys(self, graph_element):
     """Extracts all the keys and key defaults from the xml."""
     graphml_keys = {}
     graphml_key_defaults = {}
     for k in graph_element.findall(f"{{{self.NS_GRAPHML}}}key"):
         attr_id = k.get("id")
         attr_type = k.get("attr.type")
         attr_name = k.get("attr.name")
         yfiles_type = k.get("yfiles.type")
         if yfiles_type is not None:
             attr_name = yfiles_type
             attr_type = "yfiles"
         if attr_type is None:
             attr_type = "string"
             warnings.warn(f"No key type for id {attr_id}. Using string")
         if attr_name is None:
             raise eg.EasyGraphError(f"Unknown key for id {attr_id}.")
         graphml_keys[attr_id] = {
             "name": attr_name,
             "type": self.python_type[attr_type],
             "for": k.get("for"),
         }
         # check for "default" sub-element of key element
         default = k.find(f"{{{self.NS_GRAPHML}}}default")
         if default is not None:
             # Handle default values identically to data element values
             python_type = graphml_keys[attr_id]["type"]
             if python_type == bool:
                 graphml_key_defaults[attr_id] = self.convert_bool[
                     default.text.lower()
                 ]
             else:
                 graphml_key_defaults[attr_id] = python_type(default.text)
     return graphml_keys, graphml_key_defaults
Exemplo n.º 3
0
    def decode_data_elements(self, graphml_keys, obj_xml):
        """Use the key information to decode the data XML if present."""
        data = {}
        for data_element in obj_xml.findall(f"{{{self.NS_GRAPHML}}}data"):
            key = data_element.get("key")
            try:
                data_name = graphml_keys[key]["name"]
                data_type = graphml_keys[key]["type"]
            except KeyError as err:
                raise eg.EasyGraphError(f"Bad GraphML data: no key {key}") from err
            text = data_element.text
            # assume anything with subelements is a yfiles extension
            if text is not None and len(list(data_element)) == 0:
                if data_type == bool:
                    # Ignore cases.
                    # http://docs.oracle.com/javase/6/docs/api/java/lang/
                    # Boolean.html#parseBoolean%28java.lang.String%29
                    data[data_name] = self.convert_bool[text.lower()]
                else:
                    data[data_name] = data_type(text)
            elif len(list(data_element)) > 0:
                # Assume yfiles as subelements, try to extract node_label
                node_label = None
                # set GenericNode's configuration as shape type
                gn = data_element.find(f"{{{self.NS_Y}}}GenericNode")
                if gn:
                    data["shape_type"] = gn.get("configuration")
                for node_type in ["GenericNode", "ShapeNode", "SVGNode", "ImageNode"]:
                    pref = f"{{{self.NS_Y}}}{node_type}/{{{self.NS_Y}}}"
                    geometry = data_element.find(f"{pref}Geometry")
                    if geometry is not None:
                        data["x"] = geometry.get("x")
                        data["y"] = geometry.get("y")
                    if node_label is None:
                        node_label = data_element.find(f"{pref}NodeLabel")
                    shape = data_element.find(f"{pref}Shape")
                    if shape is not None:
                        data["shape_type"] = shape.get("type")
                if node_label is not None:
                    data["label"] = node_label.text

                # check all the different types of edges avaivable in yEd.
                for edge_type in [
                    "PolyLineEdge",
                    "SplineEdge",
                    "QuadCurveEdge",
                    "BezierEdge",
                    "ArcEdge",
                ]:
                    pref = f"{{{self.NS_Y}}}{edge_type}/{{{self.NS_Y}}}"
                    edge_label = data_element.find(f"{pref}EdgeLabel")
                    if edge_label is not None:
                        break

                if edge_label is not None:
                    data["label"] = edge_label.text
        return data
Exemplo n.º 4
0
def from_pandas_adjacency(df, create_using=None):
    r"""Returns a graph from Pandas DataFrame.

    The Pandas DataFrame is interpreted as an adjacency matrix for the graph.

    Parameters
    ----------
    df : Pandas DataFrame
      An adjacency matrix representation of a graph

    create_using : EasyGraph graph constructor, optional (default=eg.Graph)
       Graph type to create. If graph instance, then cleared before populated.

    Notes
    -----
    For directed graphs, explicitly mention create_using=eg.DiGraph,
    and entry i,j of df corresponds to an edge from i to j.

    If `df` has a single data type for each entry it will be converted to an
    appropriate Python data type.

    If `df` has a user-specified compound data type the names
    of the data fields will be used as attribute keys in the resulting
    EasyGraph graph.

    See Also
    --------
    to_pandas_adjacency

    Examples
    --------
    Simple integer weights on edges:

    >>> import pandas as pd
    >>> pd.options.display.max_columns = 20
    >>> df = pd.DataFrame([[1, 1], [2, 1]])
    >>> df
       0  1
    0  1  1
    1  2  1
    >>> G = eg.from_pandas_adjacency(df)
    >>> G.name = "Graph from pandas adjacency matrix"
    """

    try:
        df = df[df.index]
    except Exception as err:
        missing = list(set(df.index).difference(set(df.columns)))
        msg = f"{missing} not in columns"
        raise eg.EasyGraphError("Columns must match Indices.", msg) from err

    A = df.values
    G = from_numpy_array(A, create_using=create_using)

    G = eg.relabel_nodes(G, dict(enumerate(df.columns)))
    return G
Exemplo n.º 5
0
    def add_edge(self, G, edge_element, graphml_keys):
        """Add an edge to the graph."""
        # warn on finding unsupported ports tag
        ports = edge_element.find(f"{{{self.NS_GRAPHML}}}port")
        if ports is not None:
            warnings.warn("GraphML port tag not supported.")

        # raise error if we find mixed directed and undirected edges
        directed = edge_element.get("directed")
        if G.is_directed() and directed == "false":
            msg = "directed=false edge found in directed graph."
            raise eg.EasyGraphError(msg)
        if (not G.is_directed()) and directed == "true":
            msg = "directed=true edge found in undi rected graph."
            raise eg.EasyGraphError(msg)

        source = self.node_type(edge_element.get("source"))
        target = self.node_type(edge_element.get("target"))
        data = self.decode_data_elements(graphml_keys, edge_element)
        # GraphML stores edge ids as an attribute
        # EasyGraph uses them as keys in multigraphs too if no key
        # attribute is specified
        edge_id = edge_element.get("id")
        if edge_id:
            # self.edge_ids is used by `make_graph` method for non-multigraphs
            self.edge_ids[source, target] = edge_id
            try:
                edge_id = self.edge_key_type(edge_id)
            except ValueError:  # Could not convert.
                pass
        else:
            edge_id = data.get("key")

        if G.has_edge(source, target):
            # mark this as a multigraph
            self.multigraph = True

        # Use add_edges_from to avoid error with add_edge when `'key' in data`
        # Note there is only one edge here...
        G.add_edges_from([(source, target, edge_id, data)])
Exemplo n.º 6
0
 def add_data(self, name, element_type, value, scope="all", default=None):
     """
     Make a data element for an edge or a node. Keep a log of the
     type in the keys table.
     """
     if element_type not in self.xml_type:
         raise eg.EasyGraphError(
             f"GraphML writer does not support {element_type} as data values."
         )
     keyid = self.get_key(name, self.get_xml_type(element_type), scope, default)
     data_element = self.myElement("data", key=keyid)
     data_element.text = str(value)
     return data_element
Exemplo n.º 7
0
    def make_graph(self, graph_xml, graphml_keys, defaults, G=None):
        # set default graph type
        edgedefault = graph_xml.get("edgedefault", None)
        if G is None:
            if edgedefault == "directed":
                G = eg.MultiDiGraph()
            else:
                G = eg.MultiGraph()
        # set defaults for graph attributes
        G.graph["node_default"] = {}
        G.graph["edge_default"] = {}
        for key_id, value in defaults.items():
            key_for = graphml_keys[key_id]["for"]
            name = graphml_keys[key_id]["name"]
            python_type = graphml_keys[key_id]["type"]
            if key_for == "node":
                G.graph["node_default"].update({name: python_type(value)})
            if key_for == "edge":
                G.graph["edge_default"].update({name: python_type(value)})
        # hyperedges are not supported
        hyperedge = graph_xml.find(f"{{{self.NS_GRAPHML}}}hyperedge")
        if hyperedge is not None:
            raise eg.EasyGraphError("GraphML reader doesn't support hyperedges")
        # add nodes
        for node_xml in graph_xml.findall(f"{{{self.NS_GRAPHML}}}node"):
            self.add_node(G, node_xml, graphml_keys, defaults)
        # add edges
        for edge_xml in graph_xml.findall(f"{{{self.NS_GRAPHML}}}edge"):
            self.add_edge(G, edge_xml, graphml_keys)
        # add graph data
        data = self.decode_data_elements(graphml_keys, graph_xml)
        G.graph.update(data)

        # switch to Graph or DiGraph if no parallel edges were found
        if self.multigraph:
            return G

        G = eg.DiGraph(G) if G.is_directed() else eg.Graph(G)
        # add explicit edge "id" from file as attribute in eg graph.
        eg.set_edge_attributes(G, values=self.edge_ids, name="id")
        return G
Exemplo n.º 8
0
def from_scipy_sparse_array(A,
                            parallel_edges=False,
                            create_using=None,
                            edge_attribute="weight"):
    G = eg.empty_graph(0, create_using)
    n, m = A.shape
    if n != m:
        raise eg.EasyGraphError(
            f"Adjacency matrix not square: nx,ny={A.shape}")
    # Make sure we get even the isolated nodes of the graph.
    G.add_nodes_from(range(n))
    # Create an iterable over (u, v, w) triples and for each triple, add an
    # edge from u to v with weight w.
    triples = _generate_weighted_edges(A)
    # If the entries in the adjacency matrix are integers, the graph is a
    # multigraph, and parallel_edges is True, then create parallel edges, each
    # with weight 1, for each entry in the adjacency matrix. Otherwise, create
    # one edge for each positive entry in the adjacency matrix and set the
    # weight of that edge to be the entry in the matrix.
    if A.dtype.kind in ("i", "u") and G.is_multigraph() and parallel_edges:
        chain = itertools.chain.from_iterable
        # The following line is equivalent to:
        #
        #     for (u, v) in edges:
        #         for d in range(A[u, v]):
        #             G.add_edge(u, v, weight=1)
        #
        triples = chain(((u, v, 1) for d in range(w)) for (u, v, w) in triples)
    # If we are creating an undirected multigraph, only add the edges from the
    # upper triangle of the matrix. Otherwise, add all the edges. This relies
    # on the fact that the vertices created in the
    # `_generated_weighted_edges()` function are actually the row/column
    # indices for the matrix `A`.
    #
    # Without this check, we run into a problem where each edge is added twice
    # when `G.add_weighted_edges_from()` is invoked below.
    if G.is_multigraph() and not G.is_directed():
        triples = ((u, v, d) for u, v, d in triples if u <= v)
    G.add_edges_from(((u, v, {"weight": d}) for u, v, d in triples))
    return G
Exemplo n.º 9
0
def random_enumerate_subgraph(G, k: int, cut_prob: list):
    """
    Returns the motifs.
    Motifs are small weakly connected induced subgraphs of a given structure in a graph.

    Parameters
    ----------
    G : easygraph.Graph or easygraph.DiGraph.

    k : int
        The size of the motifs to search for.

    cut_prob : list
        list of probabilities for cutting the search tree at a given level.

    Returns
    ----------
    k_subgraphs : list
        The motifs.

    References
    ----------
    .. [1] Wernicke, Sebastian. "A faster algorithm for detecting network motifs."
    International Workshop on Algorithms in Bioinformatics. Springer, Berlin, Heidelberg, 2005.

    """
    if len(cut_prob) != k:
        raise eg.EasyGraphError(
            "length of cut_prob invalid, should equal to k")

    k_subgraphs = []
    for v, _ in G.nodes.items():
        if random.random() > cut_prob[0]:
            continue
        Vextension = {u for u in G.adj[v] if u > v}
        random_extend_subgraph(G, {v}, Vextension, v, k, k_subgraphs, cut_prob)
    return k_subgraphs
Exemplo n.º 10
0
def to_easygraph_graph(data, create_using=None, multigraph_input=False):
    """Make a EasyGraph graph from a known data structure.

    The preferred way to call this is automatically
    from the class constructor

    >>> d = {0: {1: {"weight": 1}}}  # dict-of-dicts single edge (0,1)
    >>> G = eg.Graph(d)

    instead of the equivalent

    >>> G = eg.from_dict_of_dicts(d)

    Parameters
    ----------
    data : object to be converted

        Current known types are:
         any EasyGraph graph
         dict-of-dicts
         dict-of-lists
         container (e.g. set, list, tuple) of edges
         iterator (e.g. itertools.chain) that produces edges
         generator of edges
         Pandas DataFrame (row per edge)
         numpy matrix
         numpy ndarray
         scipy sparse matrix
         pygraphviz agraph

    create_using : EasyGraph graph constructor, optional (default=eg.Graph)
        Graph type to create. If graph instance, then cleared before populated.

    multigraph_input : bool (default False)
        If True and  data is a dict_of_dicts,
        try to create a multigraph assuming dict_of_dict_of_lists.
        If data and create_using are both multigraphs then create
        a multigraph from a multigraph.

    """

    # EasyGraph graph type
    if hasattr(data, "adj"):
        try:
            result = from_dict_of_dicts(
                data.adj,
                create_using=create_using,
                multigraph_input=data.is_multigraph(),
            )
            # data.graph should be dict-like
            result.graph.update(data.graph)
            # data.nodes should be dict-like
            # result.add_node_from(data.nodes.items()) possible but
            # for custom node_attr_dict_factory which may be hashable
            # will be unexpected behavior
            for n, dd in data.nodes.items():
                result._node[n].update(dd)
            return result
        except Exception as err:
            raise eg.EasyGraphError(
                "Input is not a correct EasyGraph graph.") from err

    # pygraphviz  agraph
    if hasattr(data, "is_strict"):
        try:
            return eg.from_pyGraphviz_agraph(data, create_using=create_using)
        except Exception as err:
            raise eg.EasyGraphError(
                "Input is not a correct pygraphviz graph.") from err

    # dict of dicts/lists
    if isinstance(data, dict):
        try:
            return from_dict_of_dicts(data,
                                      create_using=create_using,
                                      multigraph_input=multigraph_input)
        except Exception as err:
            if multigraph_input is True:
                raise eg.EasyGraphError(
                    f"converting multigraph_input raised:\n{type(err)}: {err}")
            try:
                return from_dict_of_lists(data, create_using=create_using)
            except Exception as err:
                raise TypeError("Input is not known type.") from err

    # Pandas DataFrame
    try:
        import pandas as pd

        if isinstance(data, pd.DataFrame):
            if data.shape[0] == data.shape[1]:
                try:
                    return eg.from_pandas_adjacency(data,
                                                    create_using=create_using)
                except Exception as err:
                    msg = "Input is not a correct Pandas DataFrame adjacency matrix."
                    raise eg.EasyGraphError(msg) from err
            else:
                try:
                    return eg.from_pandas_edgelist(data,
                                                   edge_attr=True,
                                                   create_using=create_using)
                except Exception as err:
                    msg = "Input is not a correct Pandas DataFrame adjacency edge-list."
                    raise eg.EasyGraphError(msg) from err
    except ImportError:
        warnings.warn("pandas not found, skipping conversion test.",
                      ImportWarning)

    # numpy matrix or ndarray
    try:
        import numpy as np

        if isinstance(data, np.ndarray):
            try:
                return eg.from_numpy_array(data, create_using=create_using)
            except Exception as err:
                raise eg.EasyGraphError(
                    "Input is not a correct numpy matrix or array.") from err
    except ImportError:
        warnings.warn("numpy not found, skipping conversion test.",
                      ImportWarning)

    # scipy sparse matrix - any format
    try:
        if hasattr(data, "format"):
            try:
                return eg.from_scipy_sparse_matrix(data,
                                                   create_using=create_using)
            except Exception as err:
                raise eg.EasyGraphError(
                    "Input is not a correct scipy sparse matrix type."
                ) from err
    except ImportError:
        warnings.warn("scipy not found, skipping conversion test.",
                      ImportWarning)

    # Note: most general check - should remain last in order of execution
    # Includes containers (e.g. list, set, dict, etc.), generators, and
    # iterators (e.g. itertools.chain) of edges

    if isinstance(data, (Collection, Generator, Iterator)):
        try:
            return from_edgelist(data, create_using=create_using)
        except Exception as err:
            raise eg.EasyGraphError("Input is not a valid edge list") from err

    raise eg.EasyGraphError("Input is not a known data type for conversion.")
Exemplo n.º 11
0
def parse_graphml(
    graphml_string, node_type=str, edge_key_type=int, force_multigraph=False
):
    """Read graph in GraphML format from string.

    Parameters
    ----------
    graphml_string : string
       String containing graphml information
       (e.g., contents of a graphml file).

    node_type: Python type (default: str)
       Convert node ids to this type

    edge_key_type: Python type (default: int)
       Convert graphml edge ids to this type. Multigraphs use id as edge key.
       Non-multigraphs add to edge attribute dict with name "id".

    force_multigraph : bool (default: False)
       If True, return a multigraph with edge keys. If False (the default)
       return a multigraph when multiedges are in the graph.


    Returns
    -------
    graph: EasyGraph graph
        If no parallel edges are found a Graph or DiGraph is returned.
        Otherwise a MultiGraph or MultiDiGraph is returned.

    Examples
    --------
    >>> G = eg.path_graph(4)
    >>> linefeed = chr(10)  # linefeed = \n
    >>> s = linefeed.join(eg.generate_graphml(G))
    >>> H = eg.parse_graphml(s)

    Notes
    -----
    Default node and edge attributes are not propagated to each node and edge.
    They can be obtained from `G.graph` and applied to node and edge attributes
    if desired using something like this:

    >>> default_color = G.graph["node_default"]["color"]  # doctest: +SKIP
    >>> for node, data in G.nodes(data=True):  # doctest: +SKIP
    ...     if "color" not in data:
    ...         data["color"] = default_color
    >>> default_color = G.graph["edge_default"]["color"]  # doctest: +SKIP
    >>> for u, v, data in G.edges(data=True):  # doctest: +SKIP
    ...     if "color" not in data:
    ...         data["color"] = default_color

    This implementation does not support mixed graphs (directed and unidirected
    edges together), hypergraphs, nested graphs, or ports.

    For multigraphs the GraphML edge "id" will be used as the edge
    key.  If not specified then they "key" attribute will be used.  If
    there is no "key" attribute a default EasyGraph multigraph edge key
    will be provided.

    """
    reader = GraphMLReader(node_type, edge_key_type, force_multigraph)
    # need to check for multiple graphs
    glist = list(reader(string=graphml_string))
    if len(glist) == 0:
        # If no graph comes back, try looking for an incomplete header
        header = '<graphml xmlns="http://graphml.graphdrawing.org/xmlns">'
        new_string = graphml_string.replace("<graphml>", header)
        glist = list(reader(string=new_string))
        if len(glist) == 0:
            raise eg.EasyGraphError("file not successfully read as graphml")
    return glist[0]
Exemplo n.º 12
0
    def __init__(self,
                 incoming_graph_data=None,
                 multigraph_input=None,
                 **attr):
        """Initialize a graph with edges, name, or graph attributes.

        Parameters
        ----------
        incoming_graph_data : input graph
            Data to initialize graph.  If incoming_graph_data=None (default)
            an empty graph is created.  The data can be an edge list, or any
            EasyGraph graph object.  If the corresponding optional Python
            packages are installed the data can also be a NumPy matrix
            or 2d ndarray, a SciPy sparse matrix, or a PyGraphviz graph.

        multigraph_input : bool or None (default None)
            Note: Only used when `incoming_graph_data` is a dict.
            If True, `incoming_graph_data` is assumed to be a
            dict-of-dict-of-dict-of-dict structure keyed by
            node to neighbor to edge keys to edge data for multi-edges.
            A EasyGraphError is raised if this is not the case.
            If False, :func:`to_easygraph_graph` is used to try to determine
            the dict's graph data structure as either a dict-of-dict-of-dict
            keyed by node to neighbor to edge data, or a dict-of-iterable
            keyed by node to neighbors.
            If None, the treatment for True is tried, but if it fails,
            the treatment for False is tried.

        attr : keyword arguments, optional (default= no attributes)
            Attributes to add to graph as key=value pairs.

        See Also
        --------
        convert

        Examples
        --------
        >>> G = eg.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
        >>> G = eg.Graph(name="my graph")
        >>> e = [(1, 2), (2, 3), (3, 4)]  # list of edges
        >>> G = eg.Graph(e)

        Arbitrary graph attribute pairs (key=value) may be assigned

        >>> G = eg.Graph(e, day="Friday")
        >>> G.graph
        {'day': 'Friday'}

        """
        self.edge_key_dict_factory = self.edge_key_dict_factory
        if isinstance(incoming_graph_data,
                      dict) and multigraph_input is not False:
            Graph.__init__(self)
            try:
                convert.from_dict_of_dicts(incoming_graph_data,
                                           create_using=self,
                                           multigraph_input=True)
                self.graph.update(attr)
            except Exception as err:
                if multigraph_input is True:
                    raise eg.EasyGraphError(
                        f"converting multigraph_input raised:\n{type(err)}: {err}"
                    )
                Graph.__init__(self, incoming_graph_data, **attr)
        else:
            Graph.__init__(self, incoming_graph_data, **attr)
Exemplo n.º 13
0
def from_pandas_edgelist(
    df,
    source="source",
    target="target",
    edge_attr=None,
    create_using=None,
    edge_key=None,
):
    """Returns a graph from Pandas DataFrame containing an edge list.

    The Pandas DataFrame should contain at least two columns of node names and
    zero or more columns of edge attributes. Each row will be processed as one
    edge instance.

    Note: This function iterates over DataFrame.values, which is not
    guaranteed to retain the data type across columns in the row. This is only
    a problem if your row is entirely numeric and a mix of ints and floats. In
    that case, all values will be returned as floats. See the
    DataFrame.iterrows documentation for an example.

    Parameters
    ----------
    df : Pandas DataFrame
        An edge list representation of a graph

    source : str or int
        A valid column name (string or integer) for the source nodes (for the
        directed case).

    target : str or int
        A valid column name (string or integer) for the target nodes (for the
        directed case).

    edge_attr : str or int, iterable, True, or None
        A valid column name (str or int) or iterable of column names that are
        used to retrieve items and add them to the graph as edge attributes.
        If `True`, all of the remaining columns will be added.
        If `None`, no edge attributes are added to the graph.

    create_using : EasyGraph graph constructor, optional (default=eg.Graph)
        Graph type to create. If graph instance, then cleared before populated.

    edge_key : str or None, optional (default=None)
        A valid column name for the edge keys (for a MultiGraph). The values in
        this column are used for the edge keys when adding edges if create_using
        is a multigraph.

    See Also
    --------
    to_pandas_edgelist

    Examples
    --------
    Simple integer weights on edges:

    >>> import pandas as pd
    >>> pd.options.display.max_columns = 20
    >>> import numpy as np
    >>> rng = np.random.RandomState(seed=5)
    >>> ints = rng.randint(1, 11, size=(3, 2))
    >>> a = ["A", "B", "C"]
    >>> b = ["D", "A", "E"]
    >>> df = pd.DataFrame(ints, columns=["weight", "cost"])
    >>> df[0] = a
    >>> df["b"] = b
    >>> df[["weight", "cost", 0, "b"]]
       weight  cost  0  b
    0       4     7  A  D
    1       7     1  B  A
    2      10     9  C  E
    >>> G = eg.from_pandas_edgelist(df, 0, "b", ["weight", "cost"])
    >>> G["E"]["C"]["weight"]
    10
    >>> G["E"]["C"]["cost"]
    9
    >>> edges = pd.DataFrame(
    ...     {
    ...         "source": [0, 1, 2],
    ...         "target": [2, 2, 3],
    ...         "weight": [3, 4, 5],
    ...         "color": ["red", "blue", "blue"],
    ...     }
    ... )
    >>> G = eg.from_pandas_edgelist(edges, edge_attr=True)
    >>> G[0][2]["color"]
    'red'

    Build multigraph with custom keys:

    >>> edges = pd.DataFrame(
    ...     {
    ...         "source": [0, 1, 2, 0],
    ...         "target": [2, 2, 3, 2],
    ...         "my_edge_key": ["A", "B", "C", "D"],
    ...         "weight": [3, 4, 5, 6],
    ...         "color": ["red", "blue", "blue", "blue"],
    ...     }
    ... )
    >>> G = eg.from_pandas_edgelist(
    ...     edges,
    ...     edge_key="my_edge_key",
    ...     edge_attr=["weight", "color"],
    ...     create_using=eg.MultiGraph(),
    ... )
    >>> G[0][2]
    AtlasView({'A': {'weight': 3, 'color': 'red'}, 'D': {'weight': 6, 'color': 'blue'}})


    """
    g = eg.empty_graph(0, create_using)

    if edge_attr is None:
        g.add_edges_from(zip(df[source], df[target]))
        return g

    reserved_columns = [source, target]

    # Additional columns requested
    attr_col_headings = []
    attribute_data = []
    if edge_attr is True:
        attr_col_headings = [
            c for c in df.columns if c not in reserved_columns
        ]
    elif isinstance(edge_attr, (list, tuple)):
        attr_col_headings = edge_attr
    else:
        attr_col_headings = [edge_attr]
    if len(attr_col_headings) == 0:
        raise eg.EasyGraphError(
            "Invalid edge_attr argument: No columns found with name:"
            f" {attr_col_headings}")

    try:
        attribute_data = zip(*[df[col] for col in attr_col_headings])
    except (KeyError, TypeError) as err:
        msg = f"Invalid edge_attr argument: {edge_attr}"
        raise eg.EasyGraphError(msg) from err

    if g.is_multigraph():
        # => append the edge keys from the df to the bundled data
        if edge_key is not None:
            try:
                multigraph_edge_keys = df[edge_key]
                attribute_data = zip(attribute_data, multigraph_edge_keys)
            except (KeyError, TypeError) as err:
                msg = f"Invalid edge_key argument: {edge_key}"
                raise eg.EasyGraphError(msg) from err

        for s, t, attrs in zip(df[source], df[target], attribute_data):
            if edge_key is not None:
                attrs, multigraph_edge_key = attrs
                key = g.add_edge(s, t, key=multigraph_edge_key)
            else:
                key = g.add_edge(s, t)

            g[s][t][key].update(zip(attr_col_headings, attrs))
    else:
        for s, t, attrs in zip(df[source], df[target], attribute_data):
            g.add_edge(s, t)
            g[s][t].update(zip(attr_col_headings, attrs))

    return g
Exemplo n.º 14
0
def from_numpy_array(A, parallel_edges=False, create_using=None):
    """Returns a graph from a 2D NumPy array.

    The 2D NumPy array is interpreted as an adjacency matrix for the graph.

    Parameters
    ----------
    A : a 2D numpy.ndarray
        An adjacency matrix representation of a graph

    parallel_edges : Boolean
        If this is True, `create_using` is a multigraph, and `A` is an
        integer array, then entry *(i, j)* in the array is interpreted as the
        number of parallel edges joining vertices *i* and *j* in the graph.
        If it is False, then the entries in the array are interpreted as
        the weight of a single edge joining the vertices.

    create_using : EasyGraph graph constructor, optional (default=eg.Graph)
       Graph type to create. If graph instance, then cleared before populated.

    Notes
    -----
    For directed graphs, explicitly mention create_using=eg.DiGraph,
    and entry i,j of A corresponds to an edge from i to j.

    If `create_using` is :class:`easygraph.MultiGraph` or
    :class:`easygraph.MultiDiGraph`, `parallel_edges` is True, and the
    entries of `A` are of type :class:`int`, then this function returns a
    multigraph (of the same type as `create_using`) with parallel edges.

    If `create_using` indicates an undirected multigraph, then only the edges
    indicated by the upper triangle of the array `A` will be added to the
    graph.

    If the NumPy array has a single data type for each array entry it
    will be converted to an appropriate Python data type.

    If the NumPy array has a user-specified compound data type the names
    of the data fields will be used as attribute keys in the resulting
    EasyGraph graph.

    See Also
    --------
    to_numpy_array

    Examples
    --------
    Simple integer weights on edges:

    >>> import numpy as np
    >>> A = np.array([[1, 1], [2, 1]])
    >>> G = eg.from_numpy_array(A)
    >>> G.edges(data=True)
    EdgeDataView([(0, 0, {'weight': 1}), (0, 1, {'weight': 2}), (1, 1, {'weight': 1})])

    If `create_using` indicates a multigraph and the array has only integer
    entries and `parallel_edges` is False, then the entries will be treated
    as weights for edges joining the nodes (without creating parallel edges):

    >>> A = np.array([[1, 1], [1, 2]])
    >>> G = eg.from_numpy_array(A, create_using=eg.MultiGraph)
    >>> G[1][1]
    AtlasView({0: {'weight': 2}})

    If `create_using` indicates a multigraph and the array has only integer
    entries and `parallel_edges` is True, then the entries will be treated
    as the number of parallel edges joining those two vertices:

    >>> A = np.array([[1, 1], [1, 2]])
    >>> temp = eg.MultiGraph()
    >>> G = eg.from_numpy_array(A, parallel_edges=True, create_using=temp)
    >>> G[1][1]
    AtlasView({0: {'weight': 1}, 1: {'weight': 1}})

    User defined compound data type on edges:

    >>> dt = [("weight", float), ("cost", int)]
    >>> A = np.array([[(1.0, 2)]], dtype=dt)
    >>> G = eg.from_numpy_array(A)
    >>> G.edges()
    EdgeView([(0, 0)])
    >>> G[0][0]["cost"]
    2
    >>> G[0][0]["weight"]
    1.0

    """
    kind_to_python_type = {
        "f": float,
        "i": int,
        "u": int,
        "b": bool,
        "c": complex,
        "S": str,
        "U": str,
        "V": "void",
    }
    G = eg.empty_graph(0, create_using)
    if A.ndim != 2:
        raise eg.EasyGraphError(f"Input array must be 2D, not {A.ndim}")
    n, m = A.shape
    if n != m:
        raise eg.EasyGraphError(
            f"Adjacency matrix not square: eg,ny={A.shape}")
    dt = A.dtype
    try:
        python_type = kind_to_python_type[dt.kind]
    except Exception as err:
        raise TypeError(f"Unknown numpy data type: {dt}") from err

    # Make sure we get even the isolated nodes of the graph.
    G.add_nodes_from(range(n))
    # Get a list of all the entries in the array with nonzero entries. These
    # coordinates become edges in the graph. (convert to int from np.int64)
    edges = ((int(e[0]), int(e[1])) for e in zip(*A.nonzero()))
    # handle numpy constructed data type
    if python_type == "void":
        # Sort the fields by their offset, then by dtype, then by name.
        fields = sorted((offset, dtype, name)
                        for name, (dtype, offset) in A.dtype.fields.items())
        triples = ((
            u,
            v,
            {
                name: kind_to_python_type[dtype.kind](val)
                for (_, dtype, name), val in zip(fields, A[u, v])
            },
        ) for u, v in edges)
    # If the entries in the adjacency matrix are integers, the graph is a
    # multigraph, and parallel_edges is True, then create parallel edges, each
    # with weight 1, for each entry in the adjacency matrix. Otherwise, create
    # one edge for each positive entry in the adjacency matrix and set the
    # weight of that edge to be the entry in the matrix.
    elif python_type is int and G.is_multigraph() and parallel_edges:
        chain = itertools.chain.from_iterable
        # The following line is equivalent to:
        #
        #     for (u, v) in edges:
        #         for d in range(A[u, v]):
        #             G.add_edge(u, v, weight=1)
        #
        triples = chain(((u, v, {
            "weight": 1
        }) for d in range(A[u, v])) for (u, v) in edges)
    else:  # basic data type
        triples = ((u, v, dict(weight=python_type(A[u, v]))) for u, v in edges)
    # If we are creating an undirected multigraph, only add the edges from the
    # upper triangle of the matrix. Otherwise, add all the edges. This relies
    # on the fact that the vertices created in the
    # `_generated_weighted_edges()` function are actually the row/column
    # indices for the matrix `A`.
    #
    # Without this check, we run into a problem where each edge is added twice
    # when `G.add_edges_from()` is invoked below.
    if G.is_multigraph() and not G.is_directed():
        triples = ((u, v, d) for u, v, d in triples if u <= v)
    G.add_edges_from(triples)
    return G
Exemplo n.º 15
0
def to_numpy_array(
    G,
    nodelist=None,
    dtype=None,
    order=None,
    multigraph_weight=sum,
    weight="weight",
    nonedge=0.0,
):
    """Returns the graph adjacency matrix as a NumPy array.

    Parameters
    ----------
    G : graph
        The EasyGraph graph used to construct the NumPy array.

    nodelist : list, optional
        The rows and columns are ordered according to the nodes in `nodelist`.
        If `nodelist` is None, then the ordering is produced by G.nodes().

    dtype : NumPy data type, optional
        A valid single NumPy data type used to initialize the array.
        This must be a simple type such as int or numpy.float64 and
        not a compound data type (see to_numpy_recarray)
        If None, then the NumPy default is used.

    order : {'C', 'F'}, optional
        Whether to store multidimensional data in C- or Fortran-contiguous
        (row- or column-wise) order in memory. If None, then the NumPy default
        is used.

    multigraph_weight : {sum, min, max}, optional
        An operator that determines how weights in multigraphs are handled.
        The default is to sum the weights of the multiple edges.

    weight : string or None optional (default = 'weight')
        The edge attribute that holds the numerical value used for
        the edge weight. If an edge does not have that attribute, then the
        value 1 is used instead.

    nonedge : float (default = 0.0)
        The array values corresponding to nonedges are typically set to zero.
        However, this could be undesirable if there are array values
        corresponding to actual edges that also have the value zero. If so,
        one might prefer nonedges to have some other value, such as nan.

    Returns
    -------
    A : NumPy ndarray
        Graph adjacency matrix

    See Also
    --------
    from_numpy_array

    Notes
    -----
    For directed graphs, entry i,j corresponds to an edge from i to j.

    Entries in the adjacency matrix are assigned to the weight edge attribute.
    When an edge does not have a weight attribute, the value of the entry is
    set to the number 1.  For multiple (parallel) edges, the values of the
    entries are determined by the `multigraph_weight` parameter. The default is
    to sum the weight attributes for each of the parallel edges.

    When `nodelist` does not contain every node in `G`, the adjacency matrix is
    built from the subgraph of `G` that is induced by the nodes in `nodelist`.

    The convention used for self-loop edges in graphs is to assign the
    diagonal array entry value to the weight attribute of the edge
    (or the number 1 if the edge has no weight attribute). If the
    alternate convention of doubling the edge weight is desired the
    resulting NumPy array can be modified as follows:

    >>> import numpy as np
    >>> G = eg.Graph([(1, 1)])
    >>> A = eg.to_numpy_array(G)
    >>> A
    array([[1.]])
    >>> A[np.diag_indices_from(A)] *= 2
    >>> A
    array([[2.]])

    Examples
    --------
    >>> G = eg.MultiDiGraph()
    >>> G.add_edge(0, 1, weight=2)
    0
    >>> G.add_edge(1, 0)
    0
    >>> G.add_edge(2, 2, weight=3)
    0
    >>> G.add_edge(2, 2)
    1
    >>> eg.to_numpy_array(G, nodelist=[0, 1, 2])
    array([[0., 2., 0.],
           [1., 0., 0.],
           [0., 0., 4.]])

    """
    import numpy as np

    if nodelist is None:
        nodelist = list(G)
        nodeset = G
        nlen = len(G)
    else:
        nlen = len(nodelist)
        nodeset = set(G.nodes)
        if nlen != len(nodeset):
            for n in nodelist:
                if n not in G:
                    raise eg.EasyGraphError(
                        f"Node {n} in nodelist is not in G")
            raise eg.EasyGraphError("nodelist contains duplicates.")

    undirected = not G.is_directed()
    index = dict(zip(nodelist, range(nlen)))

    # Initially, we start with an array of nans.  Then we populate the array
    # using data from the graph.  Afterwards, any leftover nans will be
    # converted to the value of `nonedge`.  Note, we use nans initially,
    # instead of zero, for two reasons:
    #
    #   1) It can be important to distinguish a real edge with the value 0
    #      from a nonedge with the value 0.
    #
    #   2) When working with multi(di)graphs, we must combine the values of all
    #      edges between any two nodes in some manner.  This often takes the
    #      form of a sum, min, or max.  Using the value 0 for a nonedge would
    #      have undesirable effects with min and max, but using nanmin and
    #      nanmax with initially nan values is not problematic at all.
    #
    # That said, there are still some drawbacks to this approach. Namely, if
    # a real edge is nan, then that value is a) not distinguishable from
    # nonedges and b) is ignored by the default combinator (nansum, nanmin,
    # nanmax) functions used for multi(di)graphs. If this becomes an issue,
    # an alternative approach is to use masked arrays.  Initially, every
    # element is masked and set to some `initial` value. As we populate the
    # graph, elements are unmasked (automatically) when we combine the initial
    # value with the values given by real edges.  At the end, we convert all
    # masked values to `nonedge`. Using masked arrays fully addresses reason 1,
    # but for reason 2, we would still have the issue with min and max if the
    # initial values were 0.0.  Note: an initial value of +inf is appropriate
    # for min, while an initial value of -inf is appropriate for max. When
    # working with sum, an initial value of zero is appropriate. Ideally then,
    # we'd want to allow users to specify both a value for nonedges and also
    # an initial value.  For multi(di)graphs, the choice of the initial value
    # will, in general, depend on the combinator function---sensible defaults
    # can be provided.

    if G.is_multigraph():
        # Handle MultiGraphs and MultiDiGraphs
        A = np.full((nlen, nlen), np.nan, order=order)
        # use numpy nan-aware operations
        operator = {sum: np.nansum, min: np.nanmin, max: np.nanmax}
        try:
            op = operator[multigraph_weight]
        except Exception as err:
            raise ValueError(
                "multigraph_weight must be sum, min, or max") from err

        for u, v, _, attrs in G.edges:
            if (u in nodeset) and (v in nodeset):
                i, j = index[u], index[v]
                e_weight = attrs.get(weight, 1)
                A[i, j] = op([e_weight, A[i, j]])
                if undirected:
                    A[j, i] = A[i, j]
    else:
        # Graph or DiGraph, this is much faster than above
        A = np.full((nlen, nlen), np.nan, order=order)
        for u, nbrdict in G.adj.items():
            for v, d in nbrdict.items():
                try:
                    A[index[u], index[v]] = d.get(weight, 1)
                except KeyError:
                    # This occurs when there are fewer desired nodes than
                    # there are nodes in the graph: len(nodelist) < len(G)
                    pass

    A[np.isnan(A)] = nonedge
    A = np.asarray(A, dtype=dtype)
    return A