-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransitiveDigraphs.py
More file actions
2323 lines (2130 loc) · 93.2 KB
/
transitiveDigraphs.py
File metadata and controls
2323 lines (2130 loc) · 93.2 KB
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 python3
"""
Digraph3 module for working with transitive digraphs.
Copyright (C) 2006-2025 Raymond Bisdorff
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""
#######################
__version__ = "$Revision: Python 3.13.2"
from digraphsTools import *
from digraphs import *
from outrankingDigraphs import *
from transitiveDigraphs import *
#from multiprocessing import Process, active_children, cpu_count
import multiprocessing as mp
mpctx = mp.get_context('spawn')
Process = mpctx.Process
active_children = mpctx.active_children
cpu_count = mpctx.cpu_count
class TransitiveDigraph(Digraph):
"""
Abstract class for specialized methods addressing transitive digraphs.
"""
def __init__(self):
print('abstract root class')
## for comp in components.values():
## #comp = self.components[cki]
## pg = comp['subGraph']
## if rankingRule == 'Copeland':
## opg = CopelandOrder(pg)
## ranking += opg.copelandRanking
## elif rankingRule == 'NetFlows':
## opg = NetFlowsOrder(pg)
## ranking += opg.netFlowsRanking
## elif rankingRule == 'Kohler':
## opg = KohlerOrder(pg)
## ranking += opg.kohlerRanking
## return ranking
def computeBoostedOrdering(self,orderingRule='Copeland'):
"""
Renders an ordred list of decision actions ranked in
increasing preference direction following the orderingRule
on each component.
"""
ranking = self.computeBoostedRanking(rankingRule=orderingRule)
ranking.reverse()
return ranking
def showPartialOrder(self,rankingByChoosing=None,WithCoverCredibility=False):
"""
A dummy for the showTransitiveDigraph() method.
"""
self.showTransitiveDigraph(WithCoverCredibility=WithCoverCredibility)
def showPartialRanking(self,rankingByChoosing=None,WithCoverCredibility=False):
"""
A dummy for the showTransitiveDigraph() method.
"""
self.showTransitiveDigraph(WithCoverCredibility=WithCoverCredibility)
def showTransitiveDigraph(self,rankingByChoosing=None,WithCoverCredibility=False):
"""
A show method for self.rankinByChoosing result.
"""
if rankingByChoosing is None:
try:
rankingByChoosing = self.rankingByChoosing['result']
except:
#print('Error: You must first run self.computeRankingByChoosing(CoDual=False(default)|True) !')
self.computeRankingByChoosing()
rankingByChoosing = self.rankingByChoosing['result']
## else:
## try:
## rankingByChoosing = self.rankingByLastChoosing['result']
## except:
## #print('Error: You must first run self.computeRankingByChoosing(CoDual=False(default)|True) !')
## self.computeRankingByLastChoosing()
## rankingByChoosing = self.rankingByLastChoosing['result']
else:
rankingByChoosing = rankingByChoosing['result']
print('Ranking by recursively first and last choosing')
space = ''
n = len(rankingByChoosing)
for i in range(n):
if i+1 == 1:
nstr='st'
elif i+1 == 2:
nstr='nd'
elif i+1 == 3:
nstr='rd'
else:
nstr='th'
ibch = set(rankingByChoosing[i][0][1])
iwch = set(rankingByChoosing[i][1][1])
iach = iwch & ibch
#print 'ibch, iwch, iach', i, ibch,iwch,iach
ch = list(ibch)
ch.sort()
if WithCoverCredibility:
print(' %s%s%s ranked %s (%.2f)' % (space,i+1,nstr,ch,rankingByChoosing[i][0][0]))
else:
print(' %s%s%s ranked %s' % (space,i+1,nstr,ch) )
if len(iach) > 0 and i < n-1:
print(' %s Ambiguous Choice %s' % (space,list(iach)))
space += ' '
space += ' '
for i in range(n):
if n-i == 1:
nstr='st'
elif n-i == 2:
nstr='nd'
elif n-i == 3:
nstr='rd'
else:
nstr='th'
space = space[:-2]
ibch = set(rankingByChoosing[n-i-1][0][1])
iwch = set(rankingByChoosing[n-i-1][1][1])
iach = iwch & ibch
#print 'ibch, iwch, iach', i, ibch,iwch,iach
ch = list(iwch)
ch.sort()
if len(iach) > 0 and i > 0:
space = space[:-2]
print(' %s Ambiguous Choice %s' % (space,list(iach)))
if WithCoverCredibility:
print(' %s%s%s last ranked %s (%.2f)' % (space,n-i,nstr,ch,rankingByChoosing[n-i-1][1][0]))
else:
print(' %s%s%s last ranked %s' % (space,n-i,nstr,ch) )
def showRankingByChoosing(self,actionsList=None,rankingByChoosing=None,WithCoverCredibility=False):
"""
Dummy name for showTransitiveDigraph() method
"""
self.showTransitiveDigraph(rankingByChoosing=rankingByChoosing,
WithCoverCredibility=WithCoverCredibility)
def showOrderedRelationTable(self,direction="decreasing",originalRelation=False):
"""
Showing the relation table in decreasing (default) or increasing order.
"""
actionsList = []
if direction == "decreasing":
print('Decreasing Weak Ordering')
self.showRankingByBestChoosing()
try:
ordering = self.rankingByBestChoosing
except:
ordering = self.computeRankingByBestChoosing(Debug=False)
elif direction == "increasing":
print('Increasing Weak Ordering')
self.showRankingByLastChoosing()
try:
ordering = self.rankingByLastChoosing
except:
ordering = self.computeRankingByLastChoosing()
else:
print('Direction error !: %s is not a correct instruction (decreasing=default or increasing)' % direction)
for eq in ordering['result']:
#print(eq[1])
eq = eq[1]
eq.sort()
for x in eq:
actionsList.append(x)
if len(actionsList) != len(self.actions):
print('Error !: missing action(s) %s in ordered table.')
if originalRelation:
showRelation = self.originalRelation
else:
showRelation = self.relation
Digraph.showRelationTable(self,actionsSubset=actionsList,
relation=showRelation,
Sorted=False,
ReflexiveTerms=False)
def exportDigraphGraphViz(self,fileName=None, bestChoice=set(),worstChoice=set(),Comments=True,graphType='png',graphSize='7,7'):
"""
export GraphViz dot file for digraph drawing filtering.
"""
Digraph.exportGraphViz(self, fileName=fileName,
bestChoice=bestChoice,
worstChoice=worstChoice,
Comments=Comments,
graphType=graphType,
graphSize=graphSize)
# def exportTopologicalGraphViz(self,fileName=None,
# relation=None,direction='best',
# Comments=True,graphType='png',
# graphSize='7,7',
# fontSize=10,Debug=True):
# """
# export GraphViz dot file for Hasse diagram drawing filtering.
# """
# import os
# from copy import copy as deepcopy
# def _safeName(t0):
# t = t0.split(sep="-")
# t1 = t[0]
# n = len(t)
# if n > 1:
# for i in range(1,n):
# t1 += '%s%s' % ('_',t[i])
# return t1
# # working on a deepcopy of self
# digraph = deepcopy(self)
# digraph.computeTopologicalRanking()
# if not digraph.Acyclic:
# print('Error: not a transitive digraph !!!')
# return
# topologicalRanking = digraph.computeTopologicalRanking()
# if Debug:
# print(topologicalRanking)
# ## if direction == 'best':
# ## try:
# ## rankingByChoosing = digraph.rankingByBestChoosing['result']
# ## except:
# ## digraph.computeRankingByBestChoosing()
# ## rankingByChoosing = digraph.rankingByBestChoosing['result']
# ## else:
# ## try:
# ## rankingByChoosing = digraph.rankingByLastChoosing['result']
# ## except:
# ## digraph.computeRankingByLastChoosing()
# ## rankingByChoosing = digraph.rankingByLastChoosing['result']
# ## if Debug:
# ## print(rankingByChoosing)
# if Comments:
# print('*---- exporting a dot file for GraphViz tools ---------*')
# actionKeys = [x for x in digraph.actions]
# n = len(actionKeys)
# if relation is None:
# relation = deepcopy(digraph.relation)
# Med = digraph.valuationdomain['med']
# i = 0
# if fileName is None:
# name = digraph.name
# else:
# name = fileName
# dotName = name+'.dot'
# if Comments:
# print('Exporting to '+dotName)
# ## if bestChoice != set():
# ## rankBestString = '{rank=max; '
# ## if worstChoice != set():
# ## rankWorstString = '{rank=min; '
# fo = open(dotName,'w')
# fo.write('digraph G {\n')
# fo.write('graph [ bgcolor = cornsilk, ordering = out, fontname = "Helvetica-Oblique",\n fontsize = 12,\n label = "')
# fo.write('\\nDigraph3 (graphviz)\\n R. Bisdorff, 2020", size="')
# fo.write(graphSize),fo.write('",fontsize=%d];\n' % fontSize)
# # nodes
# for x in actionKeys:
# try:
# nodeName = digraph.actions[x]['shortName']
# except:
# nodeName = str(x)
# node = '%s [shape = "circle", label = "%s", fontsize=%d];\n'\
# % (str(_safeName(x)),_safeName(nodeName),fontSize)
# fo.write(node)
# # same ranks for Hasses equivalence classes
# k = len(topologicalRanking)
# i = 1
# for ich in topologicalRanking:
# sameRank = 'subGraph { rank = %d ; ' % i
# for x in topologicalRanking[ich]:
# sameRank += str(_safeName(x))+'; '
# sameRank += '}\n'
# print(i,sameRank)
# fo.write(sameRank)
# i += 1
# ## k = len(rankingByChoosing)
# ## for i in range(k):
# ## sameRank = '{ rank = same; '
# ## ich = rankingByChoosing[i][1]
# ## for x in ich:
# ## sameRank += str(_safeName(x))+'; '
# ## sameRank += '}\n'
# ## print(i,sameRank)
# ## fo.write(sameRank)
# # save original relation
# #originalRelation = deepcopy(relation)
# #digraph.closeTransitive(Reverse=False)
# relation = digraph.closeTransitive(Reverse=True,InSite=False)
# k = len(topologicalRanking)
# for i in range(1,k+1):
# ich = topologicalRanking[i]
# for x in ich:
# for j in range(i+1,k+1):
# jch = topologicalRanking[j]
# for y in jch:
# if relation[x][y] > digraph.valuationdomain['med']:
# arcColor = 'black'
# edge = '%s-> %s [style="setlinewidth(%d)",color=%s] ;\n' %\
# (_safeName(x),_safeName(y),1,arcColor)
# fo.write(edge)
# fo.write('}\n \n')
# fo.close()
# commandString = 'dot -Grankdir=TB -T'+graphType+' ' + \
# dotName+' -o '+name+'.'+graphType
# #commandString = 'dot -T'+graphType+' ' +dotName+' -o '+name+'.'+graphType
# if Comments:
# print(commandString)
# try:
# os.system(commandString)
# except:
# if Comments:
# print('graphViz tools not avalaible! Please check installation.')
def exportGraphViz(self,fileName=None,direction='best',
WithBestPathDecoration=False,
WithRatingDecoration=False,
ArrowHeads=False,
Comments=True,graphType='png',
graphSize='7,7',bgcolor='cornsilk',
fontSize=10,Debug=False):
"""
export GraphViz dot file for Hasse diagram drawing filtering.
"""
import os
from copy import copy as deepcopy
def _safeName(t0):
t = t0.split(sep="-")
t1 = t[0]
n = len(t)
if n > 1:
for i in range(1,n):
t1 += '%s%s' % ('_',t[i])
return t1
# working on a deepcopy of self
digraph = deepcopy(self)
if direction == 'best':
try:
rankingByChoosing = digraph.rankingByBestChoosing['result']
except:
digraph.computeRankingByBestChoosing()
rankingByChoosing = digraph.rankingByBestChoosing['result']
else:
try:
rankingByChoosing = digraph.rankingByLastChoosing['result']
except:
digraph.computeRankingByLastChoosing()
rankingByChoosing = digraph.rankingByLastChoosing['result']
if Debug:
print(rankingByChoosing)
if Comments:
print('*---- exporting a dot file for GraphViz tools ---------*')
actionKeys = [x for x in digraph.actions]
n = len(actionKeys)
#if relation is None:
# relation = deepcopy(digraph.relation)
Med = digraph.valuationdomain['med']
i = 0
if fileName is None:
name = digraph.name
else:
name = fileName
dotName = name+'.dot'
if Comments:
print('Exporting to '+dotName)
## if bestChoice != set():
## rankBestString = '{rank=max; '
## if worstChoice != set():
## rankWorstString = '{rank=min; '
fo = open(dotName,'w')
fo.write('digraph G {\n')
if bgcolor is None:
fo.write('graph [ ordering = out, fontname = "Helvetica-Oblique",\n fontsize = 12,\n label = "')
else:
fo.write('graph [ bgcolor = %s, ordering = out, fontname = "Helvetica-Oblique",\n fontsize = 12,\n label = "' % bgcolor)
fo.write('\\nDigraph3 (graphviz)\\n R. Bisdorff, 2020", size="')
fo.write(graphSize),fo.write('",fontsize=%d];\n' % fontSize)
# nodes
for x in actionKeys:
if WithRatingDecoration:
if x in digraph.profiles:
cat = digraph.profiles[x]['category']
if digraph.LowerClosed:
nodeName = digraph.categories[cat]['lowLimit'] + ' -'
else:
nodeName = '- ' +digraph.categories[cat]['highLimit']
node = '%s [shape = "box", fillcolor=lightcoral, style=filled, label = "%s", fontsize=%d];\n'\
% (str(x),nodeName,fontSize)
else:
try:
nodeName = digraph.actions[x]['shortName']
except:
nodeName = str(x)
node = '%s [shape = "circle", label = "%s", fontsize=%d];\n'\
% (str(_safeName(x)),_safeName(nodeName),fontSize)
elif WithBestPathDecoration:
try:
nodeName = digraph.actions[x]['shortName']
except:
nodeName = str(x)
if x in digraph.optimalPath:
node = '%s [shape = "circle", fillcolor=lightcoral, style=filled, label = "%s", fontsize=%d];\n'\
% (str(_safeName(x)),_safeName(nodeName),fontSize)
else:
node = '%s [shape = "circle", label = "%s", fontsize=%d];\n'\
% (str(_safeName(x)),_safeName(nodeName),fontSize)
else:
try:
nodeName = digraph.actions[x]['shortName']
except:
nodeName = str(x)
node = '%s [shape = "circle", label = "%s", fontsize=%d];\n'\
% (str(_safeName(x)),_safeName(nodeName),fontSize)
fo.write(node)
# same ranks for Hasses equivalence classes
k = len(rankingByChoosing)
for i in range(k):
sameRank = 'subgraph { rank=same; '
ich = rankingByChoosing[i][1]
for x in ich:
sameRank += str(_safeName(x))+'; '
sameRank += '}\n'
print(i,sameRank)
fo.write(sameRank)
# open transitive links and write the positive arcs
#if WithBestPathDecoration:
# relation = digraph.closeTransitive(Reverse=False,InSite=False)
#else:
relation = digraph.closeTransitive(Reverse=True,InSite=False)
for i in range(k-1):
ich = rankingByChoosing[i][1]
for x in ich:
for j in range(i+1,k):
jch = rankingByChoosing[j][1]
for y in jch:
#edge = 'n'+str(i+1)+'-> n'+str(i+2)+' [dir=forward,style="setlinewidth(1)",color=black, arrowhead=normal] ;\n'
if WithBestPathDecoration:
if x in digraph.optimalPath and y in digraph.optimalPath:
arcColor = 'blue'
lineWidth = 2
if relation[x][y] > digraph.valuationdomain['med']:
#arcColor = 'black'
edge = '%s-> %s [label="%.0f",style="setlinewidth(%d)",color=%s] ;\n' %\
(_safeName(x),_safeName(y),digraph.costs[x][y],lineWidth,arcColor)
fo.write(edge)
elif relation[y][x] > digraph.valuationdomain['med']:
#arcColor = 'black'
edge = '%s-> %s [label="%.0f",style="setlinewidth(%d)",color=%s] ;\n' %\
(_safeName(y),_safeName(x),digraph.costs[y][x],lineWidth,arcColor)
fo.write(edge)
else:
arcColor= 'grey'
lineWidth = 1
if relation[x][y] > digraph.valuationdomain['med']:
#arcColor = 'black'
edge = '%s-> %s [taillabel="%.0f",labelfontsize="9",style="setlinewidth(%d)",color=%s] ;\n' %\
(_safeName(x),_safeName(y),digraph.costs[x][y],lineWidth,arcColor)
fo.write(edge)
elif relation[y][x] > digraph.valuationdomain['med']:
#arcColor = 'black'
edge = '%s-> %s [taillabel="%.0f",labelfontsize="9",style="setlinewidth(%d)",color=%s] ;\n' %\
(_safeName(y),_safeName(x),digraph.costs[y][x],lineWidth,arcColor)
fo.write(edge)
else:
if relation[x][y] > digraph.valuationdomain['med']:
arcColor = 'black'
if ArrowHeads:
edge = '%s-> %s [style="setlinewidth(%d)",color=%s] ;\n' %\
(_safeName(x),_safeName(y),1,arcColor)
else:
edge = '%s-> %s [style="setlinewidth(%d)",color=%s,arrowhead=none] ;\n' %\
(_safeName(x),_safeName(y),1,arcColor)
fo.write(edge)
elif relation[y][x] > digraph.valuationdomain['med']:
arcColor = 'black'
if ArrowHeads:
edge = '%s-> %s [style="setlinewidth(%d)",color=%s] ;\n' %\
(_safeName(y),_safeName(x),1,arcColor)
else:
edge = '%s-> %s [style="setlinewidth(%d)",color=%s,arrowhead=none] ;\n' %\
(_safeName(y),_safeName(x),1,arcColor)
fo.write(edge)
fo.write('}\n \n')
fo.close()
commandString = 'dot -Grankdir=TB -T'+graphType+' ' +dotName+\
' -o '+name+'.'+graphType
#commandString = 'dot -T'+graphType+' ' +dotName+' -o '+name+'.'+graphType
if Comments:
print(commandString)
try:
os.system(commandString)
except:
if Comments:
print('graphViz tools not avalaible! Please check installation.')
class RankingsFusionDigraph(TransitiveDigraph):
"""
Specialization of the abstract TransitiveDigraph class for
digraphs resulting from the epistemic
disjunctive or conjunctive fusion (omax|omin operator) of a list of rankings.
*Parameters*:
* other = either a Digraph or a PerformanceTableau object;
* fusionOperator = 'o-max' (default) | 'o-min' : Disjunctive, resp. conjuntive epistemic fusion.
Example application:
>>> from transitiveDigraphs import RankingsFusionDigraph
>>> from sparseOutrankingDigraphs import PreRankedOutrankingDigraph
>>> t = RandomPerformanceTableau(seed=1)
>>> pr = PreRankedOutrankingDigraph(t,10,quantilesOrderingStrategy='average')
>>> r1 = pr.boostedRanking
>>> pro = PreRankedOutrankingDigraph(t,10,quantilesOrderingStrategy='optimistic')
>>> r2 = pro.boostedRanking
>>> prp = PreRankedOutrankingDigraph(t,10,quantilesOrderingStrategy='pessimistic')
>>> r3 = prp.boostedRanking
>>> wqr = RankingsFusionDigraph(pr,[r1,r2,r3])
>>> wqr.boostedRanking
['a07', 'a10', 'a06', 'a11', 'a02', 'a08', 'a04', 'a03', 'a01', 'a09', 'a12', 'a13', 'a05']
"""
def __init__(self,other,rankings,fusionOperator='o-max',Debug=False):
from digraphsTools import ranking2preorder, omax, omin
from copy import deepcopy
from decimal import Decimal
if Debug:
print(rankings)
if len(rankings) < 1:
print('Error: several rankings have to be provided!')
return
self.__dict__ = deepcopy(other.__dict__)
self.order = len(self.actions)
self.name = other.name + '_wk'
self.rankings = rankings
self.fusionOperator = fusionOperator
self.valuationdomain = {}
self.valuationdomain['min'] = Decimal('-1')
self.valuationdomain['max'] = Decimal('1')
self.valuationdomain['med'] = Decimal('0')
Med = self.valuationdomain['med']
relations = []
for rel in rankings:
if Debug:
print(rel)
relations.append(self.computePreorderRelation(ranking2preorder(rel)))
if Debug:
print(relations)
relation = {}
for x in self.actions:
relation[x] = {}
for y in self.actions:
L = [relations[i][x][y] for i in range(len(relations))]
if fusionOperator == 'o-max':
relation[x][y] = omax(Med,L)
elif fusionOperator == 'o-min':
relation[x][y] = omin(Med,L)
else:
print('Error: incorrect fusion operator %s' % fusionOperator)
return
if Debug:
print(x,y,L,relation[x][y])
if Debug:
print(relation)
self.relation = relation
self.gamma = self.gammaSets()
self.notGamma = self.notGammaSets()
class RankingsFusion(RankingsFusionDigraph):
"""
Obsolete dummy for the RankingsFusionDigraph class
"""
class KemenyOrdersFusion(TransitiveDigraph):
"""
Specialization of the abstract TransitiveDigraph class for
transitive digraphs resulting from the epistemic
disjunctive (default) or conjunctive fusion of
all potential Kemeny linear orderings.
*Parameter*:
* fusionOperator = 'o-max' (default) | 'o-min' : Disjunctive, resp. conjuntive epistemic fusion.
"""
def __init__(self,other,orderLimit=7,fusionOperator='o-max',
Debug=False):
if other.order > orderLimit:
print('Digraph order %d to high. The default limit (7) may be changed with the oderLimit argument.')
return
from digraphsTools import ranking2preorder, omax, omin
from copy import deepcopy
from decimal import Decimal
self.__dict__ = deepcopy(other.__dict__)
self.name = other.name + '_wk'
self.valuationdomain['min'] = Decimal('-1')
self.valuationdomain['max'] = Decimal('1')
self.valuationdomain['med'] = Decimal('0')
Med = self.valuationdomain['med']
#relation = copy(other.relation)
if self.computeKemenyRanking(orderLimit=orderLimit,Debug=False) is None:
# [0] = ordered actions list, [1] = maximal Kemeny index
print('Intantiation error: unable to compute the Kemeny Order !!!')
print('Digraph order %d is required to be lower than 8!' % n)
return
kemenyRankings = self.maximalRankings
if Debug:
print(kemenyRankings)
relations = []
for rel in kemenyRankings:
#print(rel)
relations.append(self.computePreorderRelation(ranking2preorder(rel)))
if Debug:
print(relations)
relation = {}
for x in self.actions:
relation[x] = {}
for y in self.actions:
L = [relations[i][x][y] for i in range(len(relations))]
if fusionOperator == 'o-max':
relation[x][y] = omax(Med,L)
elif fusionOperator == 'o-min':
relation[x][y] = omin(Med,L)
else:
print('Error: incorrect fusion operator %s' % fusionOperator)
return
if Debug:
print(x,y,L,relation[x][y])
if Debug:
print(relation)
self.relation = relation
#print(self.relation)
self.gamma = self.gammaSets()
self.notGamma = self.notGammaSets()
# myThread for KohlerArrawRaynaudFusion
## if Threading:
## from multiprocessing import Process, Lock, active_children, cpu_count
class _myKARThread(Process):
def __init__(self, threadID, name, direction, tempDirName, Debug):
Process.__init__(self)
self.threadID = threadID
self.name = name
self.direction = direction
self.workingDirectory = tempDirName
self.Debug = Debug
def run(self):
from linearOrders import KohlerOrder
from pickle import dumps, loads
from os import chdir
chdir(self.workingDirectory)
from sys import setrecursionlimit
setrecursionlimit(2**20)
if self.Debug:
print("Starting working in %s on %s" % (self.workingDirectory, self.name))
#threadLock.acquire()
fi = open('dumpDigraph.py','rb')
digraph = loads(fi.read())
fi.close()
if self.direction == 'best':
fo = open('ko.py','wb')
ko = KohlerOrder(digraph)
fo.write(dumps(ko.relation,-1))
elif self.direction == 'worst':
fo = open('ar.py','wb')
ar = KohlerOrder((~(-digraph)))
fo.write(dumps(ar.relation,-1))
fo.close()
#threadLock.release()
class KohlerArrowRaynaudFusion(TransitiveDigraph):
"""
Specialization of the abstract TransitiveDigraph class for
ranking-by-choosing orderings resulting from the epistemic
disjunctive (o-max) or conjunctive (o-min) fusion of a
Kohler linear best ordering and an Arrow-Raynaud linear worst ordering.
"""
def __init__(self,outrankingDigraph,
fusionOperator='o-max',
Threading=True,
Debug=False):
from digraphsTools import ranking2preorder, omax, omin
from copy import copy as deepcopy
from pickle import dumps, loads, load
from linearOrders import KohlerOrder
self.Debug=Debug
self.Threading = Threading
digraph=deepcopy(outrankingDigraph)
digraph.recodeValuation(-1.0,1.0)
self.name = digraph.name
#self.__class__ = digraph.__class__
self.actions = deepcopy(digraph.actions)
self.order = len(self.actions)
self.valuationdomain = deepcopy(digraph.valuationdomain)
self.originalRelation = digraph.relation
if Threading and cpu_count()>2:
print('Threading ...')
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tempDirName:
digraphFileName = tempDirName +'/dumpDigraph.py'
if Debug:
print('temDirName, digraphFileName', tempDirName,digraphFileName)
fo = open(digraphFileName,'wb')
pd = dumps(digraph,-1)
fo.write(pd)
fo.close()
threadBest = _myKARThread(1,"ComputeBest","best",tempDirName,Debug)
threadWorst = _myKARThread(2,"ComputeWorst","worst",tempDirName,Debug)
threadBest.start()
threadWorst.start()
while active_children() != []:
pass
print('Exiting computing threads')
koFileName = tempDirName +'/ko.py'
fi = open(koFileName,'rb')
KohlerRelation = loads(fi.read())
fi.close()
arFileName = tempDirName + '/ar.py'
fi = open(arFileName,'rb')
ArrowRaynaudRelation = loads(fi.read())
fi.close()
else:
ko = KohlerOrder(digraph)
ar = KohlerOrder((~(-digraph)))
KohlerRelation = deepcopy(ko.relation)
ArrowRaynaudRelation = deepcopy(ar.relation)
if Debug:
print('Kohler = ', KohlerRelation)
print('ArrowRaynaud = ', ArrowRaynaudRelation)
relation = {}
Med = self.valuationdomain['med']
for x in self.actions:
relation[x] = {}
for y in self.actions:
L = [KohlerRelation[x][y],ArrowRaynaudRelation[x][y]]
if fusionOperator == "o-max":
relation[x][y] = omax(Med,L)
elif fusionOperator == "o-min":
relation[x][y] = omin(Med,L)
else:
print('Error: invalid epistemic fusion operator %s' % fusionOperator)
return
if Debug:
print('!',x,y,KohlerRelation[x][y],
ArrowRaynaudRelation[x][y],relFusion[x][y])
self.relation=deepcopy(relation)
self.gamma = self.gammaSets()
self.notGamma = self.notGammaSets()
#---------------------
# my Thread for the RankingByChoosing class
class _myRBCThread(Process):
def __init__(self, threadID, name, direction, tempDirName, CoDual, Debug):
Process.__init__(self)
self.threadID = threadID
self.name = name
self.direction = direction
self.workingDirectory = tempDirName
self.CoDual = CoDual
self.Debug = Debug
def run(self):
from pickle import dumps, loads
from os import chdir
chdir(self.workingDirectory)
from sys import setrecursionlimit
setrecursionlimit(2**20)
Debug = self.Debug
CoDual = self.CoDual
if Debug:
print("Starting working in %s on %s" % (self.workingDirectory, self.name))
#threadLock.acquire()
fi = open('dumpDigraph.py','rb')
digraph = loads(fi.read())
fi.close()
if self.direction == 'best':
fo = open('rbbc.py','wb')
rbbc = digraph.computeRankingByBestChoosing(CoDual=CoDual,Debug=Debug)
fo.write(dumps(rbbc,-1))
elif self.direction == 'worst':
fo = open('rbwc.py','wb')
rbwc = digraph.computeRankingByLastChoosing(CoDual=CoDual,Debug=Debug)
fo.write(dumps(rbwc,-1))
fo.close()
class RankingByChoosingDigraph(TransitiveDigraph):
"""
Specialization of the abstract TransitiveDigraph class for
ranking-by-Rubis-choosing orderings.
Example python3 session:
>>> from outrankingDigraphs import *
>>> t = RandomCBPerformanceTableau(numberOfActions=7,
... numberOfCriteria=5,
... weightDistribution='equiobjectives')
>>> g = BipolarOutrankingDigraph(t,Normalized=True)
>>> g.showRelationTable()
* ---- Relation Table -----
r | 'a1' 'a2' 'a3' 'a4' 'a5' 'a6' 'a7'
-----|------------------------------------------------------------
'a1' | +1.00 +1.00 +0.67 +0.33 +0.33 -0.17 +0.00
'a2' | -1.00 +1.00 +0.00 +0.00 +1.00 +0.00 +0.50
'a3' | -0.33 +0.00 +1.00 +0.17 +0.17 -0.17 +0.00
'a4' | +0.00 +0.00 +0.50 +1.00 +0.17 -0.33 -0.50
'a5' | -0.33 -1.00 +0.00 -0.17 +1.00 +0.17 +0.00
'a6' | +0.17 +0.00 +0.42 +0.33 -0.17 +1.00 +0.00
'a7' | +0.00 +0.42 +0.00 +0.50 +0.00 +0.00 +1.00
Valuation domain: [-1.000; 1.000]
>>> from transitiveDigraphs import RankingByChoosingDigraph
>>> rbc = RankingByChoosingDigraph(g)
Threading ...
Exiting computing threads
>>> rbc.showTransitiveDigraph()
Ranking by Choosing and Rejecting
1st ranked ['a3', 'a5', 'a6']
2nd ranked ['a4']
2nd last ranked ['a7'])
1st last ranked ['a1', 'a2'])
>>> rbc.showOrderedRelationTable(direction="decreasing")
Decreasing Weak Ordering
Ranking by recursively best-choosing
1st Best Choice ['a3', 'a6'] (0.07)
2nd Best Choice ['a5'] (0.08)
3rd Best Choice ['a1', 'a4'] (0.17)
4th Best Choice ['a7'] (-0.67)
5th Best Choice ['a2'] (1.00)
* ---- Relation Table -----
S | 'a3' 'a6' 'a5' 'a1' 'a4' 'a7' 'a2'
------|-------------------------------------------
'a3' | - 0.00 0.00 0.67 0.33 0.00 1.00
'a6' | 0.00 - 0.00 0.00 0.00 0.00 0.17
'a5' | 0.00 0.00 - 0.33 0.25 0.17 0.17
'a1' | -0.67 0.00 -0.33 - 0.00 0.00 0.00
'a4' | 0.00 0.00 0.00 0.00 - 0.33 0.33
'a7' | 0.00 0.00 0.00 0.00 0.00 - 0.67
'a2' | -1.00 -0.17 -0.17 0.00 -0.33 -0.67 -
Valuation domain: [-1.00;1.00]
"""
def __repr__(self):
"""
Presentation method for RankingByChoosing Digraph instance.
"""
String = '*----- Object instance description -----------*\n'
String += 'Instance class : %s\n' % self.__class__.__name__
String += 'Instance name : %s\n' % self.name
String += 'Actions : %d\n' % len(self.actions)
String += 'Valuation domain : [%.2f-%.2f]\n' %\
(self.valuationdomain['min'],self.valuationdomain['max'])
String += 'Size : %d\n' % self.computeSize()
String += 'Attributes: %s\n' % list(self.__dict__.keys())
String += 'Determinateness (%%) : %.1f\n' %\
self.computeDeterminateness(InPercents=True)
String += '*------ Constructor run times (in sec.) ------*\n'
try:
String += 'Threads : %d\n' % self.nbrThreads
except:
pass
String += 'Total time : %.5f\n' % self.runTimes['totalTime']
String += 'Data input : %.5f\n' % self.runTimes['dataInput']
String += 'Ranking-by-choosing : %.5f\n' % self.runTimes['bestLast']
String += 'Compute fusion : %.5f\n' % self.runTimes['fusing']
String += 'Store results : %.5f\n' % self.runTimes['storing']
return String
def __init__(self,other,
fusionOperator = "o-max",
CoDual=False,
Debug=False,
#CppAgrum=False,
Threading=True):
from digraphsTools import ranking2preorder, omax, omin
from copy import copy, deepcopy
from pickle import dumps, loads, load
from time import time
self.CoDual=CoDual
self.Debug=Debug
#self.CppAgrum = CppAgrum
self.Threading = Threading
runTimes = {}
t0 = time()
#if Threading:
digraph=deepcopy(other)
digraph.recodeValuation(-1.0,1.0)
self.name = digraph.name
#self.__class__ = digraph.__class__
self.actions = copy(digraph.actions)
self.order = len(self.actions)
self.valuationdomain = digraph.valuationdomain
self.originalRelation = digraph.relation
runTimes['dataInput'] = time() - t0
# compute ranking by best and by last choosing
t1 = time()
if Threading and cpu_count()>2:
print('Threading ...')
self.nbrThreads = 2
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tempDirName:
digraphFileName = tempDirName +'/dumpDigraph.py'
if Debug:
print('temDirName, digraphFileName', tempDirName,digraphFileName)
fo = open(digraphFileName,'wb')
pd = dumps(digraph,-1)
fo.write(pd)
fo.close()
threadBest = _myRBCThread(1,"ComputeBest","best",tempDirName,CoDual,Debug)
threadWorst = _myRBCThread(2,"ComputeWorst","worst",tempDirName,CoDual,Debug)
threadBest.start()
threadWorst.start()
while active_children() != []:
pass
print('Exiting computing threads')
rbbcFileName = tempDirName +'/rbbc.py'
fi = open(rbbcFileName,'rb')
digraph.rankingByBestChoosing = loads(fi.read())
fi.close()
rbwcFileName = tempDirName + '/rbwc.py'
fi = open(rbwcFileName,'rb')
digraph.rankingByLastChoosing = loads(fi.read())
fi.close()
else:
self.nbrThreads = 1
from sys import setrecursionlimit
setrecursionlimit(2**20)
digraph.computeRankingByBestChoosing(CoDual=CoDual,Debug=Debug)
digraph.computeRankingByLastChoosing(CoDual=CoDual,Debug=Debug)
setrecursionlimit(1000)
runTimes['bestLast'] = time() - t1
# compute ranking fusion
t2 = time()
relBest = digraph.computeRankingByBestChoosingRelation()
if Debug:
digraph.showRankingByBestChoosing()
relLast = digraph.computeRankingByLastChoosingRelation()
if Debug:
digraph.showRankingByLastChoosing()
relFusion = {}
Med = digraph.valuationdomain['med']
for x in digraph.actions:
relFusion[x] = {}
fx = relFusion[x]
bx = relBest[x]
lx = relLast[x]
for y in digraph.actions:
L = [bx[y],lx[y]]
if fusionOperator == "o-max":