-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsparseOutrankingDigraphs.py
More file actions
3143 lines (2898 loc) · 135 KB
/
sparseOutrankingDigraphs.py
File metadata and controls
3143 lines (2898 loc) · 135 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
# -*- coding: utf-8 -*-
"""
Digraph3 collection of python3 modules for Algorithmic Decision Theory applications
Module for sparse outranking digraph model implementations
Copyright (C) 2016-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 ANY 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.13"
from outrankingDigraphs import *
from sortingDigraphs import *
from time import time
from decimal import Decimal
from sparseOutrankingDigraphs import *
class SparseOutrankingDigraph(BipolarOutrankingDigraph):
"""
Abstract root class for linearly decomposed sparse digraphs.
"""
def __init__():
print('Abstract root class')
def __repr__(self):
"""
Default presentation method for pre-ranked sparse digraphs instances.
"""
reprString = '*----- Object instance description ------*\n'
reprString += 'Instance class : %s\n' % self.__class__.__name__
reprString += 'Instance name : %s\n' % self.name
reprString += 'Actions : %d\n' % self.order
reprString += 'Criteria : %d\n' % self.dimension
reprString += 'Sorting by : %d-Tiling\n' \
% self.sortingParameters['limitingQuantiles']
reprString += 'Ordering strategy : %s\n' \
% self.sortingParameters['strategy']
reprString += 'Ranking rule : %s\n' % self.componentRankingRule
reprString += 'Components : %d\n' % self.nbrComponents
reprString += 'Minimal order : %d\n' % self.minimalComponentSize
reprString += 'Maximal order : %d\n' % self.maximalComponentSize
reprString += 'Average order : %.1f\n' \
% (self.order/self.nbrComponents)
reprString += 'fill rate : %.3f%%\n' % (self.fillRate*100.0)
reprString += 'Attributes : %s\n' % list(self.__dict__.keys())
reprString += '---- Constructor run times (in sec.) ----\n'
try:
reprString += 'Threads : %d\n' % self.nbrThreads
except:
self.nbrThreads = 0
reprString += 'Threads : %d\n' % self.nbrThreads
try:
reprString += 'Start method : %s\n' % self.startMethod
except:
self.startMethod = None
reprString += 'Start method : %s\n' % self.startMethod
reprString += 'Total time : %.5f\n' % self.runTimes['totalTime']
reprString += 'Data imput : %.5f\n' % self.runTimes['dataInput']
reprString += 'QuantilesSorting : %.5f\n' % self.runTimes['sorting']
reprString += 'Preordering : %.5f\n' \
% self.runTimes['preordering']
reprString += 'Decomposing : %.5f\n' \
% self.runTimes['decomposing']
try:
reprString += 'Ordering : %.5f\n' \
% self.runTimes['ordering']
except:
pass
return reprString
def relation(self,x,y,Debug=False):
"""
Dynamic construction of the global outranking characteristic function *r(x S y)*.
"""
Min = self.valuationdomain['min']
Med = self.valuationdomain['med']
Max = self.valuationdomain['max']
if x == y:
return Med
cx = self.actions[x]['component']
cy = self.actions[y]['component']
#print(x,cx,y,cy)
if cx == cy:
return self.components[cx]['subGraph'].relation[x][y]
elif self.components[cx]['rank'] > self.components[cy]['rank']:
return Min
else:
return Max
def computeDeterminateness(self):
"""
Computes the Kendalll distance in % of self
with the all median valued (indeterminate) digraph.
"""
Max = self.valuationdomain['max']
Med = self.valuationdomain['med']
actions = self.actions
relation = self.relation
order = self.order
deter = Decimal('0.0')
for x in actions:
for y in actions:
if x != y:
deter += abs(relation(x,y) - Med)
deter = ( Decimal(str(deter)) / Decimal(str((order * (order-1)))) )
return deter/(Decimal(str(Max-Med)))*Decimal('100')
def computeOrderCorrelation(self, order, Debug=False):
"""
Renders the ordinal correlation K of a sparse digraph instance
when compared with a given linear order (from worst to best) of its actions
K = sum_{x != y} [ min( max(-self.relation(x,y)),other.relation(x,y), max(self.relation(x,y),-other.relation(x,y)) ]
K /= sum_{x!=y} [ min(abs(self.relation(x,y),abs(other.relation(x,y)) ]
.. note::
Renders a dictionary with the key 'correlation' containing the actual bipolar correlation index and the key 'determination' containing the minimal determination level D of self and the other relation.
D = sum_{x != y} min(abs(self.relation(x,y)),abs(other.relation(x,y)) / n(n-1)
where n is the number of actions considered.
The correlation index with a completely indeterminate relation
is by convention 0.0 at determination level 0.0 .
.. warning::
self must be a normalized outranking digraph instance !
"""
selfMax = self.valuationdomain['max']
if selfMax != Decimal('1'):
print("Error: self's valuationdomain must be normalized !")
return
n = len(order)
corrSum = Decimal('0')
determSum = Decimal('0')
for i in range(n):
x = order[i]
for j in range(i+1,n):
y = order[j]
# x < y
selfRelation = self.relation(x,y)
otherRelation = -selfMax
corr = min( max(-selfRelation,otherRelation),
max(selfRelation,-otherRelation) )
corrSum += corr
determ = min( abs(selfRelation),abs(otherRelation) )
determSum += determ
# y > x
selfRelation = self.relation(y,x)
otherRelation = selfMax
corr = min( max(-selfRelation,otherRelation),
max(selfRelation,-otherRelation) )
corrSum += corr
determ = min( abs(selfRelation),abs(otherRelation) )
determSum += determ
if determSum > 0:
correlation = corrSum / determSum
n2 = (self.order*self.order) - self.order
determination = determSum / Decimal(str(n2))
determination /= selfMax
return { 'correlation': correlation,\
'determination': determination }
else:
return { 'correlation': 0.0,\
'determination': 0.0 }
def estimateRankingCorrelation(self,sampleSize=100,seed=1,Debug=False):
import random
random.seed(seed)
actionKeys = [x for x in self.actions]
sample = random.sample(actionKeys,sampleSize)
if Debug:
print(sample)
preRankedSample = []
for x in self.boostedRanking:
if x in sample:
preRankedSample.append(x)
if Debug:
print(preRankedSample)
ptp = PartialPerformanceTableau(self,sample)
from outrankingDigraphs import BipolarOutrankingDigraph
pg = BipolarOutrankingDigraph(ptp,Normalized=True)
corr = pg.computeRankingCorrelation(preRankedSample)
return corr
def sortingRelation(self,x,y,Debug=False):
"""
Dynamic construction of the quantiles sorting characteristic function *r(x QS y)*.
"""
Min = self.valuationdomain['min']
Med = self.valuationdomain['med']
Max = self.valuationdomain['max']
if x == y:
return Med
cx = self.actions[x]['component']
cy = self.actions[y]['component']
#print(x,cx,y,cy)
if cx == cy:
return Med
elif self.components[cx]['rank'] > self.components[cy]['rank']:
return Min
else:
return Max
def showRelationMap(self,fromIndex=None,toIndex=None,
symbols=None,actionsList=None):
"""
Prints on the console, in text map format, the location of
the diagonal outranking components of the sparse outranking digraph.
By default, symbols = {'max':'┬','positive': '+', 'median': ' ',
'negative': '-', 'min': '┴'}
Example::
>>> from sparseOutrankingDigraphs import *
>>> t = RandomCBPerformanceTableau(numberOfActions=50,seed=1)
>>> bg = PreRankedOutrankingDigraph(t,quantiles=10,minimalComponentSize=5)
>>> print(bg)
*----- show short --------------*
Instance name : randomCBperftab_mp
# Actions : 50
# Criteria : 7
Sorting by : 10-Tiling
Ordering strategy : average
Ranking Rule : Copeland
# Components : 7
Minimal size : 5
Maximal size : 13
Median size : 6
fill rate : 16.898%
---- Constructor run times (in sec.) ----
Total time : 0.08494
QuantilesSorting : 0.04339
Preordering : 0.00034
Decomposing : 0.03989
Ordering : 0.00024
>>> bg.showRelationMap()
┬+++┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴ ++┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
+ ++┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
--- -┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
-┴-+ ┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴ ┬-+┬+┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴ +┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴+ + ┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴-+- ++┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴ + ┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴ - ┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴ +++-+++++┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴+ +++++++++-+┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴+- +--+++++++┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴--+ -++++++-+┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴++++ +- ++ ┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴--+-+ +++++++┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴-+-++- ++++--┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴-++-++- + -+-┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴---- ++- + ++┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴-+--++++- -++┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴--- --+++ ++┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴+-+-++-+-+ +┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴-+- -+++-++ ┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴ - + + ┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴ -+ + ++┬++┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴++ +++++++++┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴ -- -+-++ ┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴++++ ++++++-┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴----- ++-┬+┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴ +++- -++-+┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴-----++ -++┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴ +-+-+-+ -++┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴+ +++ ┬+┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴-- --+++ -┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴--┴+ -┴--+ ┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴ +++++++┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴+ +++-+┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴-- +++┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴-- ++┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴+-+ +++┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴ +- + --┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴---+++ +┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴- ┴-+++ ┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴ ┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴ ++ ┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴ - -┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴ -+ ┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴ ┴ ┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴
Component ranking rule: Copeland
>>>
"""
if symbols is None:
symbols = {'max':'┬','positive': '+', 'median': ' ',
'negative': '-', 'min': '┴'}
relation = self.relation
Max = self.valuationdomain['max']
Med = self.valuationdomain['med']
Min = self.valuationdomain['min']
if actionsList is None:
ranking = self.boostedRanking
else:
ranking = actionsList
if fromIndex is None:
fromIndex = 0
if toIndex is None:
toIndex = len(ranking)
for x in ranking[fromIndex:toIndex]:
pictStr = ''
for y in ranking[fromIndex:toIndex]:
if relation(x,y) == Max:
pictStr += symbols['max']
elif relation(x,y) == Min:
pictStr += symbols['min']
elif relation(x,y) > Med:
pictStr += symbols['positive']
elif relation(x,y) ==Med:
pictStr += symbols['median']
elif relation(x,y) < Med:
pictStr += symbols['negative']
print(pictStr)
if actionsList is None:
print('Component ranking rule: %s' % self.componentRankingRule)
else:
print('List of actions provided.')
def showHTMLMarginalQuantileLimits(self,htmlFileName=None):
"""
shows the marginal quantiles limits.
"""
for x in self.profiles:
catKey = self.profiles[x]['category']
self.profiles[x]['shortName']= '%.2f' \
% self.categories[catKey]['quantile']
self.showHTMLPerformanceTableau(actionsSubset=self.profiles,
title='Marginal performance quantiles',
htmlFileName=htmlFileName)
def showHTMLRelationMap(self,actionsSubset=None,
Colored=True,
tableTitle='Relation Map',
relationName='r(x S y)',
symbols=['+','·',' ','–','—'],
htmlFileName=None,
):
"""
Launches a browser window with the colored relation map of self.
"""
import webbrowser
if htmlFileName == None:
from tempfile import NamedTemporaryFile
fileName = (NamedTemporaryFile(suffix='.html',
delete=False,dir='.')).name
else:
from os import getcwd
fileName = getcwd()+'/'+htmlFileName
fo = open(fileName,'w')
fo.write(self.htmlRelationMap(actionsSubset=None,
Colored=Colored,
tableTitle=tableTitle,
symbols=symbols,
ContentCentered=True,
relationName=relationName))
fo.close()
url = 'file://'+fileName
webbrowser.open(url,new=2)
def _showHTMLRelationTable(self):
"""
Not yet availbale !
"""
print('Method not yet implemented for This class of digraphs!')
print('Try instead: self.showRelationTable()')
def showHTMLRelationTable(self,actionsList=None,
#relation=None,
IntegerValues=False,
ndigits=2,
Colored=True,
tableTitle='Valued Sparse Relation Table',
relationName='r(x,y)',
ReflexiveTerms=False,
fromIndex=None,
toIndex=None,
htmlFileName=None):
"""
Launches a browser window with the colored relation table of self.
"""
import webbrowser
if htmlFileName == None:
from tempfile import NamedTemporaryFile
fileName = (NamedTemporaryFile(suffix='.html',
delete=False,dir='.')).name
else:
from os import getcwd
fileName = getcwd()+'/'+htmlFileName
fo = open(fileName,'w')
fo.write(self._htmlRelationTable(actionsSubset=actionsList,
#relation=relation,
isColored=Colored,
ndigits=ndigits,
hasIntegerValues=IntegerValues,
tableTitle=tableTitle,
relationName=relationName,
ReflexiveTerms=ReflexiveTerms,
fromIndex=fromIndex,
toIndex=toIndex))
fo.close()
url = 'file://'+fileName
webbrowser.open(url,new=2)
def _htmlRelationTable(self,tableTitle='Valued Sparse Relation Table',
#relation=None,
relationName='r(x,y)',
ndigits=2,
hasIntegerValues=False,
actionsSubset= None,
isColored=False,
ReflexiveTerms=False,
fromIndex=None,
toIndex=None):
"""
renders the relation valuation in actions X actions html table format.
"""
Med = self.valuationdomain['med']
Min = self.valuationdomain['min']
Max = self.valuationdomain['max']
if actionsSubset is None:
actions = self.boostedRanking
else:
actions = actionsSubset
#if relation is None:
relation = self.relation # dynamic function
s = ''
s += '<h1>%s</h1>' % tableTitle
s += '<table border="1">'
if isColored:
s += '<tr bgcolor="#9acd32"><th>%s</th>' % relationName
else:
s += '<tr><th>%s</th>' % relationName
actionKeys = [x for x in actions]
if fromIndex is None:
fromIndex = 0
if toIndex is None:
toIndex = len(actionKeys)
actionsList = []
for x in actionKeys[fromIndex:toIndex]:
if isinstance(x,frozenset):
try:
actionsList += [(actions[x]['shortName'],x)]
except:
actionsList += [(actions[x]['name'],x)]
else:
actionsList += [(str(x),x)]
## if actionsSubset is None:
## actionsList.sort()
#print actionsList
#actionsList.sort()
if not hasIntegerValues:
try:
hasIntegerValuation = self.valuationdomain['hasIntegerValuation']
except KeyError:
hasIntegerValuation = hasIntegerValues
self.valuationdomain['hasIntegerValuation'] = hasIntegerValuation
else:
hasIntegerValuation = hasIntegerValues
self.valuationdomain['hasIntegerValuation'] = hasIntegerValuation
for x in actionsList:
if isColored:
s += '<th bgcolor="#FFF79B">%s</th>' % (x[0])
else:
s += '<th>%s</th>' % (x[0])
s += '</tr>'
for x in actionsList:
s += '<tr>'
if isColored:
s += '<th bgcolor="#FFF79B">%s</th>' % (x[0])
else:
s += '<th>%s</th>' % (x[0])
for y in actionsList:
if x == y:
if ReflexiveTerms:
if hasIntegerValuation:
if isColored:
if relation(x[1],y[1]) > Med:
s += '<td bgcolor="#ddffdd" align="right">%d</td>' \
% (relation(x[1],y[1]))
elif relation(x[1],y[1]) < Med:
s += '<td bgcolor="#ffddff" align="right">%d</td>' \
% (relation(x[1],y[1]))
else:
s += '<td bgcolor="#dddddd" align="right" >%d</td>' \
% (relation(x[1],y[1]))
else:
s += '<td>%d</td>' % (relation(x[1],y[1]))
else:
ndigitsFormat = '%%2.%df' % ndigits
if isColored:
if relation(x[1],y[1]) > Med:
formatStr \
= '<td bgcolor="#ddffdd" align="right">%s</td>' \
% ndigitsFormat
s += formatStr % (relation(x[1],y[1]))
elif relation(x[1],y[1]) < Med:
formatStr \
= '<td bgcolor="#ffddff" align="right">%s</td>' \
% ndigitsFormat
s += formatStr % (relation(x[1],y[1]))
else:
formatStr \
= '<td bgcolor="#dddddd" align="right">%s</td>' \
% ndigitsFormat
s += formatStr % (relation(x[1],y[1]))
else:
formatStr = '<td>%s</td>' % ndigitsFormat
s += formatStr % (relation(x[1],y[1]))
else:
s += '<td bgcolor="#eeeeee" align="center"> – </td>'
else:
cx = self.actions[x[1]]['component']
cy = self.actions[y[1]]['component']
if hasIntegerValuation:
if cx == cy and isColored:
if relation(x[1],y[1]) > Med:
s += '<td bgcolor="#ddffdd" align="right">%d</td>' \
% (relation(x[1],y[1]))
elif relation(x[1],y[1]) < Med:
s += '<td bgcolor="#ffddff" align="right">%d</td>' \
% (relation(x[1],y[1]))
else:
s += '<td bgcolor="#dddddd" align="right" >%d</td>' \
% (relation[x[1]][y[1]])
elif isColored:
s += '<td bgcolor="#edf5c4" align="right" >%d</td>' \
% (relation(x[1],y[1]))
else:
s += '<td>%d</td>' % (relation(x[1],y[1]))
else:
ndigitsFormat = '%%2.%df' % ndigits
if cx == cy and isColored:
if relation(x[1],y[1]) > Med:
formatStr \
= '<td bgcolor="#ddffdd" align="right">%s</td>' \
% ndigitsFormat
s += formatStr % (relation(x[1],y[1]))
elif relation(x[1],y[1]) < Med:
formatStr \
= '<td bgcolor="#ffddff" align="right">%s</td>' \
% ndigitsFormat
s += formatStr % (relation(x[1],y[1]))
else:
formatStr \
= '<td bgcolor="#dddddd" align="right">%s</td>' \
% ndigitsFormat
s += formatStr % (relation(x[1],y[1]))
elif isColored:
formatStr = '<td bgcolor="#fffbde" align="right">%s</td>' \
% ndigitsFormat
s += formatStr % (relation(x[1],y[1]))
else:
formatStr = '<td>%s</td>' % ndigitsFormat
s += formatStr % (relation(x[1],y[1]))
s += '</tr>'
s += '</table>'
if hasIntegerValuation:
s += '<p>Valuation domain: [%d; %+d]</p>' % (Min,Max)
else:
s += '<p>Valuation domain: [%.2f; %+.2f]</p>' % (Min,Max)
return s
def htmlRelationMap(self,actionsSubset=None,
tableTitle='Relation Map',
relationName='r(x R y)',
symbols=['+','·',' ','-','_'],
Colored=True,
ContentCentered=True):
"""
renders the relation map in actions X actions html table format.
"""
Med = self.valuationdomain['med']
Min = self.valuationdomain['min']
Max = self.valuationdomain['max']
if actionsSubset is None:
actionsList = self.boostedRanking
else:
actionsList = actionsSubset
s = '<!DOCTYPE html><html><head>\n'
s += '<title>%s</title>\n' % 'Digraph3 relation map'
s += '<style type="text/css">\n'
if ContentCentered:
s += 'td {text-align: center;}\n'
s += 'td.na {color: rgb(192,192,192);}\n'
s += '</style>\n'
s += '</head>\n<body>\n'
s += '<h1>%s</h1>' % tableTitle
s += '<table border="0">\n'
if Colored:
s += '<tr bgcolor="#9acd32"><th>%s</th>\n' % relationName
else:
s += '<tr><th>%s</th>' % relationName
for x in actionsList:
if Colored:
s += '<th bgcolor="#FFF79B">%s</th>\n' % (x)
else:
s += '<th>%s</th\n>' % (x)
s += '</tr>\n'
for x in actionsList:
s += '<tr>'
if Colored:
s += '<th bgcolor="#FFF79B">%s</th>\n' % (x)
else:
s += '<th>%s</th>\n' % (x)
for y in actionsList:
if Colored:
if self.relation(x,y) == Max:
s += '<td bgcolor="#66ff66"><b>%s</b></td>\n' % symbols[0]
elif self.relation(x,y) > Med:
s += '<td bgcolor="#ddffdd">%s</td>' % symbols[1]
elif self.relation(x,y) == Min:
s += '<td bgcolor="#ff6666"><b>%s</b></td\n>' % symbols[4]
elif self.relation(x,y) < Med:
s += '<td bgcolor="#ffdddd">%s</td>\n' % symbols[3]
else:
s += '<td bgcolor="#ffffff">%s</td>\n' % symbols[2]
else:
if self.relation(x,y) == Max:
s += '<td><b>%s</b></td>\n' % symbols[0]
elif self.relation(x,y) > Med:
s += '<td>%s</td>\n' % symbols[1]
elif self.relation(x,y) == Min:
s += '<td><b>%s</b></td>\n' % symbols[4]
elif self.relation(x,y) < Med:
s += '<td>\n' % symbols[3]
else:
s += '<td>%s</td>\n' % symbols[2]
s += '</tr>'
s += '</table>\n'
# legend
s += '<span style="font-size: 100%">\n'
s += '<table border="1">\n'
s += '<tr><th align="left" colspan="5">Ranking rules:</th><td align="left" colspan="5">%s, %s quantile ordering</td></tr>\n'\
% (self.componentRankingRule,self.sortingParameters['strategy'])
s += '<tr><th align="left" colspan="10"><i>Symbol legend</i></th></tr>\n'
s += '<tr>'
if Colored:
s \
+= '<td bgcolor="#66ff66" align="center">%s</td><td>certainly valid</td>\n' \
% symbols[0]
s += '<td bgcolor="#ddffdd" align="center">%s</td><td>valid</td>\n' \
% symbols[1]
s += '<td>%s</td><td>indeterminate</td>\n' % symbols[2]
s += '<td bgcolor="#ffdddd" align="center">%s</td><td>invalid</td>\n' \
% symbols[3]
s \
+= '<td bgcolor="#ff6666" align="center">%s</td><td>certainly invalid</td>\n' \
% symbols[4]
else:
s += '<td align="center">%s</td><td>certainly valid</td>\n' % symbols[0]
s += '<td align="center">%s</td><td>valid</td>\n' % symbols[1]
s += '<td align="center">%s</td><td>indeterminate</td>\n' % symbols[2]
s += '<td align="center">%s</td><td>invalid</td>\n' % symbols[3]
s += '<td align="center">%s</td><td>certainly invalid</td>\n' % symbols[4]
s += '</tr>'
s += '</table>\n'
s += '</span>\n'
# html footer
s += '</body>\n'
s += '</html>\n'
return s
def computeOrdinalCorrelation(self, other, Debug=False):
"""
Renders the ordinal correlation K of a SpareOutrakingDigraph instance
when compared with a given compatible (same actions set) other Digraph instance.
K = sum_{x != y} [ min( max(-self.relation(x,y)),other.relation(x,y), max(self.relation(x,y),-other.relation(x,y)) ]
K /= sum_{x!=y} [ min(abs(self.relation(x,y),abs(other.relation(x,y)) ]
.. note::
The global outranking relation of SparesOutrankingDigraph instances is contructed on the fly
from the ordered dictionary of the components.
Renders a dictionary with a 'correlation' key containing the actual bipolar correlation index K and a 'determination' key containing the minimal determination level D of self and the other relation, where
D = sum_{x != y} min(abs(self.relation(x,y)),abs(other.relation(x,y)) / n(n-1)
and where n is the number of actions considered.
The correlation index K with a completely indeterminate relation
is by convention 0.0 at determination level 0.0 .
"""
if self.valuationdomain['min'] != Decimal('-1.0'):
print('Error: the BigDigraph instance must be normalized !!')
print(self.valuationdomain)
return
if issubclass(other.__class__,(Digraph)):
# if Debug:
# print('other is a Digraph instance')
if other.valuationdomain['min'] != Decimal('-1.0'):
print('Error: the other digraph must be normalized !!')
print(other.valuationdomain)
return
elif isinstance(other,(BigDigraph)):
# if Debug:
# print('other is a BigDigraph instance')
if other.valuationdomain['min'] != Decimal('-1.0'):
print('Error: the other bigDigraph instance must be normalized !!')
print(other.valuationdomain)
return
correlation = Decimal('0.0')
determination = Decimal('0.0')
for x in self.actions.keys():
for y in self.actions.keys():
if x != y:
selfRelation = self.relation(x,y)
try:
otherRelation = other.relation(x,y)
except:
otherRelation = other.relation[x][y]
#if Debug:
# print(x,y,'self', selfRelation)
# print(x,y,'other', otherRelation)
corr = min( max(-selfRelation,otherRelation), max(selfRelation,-otherRelation) )
correlation += corr
determination += min( abs(selfRelation),abs(otherRelation) )
if determination > Decimal('0.0'):
correlation /= determination
n2 = (self.order*self.order) - self.order
return { 'correlation': correlation,\
'determination': determination / Decimal(str(n2)) }
else:
return {'correlation': Decimal('0.0'),\
'determination': determination}
def showDecomposition(self,direction='decreasing'):
"""
Prints on the console the decomposition structure of the sparse outranking digraph instance
in *decreasing* (default) or *increasing* preference direction.
"""
print('*--- Relation decomposition in %s order---*' % (direction) )
compKeys = [compKey for compKey in self.components]
if direction != 'increasing':
compKeys.sort()
else:
compKeys.sort(reverse=True)
for compKey in compKeys:
comp = self.components[compKey]
sg = comp['subGraph']
actions = [x for x in sg.actions]
actions.sort()
print('%s: %s' % (compKey,actions))
def computeDecompositionSummaryStatistics(self):
"""
Returns the summary of the distribution of the length of
the components as follows::
summary = {'max': maxLength,
'median':medianLength,
'mean':meanLength,
'stdev': stdLength,
'fillrate': fillrate,
(see computeFillRate()}
"""
try:
import statistics
except:
print('Error importing the statistics module.')
print('You need to upgrade your Python to version 3.4+ !')
return
nc = self.nbrComponents
compLengths = [comp['subGraph'].order\
for comp in self.components.values()]
medianLength = statistics.median(compLengths)
stdLength = statistics.pstdev(compLengths)
summary = {
'min': self.minimalComponentSize,
'max': self.maximalComponentSize,
'median':medianLength,
'mean':self.order/nc,
'stdev': stdLength,
'fillrate': self.fillRate}
return summary
def recodeValuation(self,newMin=-1,newMax=1,Debug=False):
"""
Specialization for recoding the valuation of all the partial digraphs and the component relation.
By default the valuation domain is normalized to [-1;1]
"""
# saving old and new valuation domain
oldMax = self.valuationdomain['max']
oldMin = self.valuationdomain['min']
oldMed = self.valuationdomain['med']
oldAmplitude = oldMax - oldMin
if Debug:
print(oldMin, oldMed, oldMax, oldAmplitude)
newMin = Decimal(str(newMin))
newMax = Decimal(str(newMax))
newMed = Decimal('%.3f' % ((newMax + newMin)/Decimal('2.0')))
newAmplitude = newMax - newMin
if Debug:
print(newMin, newMed, newMax, newAmplitude)
# loop over all components
print('Recoding the valuation of a BigDigraph instance')
for cki in self.components.keys():
self.components[cki]['subGraph'].recodeValuation(newMin=newMin,newMax=newMax)
# update valuation domain
Min = Decimal(str(newMin))
Max = Decimal(str(newMax))
Med = (Min+Max)/Decimal('2')
self.valuationdomain = { 'min':Min, 'max':Max, 'med':Med }
def ranking2Preorder(self,ranking):
"""
Renders a preordering (a list of list) of a ranking (best to worst) of decision actions in increasing preference direction.
"""
#ordering = list(ranking)
#ordering.reverse()
preordering = [[x] for x in reversed(ranking)]
return preordering
def ordering2Preorder(self,ordering):
"""
Renders a preordering (a list of list) of a linar order (worst to best) of decision actions in increasing preference direction.
"""
preordering = [[x] for x in ordering]
return preordering
def computeFillRate(self):
"""
Renders the sum of the squares (without diagonal) of the orders of the component's subgraphs
over the square (without diagonal) of the big digraph order.
"""
fillRate = sum((comp['subGraph'].order*(comp['subGraph'].order-1))\
for comp in self.components.values())
return fillRate/( self.order*(self.order-1) )
def exportGraphViz(self,fileName=None,
actionsSubset=None,
direction='decreasing',
Comments=True,graphType='pdf',
graphSize='7,7',
fontSize=10,bgcolor='cornsilk',
relation=None,
Debug=False):
"""
Dummy for exportSortingDigraph.
"""
self.exportSortingGraphViz(fileName=fileName,
actionsSubset=actionsSubset,
direction=direction,
Comments=Comments,
graphType=graphType,
graphSize=graphSize,
fontSize=fontSize,
bgcolor=bgcolor,
relation=relation,
Debug=Debug)
def exportSortingGraphViz(self,fileName=None,
actionsSubset=None,
direction='decreasing',
Comments=True,graphType='pdf',
graphSize='7,7',
fontSize=10,bgcolor='cornsilk',
relation=None,
Debug=False):
"""
export GraphViz dot file for weak order (Hasse diagram) drawing
filtering from SortingDigraph instances.
Example::
>>> # Testing graph viz export of sorting Hasse diagram
>>> MP = True
>>> nbrActions=100
>>> tp = RandomCBPerformanceTableau(numberOfActions=nbrActions,
... Threading=MP,
... seed=100)
>>> bg = PreRankedOutrankingDigraph(tp,CopyPerfTab=True,quantiles=20,
... quantilesOrderingStrategy='average',
... componentRankingRule='Copeland',
... LowerClosed=False,
... minimalComponentSize=1,
... Threading=MP,nbrOfCPUs=8,
... #tempDir='.',
... nbrOfThreads=8,
... Comments=False,Debug=False)
>>> print(bg)
*----- show short --------------*
Instance name : randomCBperftab_mp
# Actions : 100
# Criteria : 7
Sorting by : 20-Tiling
Ordering strategy : average
Ranking rule : Copeland
# Components : 36
Minimal order : 1
Maximal order : 11
Average order : 2.8
fill rate : 4.121%
---- Constructor run times (in sec.) ----
Total time : 0.15991
QuantilesSorting : 0.11717
Preordering : 0.00066
Decomposing : 0.04009
Ordering : 0.00000
>>> bg.showComponents()
*--- Relation decomposition in increasing order---*
35: ['a010']
34: ['a024', 'a060']
33: ['a012']
32: ['a018']
31: ['a004', 'a054', 'a075', 'a082']
30: ['a099']
29: ['a065']
28: ['a025', 'a027', 'a029', 'a041', 'a059']
27: ['a063']
26: ['a047', 'a066']
25: ['a021']
24: ['a007']
23: ['a044']
22: ['a037', 'a062', 'a090', 'a094', 'a098', 'a100']
21: ['a005', 'a040', 'a051', 'a093']
20: ['a015', 'a030', 'a052', 'a055', 'a064', 'a077']
19: ['a006', 'a061']
18: ['a049']
17: ['a001', 'a033']
16: ['a016', 'a028', 'a032', 'a035', 'a057', 'a079', 'a084', 'a095']
15: ['a043']
14: ['a002', 'a017', 'a023', 'a034', 'a067', 'a072', 'a073', 'a074', 'a088', 'a089', 'a097']
13: ['a048']
12: ['a078', 'a092']
11: ['a070']
10: ['a014', 'a026', 'a039', 'a058', 'a068', 'a083', 'a086']
9: ['a008', 'a022', 'a038', 'a081', 'a091', 'a096']
8: ['a020']
7: ['a069']
6: ['a045']
5: ['a003', 'a009', 'a013', 'a031', 'a036', 'a056', 'a076']
4: ['a042', 'a071']
3: ['a085']
2: ['a019', 'a080', 'a087']
1: ['a046']
0: ['a011', 'a050', 'a053']
>>> bg.exportSortingGraphViz(actionsSubset=bg.boostedRanking[:100])
.. image:: preRankedDigraph.png
:alt: pre-ranked digraph
:width: 400 px
:align: center
"""
import os
from copy import copy, deepcopy
def _safeName(t0):
try:
t = t0.split(sep="-")