/
tamarincleandotlib.py
executable file
·2121 lines (1670 loc) · 54 KB
/
tamarincleandotlib.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
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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
tamarin-cleandot.py
A postprocesser for Tamarin's dot output. The idea is to provide a drop-in
replacement for the dot program that takes care of the cleanup.
Its first aim is to provide more structure in the graphs by clustering possible
threads by using a heuristic. For now, this is done by searching for connected
nodes whose names share a prefix that is followed by a digit.
The comments in the dot file are used by Tamarin to guide tamarin-cleandot. In
particular, this is how the GUI switches are propagated: they end up in the
global PARAMETERS dict:
- simplification : [0..3]
- abbreviate : True/False
E.g.:
// simplification: X
// abbreviate: True
To do:
The parameters now still include the static set of rules names. These
should be used to determine a nice colour distribution.
December 2012 -- January 2013
Cas Cremers
Usage:
tamarin-cleandot.py [options] file
Where [options] is one of:
-T imageformat
-K dotmode
-o imgfile
If [options] contains '-V' or '--version', the input is handled directly by graphviz.
***********
Short-term wish list:
- Work on 'hiding' in-cluster connecting state facts, or collapse multiple such nodes into a single record.
- If Tamarin can output the rule names in the dotfile's comments, we can do a nicer color distribution.
"""
import os
import sys
from string import digits, whitespace
from pydot import *
from pyparsing import \
Literal, Word, ZeroOrMore, OneOrMore, oneOf, Group, Dict, Optional, \
printables, alphas, alphanums, nums, ParseException, restOfLine, Forward, delimitedList, \
nestedExpr, Keyword, Combine, replaceWith, StringEnd
import pprint
# Clusters
CCOUNT = 0 # Cluster count (used for naming)
CLUSTERCOLOR1 = (0.5,0.6,0.83) # HSL
CLUSTERCOLOR2 = (1.2,0.6,0.83) # HSL
# Global variable to store the pyparsing BNF.
labelbnf = None
# Global variable for storing dictionary with special parameters
PARAMETERS = {}
# DEBUG mode
DEBUGMODE = True
DEBUGPARAMETERS = False
class rules(object):
"""
Rules object class for abbreviations purposes.
Objects from this class store all the labels from nodes in a dict.
The object serves as an interface for the abbreviation function, but it is
not so cleanly split as we would want.
My initial idea was to have a "generic" abbreviation function that I could
directly use in Scyther as well, but that's not done yet.
"""
def __init__(self,D):
# The init is a dict of lists. We can later use this to reinsert data.
self.data = D
self.abbreviations = [] # Will contain (bigterm,abbreviation) pairs
self.prefixes = {} # Will map prefixes to (firstabbreviation,count) tuples; its purpose is to determine later what was only used once.
self.dirty = True
def subst(self,l,tt,string):
"""
Substitute a single string in the data type that we use.
(which is the nested list structure coming out of pyparsing)
"""
if render(l) == tt:
if isinstance(l,list):
return [string]
else:
return string
else:
if isinstance(l,list):
nl = []
for x in l:
nl.append(self.subst(x,tt,string))
return nl
else:
return l
def replaceAll(self,src,dst):
"""
Replace src by dst throughout the object.
Return 'firstUse' usage point (or None) in existing abbreviation sequence
"""
# Replace data
for k in self.data.keys():
self.data[k] = self.subst(self.data[k],src,dst)
# Replace existing abbreviations
# compute firstUse as the first usage point
firstUse = None
for i in range(0,len(self.abbreviations)):
(ta,sa) = self.abbreviations[i]
tb = self.subst(ta,src,dst)
if sa == src:
sa = dst
self.abbreviations[i] = (tb,sa)
if ta != tb and firstUse is None:
firstUse = i
self.dirty = True
return firstUse
def simplifySinglePrefix(self,prefix):
"""
Try to simplify the abbreviation starting with the prefix.
Use case: we often generate "hash1" when only one hash occurs. In such
cases we would have wanted to abbreviate it just by "hash".
"""
(firstab,count) = self.prefixes[prefix]
if count == 1:
#print "Trying to simplify %s to %s" % (firstab,prefix)
if not self.exists(prefix):
# The isolated prefix is available, so we can replace 'firstab' by 'prefix'
self.replaceAll(firstab,prefix)
return True
return False
def simplify(self):
"""
Simplify single prefix occurrences, if possible, by removing the counter
"""
deleted = []
for prefix in self.prefixes.keys():
if self.simplifySinglePrefix(prefix):
deleted.append(prefix)
for prefix in deleted:
del self.prefixes[prefix]
def checkDirty(self):
"""
We only unfold subsequences and renders when needed.
"""
if self.dirty:
l = []
for k in self.data.keys():
l += subsequences(self.data[k])
for (ta,sa) in self.abbreviations:
l += subsequences(ta)
self.subs = l
self.renders = map(render,self.subs) # Maybe replace by list comprehension
self.dirty = False
def getTerms(self):
self.checkDirty()
return self.subs
def exists(self,string):
for (ta,sa) in self.abbreviations:
if string == sa:
return True
self.checkDirty()
return (string in self.renders)
def size(self,term):
return len(render(term))
def isIgnored(self,L):
if len(L) <= 1:
# Too small, will not abbreviate
return True
if isPort(L[0]):
# Ignoring port spec + following
return True
if matchEnds(L,'"','"'):
# Outer
return True
if matchEnds(L,"{","}"):
# Record
return True
if "[" in render(L) and "]" in render(L):
# Rule names 'Init[...]' are never abbreviated (but of course their inner parts might)
return True
for (ta,sa) in self.abbreviations:
# Check existing abbreviations
if ta == L:
# Already abbreviated
return True
return False
def ignore(self,term):
# returns true iff TERM should not be considered for abbreviations
if self.isIgnored(term):
return True
if isTermlist(term):
return False
else:
return True
def abbreviate(self,term,string,prefix):
# abbreviate TERM by string based on prefix
# Note that we might be abbreviating some subterm of an existing definition.
# We therefore want to insert the new abbreviation at a suitable point:
# before it is first used.
tt = render(term)
#print "Abbreviating '%s' to '%s'" % (tt,string)
firstUse = self.replaceAll(tt,string)
# insert the new abbreviation before firstUse
if firstUse is None:
firstUse = len(self.abbreviations)
pre = self.abbreviations[:firstUse]
post = self.abbreviations[firstUse:]
self.abbreviations = pre + [(term,string)] + post
if prefix in self.prefixes.keys():
(firstab,count) = self.prefixes[prefix]
self.prefixes[prefix] = (firstab,count+1)
else:
self.prefixes[prefix] = (string,1)
def prefix(self,term):
"""
Returns a non-empty string: if we want to abbreviate TERM, what would be an appropriate prefix string?
"""
preflen = 3 # Desired prefix length
# First check first bit
allowed = alphanums + "_-!$~"
i = 0
tt = render(term)
prefix = ""
while i < len(tt) and len(prefix) < preflen:
if tt[i] in allowed:
if tt[i] in alphanums:
prefix += tt[i]
i += 1
else:
break
# Is there a lone digit left?
lone_digit = None
if len(tt) > 0:
j = i
while j < len(tt):
if not tt[j] in allowed:
break
j += 1
j -= 1
while j >= i:
if tt[j] in nums:
break
j -= 1
if j > i:
if not tt[j-1] in nums:
lone_digit = tt[j]
# Then add the lone digit (or even overwrite)
if lone_digit and len(prefix) > 0:
if len(prefix) < preflen:
prefix += lone_digit
else:
prefix = prefix[:-1] + lone_digit
# Isolate special cases and default to simple conventions
if len(prefix) == 0:
if tt[0] == "[":
prefix = "S"
elif tt[0] == "(":
prefix = "P"
elif tt[0] == "<" or tt.startswith("\<"):
prefix = "T"
else:
prefix = "M"
return prefix.upper()
def isDone(self):
# Returns true if we are done. No need to call this, usually.
return False
def summary(self):
return (self.data, self.abbreviations)
def abbreviate(O):
"""
Abbreviate some terms
The input object should provide the following methods:
getTerms()
return a list of term-like objects of unspecified type, say TERM
exists(string)
returns true iff this string already occurs in the term list (renderings). Needed to compute a unique new string.
size(TERM)
returns a size indicator for the term
ignore(TERM)
returns true iff TERM should not be considered for abbreviations
abbreviate(TERM,string)
abbreviate TERM by string
prefix(TERM)
Returns a string: if we want to abbreviate TERM, what would be an appropriate prefix string?
isDone()
Returns true if we are done. No need to call this, usually.
"""
def niceName(prefix):
# Now come up with a name for it
#
# If ends in a digit, then we want alphas
if prefix[-1] in nums:
for c in alphas.lower():
short = "%s%s" % (prefix,c)
if not O.exists(short):
return short
# Otherwise find a number
nr = 0
while True:
nr += 1
short = "%s%i" % (prefix,nr)
if not O.exists(short):
return short
def mightAbbreviate(O,t,occ):
# Returns a "benefit" larger than 0, or -1 if no need to abbreviate
if O.ignore(t):
return -1
if O.size(t) < 7:
return -1
if O.size(t) < 20 and occ == 1:
return -1
return ((2+occ) ** 2) * O.size(t)
count = 0
while True:
# Termination conditions
if O.isDone():
break
seen = []
bestterm = None
bestgain = -1
terms = sorted(O.getTerms()) # Need the sorting
for i in range(0,len(terms)):
t = terms[i]
if not (O.ignore(t) or t in seen):
seen.append(t)
occ = 1
for j in range(i+1,len(terms)):
if terms[j] == t:
occ += 1
else:
break
gain = mightAbbreviate(O,t,occ)
if gain > bestgain:
bestterm = t
bestgain = gain
if bestgain <= 0:
break
# We could do a complex thing here relating bestgain to count, but we keep it simple for now
if count >= 10:
break
# Now come up with a name for it
prefix = O.prefix(bestterm)
short = niceName(prefix)
# Propagate
O.abbreviate(bestterm,short,prefix)
count += 1
# Iterate
# close
O.simplify()
def label_BNF():
"""
BNF for anything that occurs as a label in dot files produced by
Tamarin.
This has to cover timepoints, facts, terms, as well as dot-specifics
for record nodes (and node ports).
Currently it is a rough overapproximation, and for example, facts are
considered more or less interchangeable with terms. We could be more
precise there, which would help for, e.g., not abbreviating facts but
only their arguments.
"""
global labelbnf
if not labelbnf:
# punctuation
lparen = Literal("(")
rparen = Literal(")")
lbrack = Literal("[")
rbrack = Literal("]")
lcbrack = Literal("{")
rcbrack = Literal("}")
bang = Literal("!")
rvsep = Literal("|")
equals = Literal("=")
semi = Literal(";")
colon = Literal(":")
sharp = Literal("#")
tilde = Literal("~")
akrol = Literal("@")
dollar = Literal("$")
comma = Literal(",")
nbsp = Literal(" ")
langle = Literal("<")
rangle = Literal(">")
langleX = Literal("\<")
rangleX = Literal("\>")
langleBug = Literal("<").setParseAction(replaceWith("\<"))
rangleBug = Literal(">").setParseAction(replaceWith("\>"))
langleEsc = langleBug | langleX
rangleEsc = rangleBug | rangleX
dotnewline = Literal("\l")
quote = "'"
def exceptfor(x):
return "".join( [ c for c in printables if c not in x ] ) + " \t"
CONST = Combine(Literal(quote) + Word(exceptfor(quote)) + Literal(quote))
BASICID = Combine(Word( alphanums + "_-") + Optional(Literal(".") + Word(nums)))
senc = Literal("senc")
aenc = Literal("aenc")
KEYWORD = senc | aenc
ID = ~KEYWORD + Combine(Optional(dollar | tilde | sharp | bang) + BASICID)
TIME = Group(akrol + Combine(sharp + BASICID))
TERM = Forward()
TERMLIST = TERM + ZeroOrMore(comma + TERM)
TUPLE1 = langleEsc + TERMLIST + rangleEsc
TUPLE2 = lparen + TERMLIST + rparen
TUPLE = TUPLE1 | TUPLE2
ARG = lparen + Optional(TERMLIST) + rparen
FUNC = ID + Optional(ARG)
ENC = (senc | aenc) + ARG
OPERAND = Group(ENC | FUNC | TUPLE | CONST)
TERM << OPERAND + ZeroOrMore(oneOf("^ * +") + OPERAND)
TPAREN = lparen + TERMLIST + rparen
TBRACK = lbrack + Optional(TERMLIST) + rbrack
FACT = Group(Combine(Optional(bang) + ID) + Optional(TPAREN | TBRACK) + Optional(TIME))
PORT = Combine(langle + BASICID + rangle)
SINGLE = Optional(sharp + ID + colon) + (FACT | TERM)
FIELDID = Group(Optional(PORT) + Optional(SINGLE))
LABEL = Forward()
FIELD = (lcbrack + LABEL + rcbrack) | FIELDID
LABEL << FIELD + ZeroOrMore(rvsep + FIELD)
labelbnf = Optional(Literal('"')) + LABEL + Optional(Literal('"')) + StringEnd()
labelbnf.ignore( nbsp )
labelbnf.ignore( dotnewline )
return labelbnf
def render(tokens):
if isinstance(tokens,str):
return tokens
try:
s = ""
for x in tokens:
s += render(x)
except:
s = str(tokens)
pass
return s
def subsequences(tokens):
"""
Returns a list of lists (subsequences) of the tokens
Note that we remove redundant sublists, i.e., for [[a]] we return [a], and NOT ([a] and [[a]]).
This helps counter some overzealous grouping.
"""
if not isinstance(tokens,list):
return []
if len(tokens) == 1:
if isinstance(tokens[0],list):
# Skip redundant subsequencing
return subsequences(tokens[0])
s = []
for x in tokens:
s += subsequences(x)
return s + [tokens]
def matchEnds(L,first,last):
try:
if L[0] == first and L[-1] == last:
return True
except:
pass
return False
def isPort(tokens):
if isinstance(tokens,str):
if matchEnds(tokens,"<",">"):
return True
return False
def ports(tokens):
res = []
for l in subsequences(tokens):
if len(l) > 0:
if isPort(l[0]):
res.append(l[0])
return res
def isTermlist(L):
"""
Check if something is possibly a term (or a fact even)
"""
if len(L) == 0:
return False
if isPort(L[0]):
# Ignoring port spec + following
return False
if matchEnds(L,"{","}"):
# Record
return False
if L[0] == "@":
return False
if L[0] == "#":
return False
return True
def parseLabel( strng ):
global DEBUGMODE
#print "*" * 40
#print "Original: ", strng
# First, some cleanup for displaying
cs = strng.replace(" "," ")
cs = cs.replace(" "," ")
cs = cs.replace(" "," ")
if DEBUGMODE:
s = " Parsing: %s\n" % (cs)
appendLog(s)
pp = pprint.PrettyPrinter(2)
try:
bnf = label_BNF()
tokens = bnf.parseString( strng ).asList()
if DEBUGMODE:
s = " as: %s\n" % (tokens)
appendLog(s)
except ParseException as err:
s = str(err.line) + "\n"
s += " "*(err.column-1) + "^" + "\n"
s += str(err) + "\n"
appendLog(s)
raise
#print "New : ", render(tokens)
#print "Ports : ", ports(tokens)
#print "*" * 40
return tokens
def execDot(args,raiseErrors=False):
"""
Invoke the real dot program
Note that args should be a list.
"""
import subprocess
cmd = "dot"
l = [cmd] + args
s = " ".join(l)
appendLog("Executing command: %s\n" % s)
if raiseErrors:
retcode = subprocess.check_call([cmd] + args)
else:
retcode = subprocess.call([cmd] + args)
sys.exit(retcode)
def findArgs(infile=None):
"""
Reconstruct args list from the program, but exclude the input file
"""
args = []
for x in sys.argv[1:]:
if (infile is None) or (x != infile):
args.append(x)
appendLog(" Using arguments: %s\n" % (str(args)))
return args
def appendLog(l):
global DEBUGMODE
if DEBUGMODE:
fp = open("/tmp/tamarin-cleandot.log",'a')
fp.write(l)
fp.close()
def findInputFile():
appendLog("Scanning for input file in: "+ str(sys.argv[1:])+ "\n")
# Currently, the Tamarin implementation is such that the filename is always the last argument.
# This may change in the future, so a more robust parsing is maybe in order.
infile = sys.argv[-1]
appendLog("Using input file: %s\n" % str(infile))
return infile
def stripQuotes(s):
"""
Strip single or double quotes
"""
if len(s) > 0:
if s[0] == s[-1] and s[0] in "'\"":
return s[1:-1]
return s
def recordToList(s,start=0):
"""
Consider s as an html-formatted record type string.
Use brackets etc. to convert to "fliplist"
Returns (fliplist,index) to just after the end of the parsed string
"""
fl = []
i = start
while i < len(s):
if s[i] == "\\":
# Simply skip the escaped characters
i += 2
elif s[i] == "{":
(fl2,i) = recordToList(s,i+1)
fl.append(["<recordflip>"] + fl2)
if i >= len(s):
raise ValueError("Cannot parse record node (missing closing parenthesis? ) [%s]" % s)
if s[i] != "}":
raise ValueError("Cannot parse record node (missing closing parenthesis? ) [%s]" % s)
i += 1
start = i
elif s[i] == "|":
part = s[start:i].strip()
if len(part) > 0:
fl.append(part)
i += 1
start = i
elif s[i] == "}":
break
else:
i += 1
part = s[start:i].strip()
if len(part) > 0:
fl.append(part)
return (fl, i)
def listToRecord(fl):
if isinstance(fl,str):
return fl
left = ""
right = ""
if fl[0] == "<recordflip>":
fl = fl[1:]
left = "{"
right = "}"
inner = "|".join([listToRecord(x) for x in fl])
return "%s%s%s" % (left,inner,right)
def getSubfield(s,location):
"""
Consider s as an html-formatted record type string.
Use brackets etc. to locate the required subfield.
"""
spec = "{}|"
horizontal = True
depth = 0
loc = []
count = 1
i = 0
while i < len(s):
if s[i] == "\\":
# Simply skip the escaped characters
i += 2
elif s[i] == "{":
horizontal = not(horizontal)
loc.append(count)
count = 1
depth += 1
i += 1
elif s[i] == "}":
horizontal = not(horizontal)
depth -= 1
count = loc.pop(-1)
i += 1
elif s[i] == "|":
count += 1
i += 1
else:
j = i
while j < len(s):
if s[j] in spec:
break
j += 1
if location == loc:
return s[i:j]
i = j
return None
def getRuleName(N):
"""
Try to reconstruct the rule name or None.
Tricky business.
"""
if N is None:
return None
sh = N.get("shape")
if sh is None:
return None
if not ("record" in sh):
return None
label = N.get("label")
try:
ruleField = getSubfield(label,[1,2])
i = ruleField.index(":")
j = ruleField.index("[",i)
return ruleField[i+1:j].strip()
except:
pass
return None
def getNodePrefix(N):
"""
Get node prefix up to final digit sequence or None from a Node
"""
fullname = getRuleName(N)
if fullname is None:
return None
#print "@@@%s@@@" % fullname
i = len(fullname)
c = 0
while i > 0:
if fullname[i-1].isdigit():
c += 1
i -= 1
else:
break
if c > 0:
# Prefix must be at least 1 character
return fullname[:i]
else:
return None
def incomingEdges(G,N):
"""
Collect incoming edges of node N
"""
l = G.get_edge_list()
res = []
n = N.get_name()
for e in l:
if noPort(e.get_destination()) == n:
res.append(e)
return res
def outgoingEdges(G,N):
"""
Collect outgoing edges of node N
"""
l = G.get_edge_list()
res = []
n = N.get_name()
for e in l:
if noPort(e.get_source()) == n:
res.append(e)
return res
def areConnected(G,src,dst):
"""
src and dst are node names
return True if they are connected by an edge
"""
l = G.get_edge_list()
for e in l:
if e.get_source() == src and e.get_destination() == dst:
return True
return False
def del_node(G, name, index=None):
return G.del_node(name,index=index)
"""Delete a node from the graph.
Given a node's name all node(s) with that same name
will be deleted if 'index' is not specified or set
to None.
If there are several nodes with that same name and
'index' is given, only the node in that position
will be deleted.
'index' should be an integer specifying the position
of the node to delete. If index is larger than the
number of nodes with that name, no action is taken.
If nodes are deleted it returns True. If no action
is taken it returns False.
"""
if isinstance(name, Node):
name = name.get_name()
if G.obj_dict['nodes'].has_key(name):
if index is not None and index < len(G.obj_dict['nodes'][name]):
del G.obj_dict['nodes'][name][index]
return True
else:
del G.obj_dict['nodes'][name]
return True
return False
def del_edge(G, src_or_list, dst=None, index=None):
return G.del_edge(src_or_list,dst=dst,index=index)
"""Delete an edge from the graph.
Given an edge's (source, destination) node names all
matching edges(s) will be deleted if 'index' is not
specified or set to None.
If there are several matching edges and 'index' is
given, only the edge in that position will be deleted.
'index' should be an integer specifying the position
of the edge to delete. If index is larger than the
number of matching edges, no action is taken.
If edges are deleted it returns True. If no action
is taken it returns False.
"""
if isinstance( src_or_list, (list, tuple)):
if dst is not None and isinstance(dst, (int, long)):
index = dst
src, dst = src_or_list
else:
src, dst = src_or_list, dst
if isinstance(src, Node):
src = src.get_name()
if isinstance(dst, Node):
dst = dst.get_name()
if G.obj_dict['edges'].has_key( (src, dst) ):
if index is not None and index < len(G.obj_dict['edges'][(src, dst)]):
del G.obj_dict['edges'][(src, dst)][index]
return True
else:
del G.obj_dict['edges'][(src, dst)]
return True
return False
def clear_node(G,N):
"""
Remove node N and its connected edges from the graph
"""
print ("Clearing node ", N.get_name())
for OE in incomingEdges(G,N):
del_edge(G,OE.get_source(),OE.get_destination())
for OE in outgoingEdges(G,N):
del_edge(G,OE.get_source(),OE.get_destination())
del_node(G,N)
def removeNode(G,N):
"""
Remove node N from the graph.
Keep edge structure intact:
We hook up incoming and outgoing edges, replacing them by the product.
(flow left-to-right)
a d a a
\ / \ \
c ==> d e
/ \ / /
b e b b
Of course, we should only add edges that don't exist yet.