-
Notifications
You must be signed in to change notification settings - Fork 0
/
e3_command.py
1979 lines (1826 loc) · 86.7 KB
/
e3_command.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
'''
@author: Thomas
'''
from autologging import logged
from pinject import copy_args_to_public_fields
from subprocess import Popen, PIPE, call
import os
import shutil
from ruamel import yaml
import re
from collections import OrderedDict
import csv
from ruamel.yaml.scalarstring import SingleQuotedScalarString, DoubleQuotedScalarString
@logged
class Command(object):
@copy_args_to_public_fields
def __init__(self):
import e3_io
self.tapManager = e3_io.TapManager()
self.configManager = e3_io.ConfigManager()
import e3_io
self.graphCreator = e3_io.GraphCreator()
self.output = []
self.outputFiles = []
self.executeOutput = []
self.startTime = None
self.endTime = None
pass
def run(self):
self.__log.debug("run %s" % self.__class__.__name__)
def get_output(self):
return self.output
def get_execute_output(self):
return self.executeOutput
def get_output_files(self):
return self.outputFiles
@logged
class MiscCommand(Command):
@copy_args_to_public_fields
def __init__(self):
Command.__init__(self)
def run(self):
Command.run(self)
class Euler2(object):
alignUncertaintyReductionInputCommand = '{euler2Executable} align {cleantaxFile} -o {outputDir} -r {reasoner} -e {regions} {disjointness} {coverage} --ur'
alignExtractInputCommand = '{euler2Executable} align {cleantaxFile} -o {outputDir} -r {reasoner} -e {regions} {disjointness} {coverage} --xia'
alignArtRemCommand = '{euler2Executable} align {cleantaxFile} -o {outputDir} -r {reasoner} -e {regions} {disjointness} {coverage} --artRem'
alignFourInOneCommand = '{euler2Executable} align {cleantaxFile} -o {outputDir} -r {reasoner} -e {regions} {disjointness} {coverage} --fourinone'
alignCommand = '{euler2Executable} align {cleantaxFile} -o {outputDir} -r {reasoner} -e {regions} {disjointness} {coverage}'
alignConsistencyCommand = '{euler2Executable} align {cleantaxFile} -o {outputDir} -r {reasoner} -e {regions} {disjointness} {coverage} --consistency'
alignMaxNCommand = '{euler2Executable} align {cleantaxFile} -o {outputDir} -r {reasoner} -e {regions} {disjointness} {coverage} -n {maxN}'
alignRepairCommand = '{euler2Executable} align {cleantaxFile} -o {outputDir} -r {reasoner} -e {regions} {disjointness} {coverage} --repair={repairMethod}'
alignRepairHSTCommand = '{euler2Executable} align {cleantaxFile} -o {outputDir} -r {reasoner} -e {regions} {disjointness} {coverage} --repair=HST'
showIVCommand = '{euler2Executable} show iv {cleantaxFile} -o {outputDir} {imageFormat}';
showPWCommand = '{euler2Executable} show -o {outputDir} pw {imageFormat}'
showInconLatCommand = '{euler2Executable} show -o {outputDir} inconLat {imageFormat}'
showInconLatFullCommand = '{euler2Executable} show -o {outputDir} inconLat {imageFormat} --full'
showInconLatReducedCommand = '{euler2Executable} show -o {outputDir} inconLat {imageFormat} --reduced'
showFourInOneCommand = '{euler2Executable} show -o {outputDir} fourinone {imageFormat}'
showSummaryCommand = '{euler2Executable} show -o {outputDir} sv {imageFormat}'
showAmbLatCommand = '{euler2Executable} show -o {outputDir} ambLat {imageFormat}'
commandStyles = OrderedDict()
commandStyles[showIVCommand] = []
commandStyles[showIVCommand].append("input")
commandStyles[showIVCommand].append("singletoninput")
commandStyles[showIVCommand].append("map")
commandStyles[showIVCommand].append("ncs")
commandStyles[showPWCommand] = []
commandStyles[showPWCommand].append("rcg")
commandStyles[showPWCommand].append("zoomin")
commandStyles[showPWCommand].append("map")
commandStyles[showPWCommand].append("ncs")
commandStyles[showSummaryCommand] = []
commandStyles[showSummaryCommand].append("aggregate")
commandStyles[showSummaryCommand].append("cluster")
commandStyles[showSummaryCommand].append("map")
commandStyles[showSummaryCommand].append("ncs")
commandStyles[showAmbLatCommand] = []
commandStyles[showAmbLatCommand].append("map")
commandStyles[showAmbLatCommand].append("ncs")
commandStyles[showFourInOneCommand] = []
commandStyles[showFourInOneCommand].append("map")
commandStyles[showFourInOneCommand].append("ncs")
commandStyles[showInconLatCommand] = []
commandStyles[showInconLatCommand].append("map")
commandStyles[showInconLatCommand].append("ncs")
#not clear what "map" and "ncs" styles are used for hence added for all show commands
@copy_args_to_public_fields
def __init__(self, tap):
import e3_io
configManager = e3_io.ConfigManager()
tapManager = e3_io.TapManager()
config = configManager.get_config()
self.style = configManager.get_style()
self.euler2Executable = config['environment']['euler2Executable']
self.reasoner = config['reasoning']['reasoner']
self.imageFormat = config['cli behavior']['imageFormat']
self.repairMethod = config['reasoning']['fixMethod']
self.isCoverage = self.tap.isCoverage
self.isSiblingDisjointness = self.tap.isSiblingDisjointness
self.regions = self.tap.regions
self.tapId = self.tap.get_id()
self.cleantaxFile = tapManager.get_cleantax_file(self.tapId)
self.tapDir = tapManager.get_tap_dir(self.tapId)
self.e2InputDir = os.path.join(self.tapDir, "{uniqueParameteredRun}", "0-Input")
self.e2AspInputDir = os.path.join(self.tapDir, "{uniqueParameteredRun}", "1-ASP-input-code")
self.e2AspOutputDir = os.path.join(self.tapDir, "{uniqueParameteredRun}", "2-ASP-output")
self.e2MirDir = os.path.join(self.tapDir, "{uniqueParameteredRun}", "3-MIR")
self.e2PWsDir = os.path.join(self.tapDir, "{uniqueParameteredRun}", "4-PWs")
self.e2AggregatesDir = os.path.join(self.tapDir, "{uniqueParameteredRun}", "5-Aggregates")
self.e2LatticesDir = os.path.join(self.tapDir, "{uniqueParameteredRun}", "6-Lattices")
self.e2ExtractInputDir = os.path.join(self.tapDir, "{uniqueParameteredRun}", "11-ExtractInput")
self.isConsistent = True
if not hasattr(self, 'maxN'):
self.maxN = None
def run(self, command):
# add parameters to the command that are relevant to avoid re-runs (i.e. all tap relevant data + maxN + ...?)
# by at the same time keeping the file name minimal
coverage = "" if self.isCoverage else "--disablecov"
disjointness = "" if self.isSiblingDisjointness else "--disablesib"
imageFormat = "--svg" if self.imageFormat == "svg" else ""
uniqueParameteredRun = "{reasoner} {regions} {coverage} {disjointness} {maxN} {repairMethod} {imageFormat}"
uniqueParameteredRun = uniqueParameteredRun.format(reasoner = self.reasoner, regions = self.regions, coverage = coverage,
disjointness = disjointness, maxN = self.maxN, repairMethod = self.repairMethod,
imageFormat = imageFormat)
uniqueParameteredRun = '_'.join(uniqueParameteredRun.split())
outputDir = os.path.join(self.tapDir, uniqueParameteredRun)
if not os.path.isdir(outputDir):
os.mkdir(outputDir)
self.e2InputDir = self.e2InputDir.format(uniqueParameteredRun = uniqueParameteredRun)
self.e2AspInputDir = self.e2AspInputDir.format(uniqueParameteredRun = uniqueParameteredRun)
self.e2AspOutputDir = self.e2AspOutputDir.format(uniqueParameteredRun = uniqueParameteredRun)
self.e2MirDir = self.e2MirDir.format(uniqueParameteredRun = uniqueParameteredRun)
self.e2PWsDir = self.e2PWsDir.format(uniqueParameteredRun = uniqueParameteredRun)
self.e2AggregatesDir = self.e2AggregatesDir.format(uniqueParameteredRun = uniqueParameteredRun)
self.e2LatticesDir = self.e2LatticesDir.format(uniqueParameteredRun = uniqueParameteredRun)
self.e2ExtractInputDir = self.e2ExtractInputDir.format(uniqueParameteredRun = uniqueParameteredRun)
uniqueCommand = command.format(euler2Executable = '{euler2Executable}',
cleantaxFile = '{cleantaxFile}', outputDir = '{outputDir}',
#imageFormat = '{imageFormat}',
#reasoner = '{reasoner}',
repairMethod = self.repairMethod, maxN = self.maxN, regions = self.regions, coverage = coverage,
disjointness = disjointness, imageFormat = imageFormat, reasoner = self.reasoner)
uniqueCommand = ' '.join(uniqueCommand.split())
stdoutFile = os.path.join(outputDir, '%s.stdout' % uniqueCommand)
stderrFile = os.path.join(outputDir, '%s.stderr' % uniqueCommand)
returnCodeFile = os.path.join(outputDir, '%s.returncode' % uniqueCommand)
styleFile = os.path.join(outputDir, '%s.styles' % uniqueCommand)
currentCommandStyle = OrderedDict()
if command in Euler2.commandStyles and Euler2.commandStyles[command]:
for style in Euler2.commandStyles[command]:
currentCommandStyle[style] = self.style[style]
import e3_io
if os.path.isfile(stdoutFile) and os.path.isfile(stderrFile) and os.path.isfile(returnCodeFile) and os.path.isfile(styleFile):
refreshCommandForced = False
if command in Euler2.commandStyles and Euler2.commandStyles[command]:
with open(styleFile, 'r') as f:
previousStyle = yaml.load(f, Loader=yaml.RoundTripLoader, preserve_quotes=True)
if currentCommandStyle != previousStyle:
refreshCommandForced = True
if not refreshCommandForced:
with open(stdoutFile, 'r') as f:
self.stdout = f.read()
with open(stderrFile, 'r') as f:
self.stderr = f.read()
with open(returnCodeFile, 'r') as f:
self.returnCode = f.read()
if "Input is inconsistent" in self.stdout:
self.isConsistent = False
if self.returnCode and self.stderr:
print self.stderr.rstrip()
return self.stdout, self.stderr, self.returnCode
stylesheetsDir = os.path.join(outputDir, "stylesheets")
e3_io.mkdirs_ignore_existing(stylesheetsDir)
for key in self.style:
with open(os.path.join(stylesheetsDir, key + "style_src.yaml"), "w") as src:
yaml.dump(self.style[key], src, Dumper=yaml.RoundTripDumper, default_flow_style=False)
#to conform to the expectation of Euler's y2d that the stylesheet yaml files require an extra identation (see default-stylesheets)
with open(os.path.join(stylesheetsDir, key + "style_src.yaml"), "r") as src:
with open(os.path.join(stylesheetsDir, key + "style.yaml"), "w") as fileExpectedFormat:
for line in src:
fileExpectedFormat.write(' ' + line)
os.remove(os.path.join(stylesheetsDir, key + "style_src.yaml"))
# add remaining parameters
effectiveCommand = uniqueCommand.format(euler2Executable = self.euler2Executable,
cleantaxFile = self.cleantaxFile, outputDir = outputDir, imageFormat = self.imageFormat,
maxN = self.maxN, reasoner = self.reasoner);
with open(stdoutFile, 'w+') as out:
with open(stderrFile, 'w+') as err:
with open(returnCodeFile, 'w+') as rc:
with open(styleFile, 'w+') as s:
#print effectiveCommand
#print outputDir
p = Popen(effectiveCommand, stdout=PIPE, stderr=PIPE, shell=True, cwd = outputDir)
self.stdout, self.stderr = p.communicate()
#print self.stdout
#print self.stderr
if p.returncode and self.stderr:
print self.stderr.rstrip()
if "Input is inconsistent" in self.stdout:
self.isConsistent = False
out.write(self.stdout)
err.write(self.stderr)
rc.write('%s' % p.returncode)
yaml.dump(currentCommandStyle, s, Dumper=yaml.RoundTripDumper, default_flow_style=False)
#if os.path.isfile('report.csv'):
# os.remove('report.csv') not needed with Popen(..cwd=)
self.returncode = p.returncode
return self.stdout, self.stderr, self.returncode
def is_consistent(self):
return self.isConsistent
def get_world_yaml(self):
for filename in os.listdir(self.e2PWsDir):
if filename.startswith("cleantax_0_") and filename.endswith(".yaml"):
with open(os.path.join(self.e2PWsDir, filename), "r") as f:
return yaml.load(f)
def get_worlds(self):
worlds = []
worldStart = False
world = []
for line in self.stdout.splitlines():
if len(line.strip()) == 0:
continue
if line.startswith('Possible world'):
if worldStart:
worlds.append(world)
worldStart = True
world = []
elif worldStart:
line = line.strip()[1:-1]
line = line.split(", ")
for a in line:
a = a.replace("\"!\"", " disjoint ")
a = a.replace("\"=\"", " equals ")
a = a.replace("\"<\"", " is_included_in ")
a = a.replace("\">\"", " includes ")
a = a.replace("\"><\"", " overlaps ")
world.append(a)
if world:
worlds.append(world)
return worlds
def get_world_count(self):
return len(self.get_worlds())
def get_maximal_articulation_sets(self):
sets = []
for filename in os.listdir(self.e2ExtractInputDir):
if filename.startswith("cleantax-alt"):
set = []
file = os.path.join(self.e2ExtractInputDir, filename)
import e3_io
tap = e3_io.CleantaxReader().get_tap_from_cleantax_file(file)
for a in tap.articulations:
set.append(a.__str__()[1:-1]);
sets.append(set)
return sets
def get_unique_articulation_sets(self):
uniqueArtSets = []
for line in self.stdout.splitlines():
if 'Min articulation subset that makes unique PW' in line:
uniqueArtSet = []
articulationsLine = line.split('[')[1]
articulationsLine = articulationsLine.split(']')[0].strip()
articulations = articulationsLine.split(" , ")
for i, articulation in enumerate(articulations):
uniqueArtSet.append(articulation.strip())
uniqueArtSets.append(uniqueArtSet)
return uniqueArtSets
#['1.B is_included_in 2.B', '1.A equals 2.A', '1.G equals 2.G', '1.C 1.D lsum 2.C', '1.F equals 2.F', '1.E equals 2.E'] ['1.B is_included_in 2.B', '1.H equals 2.H', '1.A equals 2.A', '1.G equals 2.G', '1.C 1.D lsum 2.C', '1.E equals 2.E']
def get_maximal_ambiguity_sets(self):
for line in self.stdout.splitlines():
if line.startswith('MAA'):
uniqueArtSets = []
articulationSets = re.compile("\] \[|\[|\]").split(line)[1:-1]
for articulationSet in articulationSets:
uniqueArtSet = []
for i, articulation in enumerate(articulationSet.split(", ")):
uniqueArtSet.append(articulation.strip()[1:-1])
uniqueArtSets.append(uniqueArtSet)
return uniqueArtSets
def get_maximal_consistency_sets(self):
for line in self.stdout.splitlines():
if line.startswith('MCS'):
uniqueArtSets = []
articulationSets = re.compile("\] \[|\[|\]").split(line)[1:-1]
for articulationSet in articulationSets:
uniqueArtSet = []
for i, articulation in enumerate(articulationSet.split(", ")):
uniqueArtSet.append(articulation.strip()[1:-1])
uniqueArtSets.append(uniqueArtSet)
return uniqueArtSets
def get_minimal_inconsistency_sets(self):
for line in self.stdout.splitlines():
if line.startswith('MIS'):
uniqueArtSets = []
articulationSets = re.compile("\] \[|\[|\]").split(line)[1:-1]
for articulationSet in articulationSets:
uniqueArtSet = []
for i, articulation in enumerate(articulationSet.split(", ")):
uniqueArtSet.append(articulation.strip()[1:-1])
uniqueArtSets.append(uniqueArtSet)
return uniqueArtSets
def get_minimal_uniqueness_sets(self):
for line in self.stdout.splitlines():
if line.startswith('MUS'):
uniqueArtSets = []
articulationSets = re.compile("\] \[|\[|\]").split(line)[1:-1]
for articulationSet in articulationSets:
uniqueArtSet = []
for i, articulation in enumerate(articulationSet.split(", ")):
uniqueArtSet.append(articulation.strip()[1:-1])
uniqueArtSets.append(uniqueArtSet)
return uniqueArtSets
def get_input_graphs(self):
files = []
for filename in os.listdir(self.e2InputDir):
if filename.endswith(".%s" % self.imageFormat):
file = os.path.join(self.e2InputDir, filename)
files.append(file)
return files
def get_world_graphs(self):
files = []
for filename in os.listdir(self.e2PWsDir):
if filename.endswith(".%s" % self.imageFormat):
file = os.path.join(self.e2PWsDir, filename)
files.append(file)
return files
def get_world_graphs_count(self):
return len(self.get_world_graphs())
def get_fix_option_sets(self):
sets = []
for line in self.stdout.splitlines():
if line.startswith('Repair option'):
set = []
articulations = line.split("[")[1].strip()[:-1]
for a in articulations.split(" , "):
set.append(a)
sets.append(set)
if line.startswith('Possible world'):
return []
return sets
def get_mir(self):
mir = []
mirFile = os.path.join(self.e2MirDir, "cleantax_mir.csv")
if os.path.isfile(mirFile):
with open(mirFile, 'r') as f:
lines = f.read().split('\n')
for line in lines:
line = line.strip()
if line:
elements = line.split(",")
newElements = []
collectSet = []
insideSet = False
for e in elements:
if not e.startswith("{") and not e.endswith("}") and not insideSet:
newElements.append(e)
else:
collectSet.append(e.replace("{", "").replace("}", "").strip())
if e.startswith("{"):
insideSet = True
if e.endswith("}"):
insideSet = False
newElements.append(','.join(collectSet))
import e3_model
relations = []
if "," in newElements[1]:
relations = newElements[1].split(',')
else:
relations.append(newElements[1])
for relation in relations:
if relation == "!": relation = "disjoint"
if relation == "=": relation = "equals"
if relation == "<": relation = "is_included_in"
if relation == ">": relation = "includes"
if relation == "><": relation = "overlaps"
leftNodes = []
leftNodes.append(newElements[0])
rightNodes = []
rightNodes.append(newElements[2])
a = e3_model.Articulation(leftNodes, rightNodes, relation)
mir.append({
"type": newElements[3],
"articulation": a
})
return mir
def get_inconsistency_lattice_graphs(self, type):
graphs = []
for filename in os.listdir(self.e2LatticesDir):
if filename.endswith(".%s" % self.imageFormat):
file = os.path.join(self.e2LatticesDir, filename)
if type == "full":
if "_fulllat" in filename:
graphs.append(file)
elif type == "reduced":
if "_lat" in filename:
graphs.append(file)
else:
graphs.append(file)
return graphs
def get_four_in_one_lattice_graphs(self):
graphs = []
for filename in os.listdir(self.e2LatticesDir):
if filename.endswith(".%s" % self.imageFormat):
file = os.path.join(self.e2LatticesDir, filename)
graphs.append(file)
return graphs
def get_summary_graphs(self):
graphs = []
for filename in os.listdir(self.e2AggregatesDir):
if filename.endswith(".%s" % self.imageFormat):
file = os.path.join(self.e2AggregatesDir, filename)
graphs.append(file)
return graphs
def get_ambiguity_lattice_graphs(self):
graphs = []
for filename in os.listdir(self.e2LatticesDir):
if filename.endswith(".%s" % self.imageFormat):
file = os.path.join(self.e2LatticesDir, filename)
graphs.append(file)
return graphs
class Euler2Command(Command):
@copy_args_to_public_fields
def __init__(self, tap):
Command.__init__(self)
config = self.configManager.get_config()
self.imageViewer = config['environment']['imageViewer']
self.maxWorldsToShow = config['cli behavior']['maxWorldsToShow']
def run(self):
Command.run(self)
class ModelCommand(Command):
@copy_args_to_public_fields
def __init__(self):
Command.__init__(self)
def run(self):
Command.run(self)
class SetConfig(MiscCommand):
@copy_args_to_public_fields
def __init__(self, key, value):
MiscCommand.__init__(self)
def run(self):
MiscCommand.run(self)
config = self.configManager.get_config()
oldValue = None
existsKey = False
for firstLevelKey in config:
if self.key in config[firstLevelKey]:
oldValue = config[firstLevelKey][self.key]
existsKey = True
break
if not existsKey:
self.output.append("Configuration parameter " + self.key + " does not exist.")
return
if type(oldValue) is bool:
self.value = True if not (self.value == 'false' or self.value == 'False') else False
elif type(oldValue) is int:
self.value = int(self.value)
elif type(oldValue) is str:
self.value = str(self.value)
if type(oldValue) is DoubleQuotedScalarString:
self.value = DoubleQuotedScalarString(self.value)
if type(oldValue) is SingleQuotedScalarString:
self.value = SingleQuotedScalarString(self.value)
config[firstLevelKey][self.key] = self.value
self.configManager.store_config(config)
self.output.append("Configuration updated: " + self.key + " = " + str(self.value))
class SetStyle(MiscCommand):
@copy_args_to_public_fields
def __init__(self, key, value):
MiscCommand.__init__(self)
def run(self):
MiscCommand.run(self)
style = self.configManager.get_style()
keys = self.key.split("/")
currentDict = style
pastKey = "/"
for i, key in enumerate(keys):
if i == len(keys) - 1:
break
if key in currentDict:
currentDict = currentDict[key]
pastKey += key + "/"
else:
self.output.append("Style parameter " + key + " does not exist in " + pastKey)
return
oldValue = currentDict[keys[i]]
if type(oldValue) is bool:
self.value = True if not (self.value == 'false' or self.value == 'False') else False
if type(oldValue) is int:
self.value = int(self.value)
if type(oldValue) is str:
self.value = str(self.value)
if type(oldValue) is DoubleQuotedScalarString:
self.value = DoubleQuotedScalarString(self.value)
if type(oldValue) is SingleQuotedScalarString:
self.value = SingleQuotedScalarString(self.value)
currentDict[keys[i]] = self.value
self.configManager.store_style(style)
self.output.append("Configuration updated: " + self.key + " = " + str(self.value))
class PrintConfig(MiscCommand):
@copy_args_to_public_fields
def __init__(self):
MiscCommand.__init__(self)
def run(self):
MiscCommand.run(self)
config = self.configManager.get_config()
print yaml.dump(config, Dumper=yaml.RoundTripDumper, default_flow_style=False)
class PrintStyle(MiscCommand):
@copy_args_to_public_fields
def __init__(self):
MiscCommand.__init__(self)
def run(self):
MiscCommand.run(self)
style = self.configManager.get_style()
print yaml.dump(style, Dumper=yaml.RoundTripDumper, default_flow_style=False)
@logged
class Reset(MiscCommand):
@copy_args_to_public_fields
def __init__(self):
MiscCommand.__init__(self)
def run(self):
MiscCommand.run(self)
import e3_io
e3_io.reset()
self.output.append("Reset successful")
self.output.append("Tap: " + self.tapManager.get_current_tap_name_and_status())
@logged
class ResetConfig(MiscCommand):
@copy_args_to_public_fields
def __init__(self):
MiscCommand.__init__(self)
def run(self):
MiscCommand.run(self)
import e3_io
self.configManager.store_config(self.configManager.get_default_config())
self.output.append("Reset config successfully")
@logged
class ResetStyle(MiscCommand):
@copy_args_to_public_fields
def __init__(self):
MiscCommand.__init__(self)
def run(self):
MiscCommand.run(self)
import e3_io
self.configManager.store_style(self.configManager.get_default_style())
self.output.append("Reset style successfully")
@logged
class ClearHistory(MiscCommand):
@copy_args_to_public_fields
def __init__(self):
MiscCommand.__init__(self)
def run(self):
MiscCommand.run(self)
self.tapManager.clear_history()
self.output.append("Cleared history successfully")
@logged
class Clear(ModelCommand):
@copy_args_to_public_fields
def __init__(self):
ModelCommand.__init__(self)
def run(self):
ModelCommand.run(self)
import e3_io
e3_io.clear()
self.output.append("Clear successful")
self.output.append("Tap: " + self.tapManager.get_current_tap_name_and_status())
@logged
class ShowHistory(MiscCommand):
@copy_args_to_public_fields
def __init__(self):
MiscCommand.__init__(self)
def run(self):
MiscCommand.run(self)
config = self.configManager.get_config()
import e3_io
self.executeOutput.append(config['environment']['htmlViewer'].format(file = os.path.join(e3_io.get_working_dir(), "index.html")))
@logged
class SetGitCredentials(MiscCommand):
@copy_args_to_public_fields
def __init__(self, host, user, password):
MiscCommand.__init__(self)
pass
def run(self):
MiscCommand.run(self)
import e3_io
e3_io.set_git_credencials(self.host, self.user, self.password)
self.output.append("git credentials set successfully")
@logged
class GitStatePull(MiscCommand):
@copy_args_to_public_fields
def __init__(self, name):
MiscCommand.__init__(self)
pass
def run(self):
MiscCommand.run(self)
config = self.configManager.get_config()
repo = config['sharing']['stateGitRepo']
if repo == None or not repo.strip() :
self.output.append("Configuration value stateGitRepo is not set.")
return
import git
import e3_io
gitDir = os.path.join(e3_io.get_e3_git_dir(),
"_".join(re.compile("\W+").split(repo)))
if not os.path.isdir(gitDir):
os.mkdir(gitDir)
g = git.Git(gitDir)
try:
g.status()
g.pull()
except git.exc.GitCommandError as e:
shutil.rmtree(gitDir)
e3_io.mkdirs_ignore_existing(gitDir)
g.clone(repo, gitDir)
targetDir = os.path.join(gitDir, os.path.join(*(self.name.split("/"))))
if not os.path.isdir(targetDir):
self.output.append("Pulled successfully but " + self.name + " not found in the repository.")
return
e3Dir = e3_io.get_e3_dir()
if os.path.isdir(e3Dir):
shutil.rmtree(e3Dir)
shutil.copytree(targetDir, e3Dir)
self.output.append("Pulled successfully")
self.output.append("Tap: " + self.tapManager.get_tap_name_and_status(self.tapManager.get_current_tap().get_id()))
@logged
class GitPull(MiscCommand):
@copy_args_to_public_fields
def __init__(self, name):
MiscCommand.__init__(self)
pass
def run(self):
MiscCommand.run(self)
config = self.configManager.get_config()
repo = config['sharing']['workspaceGitRepo']
if repo == None or not repo.strip() :
self.output.append("Configuration value workspaceGitRepo is not set.")
return
import git
import e3_io
gitDir = os.path.join(e3_io.get_e3_data_git_dir(),
"_".join(re.compile("\W+").split(repo)))
if not os.path.isdir(gitDir):
os.mkdir(gitDir)
g = git.Git(gitDir)
try:
g.status()
g.pull()
except git.exc.GitCommandError as e:
shutil.rmtree(gitDir)
e3_io.mkdirs_ignore_existing(gitDir)
g.clone(repo, gitDir)
targetDir = os.path.join(gitDir, os.path.join(*(self.name.split("/"))))
if not os.path.isdir(targetDir):
self.output.append("Pulled successfully but " + self.name + " not found in the repository.")
return
workingDir = e3_io.get_working_dir()
if os.path.isdir(workingDir):
shutil.rmtree(workingDir)
shutil.copytree(targetDir, workingDir)
self.output.append("Pulled successfully")
@logged
class GitPush(MiscCommand):
@copy_args_to_public_fields
def __init__(self, name, message):
MiscCommand.__init__(self)
def run(self):
MiscCommand.run(self)
config = self.configManager.get_config()
repo = config['sharing']['workspaceGitRepo']
if repo == None or not repo.strip() :
self.output.append("Configuration value workspaceGitRepo is not set.")
return
import git
import e3_io
try:
gitDir = os.path.join(e3_io.get_e3_data_git_dir(),
"_".join(re.compile("\W+").split(repo)))
if not os.path.isdir(gitDir):
os.mkdir(gitDir)
g = git.Git(gitDir)
try:
g.status()
except git.exc.GitCommandError as e:
g.init() # can already have a .git folder
g.remote("add", "origin", repo) # can already have an "origin"
g.pull("origin", "master") # may not be able to if remote is invalid url
targetDir = os.path.join(gitDir, os.path.join(*(self.name.split("/"))))
if os.path.isdir(targetDir):
shutil.rmtree(targetDir)
import e3_io
e3_io.mkdirs_ignore_existing(os.path.abspath(os.path.join(targetDir, os.path.pardir)))
shutil.copytree(e3_io.get_working_dir(), targetDir)
g.add(".")
try:
g.commit("-m", self.message) #could fail if nothing to commit anymore locally, but push missing
except git.exc.GitCommandError as e:
self.output.append(str(e))
#could in theory have empty message
g.push("--all")
self.output.append("Pushed successfully")
except git.exc.GitCommandError as e:
self.output.append(str(e))
@logged
class GitStatePush(MiscCommand):
@copy_args_to_public_fields
def __init__(self, name, message):
MiscCommand.__init__(self)
def run(self):
MiscCommand.run(self)
config = self.configManager.get_config()
repo = config['sharing']['stateGitRepo']
if repo == None or not repo.strip() :
self.output.append("Configuration value stateGitRepo is not set.")
return
import git
import e3_io
try:
gitDir = os.path.join(e3_io.get_e3_git_dir(),
"_".join(re.compile("\W+").split(repo)))
if not os.path.isdir(gitDir):
os.mkdir(gitDir)
g = git.Git(gitDir)
try:
g.status()
except git.exc.GitCommandError as e:
g.init() # can already have a .git folder
g.remote("add", "origin", repo) # can already have an "origin"
g.pull("origin", "master") # may not be able to if remote is invalid url
targetDir = os.path.join(gitDir, os.path.join(*(self.name.split("/"))))
if os.path.isdir(targetDir):
shutil.rmtree(targetDir)
import e3_io
e3_io.mkdirs_ignore_existing(os.path.abspath(os.path.join(targetDir, os.pardir)))
shutil.copytree(e3_io.get_e3_dir(), targetDir)
g.add(".")
try:
g.commit("-m", self.message) #could fail if nothing to commit anymore locally, but push missing
except git.exc.GitCommandError as e:
self.output.append(str(e))
#could in theory have empty message
g.push("--all")
self.output.append("Pushed successfully")
except git.exc.GitCommandError as e:
self.output.append(str(e))
@logged
class Bye(MiscCommand):
@copy_args_to_public_fields
def __init__(self):
MiscCommand.__init__(self)
def run(self):
MiscCommand.run(self)
self.output.append("See you soon!")
self.executeOutput.append("Exit")
@logged
class Help(MiscCommand):
@copy_args_to_public_fields
def __init__(self):
MiscCommand.__init__(self)
def run(self):
MiscCommand.run(self)
import e3_parse
for commandParser in e3_parse.commandParsers:
help = commandParser.get_help()
if help:
self.output.append('-------------------')
self.output.append(commandParser.get_help())
@logged
class NameTap(MiscCommand):
@copy_args_to_public_fields
def __init__(self, tap, name):
MiscCommand.__init__(self)
def run(self):
MiscCommand.run(self)
self.tapManager.set_name(self.name, self.tap.get_id());
self.output.append("Tap: " + self.tapManager.get_tap_name_and_status(self.tap.get_id()))
class PrintNames(MiscCommand):
@copy_args_to_public_fields
def __init__(self):
MiscCommand.__init__(self)
def run(self):
MiscCommand.run(self)
names = self.tapManager.get_names()
if names:
self.output.append('\n'.join(names))
else:
self.output.append('No names stored.')
class PrintTap(MiscCommand):
@copy_args_to_public_fields
def __init__(self, tap):
MiscCommand.__init__(self)
def run(self):
MiscCommand.run(self)
self.output.append(self.tap.__str__())
class PrintTaxonomies(MiscCommand):
@copy_args_to_public_fields
def __init__(self, tap):
MiscCommand.__init__(self)
def run(self):
MiscCommand.run(self)
for taxonomy in self.tap.taxonomies:
self.output.append(taxonomy.__str__() + "\n")
class PrintArticulations(MiscCommand):
@copy_args_to_public_fields
def __init__(self, tap):
MiscCommand.__init__(self)
def run(self):
MiscCommand.run(self)
indices = []
for x in range(1, len(self.tap.articulations) + 1):
indices.append(str(x) + ". ")
articulationLines = [x + y for x, y in zip(indices, [a.__str__() for a in self.tap.articulations])]
self.output.append('\n'.join(articulationLines))
@logged
class LoadTap(ModelCommand):
@copy_args_to_public_fields
def __init__(self, cleantaxFile):
ModelCommand.__init__(self)
def run(self):
ModelCommand.run(self)
import e3_validation
try:
import e3_io
tap = e3_io.CleantaxReader().get_tap_from_cleantax_file(self.cleantaxFile)
self.tapManager.set_current_tap(tap)
self.output.append("Tap: " + self.tapManager.get_tap_name_and_status(tap.get_id()))
except IOError as e:
self.output.append("File not found.")
return
except e3_validation.ValidationException as e:
self.output.append(str(e))
@logged
class ClearTap(ModelCommand):
@copy_args_to_public_fields
def __init__(self):
ModelCommand.__init__(self)
def run(self):
ModelCommand.run(self)
currentTap = self.tapManager.get_current_tap()
config = ConfigManager().get_config()
import e3_model
tap = e3_model.Tap(config['defaultIsCoverage'], config['defaultIsSiblingDisjointness'], config['defaultRegions'], [], [])
self.tapManager.set_current_tap(tap)
self.output.append("Tap: " + self.tapManager.get_tap_name_and_status(currentTap.get_id()))
class AddConcepts(ModelCommand):
@copy_args_to_public_fields
def __init__(self, tap, taxonomyId, children):
ModelCommand.__init__(self)
def run(self):
ModelCommand.run(self)
parts = self.children[1:-1].split()
#1 part will add concept as root
#if len(parts) <= 1:
# self.output.append("Taxonomy line with <= 1 nodes is invalid.")
# return
import e3_validation
try:
if len(parts) == 1:
self.tap.add_node(self.taxonomyId, parts[0])
elif len(parts) > 1:
self.tap.add_children(self.taxonomyId, parts[0], parts[1:])
self.tapManager.set_current_tap(self.tap)
self.output.append("Tap: " + self.tapManager.get_tap_name_and_status(self.tap.get_id()))
except ValueError as e:
self.output.append(str(e))
return
except e3_validation.ValidationException as e:
self.output.append(str(e))
return
class RemoveConcepts(ModelCommand):
@copy_args_to_public_fields
def __init__(self, tap, taxonomyId, children, recursive):
ModelCommand.__init__(self)
def run(self):
ModelCommand.run(self)
parts = self.children[1:-1].split()
#1 part will remove concept as root
#if len(parts) <= 1:
# self.output.append("Taxonomy line with <= 1 nodes is invalid.")
# return
import e3_validation
try:
if len(parts) == 1:
self.tap.remove_node(self.taxonomyId, parts[0])
elif len(parts) > 1:
self.tap.remove_children(self.taxonomyId, parts[0], parts[1:], self.recursive)
self.tapManager.set_current_tap(self.tap)
self.output.append("Tap: " + self.tapManager.get_tap_name_and_status(self.tap.get_id()))
except ValueError as e:
self.output.append(str(e))
return
except e3_validation.ValidationException as e:
self.output.append(str(e))
return
class AddTaxonomy(ModelCommand):
@copy_args_to_public_fields
def __init__(self, tap, id, name):
ModelCommand.__init__(self)
def run(self):
ModelCommand.run(self)
if self.tap.has_taxonomy(self.id):
self.output.append("Taxonomy with id: " + self.id + " already exists")
import e3_model
self.tap.add_taxonomy(e3_model.Taxonomy(self.id, self.name))
self.tapManager.set_current_tap(self.tap)
self.output.append("Tap: " + self.tapManager.get_tap_name_and_status(self.tap.get_id()))
class RemoveTaxonomy(ModelCommand):
@copy_args_to_public_fields
def __init__(self, tap, id):
ModelCommand.__init__(self)
def run(self):
ModelCommand.run(self)
if not self.tap.has_taxonomy(self.id):
self.output.append("Taxonomy with id " + self.id + " does not exist")
return
self.tap.remove_taxonomy(self.id)
self.tapManager.set_current_tap(self.tap)
self.output.append("Tap: " + self.tapManager.get_tap_name_and_status(self.tap.get_id()))
class ClearTaxonomy(ModelCommand):
@copy_args_to_public_fields
def __init__(self, tap, id):
ModelCommand.__init__(self)
def run(self):
ModelCommand.run(self)
if not self.tap.has_taxonomy(self.id):
self.output.append("Taxonomy with id " + self.id + " does not exist")
return
self.tap.clear_taxonomy(self.id)
self.tapManager.set_current_tap(self.tap)
self.output.append("Tap: " + self.tapManager.get_tap_name_and_status(self.tap.get_id()))