-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathratingDigraphs.py
More file actions
2368 lines (2154 loc) · 101 KB
/
ratingDigraphs.py
File metadata and controls
2368 lines (2154 loc) · 101 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 collection of python3 modules for
Algorithmic Decision Theory applications.
Module for relative and absolute rating of multicriteria performance records
with abstract *RatingDigraph* root class.
The module, better suitable for rating problems of small sizes (< 500 mulicriteria performance records), reimplements a simpler and more consistent version
of the MP optimised :py:class:`~sortingDigraphs.QuantilesSortingDigraph` and the
:py:class:`~sortingDigraphs.LearnedQuantilesRatingDigraph` classes from the
:py:mod:`sortingDigraphs` module.
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.
.. note::
The actions attribute of RatingDigraph instances contains besides the
standard Digraph.actions (stored in *self.actionsOrig*) also the
quantile limit profiles (stored in *self.profiles*).
The *ratingDigraphs* module is not optimised for *BigData* applications.
In such cases, it is recommended to use instead the
MP optimised *sortingDigraph* module.
"""
######### abstract root class
from outrankingDigraphs import BipolarOutrankingDigraph
class RatingDigraph(BipolarOutrankingDigraph):
"""
Abstract root class with generic private and public methods
"""
def __init__(self):
print('Abstract root class with private and public methods for RatingDigraph instances')
def __repr__(self):
"""
Default presentation method for relative quantiles
rating digraph instance.
"""
from decimal import Decimal
repString = '*----- Object instance description -----------*\n'
repString += 'Instance class : %s\n' % self.__class__.__name__
repString += 'Instance name : %s\n' % self.name
repString += 'Actions : %d\n' % len(self.actions)
repString += 'Criteria : %d\n' % len(self.criteria)
repString += 'Quantiles : %d\n' % len(self.categories)
repString += 'Lowerclosed : %s\n' % str(self.criteriaCategoryLimits['LowerClosed'])
repString += 'Rankingrule : %s\n' % self.rankingRule
repString += 'Size : %d\n' % self.computeSize()
repString += 'Valuation domain : [%.2f;%.2f]\n'\
% (self.valuationdomain['min'],self.valuationdomain['max'])
try:
if self.distribution == 'beta':
repString += 'Uncertainty model : %s(a=%.1f,b=%.1f)\n' %\
(self.distribution,self.betaParameter,self.betaParameter)
else:
repString += 'Uncertainty model : %s(a=%s,b=%s)\n' %\
(self.distribution,'0','2w')
repString += 'Likelihood domain : [-1.0;+1.0]\n'
repString += 'Confidence level : %.2f (%.1f%%)\n' %\
( self.bipolarConfidenceLevel,\
(self.bipolarConfidenceLevel+1.0)/2.0*100.0 )
repString += 'Confident majority : %.2f (%.1f%%)\n' %\
(self.confidenceCutLevel,\
(self.confidenceCutLevel+Decimal('1.0'))/Decimal('2.0')*Decimal('100.0'))
except:
pass
repString += 'Determinateness (%%): %.2f\n' %\
self.computeDeterminateness(InPercents=True)
repString += 'Attributes : %s\n' % list(self.__dict__.keys())
repString += '*------ Constructor run times (in sec.) ------*\n'
try:
repString += 'Threads : %d\n' % self.nbrThreads
except:
self.nbrThreads = 0
repString += 'Threads : %d\n' % self.nbrThreads
try:
repString += 'StartMethod : %s\n' % self.startMethod
except:
self.startMethod = None
repString += 'StartMethod : %s\n' % self.startMethod
repString += 'Total time : %.5f\n' % self.runTimes['totalTime']
repString += 'Data input : %.5f\n' % self.runTimes['dataInput']
repString += 'Compute quantiles : %.5f\n' % self.runTimes['computeProfiles']
repString += 'Compute outrankings : %.5f\n' % self.runTimes['outrankingRelation']
repString += 'rating-by-sorting : %.5f\n' % self.runTimes['sortingRelation']
repString += 'rating-by-ranking : %.5f\n' % self.runTimes['rating-by-ranking']
return repString
def exportRatingBySortingGraphViz(self,fileName=None,direction='decreasing',
Comments=True,graphType='png',bgcolor='cornsilk',
graphSize='7,7',
fontSize=10,
relation=None,
Debug=False):
"""
export GraphViz dot file for weak order (Hasse diagram) drawing
filtering from SortingDigraph instances.
"""
from copy import deepcopy
# backup actions and relation
relationBkp = deepcopy(self.relation)
actionsBkp = deepcopy(self.actions)
# computing rating preorder
if direction == 'decreasing':
ordering = self._computeQuantileOrdering(Descending=True)
else:
ordering = self._computeQuantileOrdering(Descending=False)
if Debug:
print(ordering)
# the preorder reltion being transitive
# we use the exportGraphViz() method of the TransitiveDigraph class
self.relation = self._computePreorderRelation(ordering)
self.actions = self._getActionsKeys()
if Debug:
print(self.isTransitive())
from transitiveDigraphs import TransitiveDigraph
TransitiveDigraph.exportGraphViz(self,
fileName=fileName,
direction=direction,
Comments=Comments,
graphType=graphType,
bgcolor=bgcolor,
graphSize=graphSize,
fontSize=10)
# restore original actions and relation
self.actions = actionsBkp
self.relation = relationBkp
#------------
def exportRatingByRankingGraphViz(self,fileName=None,
Comments=True,graphType='png',
graphSize='7,7',
fontSize=10,bgcolor='cornsilk',
Debug=False):
"""
export GraphViz dot file for Hasse diagram drawing filtering.
"""
import os
from copy import deepcopy
from decimal import Decimal
def _safeName(t0,QuantileName=False):
if QuantileName: # graphviz node names must not start with a digit
t0 = t0[::-1]
t = t0.split(sep="-")
t1 = t[0]
n = len(t)
if n > 1:
for i in range(1,n):
t1 += '%s' % (t[i])
return t1
# working on a deepcopy of self
digraph = deepcopy(self)
if Debug:
print('profile limits:\n',
digraph.profileLimits)
print('relative quantile contents:\n',
digraph.relativeCategoryContent)
# constructing rankingByBestChoosing result
rankingByChoosing = []
k = len(digraph.profileLimits)
if digraph.LowerClosed:
i = 0
j = 1
while i < k:
rankingByChoosing.append((Decimal('1'),[self.profileLimits[i]]))
if self.relativeCategoryContent[str(j)] != []:
rankingByChoosing.append((Decimal('1'),self.relativeCategoryContent[str(j)]))
i += 1
j += 1
else:
i = 0
j = 1
while i < k:
if self.relativeCategoryContent[str(j)] != []:
rankingByChoosing.append((Decimal('1'),self.relativeCategoryContent[str(j)]))
rankingByChoosing.append((Decimal('1'),[self.profileLimits[i]]))
i += 1
j += 1
if Debug:
print(rankingByChoosing)
if Comments:
print('*---- exporting a dot file for GraphViz tools ---------*')
# install rating relation (weakly transitive)
digraph.relation = digraph._computeRatingRelation()
if Debug:
print('digraph is transitive ?', digraph.isTransitive())
# sorting actionsKeys
actionKeys = digraph.computeCopelandRanking()
n = len(actionKeys)
Med = digraph.valuationdomain['med']
i = 0
if fileName is None:
name = digraph.name+'_ratbyrank'
else:
name = fileName
dotName = name+'.dot'
if Comments:
print('Exporting to '+dotName)
# writing out graphviz instructions
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:
#print(digraphClass)
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'\
% (_safeName(str(x),QuantileName=True),_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)
# keep only relation skeleton
if Debug:
print(digraph.isTransitive())
digraph.closeTransitive(Reverse=True,InSite=True)
if Debug:
# actionKeys = digraph.computeCopelandRanking()
digraph.showRelationMap()
# write out relations between nodes
for i in range(n):
x = actionKeys[i]
if x in self.profiles:
xQuantileName=True
else:
xQuantileName=False
for j in range(i+1,n):
y = actionKeys[j]
if y in self.profiles:
yQuantileName=True
else:
yQuantileName=False
if digraph.relation[x][y] > digraph.valuationdomain['med']:
arcColor = 'black'
edge = '%s-> %s [style="setlinewidth(%d)",color=%s] ;\n' %\
(_safeName(x,xQuantileName),_safeName(y,yQuantileName),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 showSortingCharacteristics(self, action=None):
"""
Renders a bipolar-valued bi-dictionary relation
representing the degree of credibility of the
assertion that "action x in A belongs to category c in C",
ie x outranks low category limit and does not outrank
the high category limit.
"""
try:
sorting = self.sorting
except:
sorting = self._computeSortingCharacteristics(action=action)
self.sorting = sorting
actions = self._getActionsKeys(action)
categories = self._orderedCategoryKeys()
try:
LowerClosed = self.criteriaCategoryLimits['LowerClosed']
except:
LowerClosed = True
if LowerClosed:
print('x in K_k\t r(x >= m_k)\t r(x < M_k)\t r(x in K_k)')
else:
print('x in K_k\t r(m_k < x)\t r(M_k >= x)\t r(x in K_k)')
for x in actions:
for c in categories:
print('%s in %s - %s\t' % (x, self.categories[c]['lowLimit'],
self.categories[c]['highLimit'],), end=' ')
print('%.2f\t\t %.2f\t\t %.2f' %\
(sorting[x][c]['lowLimit'],
sorting[x][c]['notHighLimit'], sorting[x][c]['categoryMembership']))
print()
def showHTMLRatingByQuantileSorting(self,title='Quantiles Preordering',
Descending=True,strategy='average',
htmlFileName=None):
"""
Shows the html version of the quantile preordering in a browser window.
The ordring strategy is either:
* **average** (default), following the averag of the upper and lower quantile limits,
* **optimistic**, following the upper quantile limits (default),
* **pessimistic**, following the lower quantile limits.
"""
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._computeQuantileOrdering(Descending=Descending,
strategy=strategy,
HTML=True,
title=title,
Comments=True))
fo.close()
url = 'file://'+fileName
webbrowser.open(url,new=2)
def showHTMLSorting(self,Reverse=True,htmlFileName=None):
"""
shows the html version of the sorting result in a browser window.
"""
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.showSorting(Reverse=Reverse,isReturningHTML=True))
fo.close()
url = 'file://'+fileName
webbrowser.open(url,new=2)
def showSorting(self,Reverse=True,isReturningHTML=False,Debug=False):
"""
Shows sorting results in decreasing or increasing (Reverse=False)
order of the categories. If isReturningHTML is True (default = False)
the method returns a htlm table with the sorting result.
"""
#from string import replace
from copy import copy, deepcopy
try:
categoryContent = self.relativeCategoryContent
except:
categoryContent = self._computeCategoryContents()
self.relativeCategoryContent = categoryContent
categoryKeys = self._orderedCategoryKeys(Reverse=Reverse)
try:
LowerClosed = self.criteriaCategoryLimits['LowerClosed']
except:
LowerClosed = True
if Reverse:
print('\n*--- Sorting results in descending order ---*\n')
if isReturningHTML:
html = '<h2>Sorting results in descending order</h2>'
html += '<table style="background-color:White;" border="1"><tr bgcolor="#9acd32"><th>Quantiles</th><th>Assortment</th></tr>'
else:
print('\n*--- Sorting results in ascending order ---*\n')
if isReturningHTML:
html = '<h2>Sorting results in ascending order</h2>'
html += '<table style="background-color:White;" border="1"><tr bgcolor="#9acd32"><th>Quantiles</th><th>Assortment</th></tr>'
for c in categoryKeys:
print('%s:' % (self.categories[c]['name']), end=' ')
print('\t',categoryContent[c])
if isReturningHTML:
#html += '<tr><td bgcolor="#FFF79B">[%s - %s[</td>' % (limprevc,limc)
html += '<tr><td bgcolor="#FFF79B">%s</td>' % (self.categories[c]['name'])
catString = str(categoryContent[c])
html += '<td>%s</td></tr>' % catString.replace('\'',''')
if isReturningHTML:
html += '</table>'
return html
def showAllQuantiles(self):
self.showCriteriaQuantileLimits()
def showCriteriaQuantileLimits(self,ByCriterion=False):
"""
Shows category minimum and maximum limits for each criterion.
"""
catLimits = self.criteriaCategoryLimits
try:
LowerClosed = catLimits['LowerClosed']
except:
LowerClosed = True
criteria = self.criteria
categories = self.categories
print('Quantile Class Limits (q = %d)' % len(self.categories))
if LowerClosed:
print('Lower-closed classes')
else:
print('Upper-closed classes')
if ByCriterion:
nc = len(categories)
for g in criteria:
print(g)
catg = catLimits[g]
for c in range(1,nc):
print('\t%.2f [%.2f; %.2f[' %\
(categories[str(c)]['quantile'], catg[c-1], catg[c]) )
else:
nc = len(categories)
print('crit.', end='\t ')
for c in categories:
print('%.2f' % (categories[c]['quantile']), end='\t ')
print('\n*----------------------------------------------')
for g in criteria:
print(g, end='\t ')
catg = catLimits[g]
for c in range(1,nc+1):
print('%.2f' % (catg[c-1]), end='\t ')
print()
def showHTMLPerformanceHeatmap(self):
print('Please use the showHTMLRatingHeatmap() here !!')
def showHTMLRatingHeatmap(self,#actionsList=None,
WithActionNames=False,
#criteriaList=None,
colorLevels=7,
pageTitle=None,
ndigits=2,
rankingRule=None,
Correlations=False,
Threading=False,
nbrOfCPUs=None,
startMethod=None,
Debug=False,
htmlFileName=None):
"""
Specialisation of html heatmap version showing the performance tableau in a browser window;
see :py:meth:`perfTabs.showHTMLPerformanceHeatMap` method.
**Parameters**:
- *ndigits* = 0 may be used to show integer evaluation values.
- If no *actionsList* is provided, the decision actions are ordered from the best to the worst following the ranking of the LearnedQuatilesRatingDigraph instance.
- It may interesting in some cases to use *RankingRule* = 'NetFlows'.
- With *Correlations* = *True* and *criteriaList* = *None*, the criteria will be presented from left to right in decreasing order of the correlations between the marginal criterion based ranking and the global ranking used for presenting the decision alternatives.
- Computing the marginal correlations may be boosted with Threading = True, if multiple parallel computing cores are available.
"""
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')
if pageTitle is None:
pageTitle = 'Rating-by-ranking result of \'%s\'' % self.name
#quantiles = len(self.quantilesFrequencies)
fo.write(self._htmlRatingHeatmap( #argCriteriaList=criteriaList,
# argActionsList=actionsList,
WithActionNames=WithActionNames,
#quantiles=quantiles,
ndigits=ndigits,
colorLevels=colorLevels,
pageTitle=pageTitle,
rankingRule=rankingRule,
Correlations=Correlations,
Threading=Threading,
nbrOfCPUs=None,
Debug=Debug))
fo.close()
url = 'file://'+fileName
webbrowser.open(url,new=2)
def showRatingByQuantilesRanking(self,Descending=True,Debug=False):
"""
Show rating-by-ranking result.
"""
ratingCategories = self.ratingCategories
print('*-------- rating by quantiles %s ranking result ---------' %\
(self.rankingRule) )
if self.LowerClosed:
if Descending:
for cat in reversed(ratingCategories):
c = self.profiles[cat]['category']
print(self.categories[c]['name'],ratingCategories[cat])
else:
for cat in ratingCategories:
c = self.profiles[cat]['category']
print(self.categories[c]['name'],ratingCategories[cat])
else:
if Descending:
for cat in ratingCategories:
c = self.profiles[cat]['category']
print(self.categories[c]['name'],ratingCategories[cat])
else:
for cat in reversed(ratingCategories):
c = self.profiles[cat]['category']
print(self.categories[c]['name'],ratingCategories[cat])
def showRatingByQuantilesSorting(self,strategy='average'):
"""
Dummy show method for the commenting _computeQuantileOrdering() method.
"""
from decimal import Decimal
if strategy is None:
strategy = 'average'
self._computeQuantileOrdering(strategy=strategy,Comments=True)
def computeRatingByRankingCorrelation(self,Debug=False):
from decimal import Decimal
E = Decimal('0')
D = Decimal('0')
ratingRelation = self._computeRatingRelation()
for q in self.ratingCategories:
for x in self.actionsOrig:
#print(q,x)
#if self.LowerClosed:
E += min( max(-self.relation[x][q],ratingRelation[x][q]),
max(self.relation[x][q],-ratingRelation[x][q]))
D += min(abs(self.relation[x][q]),abs(ratingRelation[x][q]))
if Debug:
print(E,D,E/D)
nq = len(self.categories)
na = len(self.actionsOrig)
return {'correlation':E/D, 'determination': D/Decimal((nq*na))}
## def computeRatingBySortingCorrelation(self,strategy='average',Debug=False):
## from decimal import Decimal
## E = Decimal('0')
## D = Decimal('0')
## #qspo = self.computePreorderRelation(list(reversed(self._computeQuantileOrdering(strategy=strategy))))
## qspo = self.computePreorderRelation(self._computeQuantileOrdering(strategy=strategy))
## #print('qspo',qspo)
## for q in self.ratingCategories:
## for x in self.actionsOrig:
## #if self.LowerClosed:
## E -= min( max(-self.relation[x][q],qspo[x][q]),\
## max(self.relation[x][q],-qspo[x][q]))
## D += min(abs(self.relation[x][q]),abs(qspo[x][q]))
#### else:
#### E += min( max(self.relation[q][x],-qspo[q][x]),\
#### max(-self.relation[q][x],qspo[q][x]))
#### D += min(abs(self.relation[q][x]),abs(qspo[q][x]))
## if Debug:
## print(E,D,E/D)
## return E/D
####### private genric class methods
def _getActionsKeys(self,action=None,withoutProfiles=True):
"""
extract normal actions keys()
"""
profiles = set([x for x in self.profiles])
if action is None:
actionsExt = set([x for x in self.actions])
if withoutProfiles:
return actionsExt - profiles
else:
return actionsExt | profiles
else:
return set([action])
def _computeCategoryContents(self,Reverse=False):
"""
Computes the sorting results per category.
"""
actions = list(self._getActionsKeys())
actions.sort()
try:
sorting = self.sorting
except:
sorting = self._computeSortingCharacteristics()
self.sorting=sorting
categoryContent = {}
for c in self._orderedCategoryKeys(Reverse=Reverse):
categoryContent[c] = []
for x in actions:
if sorting[x][c]['categoryMembership'] >= self.valuationdomain['med']:
categoryContent[c].append(x)
self.relativeCategoryContent = categoryContent
return categoryContent
def _computeLimitingQuantiles(self,g,Debug=False,PrefThresholds=True):
"""
Renders the list of limiting quantiles on criteria g
"""
from math import floor
from copy import copy, deepcopy
from decimal import Decimal
LowerClosed = self.criteriaCategoryLimits['LowerClosed']
LowerClosed = self.LowerClosed
criterion = self.criteria[g]
evaluation = self.evaluation
NA = self.NA
actionsOrig = self.actionsOrig
gValues = []
for x in actionsOrig:
if Debug:
print('g,x,evaluation[g][x]',g,x,evaluation[g][x])
if evaluation[g][x] != NA:
gValues.append(evaluation[g][x])
gValues.sort()
if PrefThresholds:
try:
gPrefThrCst = criterion['thresholds']['pref'][0]
gPrefThrSlope = criterion['thresholds']['pref'][1]
except:
gPrefThrCst = Decimal('0')
gPrefThrSlope = Decimal('0')
n = len(gValues)
if Debug:
print('g,n,gValues',g,n,gValues)
## if n > 0:
## nf = Decimal(str(n+1))
nf = Decimal(str(n))
quantilesFrequencies = copy(self.quantilesFrequencies)
#limitingQuantiles.sort()
if Debug:
print(quantilesFrequencies)
if LowerClosed:
quantilesFrequencies = quantilesFrequencies[:-1]
else:
quantilesFrequencies = quantilesFrequencies[1:]
if Debug:
print(quantilesFrequencies)
# computing the quantiles on criterion g
gQuantiles = []
if LowerClosed:
# we ignore the 1.00 quantile and replace it with +infty
for q in quantilesFrequencies:
r = (Decimal(str(nf)) * q)
rq = int(floor(r))
if Debug:
print('r,rq',r,rq, end=' ')
if rq < (n-1):
quantile = gValues[rq]\
+ ((r-Decimal(str(rq)))*(gValues[rq+1]-gValues[rq]))
if rq > 0 and PrefThresholds:
quantile += gPrefThrCst + quantile*gPrefThrSlope
else :
if self.criteria[g]['preferenceDirection'] == 'min':
quantile = Decimal('100.0')
else:
quantile = Decimal('200.0')
if Debug:
print('quantile',quantile)
gQuantiles.append(quantile)
else: # upper closed categories
# we ignore the quantile 0.0 and replace it with -\infty
for q in quantilesFrequencies:
r = (Decimal(str(nf)) * q)
rq = int(floor(r))
if Debug:
print('r,rq',r,rq, end=' ')
if rq == 0:
if self.criteria[g]['preferenceDirection'] == 'min':
quantile = Decimal('-200.0')
else:
quantile = Decimal('-100.0')
elif rq < (n-1):
quantile = gValues[rq]\
+ ((r-Decimal(str(rq)))*(gValues[rq+1]-gValues[rq]))
if PrefThresholds:
quantile -= gPrefThrCst - quantile*gPrefThrSlope
else:
if n > 0:
quantile = gValues[n-1]
else:
if self.criteria[g]['preferenceDirection'] == 'min':
quantile = Decimal('-200.0')
else:
quantile = Decimal('-100.0')
if Debug:
print('quantile',quantile)
gQuantiles.append(quantile)
## else:
## gQuantiles = []
if Debug:
print(g,LowerClosed,self.criteria[g]['preferenceDirection'],gQuantiles)
return gQuantiles
def _computePreorderRelation(self,preorder,Normalized=True,Debug=False):
"""
Renders the bipolar-valued relation obtained from
a given preordering in increasing levels (list of lists) result.
"""
from decimal import Decimal
if Normalized:
Max = Decimal('1')
Med = Decimal('0')
Min = Decimal('-1')
else:
Max = self.valuationdomain['max']
Med = self.valuationdomain['med']
Min = self.valuationdomain['min']
actions = list(self.actions.keys())
currentActions = set(actions)
preorderRelation = {}
for x in actions:
preorderRelation[x] = {}
for y in actions:
preorderRelation[x][y] = Med
for eqcl in preorder:
currRest = currentActions - set(eqcl)
if Debug:
print(currentActions, eqcl, currRest)
for x in eqcl:
for y in eqcl:
if x != y:
preorderRelation[x][y] = Med
preorderRelation[y][x] = Med
for x in eqcl:
for y in currRest:
preorderRelation[x][y] = Max
preorderRelation[y][x] = Min
currentActions = currentActions - set(eqcl)
return preorderRelation
def _computeQuantileOrdering(self,strategy='average',
Descending=True,
HTML=False,
title='Quantiles Preordering',
Comments=False,
Debug=False):
"""
*Parameters*:
* Descending: listing in *decreasing* (default) or *increasing* quantile order.
* strategy: ordering in an {'optimistic' | 'pessimistic' | 'average' (default)}
in the uppest, the lowest or the average potential quantile.
"""
from operator import itemgetter
if strategy is None:
strategy = 'optimistic'
if HTML:
html = '<h1>%s</h1>\n' % title
html += '<table style="background-color:White;" border="1">\n'
html += '<tr bgcolor="#9acd32"><th>quantile limits</th>\n'
html += '<th>%s sorting</th>\n' % strategy
html += '</tr>\n'
actionsCategories = {}
for x in self.actionsOrig:
a,lowCateg,highCateg,credibility =\
self._showActionCategories(x,Comments=Debug)
ilowCateg = int(lowCateg)
ihighCateg = int(highCateg)
if Debug:
print(a,lowCateg,highCateg,credibility)
if strategy == "optimistic":
try:
actionsCategories[(ihighCateg,ilowCateg,ilowCateg)].append(a)
except:
actionsCategories[(ihighCateg,ilowCateg,ilowCateg)] = [a]
elif strategy == "pessimistic":
try:
actionsCategories[(ilowCateg,ihighCateg,ilowCateg)].append(a)
except:
actionsCategories[(ilowCateg,ihighCateg,ilowCateg)] = [a]
elif strategy == "average":
lc = float(lowCateg)
hc = float(highCateg)
ac = (lc+hc)/2.0
try:
actionsCategories[(ac,ihighCateg,ilowCateg)].append(a)
except:
actionsCategories[(ac,ihighCateg,ilowCateg)] = [a]
else:
print('Error: %s not a valid ordering strategy !!!' % strategy)
break
# sorting the quantile equivalence classes
actionsCategoriesKeys = [key for key in actionsCategories]
actionsCategoriesKeys = sorted(actionsCategoriesKeys,key=itemgetter(0,1,2), reverse=True)
actionsCategIntervals = []
for interval in actionsCategoriesKeys:
actionsCategIntervals.append([interval,\
actionsCategories[interval]])
# gathering the result with output when Comments=True
weakOrdering = []
if Comments and not HTML:
print('*---- rating by quantiles sorting result----*')
for item in actionsCategIntervals:
#print(item)
if Comments:
if strategy == "optimistic":
if self.criteriaCategoryLimits['LowerClosed']:
if HTML:
html += '<tr><tdbgcolor="#FFF79B">%s-%s</td>' \
% (self.categories[str(item[0][1])]['lowLimit'],
self.categories[str(item[0][0])]['highLimit'])
html += '<td>%s</td></tr>' % str(item[1])
else:
print('%s-%s : %s' \
% (self.categories[str(item[0][1])]['lowLimit'],
self.categories[str(item[0][0])]['highLimit'],
str(item[1])) )
else:
if HTML:
html += '<tr><td bgcolor="#FFF79B">%s-%s</td>' \
% (self.categories[str(item[0][0])]['lowLimit'],
self.categories[str(item[0][1])]['highLimit'])
html += '<td>%s</td></tr>' % str(item[1])
else:
print('%s-%s : %s' \
% (self.categories[str(item[0][1])]['lowLimit'],
self.categories[str(item[0][0])]['highLimit'],\
str(item[1])) )
elif strategy == "pessimistic":
if self.criteriaCategoryLimits['LowerClosed']:
if HTML:
html += '<tr><td bgcolor="#FFF79B">%s-%s</td>' \
% (self.categories[str(item[0][0])]['lowLimit'],
self.categories[str(item[0][1])]['highLimit'])
html += '<td>%s</td></tr>' % str(item[1])
else:
print('%s-%s : %s' \
% (self.categories[str(item[0][0])]['lowLimit'],
self.categories[str(item[0][1])]['highLimit'],
str(item[1])) )
else:
if HTML:
html += '<tr><td bgcolor="#FFF79B">%s-%s</td>' \
% (self.categories[str(item[0][0])]['lowLimit'],
self.categories[str(item[0][1])]['highLimit'])
html += '<td>%s</td></tr>' % str(item[1])
else:
print('%s-%s : %s'\
% (self.categories[str(item[0][0])]['lowLimit'],
self.categories[str(item[0][1])]['highLimit'],\
str(item[1])) )
elif strategy == "average":
if self.criteriaCategoryLimits['LowerClosed']:
if HTML:
html += '<tr><td bgcolor="#FFF79B">%s-%s</td>' \
% (self.categories[str(item[0][2])]['lowLimit'],
self.categories[str(item[0][1])]['highLimit'])
html += '<td>%s</td></tr>' % str(item[1])
else:
print('%s-%s : %s' \
% (self.categories[str(item[0][2])]['lowLimit'],
self.categories[str(item[0][1])]['highLimit'],
str(item[1])) )
else:
if HTML:
html += '<tr><td bgcolor="#FFF79B">%s-%s</td>' \
% (self.categories[str(item[0][2])]['lowLimit'],
self.categories[str(item[0][1])]['highLimit'])
html += '<td>%s</td></tr>' % str(item[1])
else:
print('%s-%s : %s' \
% (self.categories[str(item[0][2])]['lowLimit'],
self.categories[str(item[0][1])]['highLimit'],
str(item[1])) )
weakOrdering.append(item[1])
if HTML:
html += '</table>'
return html
else:
return weakOrdering
def _computeQuantilesFrequencies(self,x,Debug=False):
"""
renders the quantiles frequencies
"""
from math import floor
from decimal import Decimal
if isinstance(x,int):
n = x
elif x is None:
n = 4
elif x == 'bitiles':
n = 2
elif x == 'tritiles':
n = 3
elif x == 'quartiles':
n = 4
elif x == 'quintiles':
n = 5
elif x == 'sextiles':
n = 6
elif x == 'septiles':
n = 7
elif x == 'octiles':
n = 8
elif x == 'deciles':
n = 10
elif x == 'dodeciles':
n = 20
elif x == 'centiles':
n = 100
elif x == 'automatic':
pth = [5]
for g in self.criteria:
try:
pref = self.criteria[g]['thresholds']['ind'][0] + \
(self.criteria[g]['thresholds']['ind'][1]*Decimal('100'))
pth.append(pref)
except:
pass
amp = max(Decimal('1'),min(pth))
n = int(floor(Decimal('100')/amp))
if Debug:
print('Detected preference thresholds = ',pth)
print('amplitude, n',amp,n)
quantilesFrequencies = []
for i in range(n+1):
quantilesFrequencies.append( Decimal(str(i)) / Decimal(str(n)) )
#self.name = 'sorting_with_%d-tile_limits' % n
return quantilesFrequencies
def _computeQuantilesRatingByRanking(self,Debug=False):
"""
Renders an ordered dictionary of non empty quantiles in ascending order.
"""
from collections import OrderedDict
ranking = list(self.actionsRanking)
if self.LowerClosed: # lower closed quantiles
ranking.reverse()
if Debug:
print('9.1')
print(ranking)