forked from rlindsgaard/graphviz-overlay
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph.py
553 lines (484 loc) · 13.1 KB
/
graph.py
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
"""
Generate a undirected graph
"""
from argparse import ArgumentParser, FileType
import graphviz
import json
from overlays.er import EntityRelationshipOverlay
from overlays.graphviz import GraphOverlay, DigraphOverlay
import sys
valid_attrs = [
'_background',
'area',
'arrowhead',
'arrowsize',
'arrowtail',
'bb',
'bgcolor',
'center',
'charset',
'class',
'clusterrank',
'color',
'colorscheme',
'comment',
'compound',
'concentrate',
'constraint',
'Damping',
'decorate',
'defaultdist',
'dim',
'dimen',
'dir',
'diredgeconstraints',
'distortion',
'dpi',
'edgehref',
'edgetarget',
'edgetooltip',
'edgeURL',
'epsilon',
'esep',
'fillcolor',
'fixedsize',
'fontcolor',
'fontname',
'fontnames',
'fontpath',
'fontsize',
'forcelabels',
'gradientangle',
'group',
'head_lp',
'headclip',
'headhref',
'headlabel',
'headport',
'headtarget',
'headtooltip',
'headURL',
'height',
'href',
'id',
'image',
'imagepath',
'imagepos',
'imagescale',
'inputscale',
'K',
'label',
'label_scheme',
'labelangle',
'labeldistance',
'labelfloat',
'labelfontcolor',
'labelfontname',
'labelfontsize',
'labelhref',
'labeljust',
'labelloc',
'labeltarget',
'labeltooltip',
'labelURL',
'landscape',
'layer',
'layerlistsep',
'layers',
'layerselect',
'layersep',
'layout',
'len',
'levels',
'levelsgap',
'lhead',
'lheight',
'lp',
'ltail',
'lwidth',
'margin',
'maxiter',
'mclimit',
'mindist',
'minlen',
'mode',
'model',
'mosek',
'newrank',
'nodesep',
'nojustify',
'normalize',
'notranslate',
'nslimit',
'nslimit1',
'ordering',
'orientation',
'outputorder',
'overlap',
'overlap_scaling',
'overlap_shrink',
'pack',
'packmode',
'pad',
'page',
'pagedir',
'pencolor',
'penwidth',
'peripheries',
'pin',
'pos',
'quadtree',
'quantum',
# 'rank', # We intepret this one ourselves
'rankdir',
'ranksep',
'ratio',
'rects',
'regular',
'remincross',
'repulsiveforce',
'resolution',
'root',
'rotate',
'rotation',
'samehead',
'sametail',
'samplepoints',
'scale',
'searchsize',
'sep',
'shape',
'shapefile',
'showboxes',
'sides',
'size',
'skew',
'smoothing',
'sortv',
'splines',
'start',
'style',
'stylesheet',
'tail_lp',
'tailclip',
'tailhref',
'taillabel',
'tailport',
'tailtarget',
'tailtooltip',
'tailURL',
'target',
'tooltip',
'truecolor',
'URL',
'vertices',
'viewport',
'voro_margin',
'weight',
'width',
'xdotversion',
'xlabel',
'xlp',
'z',
]
def main(opts):
model = load_json_file(opts.infile)
styles = load_json_file(opts.stylesheet)
ctx = GraphContext(styles)
overlay_args = {
arg: getattr(opts, arg)
for arg in opts.overlay.arguments()
}
overlay = opts.overlay(ctx, **overlay_args)
overlay.draw(opts.name, model)
print(overlay.source())
def load_json_file(file):
if file:
return json.load(file)
return {}
class GraphContext(object):
"""
Defines a context for graph objects.
A wrapper for the Graphviz interface to define objects via
a dictionary structure and turn it into a graph.
Automatically adds graphviz attributes defined in the object
see https://graphviz.org/doc/info/attrs.html for availability.
Attributes added to the root dictionary is added as graph attributes.
Furthermore special "attributes" are interpreted as such::
"nodes": {
"node_id": {
# Node attributes
"classes": ["mynode"], # Nodes have the base style "node"
#
The ``rank`` attribute is treated differently, as it is defined
by an id in the node object. e.g. "rank": "myrank". At the
"rank": "myrank"
}
},
"edges": [
# An edge pointing to and from the same node
{
"from": "node_id",
"to": "node_id"
"classes": ["myedge"], # Edges have the base style "edge"
}
],
"subgraphs": {
"subgraph_name": {
# Recursively treated as an individual graph
}
}
"classes": ["mygraph"], # All graphs have the base style "graph"
"ranks": {
"myrank": "same",
}
"styles": {
"mynode": {
}
}
}
"""
base_styles = {
'graph': {},
'node': {},
'edge': {},
}
def __init__(
self, stylesheet: dict, path: str = '', prefix: str = '',
_level: int = 0
):
self.graph = None
self.styles = self.base_styles.copy()
self.add_stylesheet(stylesheet)
self._ranks = {}
self._level = _level
self.prefix = prefix
self.path = path
def init_graph(self, name, graph_class, attributes):
styles = attributes.get('styles', {})
graph_attrs = styles.get('graph', {})
graph_attrs.update(attributes)
graph_attrs = self._build_attributes(
'graph',
graph_attrs
)
self.graph = graph_class(
name,
graph_attr=graph_attrs,
node_attr=self._build_attributes(
'node',
styles.get('node'),
),
edge_attr=self._build_attributes(
'edge',
styles.get('edge'),
),
)
def add_stylesheet(self, stylesheet: dict):
"""
Add stylesheet to the context stylesheet.
A stylesheet consists of a dictionary of class
definitions which are themselves dictionaries.
"""
new_stylesheet = self.styles.copy()
for class_name, styles in stylesheet.items():
new_class = new_stylesheet.get(class_name, {})
for attr, value in styles.items():
if attr == 'style':
if 'style' not in new_class:
new_class['style'] = value
else:
for v in value:
if v in new_class['style']:
continue
new_class['style'].append(v)
else:
new_class[attr] = value
new_stylesheet[class_name] = new_class
self.styles = new_stylesheet
def new_context(self, name, path, model):
stylesheet = self.styles.copy()
ctx = GraphContext(
stylesheet,
path=path,
prefix=model.get('prefix', ''),
_level=self._level + 1,
)
if model.get('cluster', False):
if not name.startswith('cluster_'):
name = f'cluster_{name}'
ctx.init_graph(name, self.graph.__class__, model)
return ctx
def add_subgraph_from_context(self, ctx):
self.graph.subgraph(
ctx.graph,
)
for rank, nodes in ctx.get_ranks().items():
self._ranks[rank] = self._ranks.get(rank, []) + nodes
def get_ranks(self):
return self._ranks
def node_id(self, name):
if not self.prefix:
return name
return f'{self.prefix}_{name}'
def add_edge(
self, node_from: str, node_to: str, attributes: dict = None,
classes=None
):
classes = classes or []
attrs = self._build_attributes(
'edge',
attributes,
classes,
)
self.graph.edge(
node_from,
node_to,
**attrs
)
def add_node(self, name, attributes=None, classes=None):
classes = classes or []
if 'rank' in attributes:
rank_name = attributes['rank']
rank_nodes = self._ranks.get(rank_name, [])
self._ranks[rank_name] = rank_nodes + [name]
attrs = self._build_attributes(
'node',
attributes,
classes,
)
if 'label' in attrs and isinstance(attrs['label'], dict):
attrs['label'] = format_html_label(attrs['label'])
attrs['shape'] = 'plain'
self.graph.node(
self.node_id(name),
**attrs
)
def _build_attributes(
self, element_type: str, attributes: dict, classes: list = None
) -> dict:
"""
Construct a dictionary of attributes for a graphviz element.
Filters out any non-valid attributes and applies any attributes
defined in any of the classes.
Classes work like CSS classes, any attribute defined gets
overriden by that later defined one.
Any attributes specified overrides the one supplied by
any classes.
:param str type: The DOT element, graph, subgraph, node, edge
:param dict attributes: (key, value) pairs. The value is
treated as a literal.
:param list classes: Any classes to apply defined by the stylesheet.
:returns: A (key, value) mapping of element attributes.
:rtype: dict
"""
attrs = self.styles.get(element_type, {}).copy()
classes = classes or []
attributes = attributes or {}
for c in classes + attributes.get('classes', []):
attrs.update(self.styles.get(c, {}))
if attributes:
attrs.update(attributes)
styles = attrs.get('style', [])
if not isinstance(styles, list):
raise ValueError(
"style attribute must be a list, got '%r'" % styles
)
if not attributes.get('visible', True):
styles.append('invis')
elif attributes.get('cluster', False):
if not styles:
styles.append('solid')
if styles:
attrs['style'] = ','.join(styles)
result = {}
for attr in attrs.keys():
if attr in valid_attrs:
result[attr] = attrs[attr]
return result
def add_rank(self, rank_name, rank_type):
rank_nodes = self._ranks.get(rank_name)
fmt = '{{rank={rank_type}; {nodenames}}}'
self.graph.body.append(
fmt.format(
rank_type=rank_type,
nodenames=' '.join(rank_nodes)),
)
def source(self):
return self.graph.source
def format_html_label(label):
"""Produces a graphviz html label from a dictionary."""
rows = []
for row in label['trs']:
tds = []
for td in row:
tds.append(
format_html_tag('td', td, td['value'])
)
rows.append(
format_html_tag('tr', inner=''.join(tds))
)
table = format_html_tag('table', label, ''.join(rows))
return f'<{table}>'
def format_html_tag(tag, attrs={}, inner=''):
html_attrs = {
'TABLE': [
'ALIGN', 'BGCOLOR', 'BORDER', 'CELLBORDER', 'CELLPADDING',
'CELLSPACING', 'COLOR', 'COLUMNS', 'FIXEDSIZE', 'GRADIENTANGLE',
'HEIGHT', 'HREF', 'ID', 'PORT', 'ROWS', 'SIDES',
'STYLE', 'TARGET', 'TITLE', 'TOOLTIP', 'VALIGN',
'WIDTH',
],
'TD': [
'ALIGN', 'BALIGN', 'BGCOLOR', 'BORDER', 'CELLPADDING',
'CELLSPACING', 'COLOR', 'COLSPAN', 'FIXEDSIZE', 'GRADIENTANGLE',
'HEIGHT', 'HREF', 'ID', 'PORT', 'ROWSPAN', 'SIDES',
'STYLE', 'TARGET', 'TITLE', 'TOOLTIP', 'VALIGN',
'WIDTH',
]
}
tag = tag.upper()
tag_attrs = [
f'{k.upper()}="{v}"'
for k, v in attrs.items()
if k.upper() in html_attrs[tag]
]
return f"<{tag} {' '.join(tag_attrs)}>{inner}</{tag}>"
overlays = [
GraphOverlay,
DigraphOverlay,
EntityRelationshipOverlay,
]
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument(
'-n', '--name',
default='G',
help='Name of the graph')
parser.add_argument(
'-i', '--infile',
type=FileType(mode='r'),
help='Input json file',
default=sys.stdin
)
parser.add_argument(
'-s', '--stylesheet',
type=FileType(mode='r'),
default=None,
help='Stylesheet file',
)
subparsers = parser.add_subparsers(
title='Overlays',
description='The overlay that will be used to generate the graph.',
required=True,
dest='overlay',
help='Select the overlay to render the graph.',
)
for overlay in overlays:
subparser = subparsers.add_parser(overlay.name)
args = overlay.arguments()
for arg, params in args.items():
arg = arg.replace('_', '-')
subparser.add_argument(f'--{arg}', **params)
subparser.set_defaults(overlay=overlay)
main(parser.parse_args())