-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpythonize.py
More file actions
231 lines (182 loc) · 7.78 KB
/
pythonize.py
File metadata and controls
231 lines (182 loc) · 7.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import functools
import re
import tempfile
import os
import json
import cppyy
class GraphAttributesProxy(object):
def __init__(self, GA, getter, setter):
self.GA = GA
self.getter = getter
self.setter = setter
def __setitem__(self, key, item):
return self.setter(self.GA, key, item)
def __getitem__(self, key):
return self.getter(self.GA, key)
def __call__(self, key):
return self.getter(self.GA, key)
class GraphAttributesDescriptor(object):
def __init__(self, getter, setter):
self.getter = getter
self.setter = setter
def __get__(self, obj, type=None):
return GraphAttributesProxy(obj, self.getter, self.setter)
GA_FIELDS = [
("x", "ogdf::node", "double"),
("y", "ogdf::node", "double"),
("z", "ogdf::node", "double"),
("xLabel", "ogdf::node", "double"),
("yLabel", "ogdf::node", "double"),
("zLabel", "ogdf::node", "double"),
("width", "ogdf::node", "double"),
("height", "ogdf::node", "double"),
("shape", "ogdf::node", "ogdf::Shape"),
("strokeType", "ogdf::node", "ogdf::StrokeType"),
("strokeColor", "ogdf::node", "const ogdf::Color &"),
("strokeWidth", "ogdf::node", "float"),
("fillPattern", "ogdf::node", "ogdf::FillPattern"),
("fillColor", "ogdf::node", "const ogdf::Color &"),
("fillBgColor", "ogdf::node", "const ogdf::Color &"),
("label", "ogdf::node", "const std::string &"),
("templateNode", "ogdf::node", "const std::string &"),
("weight", "ogdf::node", "int"),
("type", "ogdf::node", "ogdf::Graph::NodeType"),
("idNode", "ogdf::node", "int"),
("bends", "ogdf::edge", "const ogdf::DPolyline &"),
("arrowType", "ogdf::edge", "ogdf::EdgeArrow"),
("strokeType", "ogdf::edge", "ogdf::StrokeType"),
("strokeColor", "ogdf::edge", "const ogdf::Color &"),
("strokeWidth", "ogdf::edge", "float"),
("label", "ogdf::edge", "const std::string &"),
("intWeight", "ogdf::edge", "int"),
("doubleWeight", "ogdf::edge", "double"),
("type", "ogdf::edge", "ogdf::Graph::EdgeType"),
("subGraphBits", "ogdf::edge", "uint32_t"),
]
CGA_FIELDS = [
("x", "ogdf::cluster", "double"),
("y", "ogdf::cluster", "double"),
("width", "ogdf::cluster", "double"),
("height", "ogdf::cluster", "double"),
("label", "ogdf::cluster", "const std::string &"),
("strokeType", "ogdf::cluster", "ogdf::StrokeType"),
("strokeColor", "ogdf::cluster", "const ogdf::Color &"),
("strokeWidth", "ogdf::cluster", "float"),
("fillPattern", "ogdf::cluster", "ogdf::FillPattern"),
("fillColor", "ogdf::cluster", "const ogdf::Color &"),
("fillBgColor", "ogdf::cluster", "const ogdf::Color &"),
("templateCluster", "ogdf::cluster", "const std::string &"),
]
GA_FIELD_NAMES = set(t[0] for t in GA_FIELDS)
CGA_FIELD_NAMES = set(t[0] for t in GA_FIELDS + CGA_FIELDS)
def generate_GA_setters():
DEFS = """
#include <ogdf/basic/GraphAttributes.h>
#include <ogdf/cluster/ClusterGraphAttributes.h>
namespace ogdf_pythonization {
void GraphAttributes_set_directed(ogdf::GraphAttributes &GA, bool v) { GA.directed() = v; }"""
for name, obj, val in GA_FIELDS:
DEFS += ("\n\tvoid GraphAttributes_set_{name}(ogdf::GraphAttributes &GA, {obj} o, {val} v) "
"{{ GA.{name}(o) = v; }}\n".format(name=name, obj=obj, val=val))
for name, obj, val in CGA_FIELDS:
DEFS += ("\n\tvoid GraphAttributes_set_{name}(ogdf::ClusterGraphAttributes &GA, {obj} o, {val} v) "
"{{ GA.{name}(o) = v; }}\n".format(name=name, obj=obj, val=val))
cppyy.cppdef(DEFS + "};")
SVGConf = None
def GraphAttributes_to_html(self):
# global SVGConf
# if SVGConf == None:
# SVGConf = cppyy.gbl.ogdf.GraphIO.SVGSettings()
# SVGConf.margin(50)
# SVGConf.bezierInterpolation(True)
# SVGConf.curviness(0.3)
#
# with tempfile.NamedTemporaryFile("w+t", suffix=".svg", prefix="ogdf-python-") as f:
# cppyy.gbl.ogdf.GraphIO.drawSVG(self, f.name, SVGConf)
# return f.read()
respect_graph_attributes = False
json_string = construct_json_string(self, respect_graph_attributes)
__location__ = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
if respect_graph_attributes:
filename = 'graphVisualizationWithGraphAttributes.html'
else:
filename = 'graphVisualization.html'
with open(os.path.join(__location__, filename), 'r') as file:
data = file.read()
data = data.replace("var data = {}", json_string)
return data
def construct_json_string(self, respect_graph_attributes):
#TODO: use import json
# Starting creation of Json String which will be used by d3Js
json_string = "var data = { \n\"nodes\":["
for x in self.constGraph().nodes:
json_string += ",\n{\n\"id\":" + str(x.index()) + ",\n\"name\":" + str(x.index())
if respect_graph_attributes:
json_string += ",\n\"x\":" + str(int(self.x(x) + 0.5)) + ",\n\"y\":" + str(int(self.y(x) + 0.5))
json_string += "\n}"
json_string += "\n],\n\"links\":["
for x in self.constGraph().edges:
json_string += ",\n{\n\"source\":" + str(x.source().index()) + ",\n\"target\":" + str(
x.target().index()) + "\n}"
json_string += "\n]\n};"
json_string = json_string.replace("\"links\":[,", "\"links\":[")
json_string = json_string.replace("\"nodes\":[,", "\"nodes\":[")
return json_string
def replace_GraphAttributes(klass, name):
if not name.endswith("GraphAttributes"): return
klass.directed = property(klass.directed, cppyy.gbl.ogdf_pythonization.GraphAttributes_set_directed)
for field in (CGA_FIELD_NAMES if name.startswith("Cluster") else GA_FIELD_NAMES):
setattr(klass, field, GraphAttributesDescriptor(
getattr(klass, field),
getattr(cppyy.gbl.ogdf_pythonization, "GraphAttributes_set_%s" % field)
))
klass._repr_html_ = GraphAttributes_to_html
generate_GA_setters()
replace_GraphAttributes(cppyy.gbl.ogdf.GraphAttributes, "GraphAttributes")
replace_GraphAttributes(cppyy.gbl.ogdf.ClusterGraphAttributes, "ClusterGraphAttributes")
cppyy.gbl.ogdf.Graph._repr_html_ = GraphAttributes_to_html # TODO layout
cppyy.gbl.ogdf.ClusterGraph._repr_html_ = GraphAttributes_to_html
def GraphObjectContainer_getitem(self, idx):
for e in self:
if e.index() == idx:
return e
raise IndexError()
def pythonize_ogdf_internal(klass, name):
if name.startswith("GraphObjectContainer"):
klass.__getitem__ = GraphObjectContainer_getitem
cppyy.py.add_pythonization(pythonize_ogdf_internal, "ogdf::internal")
class StreamToStr(object):
def __init__(self, klass):
self.klass = klass
self.old_str = klass.__str__
def __get__(self, obj, type=None):
@functools.wraps(self.old_str)
def to_str():
try:
return cppyy.gbl.ogdf_pythonization.to_string(obj)
except TypeError as e:
print(e)
return self.old_str(obj)
return to_str
def generic_getitem(self, idx):
# TODO more efficient implementation for random-access, reverse iteration
for i, e in enumerate(self):
if i == idx:
return e
raise IndexError()
def pythonize_ogdf(klass, name):
if not isinstance(klass.__str__, StreamToStr):
klass.__str__ = StreamToStr(klass)
if re.match("List(Const)?(Reverse)?Iterator(Base)?(<.+>)?", name):
def advance(self):
if not self.valid():
raise StopIteration()
val = self.__deref__()
self.__preinc__()
return val
klass.__next__ = advance
if re.match("S?List(Pure)?", name):
klass.__getitem__ = generic_getitem
# TODO setitem?
cppyy.py.add_pythonization(pythonize_ogdf, "ogdf")