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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
|
# ==================================================================================================================== #
# _____ _ _ ____ _ #
# _ __ _ |_ _|__ ___ | (_)_ __ __ _ / ___|_ __ __ _ _ __ | |__ #
# | '_ \| | | || |/ _ \ / _ \| | | '_ \ / _` || | _| '__/ _` | '_ \| '_ \ #
# | |_) | |_| || | (_) | (_) | | | | | | (_| || |_| | | | (_| | |_) | | | | #
# | .__/ \__, ||_|\___/ \___/|_|_|_| |_|\__, (_)____|_| \__,_| .__/|_| |_| #
# |_| |___/ |___/ |_| #
# ==================================================================================================================== #
# Authors: #
# Patrick Lehmann #
# #
# License: #
# ==================================================================================================================== #
# Copyright 2017-2024 Patrick Lehmann - Bötzingen, Germany #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License. #
# You may obtain a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
# #
# SPDX-License-Identifier: Apache-2.0 #
# ==================================================================================================================== #
#
"""
A data model to write out GraphML XML files.
.. seealso::
* http://graphml.graphdrawing.org/primer/graphml-primer.html
"""
from enum import Enum, auto
from pathlib import Path
from typing import Any, List, Dict, Union, Optional as Nullable
try:
from pyTooling.Decorators import export, readonly
from pyTooling.MetaClasses import ExtendedType
from pyTooling.Graph import Graph as pyToolingGraph, Subgraph as pyToolingSubgraph
from pyTooling.Tree import Node as pyToolingNode
except (ImportError, ModuleNotFoundError): # pragma: no cover
print("[pyTooling.Graph.GraphML] Could not import from 'pyTooling.*'!")
try:
from Decorators import export, readonly
from MetaClasses import ExtendedType, mixin
from Graph import Graph as pyToolingGraph, Subgraph as pyToolingSubgraph
from Tree import Node as pyToolingNode
except (ImportError, ModuleNotFoundError) as ex: # pragma: no cover
print("[pyTooling.Graph.GraphML] Could not import directly!")
raise ex
@export
class AttributeContext(Enum):
"""
Enumeration of all attribute contexts.
An attribute context describes to what kind of GraphML node an attribute can be applied.
"""
GraphML = auto()
Graph = auto()
Node = auto()
Edge = auto()
Port = auto()
def __str__(self) -> str:
return f"{self.name.lower()}"
@export
class AttributeTypes(Enum):
"""
Enumeration of all attribute types.
An attribute type describes what datatype can be applied to an attribute.
"""
Boolean = auto()
Int = auto()
Long = auto()
Float = auto()
Double = auto()
String = auto()
def __str__(self) -> str:
return f"{self.name.lower()}"
@export
class EdgeDefault(Enum):
"""An enumeration describing the default edge direction."""
Undirected = auto()
Directed = auto()
def __str__(self) -> str:
return f"{self.name.lower()}"
@export
class ParsingOrder(Enum):
"""An enumeration describing the parsing order of the graph's representation."""
NodesFirst = auto() #: First, all nodes are given, then followed by all edges.
AdjacencyList = auto()
Free = auto()
def __str__(self) -> str:
return f"{self.name.lower()}"
@export
class IDStyle(Enum):
"""An enumeration describing the style of identifiers (IDs)."""
Canonical = auto()
Free = auto()
def __str__(self) -> str:
return f"{self.name.lower()}"
@export
class Base(metaclass=ExtendedType, slots=True):
"""
Base-class for all GraphML data model classes.
"""
@readonly
def HasClosingTag(self) -> bool:
return True
def Tag(self, indent: int = 0) -> str:
raise NotImplementedError()
def OpeningTag(self, indent: int = 0) -> str:
raise NotImplementedError()
def ClosingTag(self, indent: int = 0) -> str:
raise NotImplementedError()
def ToStringLines(self, indent: int = 0) -> List[str]:
raise NotImplementedError()
@export
class BaseWithID(Base):
_id: str
def __init__(self, identifier: str) -> None:
super().__init__()
self._id = identifier
@readonly
def ID(self) -> str:
return self._id
@export
class BaseWithData(BaseWithID):
_data: List['Data']
def __init__(self, identifier: str) -> None:
super().__init__(identifier)
self._data = []
@readonly
def Data(self) -> List['Data']:
return self._data
def AddData(self, data: Data) -> Data:
self._data.append(data)
return data
@export
class Key(BaseWithID):
_context: AttributeContext
_attributeName: str
_attributeType: AttributeTypes
def __init__(self, identifier: str, context: AttributeContext, name: str, type: AttributeTypes) -> None:
super().__init__(identifier)
self._context = context
self._attributeName = name
self._attributeType = type
@readonly
def Context(self) -> AttributeContext:
return self._context
@readonly
def AttributeName(self) -> str:
return self._attributeName
@readonly
def AttributeType(self) -> AttributeTypes:
return self._attributeType
@readonly
def HasClosingTag(self) -> bool:
return False
def Tag(self, indent: int = 2) -> str:
return f"""{' '*indent}<key id="{self._id}" for="{self._context}" attr.name="{self._attributeName}" attr.type="{self._attributeType}" />\n"""
def ToStringLines(self, indent: int = 2) -> List[str]:
return [self.Tag(indent)]
@export
class Data(Base):
_key: Key
_data: Any
def __init__(self, key: Key, data: Any) -> None:
super().__init__()
self._key = key
self._data = data
@readonly
def Key(self) -> Key:
return self._key
@readonly
def Data(self) -> Any:
return self._data
@readonly
def HasClosingTag(self) -> bool:
return False
def Tag(self, indent: int = 2) -> str:
data = str(self._data)
data = data.replace("&", "&")
data = data.replace("<", "<")
data = data.replace(">", ">")
data = data.replace("\n", "\\n")
return f"""{' '*indent}<data key="{self._key._id}">{data}</data>\n"""
def ToStringLines(self, indent: int = 2) -> List[str]:
return [self.Tag(indent)]
@export
class Node(BaseWithData):
def __init__(self, identifier: str) -> None:
super().__init__(identifier)
@readonly
def HasClosingTag(self) -> bool:
return len(self._data) > 0
def Tag(self, indent: int = 2) -> str:
return f"""{' '*indent}<node id="{self._id}" />\n"""
def OpeningTag(self, indent: int = 2) -> str:
return f"""{' '*indent}<node id="{self._id}">\n"""
def ClosingTag(self, indent: int = 2) -> str:
return f"""{' ' * indent}</node>\n"""
def ToStringLines(self, indent: int = 2) -> List[str]:
if not self.HasClosingTag:
return [self.Tag(indent)]
lines = [self.OpeningTag(indent)]
for data in self._data:
lines.extend(data.ToStringLines(indent + 1))
lines.append(self.ClosingTag(indent))
return lines
@export
class Edge(BaseWithData):
_source: Node
_target: Node
def __init__(self, identifier: str, source: Node, target: Node) -> None:
super().__init__(identifier)
self._source = source
self._target = target
@readonly
def Source(self) -> Node:
return self._source
@readonly
def Target(self) -> Node:
return self._target
@readonly
def HasClosingTag(self) -> bool:
return len(self._data) > 0
def Tag(self, indent: int = 2) -> str:
return f"""{' ' * indent}<edge id="{self._id}" source="{self._source._id}" target="{self._target._id}" />\n"""
def OpeningTag(self, indent: int = 2) -> str:
return f"""{' '*indent}<edge id="{self._id}" source="{self._source._id}" target="{self._target._id}">\n"""
def ClosingTag(self, indent: int = 2) -> str:
return f"""{' ' * indent}</edge>\n"""
def ToStringLines(self, indent: int = 2) -> List[str]:
if not self.HasClosingTag:
return [self.Tag(indent)]
lines = [self.OpeningTag(indent)]
for data in self._data:
lines.extend(data.ToStringLines(indent + 1))
lines.append(self.ClosingTag(indent))
return lines
@export
class BaseGraph(BaseWithData, mixin=True):
_subgraphs: Dict[str, 'Subgraph']
_nodes: Dict[str, Node]
_edges: Dict[str, Edge]
_edgeDefault: EdgeDefault
_parseOrder: ParsingOrder
_nodeIDStyle: IDStyle
_edgeIDStyle: IDStyle
def __init__(self, identifier: Nullable[str] = None) -> None:
super().__init__(identifier)
self._subgraphs = {}
self._nodes = {}
self._edges = {}
self._edgeDefault = EdgeDefault.Directed
self._parseOrder = ParsingOrder.NodesFirst
self._nodeIDStyle = IDStyle.Free
self._edgeIDStyle = IDStyle.Free
@readonly
def Subgraphs(self) -> Dict[str, 'Subgraph']:
return self._subgraphs
@readonly
def Nodes(self) -> Dict[str, Node]:
return self._nodes
@readonly
def Edges(self) -> Dict[str, Edge]:
return self._edges
def AddSubgraph(self, subgraph: 'Subgraph') -> 'Subgraph':
self._subgraphs[subgraph._subgraphID] = subgraph
self._nodes[subgraph._id] = subgraph
return subgraph
def GetSubgraph(self, subgraphName: str) -> 'Subgraph':
return self._subgraphs[subgraphName]
def AddNode(self, node: Node) -> Node:
self._nodes[node._id] = node
return node
def GetNode(self, nodeName: str) -> Node:
return self._nodes[nodeName]
def AddEdge(self, edge: Edge) -> Edge:
self._edges[edge._id] = edge
return edge
def GetEdge(self, edgeName: str) -> Edge:
return self._edges[edgeName]
def OpeningTag(self, indent: int = 1) -> str:
return f"""\
{' '*indent}<graph id="{self._id}"
{' '*indent} edgedefault="{self._edgeDefault!s}"
{' '*indent} parse.nodes="{len(self._nodes)}"
{' '*indent} parse.edges="{len(self._edges)}"
{' '*indent} parse.order="{self._parseOrder!s}"
{' '*indent} parse.nodeids="{self._nodeIDStyle!s}"
{' '*indent} parse.edgeids="{self._edgeIDStyle!s}">
"""
def ClosingTag(self, indent: int = 1) -> str:
return f"{' '*indent}</graph>\n"
def ToStringLines(self, indent: int = 1) -> List[str]:
lines = [self.OpeningTag(indent)]
for node in self._nodes.values():
lines.extend(node.ToStringLines(indent + 1))
for edge in self._edges.values():
lines.extend(edge.ToStringLines(indent + 1))
# for data in self._data:
# lines.extend(data.ToStringLines(indent + 1))
lines.append(self.ClosingTag(indent))
return lines
@export
class Graph(BaseGraph):
_document: 'GraphMLDocument'
_ids: Dict[str, Union[Node, Edge, 'Subgraph']]
def __init__(self, document: 'GraphMLDocument', identifier: str) -> None:
super().__init__(identifier)
self._document = document
self._ids = {}
def GetByID(self, identifier: str) -> Union[Node, Edge, 'Subgraph']:
return self._ids[identifier]
def AddSubgraph(self, subgraph: 'Subgraph') -> 'Subgraph':
result = super().AddSubgraph(subgraph)
self._ids[subgraph._subgraphID] = subgraph
subgraph._root = self
return result
def AddNode(self, node: Node) -> Node:
result = super().AddNode(node)
self._ids[node._id] = node
return result
def AddEdge(self, edge: Edge) -> Edge:
result = super().AddEdge(edge)
self._ids[edge._id] = edge
return result
@export
class Subgraph(Node, BaseGraph):
_subgraphID: str
_root: Nullable[Graph]
def __init__(self, nodeIdentifier: str, graphIdentifier: str) -> None:
super().__init__(nodeIdentifier)
BaseGraph.__init__(self, nodeIdentifier)
self._subgraphID = graphIdentifier
self._root = None
@readonly
def RootGraph(self) -> Graph:
return self._root
@readonly
def SubgraphID(self) -> str:
return self._subgraphID
@readonly
def HasClosingTag(self) -> bool:
return True
def AddNode(self, node: Node) -> Node:
result = super().AddNode(node)
self._root._ids[node._id] = node
return result
def AddEdge(self, edge: Edge) -> Edge:
result = super().AddEdge(edge)
self._root._ids[edge._id] = edge
return result
def Tag(self, indent: int = 2) -> str:
raise NotImplementedError()
def OpeningTag(self, indent: int = 1) -> str:
return f"""\
{' ' * indent}<graph id="{self._subgraphID}"
{' ' * indent} edgedefault="{self._edgeDefault!s}"
{' ' * indent} parse.nodes="{len(self._nodes)}"
{' ' * indent} parse.edges="{len(self._edges)}"
{' ' * indent} parse.order="{self._parseOrder!s}"
{' ' * indent} parse.nodeids="{self._nodeIDStyle!s}"
{' ' * indent} parse.edgeids="{self._edgeIDStyle!s}">
"""
def ClosingTag(self, indent: int = 2) -> str:
return BaseGraph.ClosingTag(self, indent)
def ToStringLines(self, indent: int = 2) -> List[str]:
lines = [super().OpeningTag(indent)]
for data in self._data:
lines.extend(data.ToStringLines(indent + 1))
# lines.extend(Graph.ToStringLines(self, indent + 1))
lines.append(self.OpeningTag(indent + 1))
for node in self._nodes.values():
lines.extend(node.ToStringLines(indent + 2))
for edge in self._edges.values():
lines.extend(edge.ToStringLines(indent + 2))
# for data in self._data:
# lines.extend(data.ToStringLines(indent + 1))
lines.append(self.ClosingTag(indent + 1))
lines.append(super().ClosingTag(indent))
return lines
@export
class GraphMLDocument(Base):
xmlNS = {
None: "http://graphml.graphdrawing.org/xmlns",
"xsi": "http://www.w3.org/2001/XMLSchema-instance"
}
xsi = {
"schemaLocation": "http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd"
}
_graph: Graph
_keys: Dict[str, Key]
def __init__(self, identifier: str = "G") -> None:
super().__init__()
self._graph = Graph(self, identifier)
self._keys = {}
@readonly
def Graph(self) -> BaseGraph:
return self._graph
@readonly
def Keys(self) -> Dict[str, Key]:
return self._keys
def AddKey(self, key: Key) -> Key:
self._keys[key._id] = key
return key
def GetKey(self, keyName: str) -> Key:
return self._keys[keyName]
def HasKey(self, keyName: str) -> bool:
return keyName in self._keys
def FromGraph(self, graph: pyToolingGraph):
document = self
self._graph._id = graph._name
nodeValue = self.AddKey(Key("nodeValue", AttributeContext.Node, "value", AttributeTypes.String))
edgeValue = self.AddKey(Key("edgeValue", AttributeContext.Edge, "value", AttributeTypes.String))
def translateGraph(rootGraph: Graph, pyTGraph: pyToolingGraph):
for vertex in pyTGraph.IterateVertices():
newNode = Node(vertex._id)
newNode.AddData(Data(nodeValue, vertex._value))
for key, value in vertex._dict.items():
if document.HasKey(str(key)):
nodeKey = document.GetKey(f"node{key!s}")
else:
nodeKey = document.AddKey(Key(f"node{key!s}", AttributeContext.Node, str(key), AttributeTypes.String))
newNode.AddData(Data(nodeKey, value))
rootGraph.AddNode(newNode)
for edge in pyTGraph.IterateEdges():
source = rootGraph.GetByID(edge._source._id)
target = rootGraph.GetByID(edge._destination._id)
newEdge = Edge(edge._id, source, target)
newEdge.AddData(Data(edgeValue, edge._value))
for key, value in edge._dict.items():
if self.HasKey(str(key)):
edgeKey = self.GetBy(f"edge{key!s}")
else:
edgeKey = self.AddKey(Key(f"edge{key!s}", AttributeContext.Edge, str(key), AttributeTypes.String))
newEdge.AddData(Data(edgeKey, value))
rootGraph.AddEdge(newEdge)
for link in pyTGraph.IterateLinks():
source = rootGraph.GetByID(link._source._id)
target = rootGraph.GetByID(link._destination._id)
newEdge = Edge(link._id, source, target)
newEdge.AddData(Data(edgeValue, link._value))
for key, value in link._dict.items():
if self.HasKey(str(key)):
edgeKey = self.GetKey(f"link{key!s}")
else:
edgeKey = self.AddKey(Key(f"link{key!s}", AttributeContext.Edge, str(key), AttributeTypes.String))
newEdge.AddData(Data(edgeKey, value))
rootGraph.AddEdge(newEdge)
def translateSubgraph(nodeGraph: Subgraph, pyTSubgraph: pyToolingSubgraph):
rootGraph = nodeGraph.RootGraph
for vertex in pyTSubgraph.IterateVertices():
newNode = Node(vertex._id)
newNode.AddData(Data(nodeValue, vertex._value))
for key, value in vertex._dict.items():
if self.HasKey(str(key)):
nodeKey = self.GetKey(f"node{key!s}")
else:
nodeKey = self.AddKey(Key(f"node{key!s}", AttributeContext.Node, str(key), AttributeTypes.String))
newNode.AddData(Data(nodeKey, value))
nodeGraph.AddNode(newNode)
for edge in pyTSubgraph.IterateEdges():
source = nodeGraph.GetNode(edge._source._id)
target = nodeGraph.GetNode(edge._destination._id)
newEdge = Edge(edge._id, source, target)
newEdge.AddData(Data(edgeValue, edge._value))
for key, value in edge._dict.items():
if self.HasKey(str(key)):
edgeKey = self.GetKey(f"edge{key!s}")
else:
edgeKey = self.AddKey(Key(f"edge{key!s}", AttributeContext.Edge, str(key), AttributeTypes.String))
newEdge.AddData(Data(edgeKey, value))
nodeGraph.AddEdge(newEdge)
for subgraph in graph.Subgraphs:
nodeGraph = Subgraph(subgraph.Name, "sg" + subgraph.Name)
self._graph.AddSubgraph(nodeGraph)
translateSubgraph(nodeGraph, subgraph)
translateGraph(self._graph, graph)
def FromTree(self, tree: pyToolingNode):
self._graph._id = tree._id
nodeValue = self.AddKey(Key("nodeValue", AttributeContext.Node, "value", AttributeTypes.String))
rootNode = self._graph.AddNode(Node(tree._id))
rootNode.AddData(Data(nodeValue, tree._value))
for i, node in enumerate(tree.GetDescendants()):
newNode = self._graph.AddNode(Node(node._id))
newNode.AddData(Data(nodeValue, node._value))
newEdge = self._graph.AddEdge(Edge(f"e{i}", newNode, self._graph.GetNode(node._parent._id)))
def OpeningTag(self, indent: int = 0) -> str:
return f"""\
{' '*indent}<graphml xmlns="{self.xmlNS[None]}"
{' '*indent} xmlns:xsi="{self.xmlNS["xsi"]}"
{' '*indent} xsi:schemaLocation="{self.xsi["schemaLocation"]}">
"""
def ClosingTag(self, indent: int = 0) -> str:
return f"{' '*indent}</graphml>\n"
def ToStringLines(self, indent: int = 0) -> List[str]:
lines = [self.OpeningTag(indent)]
for key in self._keys.values():
lines.extend(key.ToStringLines(indent + 1))
lines.extend(self._graph.ToStringLines(indent + 1))
lines.append(self.ClosingTag(indent))
return lines
def WriteToFile(self, file: Path) -> None:
with file.open("w") as f:
f.write(f"""<?xml version="1.0" encoding="utf-8"?>""")
f.writelines(self.ToStringLines())
|