Statistics
| Branch: | Revision:

iof-tools / networkxMiCe / networkx-master / networkx / readwrite / json_graph / adjacency.py @ 5cef0f13

History | View | Annotate | Download (4.87 KB)

1
#    Copyright (C) 2011-2013 by
2
#    Aric Hagberg <hagberg@lanl.gov>
3
#    Dan Schult <dschult@colgate.edu>
4
#    Pieter Swart <swart@lanl.gov>
5
#    All rights reserved.
6
#    BSD license.
7
from itertools import chain
8
import networkx as nx
9
__author__ = """Aric Hagberg <aric.hagberg@gmail.com>"""
10
__all__ = ['adjacency_data', 'adjacency_graph']
11

    
12
_attrs = dict(id='id', key='key')
13

    
14

    
15
def adjacency_data(G, attrs=_attrs):
16
    """Returns data in adjacency format that is suitable for JSON serialization
17
    and use in Javascript documents.
18

19
    Parameters
20
    ----------
21
    G : NetworkX graph
22

23
    attrs : dict
24
        A dictionary that contains two keys 'id' and 'key'. The corresponding
25
        values provide the attribute names for storing NetworkX-internal graph
26
        data. The values should be unique. Default value:
27
        :samp:`dict(id='id', key='key')`.
28

29
        If some user-defined graph data use these attribute names as data keys,
30
        they may be silently dropped.
31

32
    Returns
33
    -------
34
    data : dict
35
       A dictionary with adjacency formatted data.
36

37
    Raises
38
    ------
39
    NetworkXError
40
        If values in attrs are not unique.
41

42
    Examples
43
    --------
44
    >>> from networkx.readwrite import json_graph
45
    >>> G = nx.Graph([(1,2)])
46
    >>> data = json_graph.adjacency_data(G)
47

48
    To serialize with json
49

50
    >>> import json
51
    >>> s = json.dumps(data)
52

53
    Notes
54
    -----
55
    Graph, node, and link attributes will be written when using this format
56
    but attribute keys must be strings if you want to serialize the resulting
57
    data with JSON.
58

59
    The default value of attrs will be changed in a future release of NetworkX.
60

61
    See Also
62
    --------
63
    adjacency_graph, node_link_data, tree_data
64
    """
65
    multigraph = G.is_multigraph()
66
    id_ = attrs['id']
67
    # Allow 'key' to be omitted from attrs if the graph is not a multigraph.
68
    key = None if not multigraph else attrs['key']
69
    if id_ == key:
70
        raise nx.NetworkXError('Attribute names are not unique.')
71
    data = {}
72
    data['directed'] = G.is_directed()
73
    data['multigraph'] = multigraph
74
    data['graph'] = list(G.graph.items())
75
    data['nodes'] = []
76
    data['adjacency'] = []
77
    for n, nbrdict in G.adjacency():
78
        data['nodes'].append(dict(chain(G.nodes[n].items(), [(id_, n)])))
79
        adj = []
80
        if multigraph:
81
            for nbr, keys in nbrdict.items():
82
                for k, d in keys.items():
83
                    adj.append(dict(chain(d.items(), [(id_, nbr), (key, k)])))
84
        else:
85
            for nbr, d in nbrdict.items():
86
                adj.append(dict(chain(d.items(), [(id_, nbr)])))
87
        data['adjacency'].append(adj)
88
    return data
89

    
90

    
91
def adjacency_graph(data, directed=False, multigraph=True, attrs=_attrs):
92
    """Returns graph from adjacency data format.
93

94
    Parameters
95
    ----------
96
    data : dict
97
        Adjacency list formatted graph data
98

99
    Returns
100
    -------
101
    G : NetworkX graph
102
       A NetworkX graph object
103

104
    directed : bool
105
        If True, and direction not specified in data, return a directed graph.
106

107
    multigraph : bool
108
        If True, and multigraph not specified in data, return a multigraph.
109

110
    attrs : dict
111
        A dictionary that contains two keys 'id' and 'key'. The corresponding
112
        values provide the attribute names for storing NetworkX-internal graph
113
        data. The values should be unique. Default value:
114
        :samp:`dict(id='id', key='key')`.
115

116
    Examples
117
    --------
118
    >>> from networkx.readwrite import json_graph
119
    >>> G = nx.Graph([(1,2)])
120
    >>> data = json_graph.adjacency_data(G)
121
    >>> H = json_graph.adjacency_graph(data)
122

123
    Notes
124
    -----
125
    The default value of attrs will be changed in a future release of NetworkX.
126

127
    See Also
128
    --------
129
    adjacency_graph, node_link_data, tree_data
130
    """
131
    multigraph = data.get('multigraph', multigraph)
132
    directed = data.get('directed', directed)
133
    if multigraph:
134
        graph = nx.MultiGraph()
135
    else:
136
        graph = nx.Graph()
137
    if directed:
138
        graph = graph.to_directed()
139
    id_ = attrs['id']
140
    # Allow 'key' to be omitted from attrs if the graph is not a multigraph.
141
    key = None if not multigraph else attrs['key']
142
    graph.graph = dict(data.get('graph', []))
143
    mapping = []
144
    for d in data['nodes']:
145
        node_data = d.copy()
146
        node = node_data.pop(id_)
147
        mapping.append(node)
148
        graph.add_node(node)
149
        graph.nodes[node].update(node_data)
150
    for i, d in enumerate(data['adjacency']):
151
        source = mapping[i]
152
        for tdata in d:
153
            target_data = tdata.copy()
154
            target = target_data.pop(id_)
155
            if not multigraph:
156
                graph.add_edge(source, target)
157
                graph[source][target].update(tdata)
158
            else:
159
                ky = target_data.pop(key, None)
160
                graph.add_edge(source, target, key=ky)
161
                graph[source][target][ky].update(tdata)
162
    return graph