Source code

Download source archive ↓

upstream/tools/graph_converter/xgmml_networkx.py

1__author__ = "Yasunobu OKAMURA"
2__copyright__ = "Copyright (c) 2012 Y.Okamura"
3__license__ = "GPL v3+"
4
5import xml.parsers.expat
6
7import networkx as nx
8
9
10class XGMMLParserHelper(object):
11    """"""
12
13    def __init__(self, graph=nx.DiGraph()):
14        """
15
16        Arguments:
17        - `graph`: Network X graph object
18        """
19        self._graph = graph
20        self._parser = xml.parsers.expat.ParserCreate()
21        self._parser.StartElementHandler = self._start_element
22        self._parser.EndElementHandler = self._end_element
23        self._tagstack = list()
24
25        self._current_attr = dict()
26        self._current_obj = dict()
27
28    def _start_element(self, tag, attr):
29        """
30
31        Arguments:
32        - `self`:
33        - `tag`:
34        - `attr`:
35        """
36
37        self._tagstack.append(tag)
38
39        if tag == "node" or tag == "edge":
40            self._current_obj = dict(attr)
41
42        if tag == "att" and (
43            self._tagstack[-2] == "node" or self._tagstack[-2] == "edge"
44        ):
45            if attr["type"] == "string":
46                self._current_attr[attr["name"]] = attr["value"]
47            elif attr["type"] == "real":
48                self._current_attr[attr["name"]] = float(attr["value"])
49            elif attr["type"] == "integer":
50                self._current_attr[attr["name"]] = int(attr["value"])
51            elif attr["type"] == "boolean":
52                self._current_attr[attr["name"]] = bool(attr["value"])
53            else:
54                raise NotImplementedError(attr["type"])
55
56    def _end_element(self, tag):
57        """
58
59        Arguments:
60        - `self`:
61        - `tag`:
62        """
63
64        if tag == "node":
65            self._graph.add_node(
66                self._current_obj["id"],
67                label=self._current_obj["label"],
68                **self._current_attr
69            )
70            # print 'add node', self._current_obj
71        elif tag == "edge":
72            self._graph.add_edge(
73                self._current_obj["source"],
74                self._current_obj["target"],
75                **self._current_attr
76            )
77
78        self._tagstack.pop()
79
80    def parseFile(self, file):
81        """
82
83        Arguments:
84        - `self`:
85        - `file`:
86        """
87
88        self._parser.ParseFile(file)
89
90    def graph(self):
91        """
92
93        Arguments:
94        - `self`:
95        """
96
97        return self._graph
98
99
100def XGMMLWriter(file, graph, graph_name):
101    """
102
103    Arguments:
104    - `graph`:
105    """
106
107    print("""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
108<graph directed="1"  xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://www.cs.rpi.edu/XGMML">
109<att name="selected" value="1" type="boolean" />
110<att name="name" value="{0}" type="string"/>
111<att name="shared name" value="{0}" type="string"/>
112""".format(
113        graph_name
114    ), file=file)
115
116    for onenode in graph.nodes(data=True):
117        id = onenode[0]
118        attr = dict(onenode[1])
119
120        if "label" in attr:
121            label = attr["label"]
122            del attr["label"]
123        else:
124            label = id
125
126        print('<node id="{id}" label="{label}">'.format(id=id, label=label), file=file)
127        for k, v in attr.iteritems():
128            print('<att name="{}" value="{}" type="string" />'.format(k, v), file=file)
129        print("</node>", file=file)
130
131    for oneedge in graph.edges(data=True):
132        print('<edge source="{}" target="{}">'.format(oneedge[0], oneedge[1]), file=file)
133        for k, v in oneedge[2].iteritems():
134            print('<att name="{}" value="{}" type="string" />'.format(k, v), file=file)
135        print("</edge>", file=file)
136    print("</graph>", file=file)