-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathringo.py
1948 lines (1660 loc) · 73.7 KB
/
ringo.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
import snap
import time
import inspect
import hashlib
import re
import socket
import json
import types
def inspectStack(ringo, stackFrameOffset):
locals = inspect.getouterframes(inspect.currentframe())[1+stackFrameOffset][0].f_locals
ringo_locals = dict((var, locals[var]) for var in locals if isinstance(locals[var], RingoObject))
for var in locals:
if isinstance(locals[var], tuple):
all_ringo = True
for tuple_elem in locals[var]:
if not isinstance(tuple_elem, RingoObject):
all_ringo = False
if all_ringo == True: ringo_locals[var] = locals[var]
ringo._Ringo__UpdateNaming(ringo_locals)
"""
Decorator used to automate the registration of TTable operations
"""
def registerOp(opName, trackOp = True, stackFrameOffset = 0):
def decorator(func):
def wrapper(*args, **kwargs):
ringo = args[0]
if isinstance(ringo, RingoObject):
ringo = ringo.Ringo
inspectStack(ringo, stackFrameOffset+1)
unpack_args = [arg.Id if isinstance(arg, RingoObject) else arg for arg in args]
start_time = time.time()
RetVal = func(*unpack_args, **kwargs)
end_time = time.time()
if trackOp:
ringo._Ringo__UpdateOperation(opName, RetVal, [args[1:], kwargs], end_time - start_time, args[0])
return RetVal
return wrapper
return decorator
class RingoObject(object):
def __init__(self, Id, Ringo):
self.Id = Id
self.Ringo = Ringo
def __eq__(self, other):
return self.Id == other.Id
def __hash__(self):
return hash(self.Id)
def __iter__(self):
Obj = self.__GetSnapObj()
return Obj.__iter__()
def __contains__(self, elem):
Obj = self.__GetSnapObj()
return Obj.__contains__(elem)
@registerOp('__getitem__', stackFrameOffset=1)
def __getitem__(self, key):
Obj = self.__GetSnapObj()
return Obj.__getitem__(key)
@registerOp('__setitem__', stackFrameOffset=1)
def __setitem__(self, key, item):
Obj = self.__GetSnapObj()
Obj.__setitem__(key, item)
def __len__(self):
Obj = self.__GetSnapObj()
return len(Obj)
def __getattr__(self, name):
Obj = self.__GetSnapObj()
if hasattr(self.Ringo, name):
inspectStack(self.Ringo, 1)
def wrapper(*args, **kwargs):
return getattr(self.Ringo, name)(self, *args, **kwargs)
return wrapper
if hasattr(Obj, name):
def wrapper(*args, **kwargs):
def func(self, *args, **kwargs):
return getattr(Obj, name)(*args, **kwargs)
return registerOp(name, stackFrameOffset=1)(func)(self, *args, **kwargs)
return wrapper
raise AttributeError
def __GetSnapObj(self):
return self.Ringo.Objects[self.Id]
# A utility function to determine if two names are an alias for the same table attribute
def colNamesEqual(name1, name2):
return snap.TTable.NormalizeColName(name1) == snap.TTable.NormalizeColName(name2)
class Ringo(object):
def __init__(self, parallel = True):
# mapping between object ids and snap objects
self.Objects = {}
# mapping between ringo objects and their user-given names
self.ObjectNames = {}
# mapping between an id and a record
# an operation record has the form: <id (string), type (string), result id, argument list (as used in python interface; ringo objects are used for table arguments), time stamp, object on which operation was called>
self.Operations = {}
# mapping between a object (id) and the sequence of operation ids that led to it
self.Lineage = {}
# mapping between a object (id) and the list of object ids it depends on
self.Dependencies = {}
# mapping between object ids and their metadata (dict)
self.Metadata = {}
self.Context = snap.TTableContext()
# if parallel:
# snap.TTable.SetMP(1)
# else:
# snap.TTable.SetMP(0)
def __getattr__(self, name):
match = re.match('Construct(\w*)', name)
if match is not None and match.group(1) in dir(snap):
ObjName = match.group(1)
def func(self, *args, **kwargs):
Obj = getattr(snap, ObjName)(*args, **kwargs)
Id = self.__UpdateObjects(Obj, [])
return RingoObject(Id, self)
def wrapper(*args, **kwargs):
return registerOp(name)(func)(self, *args, **kwargs)
return wrapper
if hasattr(snap, name) and type(getattr(snap,name)) == types.TypeType:
Obj = getattr(snap, name)
Id = self.__UpdateObjects(Obj, [])
Ret = RingoObject(Id, self)
self.__UpdateNaming({self.__GetName(self) + '.' + name: Ret})
return RingoObject(Id, self)
#For enums
if hasattr(snap, name) and type(getattr(snap, name)) == types.IntType:
return getattr(snap, name)
raise AttributeError
def IsParallel(self):
return (snap.TTable.GetMP() > 0)
# Use case:
# S = [('name','string'), ('age','int'), ('weight','float')]
# MyTable = ringo.LoadTableTSV(S, 'table.tsv')
# MyTable = ringo.LoadTableTSV(S, 'table.tsv', [0,1]) if we want to load only columns 'name' and 'age'
@registerOp('LoadTableTSV')
def LoadTableTSV(self, Schema, InFnm, SeparatorChar = '\t', HasTitleLine = False):
# prepare parameters to call TTable::LoadSS
S = snap.Schema()
for Col in Schema:
if Col[1] == 'int':
S.Add(snap.TStrTAttrPr(Col[0], snap.atInt))
elif Col[1] == 'float':
S.Add(snap.TStrTAttrPr(Col[0], snap.atFlt))
elif Col[1] == 'string':
S.Add(snap.TStrTAttrPr(Col[0], snap.atStr))
else:
print "Illegal type %s for attribute %s" % (Col[1], Col[0])
# Load input and create new TTable object
TableId = self.__GetId(self.Objects)
T = snap.TTable.LoadSS(S, InFnm, self.Context, SeparatorChar, snap.TBool(HasTitleLine))
self.__UpdateObjects(T, [], TableId)
return RingoObject(TableId, self)
# USE CASE 2 OK
@registerOp('SaveTableTSV')
def SaveTableTSV(self, TableId, OutFnm):
T = self.Objects[TableId]
T.SaveSS(OutFnm)
return RingoObject(TableId, self)
@registerOp('Load', False)
def Load(self, InFnm):
def ConvertJSON(JSON):
if isinstance(JSON, dict):
return dict([(ConvertJSON(key), ConvertJSON(JSON[key])) for key in JSON])
elif isinstance(JSON, list):
return [ConvertJSON(value) for value in JSON]
elif isinstance(JSON, unicode):
return JSON.encode('UTF-8')
else:
return JSON
def UnpackObject(self, Packed):
ObjectId = Packed['Id']
self.ObjectNames[RingoObject(ObjectId, self)] = Packed['Name']
self.Lineage[ObjectId] = Packed['Lineage']
self.Dependencies[ObjectId] = Packed['Dependencies']
self.Metadata[ObjectId] = Packed['Metadata']
def ObjectDecoder(Object):
if 'RingoObject' in Object:
return RingoObject(Object['Id'], self)
elif 'Set' in Object:
return set(Object['Content'])
elif 'Ringo' in Object:
return self
else:
return Object
with open(InFnm+'.json') as inp:
JSON = ConvertJSON(json.load(inp, object_hook = ObjectDecoder))
for OpId in JSON['Operations']:
self.Operations[OpId] = JSON['Operations'][OpId]
for ObjectId in JSON['Objects']:
UnpackObject(self, JSON['Objects'][ObjectId])
SIn = snap.TFIn(InFnm+'.bin')
if JSON['Type'] == 'TTable':
Obj = getattr(snap, JSON['Type']).Load(SIn, self.Context)
else:
Obj = getattr(snap, JSON['Type']).Load(SIn)
ObjId = JSON['ID']
self.__UpdateObjects(Obj, self.Lineage[ObjId], ObjId)
return RingoObject(ObjId, self)
@registerOp('Save', False)
def Save(self, ObjectId, OutFnm):
def PackObject(self, ObjectId):
Pack = {}
Pack['Id'] = ObjectId
Pack['Name'] = self.ObjectNames[RingoObject(ObjectId, self)]
Pack['Lineage'] = self.Lineage[ObjectId]
Pack['Dependencies'] = self.Dependencies[ObjectId]
Pack['Metadata'] = self.Metadata[ObjectId]
return Pack
def AssembleObject(self, ObjectId):
Assembled = {ObjectId: PackObject(self,ObjectId)}
for Parent in self.Dependencies[ObjectId]:
Assembled.update(AssembleObject(self, Parent))
return Assembled
def ObjectEncoder(Object):
if isinstance(Object, RingoObject):
return {'RingoObject':True, 'Id':Object.Id}
elif isinstance(Object, dict):
return Object
elif isinstance(Object, set):
return {'Set':True, 'Content':list(Object)}
elif isinstance(Object, Ringo):
return {'Ringo':True}
raise TypeError(type(Object))
Object = self.Objects[ObjectId]
JSON = {}
JSON['Operations'] = dict([(Id, self.Operations[Id]) for Id in self.Lineage[ObjectId]])
JSON['Objects'] = AssembleObject(self, ObjectId)
JSON['ID'] = ObjectId
TypeMatch = re.match("<class 'snap.(\w*)'>", str(type(Object)))
if TypeMatch is None:
raise TypeError('Given object is not a snap object')
Type = TypeMatch.group(1)
if Type[0] == 'P':
Type = 'T' + Type[1:]
JSON['Type'] = Type
with open(OutFnm+'.json', 'w') as out:
json.dump(JSON, out, default = ObjectEncoder)
SOut = snap.TFOut(OutFnm+'.bin')
Object.Save(SOut)
@registerOp('Import', False)
def Import(self, Object):
start_time = time.time()
ObjId = self.__UpdateObjects(Object, [])
Ret = RingoObject(ObjId, self)
end_time = time.time()
InFnm = 'Import_' + ObjId
self.__UpdateOperation('Load', Ret, [[InFnm], {}], end_time - start_time, self)
self.Save(ObjId, InFnm)
return Ret
@registerOp('Export', False)
def Export(self, ObjId):
return self.Objects[ObjId]
@registerOp('TableFromHashMap')
def TableFromHashMap(self, HashId, ColName1, ColName2, TableIsStrKeys = False):
HashMap = self.Objects[HashId]
TableId = self.__GetId(self.Objects)
T = snap.TTable.TableFromHashMap(HashMap, ColName1, ColName2, self.Context, snap.TBool(TableIsStrKeys))
self.__UpdateObjects(T, self.Lineage[HashId], TableId)
return RingoObject(TableId, self)
@registerOp('ShowMetadata', False)
def ShowMetadata(self, ObjectId):
template = '{0: <35}{1}'
print template.format('Name', self.ObjectNames[RingoObject(ObjectId, self)])
for Label, Info in self.Metadata[ObjectId]:
print template.format(Label, re.sub('<#(\d+)>',
lambda m: self.__GetName(RingoObject(int(m.group(1)))), str(Info)))
@registerOp('ShowDependencies', False)
def ShowDependencies(self, ObjectId, HideMiddle = False):
def Outputter(self, ObjectId, TabCount):
print ' '*TabCount + self.__GetName(RingoObject(ObjectId, self))
for Parent in self.Dependencies[ObjectId]:
Outputter(self, Parent, TabCount+1)
print 'Dependency Tree'
if HideMiddle:
Ancestors = set()
Parents = set()
Parents.add(ObjectId)
while len(Parents) > 0:
Curr = Parents.pop()
if len(self.Dependencies[Curr]) == 0:
Ancestors.add(Curr)
for Obj in self.Dependencies[Curr]:
Parents.add(Obj)
print self.__GetName(RingoObject(ObjectId, self))
for Obj in Ancestors:
if Obj != ObjectId:
print ' '+self.__GetName(RingoObject(Obj, self))
else:
Outputter(self, ObjectId, 0)
@registerOp('ShowProvenance', False)
def ShowProvenance(self, ObjectId):
print 'Provenance Script:'
print '------------------'
print self.__GetProvenance(ObjectId)
@registerOp('GetSchema', False)
def GetSchema(self, TableId):
T = self.Objects[TableId]
Schema = T.GetSchema()
S = []
for Col in Schema:
ColName = Col.Val1.CStr()
ColType = Col.Val2
S.append((ColName, ColType))
return S
@registerOp('GetRows', False)
def Rows(self, TableId, MaxRows = None):
T = self.Objects[TableId]
S = T.GetSchema()
Names = []
Types = []
for i, attr in enumerate(S):
Names.append(attr.GetVal1())
Types.append(attr.GetVal2())
RI = T.BegRI()
Cnt = 0
while RI < T.EndRI() and (MaxRows is None or Cnt < MaxRows):
Elements = []
for c,t in zip(Names,Types):
if t == snap.atInt:
Elements.append(str(RI.GetIntAttr(c)))
elif t == snap.atFlt:
Elements.append(RI.GetFltAttr(c))
elif t == snap.atStr:
Elements.append(RI.GetStrAttr(c))
else:
raise NotImplementedError("Unsupported column type")
yield Elements
RI.Next()
Cnt += 1
@registerOp('DumpTableContent', False)
def DumpTableContent(self, TableId, MaxRows = None):
T = self.Objects[TableId]
ColSpace = 25
S = T.GetSchema()
Template = ""
Line = ""
Names = []
Types = []
for i, attr in enumerate(S):
Template += "{%d: <%d}" % (i, ColSpace)
Names.append(attr.GetVal1())
Types.append(attr.GetVal2())
Line += "-" * ColSpace
print Template.format(*Names)
print Line
for row in self.Rows(TableId, MaxRows):
print Template.format(*row)
# UNTESTED
@registerOp('AddLabel')
def AddLabel(self, TableId, Attr, Label):
T = self.Objects[TableId]
T.AddLabel(Attr, Label)
return RingoObject(TableId, self)
# UNTESTED
@registerOp('Unique')
def Unique(self, TableId, GroupByAttr, InPlace = True):
if not InPlace:
TableId = self.__CopyTable(TableId)
T = self.Objects[TableId]
T.Unique(GroupByAttr)
return RingoObject(TableId, self)
# UNTESTED
@registerOp('Unique')
def Unique(self, TableId, GroupByAttrs, Ordered, InPlace = True):
Attrs = TStrV()
for Attr in GroupByAttr:
Attrs.Add(Attr)
if not InPlace:
TableId = self.__CopyTable(TableId)
T = self.Objects[TableId]
T.Unique(Attrs, Ordered)
return RingoObject(TableId, self)
# USE CASE 2 OK
@registerOp('Select')
def Select(self, TableId, Predicate, InPlace = True):
def GetOp(OpString):
try:
Op = {
'=': snap.EQ,
'!=': snap.NEQ,
'<': snap.LT,
'<=': snap.LTE,
'>': snap.GT,
'>=': snap.GTE,
'in': snap.SUBSTR,
'contains': snap.SUPERSTR
}[OpString]
except KeyError:
raise NotImplementedError("Operator %s undefined" % OpString)
return Op
def GetColType(Schema, ColName):
for Col in Schema:
if colNamesEqual(Col.Val1.CStr(), ColName):
return Col.Val2
raise ValueError("No column with name %s found" % ColName)
def IsConstant(Arg):
if '0' <= Arg[0] and Arg[0] <= '9':
return True
return Arg[0] == "'" or Arg[0] == '"'
def Merge(Expression):
while '(' in Expression:
left = Expression.index('(')
right = left+1
count = 0
while count > 0 or Expression[right] != ')':
if Expression[right] == ')':
count += 1
elif Expression[right] == '(':
count -= 1
right += 1
Expression[left:right+1] = Merge(Expression[left+1:right])
while 'and' in Expression:
op = Expression.index('and')
Merged = snap.TPredicateNode(snap.AND)
Merged.addLeftChild(Expression[op-1])
Merged.addRightChild(Expression[op+1])
Expression[op-1:op+2] = snap.TPredicate(Merged)
while 'or' in Expression:
op = Expression.index('or')
Merged = snap.TPredicateNode(snap.OR)
Merged.addLeftChild(Expression[op-1])
Merged.addRightChild(Expression[op+1])
Expression[op-1:op+2] = snap.TPredicate(Merged)
if len(Expression) > 1:
raise ValueError("Invalid expression - too many operands")
return Expression[0]
def ConstructPredicate(elements, Schema):
Expression = []
i = 0
NumParens = 0
while i < len(elements):
if i > 0:
if elements[i].lower() == 'and':
Expression.append('and')
elif elements[i].lower() == 'or':
Expression.append('or')
else:
raise ValueError("Improper conjuction %s: only AND/OR supported" % elements[i])
i += 1
while elements[i] == '(':
Expression.append('(')
NumParens += 1
i += 1
Left = elements[i]
ColType = GetColType(Schema, Left)
Op = GetOp(elements[i+1])
Right = elements[i+2]
if IsConstant(Right):
Args = ()
if ColType == snap.atInt:
Args = (int(Right), 0, "")
elif ColType == snap.atFlt:
Args = (0, float(Right), "")
elif ColType == snap.atStr:
Args = (0, 0, Right[1:-1])
Expression.append(snap.TAtomicPredicate(ColType, snap.TBool(True), Op, Left, "",
*Args))
else:
Expression.append(snap.TAtomicPredicate(ColType, snap.TBool(False), Op, Left, Right))
i += 2
while element[i] == ')':
Expression.append(')')
NumParens -= 1
i += 1
if NumParens < 0:
raise ValueError("Unbalanced parentheses found")
if NumParens !=0:
raise ValueError("Unbalanced parentheses found")
return Merge(Expression)
if not InPlace:
TableId = self.__CopyTable(TableId)
# Parse predicate
elements = Predicate.split()
special = ['\(', '\)', '=', '!', '<', '>']
pat = '((?:%s)*)' % '|'.join(special)
elements = [j for i in map(lambda s: re.split(pat, s), elements) for j in i if len(j) > 0]
T = self.Objects[TableId]
Schema = T.GetSchema()
if (len(elements) == 3):
Op = GetOp(elements[1])
ColType = GetColType(Schema, elements[0])
if IsConstant(elements[2]):
if ColType == snap.atInt:
T.SelectAtomicIntConst(elements[0], int(elements[2]), Op)
elif ColType == snap.atFlt:
T.SelectAtomicFltConst(elements[0], float(elements[2]), Op)
elif ColType == snap.atStr:
T.SelectAtomicStrConst(elements[0], str(elements[2][1:-1]), Op)
else:
T.SelectAtomic(elements[0], elements[2], Op)
else:
T.Select(ConstructPredicate(elements, Schema))
return RingoObject(TableId, self)
# USE CASE 8 OK
@registerOp('Project')
def Project(self, TableId, Columns, InPlace = True):
PrepCols = snap.TStrV()
for Col in Columns:
PrepCols.Add(Col)
if not InPlace:
TableId = self.__CopyTable(TableId)
T = self.Objects[TableId]
T.ProjectInPlace(PrepCols)
return RingoObject(TableId, self)
# UNTESTED
@registerOp('Join')
def Join(self, LeftTableId, RightTableId, LeftAttr, RightAttr):
LeftT = self.Objects[LeftTableId]
RightT = self.Objects[RightTableId]
JoinT = LeftT.Join(LeftAttr, RightT, RightAttr)
JoinTId = self.__UpdateObjects(JoinT, self.Lineage[LeftTableId] + self.Lineage[RightTableId])
return RingoObject(JoinTId, self)
@registerOp('Union')
def Union(self, LeftTableId, RightTableId):
LeftT = self.Objects[LeftTableId]
RightT = self.Objects[RightTableId]
UnionT = LeftT.Union(RightT)
UnionTId = self.__UpdateObjects(UnionT, self.Lineage[LeftTableId] + self.Lineage[RightTableId])
return RingoObject(UnionTId, self)
@registerOp('UnionAll')
def UnionAll(self, LeftTableId, RightTableId):
LeftT = self.Objects[LeftTableId]
RightT = self.Objects[RightTableId]
UnionT = LeftT.UnionAll(RightT)
UnionTId = self.__UpdateObjects(UnionT, self.Lineage[LeftTableId] + self.Lineage[RightTableId])
return RingoObject(UnionTId, self)
@registerOp('Rename')
def Rename(self, TableId, Column, NewLabel):
T = self.Objects[TableId]
T.Rename(Column, NewLabel)
return RingoObject(TableId, self)
# USE CASE 1 OK
@registerOp('SelfJoin')
def SelfJoin(self, TableId, Attr):
T = self.Objects[TableId]
JoinT = T.SelfJoin(Attr)
JoinTId = self.__UpdateObjects(JoinT, self.Lineage[TableId])
return RingoObject(JoinTId, self)
@registerOp('Order')
def Order(self, TableId, Attrs, Asc = False, InPlace = True):
if not InPlace:
TableId = self.__CopyTable(TableId)
T = self.Objects[TableId]
V = snap.TStrV()
for attr in Attrs:
V.Add(attr)
T.Order(V, "", snap.TBool(False), snap.TBool(Asc))
return RingoObject(TableId, self)
@registerOp('ColMax')
def ColMax(self, TableId, Attr1, Attr2, ResultAttrName):
T = self.Objects[TableId]
T.ColMax(Attr1, Attr2, ResultAttrName)
return RingoObject(TableId, self)
@registerOp('ColMin')
def ColMin(self, TableId, Attr1, Attr2, ResultAttrName):
T = self.Objects[TableId]
T.ColMin(Attr1, Attr2, ResultAttrName)
return RingoObject(TableId, self)
# USE CASE 1 OK
@registerOp('ToGraph')
def ToGraph(self, GraphTypeId, TableId, SrcCol, DstCol, Directed = True):
GraphType = self.Objects[GraphTypeId]
T = self.Objects[TableId]
if hasattr(snap, 'ToGraphMP') and GraphType is snap.PNGraph:
G = snap.ToGraphMP(snap.PNGraphMP, T, SrcCol, DstCol)
else:
G = snap.ToGraph(GraphType, T, SrcCol, DstCol, snap.aaFirst)
GraphId = self.__UpdateObjects(G, self.Lineage[TableId])
return RingoObject(GraphId, self)
@registerOp('GetHits')
def GetHits(self, GraphId):
G = self.Objects[GraphId]
HT1 = snap.TIntFltH()
HT2 = snap.TIntFltH()
snap.GetHits(G, HT1, HT2)
HT1Id = self.__UpdateObjects(HT1, self.Lineage[GraphId])
HT2Id = self.__UpdateObjects(HT2, self.Lineage[GraphId])
RetVal = (RingoObject(HT1Id, self), RingoObject(HT2Id, self))
return RetVal
# UNTESTED
def GetOpType(self, OpId):
return Operations[OpId][1]
# USE CASE 2 OK
@registerOp('PageRank')
def PageRank(self, GraphId, AddToNetwork = False, C = 0.85, Eps = 1e-4, MaxIter = 100):
if AddToNetwork:
raise NotImplementedError()
Graph = self.Objects[GraphId]
HT = snap.TIntFltH()
# Which version of PageRank is called ?
if hasattr(snap, 'GetPageRankMP1'):
snap.GetPageRankMP1(Graph, HT, C, Eps, MaxIter)
else:
snap.GetPageRank(Graph, HT, C, Eps, MaxIter)
TableId = self.__GetId(self.Objects)
HTId = self.__UpdateObjects(HT, self.Lineage[GraphId])
return RingoObject(HTId, self)
@registerOp('GetEdgeTable')
def GetEdgeTable(self, GraphId):
Graph = self.Objects[GraphId]
Table = snap.TTable.GetEdgeTable(Graph, self.Context)
TableId = self.__UpdateObjects(Table, self.Lineage[GraphId])
return RingoObject(TableId, self)
@registerOp('GenerateProvenance', False)
def GenerateProvenance(self, ObjectId, OutFnm):
with open(OutFnm, 'w') as file:
file.write(self.__GetProvenance(ObjectId))
def __GetProvenance(self, ObjectId):
Preamble = ['import sys', 'import ringo', '']
Lines = []
Files = []
SchemaMap = {} #dictionary from ringo objects to a dictionary from names to variable names
for OpId in self.Lineage[ObjectId]:
Op = self.Operations[OpId]
SpecialArg = -1
if Op[1] == 'LoadTableTSV' or Op[1] == 'SaveTableTSV' or Op[1] == 'Save':
SpecialArg = 1
elif Op[1] == 'Load':
SpecialArg = 0
FuncArgs = []
for Arg in Op[3][0]:
if SpecialArg == 0:
FuncArgs.append('filename'+str(len(Files)))
Files.append(self.__GetName(Arg))
else:
FuncArgs.append(self.__GetName(Arg))
SpecialArg -= 1
for Arg in Op[3][1]:
FuncArgs.append(str(Arg)+'='+self.__GetName(Op[3][1][Arg]))
RetName = self.__GetName(Op[2])
Callee = Op[6]
if isinstance(Callee, RingoObject):
Callee = self.__GetName(Callee)
else:
Callee = self.__GetName(self)
FuncCall = '%s.%s(%s)' % (Callee, Op[1], str.join(', ', FuncArgs))
if RetName != str(Op[2]):
FuncCall = RetName+' = '+FuncCall
Lines.append(FuncCall)
FinalName = self.__GetName(RingoObject(ObjectId, self))
Lines.append('return '+FinalName)
Script = str.join('\n', Preamble) + '\n\ndef generate(' + self.__GetName(self)
for x in xrange(len(Files)):
Script += ', filename'+str(x)
Script += '):\n'
for Line in Lines:
Script += ' '+Line+'\n'
Script += '\n%s = ringo.Ringo()\n' % self.__GetName(self)
Script += 'files = [%s]\n' % str.join(', ', Files)
Script += 'for i in xrange(min(len(files), len(sys.argv)-1)):\n'
Script += ' files[i] = sys.argv[i+1]\n'
Script += FinalName + ' = generate(%s, *files)\n' % self.__GetName(self)
return Script
def __GetName(self, Value):
if isinstance(Value, basestring):
return "'"+Value+"'"
if isinstance(Value, Ringo):
return "engine"
try:
if Value in self.ObjectNames:
return self.ObjectNames[Value]
elif isinstance(Value, RingoObject):
return '<#%d>' % Value.Id
except:
pass
if isinstance(Value, tuple):
Ret = '('
for SubVal in Value:
SubName = self.__GetName(SubVal)
if SubName == str(SubVal):
SubName = '_'
Ret += SubName+', '
Ret = Ret[:-2]+')'
return str(Value)
def __CopyTable(self, TableId):
T = snap.TTable.New(self.Objects[TableId])
CopyTableId = self.__UpdateObjects(T, self.Lineage[TableId])
return CopyTableId
def __UpdateObjects(self, Object, Lineage, Id = None):
if Id is None:
Id = self.__GetId(self.Objects)
self.Objects[Id] = Object
self.Lineage[Id] = sorted(list(set(Lineage)))
return Id
def __UpdateOperation(self, OpType, RetVal, Args, Time, Callee):
OpId = self.__AddOperation(OpType, RetVal, Args, Time, Callee)
if not isinstance(RetVal, tuple):
RetVal = [RetVal]
ObjectIds = [Object.Id for Object in RetVal if isinstance(Object, RingoObject)]
if isinstance(Callee, RingoObject):
ObjectIds.append(Callee.Id)
for ObjectId in ObjectIds:
if ObjectId not in self.Lineage:
self.Lineage[ObjectId] = [OpId]
else:
self.Lineage[ObjectId] += [OpId]
self.__UpdateMetadata(OpId)
def __UpdateMetadata(self, OpId):
Op = self.Operations[OpId]
Objects = Op[2]
Objects = [Obj for Obj in Objects] if isinstance(Objects, tuple) else [Objects]
Objects.append(Op[5])
for Object in Objects:
if not isinstance(Object, RingoObject):
continue
Metadata = []
self.__AddTypeSpecificInfo(self.Objects[Object.Id], Metadata)
Datasets = set()
FuncArgs = []
Dependencies = set()
for Arg in Op[3][0]:
FuncArgs.append(self.__GetName(Arg))
if isinstance(Arg, RingoObject) and Arg.Id in self.Metadata:
Datasets.update(dict(self.Metadata[Arg.Id])['Datasets'].split(', '))
Dependencies.add(Arg.Id)
for Arg in Op[3][1]:
Obj = Op[3][1][Arg]
FuncArgs.append(str(Arg)+'='+self.__GetName(Obj))
if isinstance(Obj, RingoObject) and Obj.Id in self.Metadata:
Datasets.update(dict(self.Metadata[Obj.Id])['Datasets'].split(', '))
Dependencies.add(Arg.Id)
if Op[1] == 'LoadTableTSV':
Datasets.add(Op[3][0][1])
MethodCall = Op[1]
if isinstance(Op[6], RingoObject):
MethodCall = self.__GetName(Op[6]) + MethodCall
LastCommand = '%s = %s(%s)' % (self.__GetName(Op[2]), MethodCall, str.join(', ', FuncArgs))
if Object.Id in Dependencies: Dependencies.remove(Object.Id)
Metadata.append(('Datasets', str.join(', ', Datasets)))
if Object.Id in self.Metadata:
OldMeta = dict(self.Metadata[Object.Id])
Metadata.append(('Inputs', OldMeta['Inputs']))
Metadata.append(('Operation', OldMeta['Operation']))
Metadata.append(('Command', OldMeta['Command']))
Metadata.append(('Last Modification', LastCommand))
self.Dependencies[Object.Id] |= Dependencies
else:
Metadata.append(('Inputs', str.join(', ', FuncArgs)))
Metadata.append(('Operation', Op[1]))
Metadata.append(('Command', LastCommand))
self.Dependencies[Object.Id] = Dependencies
Metadata.append(('Last Edited', Op[4]))
Metadata.append(('Last Operation Time', '%.1fs' % Op[5]))
TotalTime = 0
for PrevOpId in self.Lineage[Object.Id]:
TotalTime += self.Operations[PrevOpId][5]
Metadata.append(('Total Creation Time', '%.1fs' % TotalTime))
Provenance = self.__GetProvenance(Object.Id)
Metadata.append(('Provenance Script', '%d lines, %d characters'
% (len(str.splitlines(Provenance)), len(Provenance))))
self.Metadata[Object.Id] = Metadata
def __AddTypeSpecificInfo(self, Object, Metadata):
if isinstance(Object, snap.PTable):
Metadata.append(('Type', 'Table'))
Metadata.append(('Number of Rows', Object.GetNumValidRows()))
Schema = []
for attr in Object.GetSchema():
Schema.append(attr.GetVal1())
if attr.GetVal2() == snap.atInt:
Schema[-1] += ' (int)'
elif attr.GetVal2() == snap.atFlt:
Schema[-1] += ' (float)'
elif attr.GetVal2() == snap.atStr:
Schema[-1] += ' (string)'
Metadata.append(('Schema', Schema))
elif isinstance(Object, snap.PNEANet):
Metadata.append(('Type', 'Network'))
Metadata.append(('Number of Nodes', Object.GetNodes()))
Metadata.append(('Number of Edges', Object.GetEdges()))
elif isinstance(Object, snap.PUNGraph):
Metadata.append(('Type', 'Undirected Graph'))
Metadata.append(('Number of Nodes', Object.GetNodes()))
Metadata.append(('Number of Edges', Object.GetEdges()))
elif isinstance(Object, snap.PNGraph):
Metadata.append(('Type', 'Directed Graph'))
Metadata.append(('Number of Nodes', Object.GetNodes()))
Metadata.append(('Number of Edges', Object.GetEdges()))
elif isinstance(Object, snap.PNGraphMP):
Metadata.append(('Type', 'Parallel Directed Graph'))
Metadata.append(('Number of Nodes', Object.GetNodes()))
Metadata.append(('Number of Edges', Object.GetEdges()))
elif str(type(Object))[-3] == 'H':
Metadata.append(('Type', 'HashMap'))
Metadata.append(('Number of Elements', Object.Len()))
def __AddOperation(self, OpType, RetVal, Args, Time, Callee):
OpId = self.__GetId(self.Operations)
Op = (OpId, OpType, RetVal, Args, time.strftime("%a, %d %b %Y %H:%M:%S"), Time, Callee)
self.Operations[OpId] = Op
return OpId
def __UpdateNaming(self, Locals):
for Var in Locals:
Object = Locals[Var]
if Object not in self.ObjectNames:
self.ObjectNames[Object] = Var
if isinstance(Object, tuple):
for i in xrange(len(Object)):
self.ObjectNames[Object[i]] = '%s[%d]' %(Var, i)
def __GetId(self, Container):
Prefix = socket.gethostname()+'_'+time.strftime("%Y%m%d_%H%M%S")
Num = 0
while True:
Id = Prefix+'_'+str(Num)
if Id not in Container:
break
Num += 1
return Id
@registerOp('CntInDegNodes', False)
def CntInDegNodes(self, GraphId, NodeInDeg):
Graph = self.Objects[GraphId]
Count = snap.CntInDegNodes(Graph, NodeInDeg)
return Count
@registerOp('CntOutDegNodes', False)
def CntOutDegNodes(self, GraphId, NodeOutDeg):
Graph = self.Objects[GraphId]
Count = snap.CntOutDegNodes(Graph, NodeOutDeg)
return Count
@registerOp('CntDegNodes', False)
def CntDegNodes(self, GraphId, NodeDeg):
Graph = self.Objects[GraphId]
Count = snap.CntDegNodes(Graph, NodeDeg)
return Count
@registerOp('CntNonZNodes', False)
def CntNonZNodes(self, GraphId):
Graph = self.Objects[GraphId]
Count = snap.CntNonZNodes(Graph)
return Count
@registerOp('CntEdgesToSet', False)
def CntEdgesToSet(self, GraphId, NId, NodeSetId):
Graph = self.Objects[GraphId]
NodeSet = self.Objects[NodeSetId]
Count = snap.CntEdgesToSet(Graph, NId, NodeSet)
return Count
@registerOp('GetMxDegNId', False)
def GetMxDegNId(self, GraphId):
Graph = self.Objects[GraphId]
NId = snap.GetMxDegNId(Graph)
return NId
@registerOp('GetMxInDegNId', False)
def GetMxInDegNId(self, GraphId):
Graph = self.Objects[GraphId]
NId = snap.GetMxInDegNId(Graph)
return NId
@registerOp('GetMxOutDegNId', False)
def GetMxOutDegNId(self, GraphId):
Graph = self.Objects[GraphId]
NId = snap.GetMxOutDegNId(Graph)
return NId
@registerOp('GetInDegCnt')
def GetInDegCnt(self, GraphId):
Graph = self.Objects[GraphId]
DegToCntV = snap.TIntPrV()
snap.GetInDegCnt(Graph, DegToCntV)
DegToCntVId = self.__UpdateObjects(DegToCntV, self.Lineage[GraphId])
return RingoObject(DegToCntVId, self)
@registerOp('GetOutDegCnt')
def GetOutDegCnt(self, GraphId):