-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPyXMCDA.py
More file actions
executable file
·1174 lines (857 loc) · 33.9 KB
/
PyXMCDA.py
File metadata and controls
executable file
·1174 lines (857 loc) · 33.9 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
# -*- coding: utf-8 -*-
#############################################################################
#
# Copyright 2010 University of Luxembourg
#
# Contributors :
# Thomas Veneziano thomas.veneziano@uni.lu
# Sébastien Bigaret sebastien.bigaret@telecom-bretagne.eu
#
# This software is a package for Python
#
# This software is governed by the CeCILL license under French law and
# abiding by the rules of distribution of free software. You can use,
# modify and/ or redistribute the software under the terms of the CeCILL
# license as circulated by CEA, CNRS and INRIA at the following URL
# "http://www.cecill.info".
#
# As a counterpart to the access to the source code and rights to copy,
# modify and redistribute granted by the license, users are provided only
# with a limited warranty and the software's author, the holder of the
# economic rights, and the successive licensors have only limited
# liability.
#
# In this respect, the user's attention is drawn to the risks associated
# with loading, using, modifying and/or developing or reproducing the
# software by the user in light of its specific status of free software,
# that may mean that it is complicated to manipulate, and that also
# therefore means that it is reserved for developers and experienced
# professionals having in-depth computer knowledge. Users are therefore
# encouraged to load and test the software's suitability as regards their
# requirements in conditions enabling the security of their systems and/or
# data to be ensured and, more generally, to use and operate it in the
# same conditions as regards security.
#
# The fact that you are presently reading this means that you have had
# knowledge of the CeCILL license and that you accept its terms.
#
##############################################################################
XMCDA_2_0 = "http://www.decision-deck.org/xmcda/_downloads/XMCDA-2.0.0.xsd"
XMCDA_2_1 = "http://www.decision-deck.org/xmcda/_downloads/XMCDA-2.1.0.xsd"
XMCDA_2_2 = "http://www.decision-deck.org/xmcda/_downloads/XMCDA-2.2.0.xsd"
from lxml import etree
import sys, traceback
__version__="20111208-001"
##########################################################################
# #
# PARSING AND VALIDATING #
# #
##########################################################################
def parseValidate (xmlfile) :
"""
Parses and validates supplied the XMCDA file.
Returns the parsed (lxml) ElementTree, or None if the file
is not a valid XMCDA file.
"""
try :
xmltree = etree.parse(open(xmlfile, 'r'))
if validateXMCDA(xmltree) :
return xmltree.getroot()
except Exception as e:
traceback.print_exc(sys.stderr)
return None
def validateXMCDA (xmltree):
"Checks if xmltree is a valid XMCDA file."
ret = False
try: ret = validate(xmltree, XMCDA_2_0)
except Exception as e: traceback.print_exc(sys.stderr)
if ret:
return True
try: ret = validate(xmltree, XMCDA_2_1)
except Exception as e: traceback.print_exc(sys.stderr)
if ret:
return True
try: ret = validate(xmltree, XMCDA_2_2)
except Exception as e: traceback.print_exc(sys.stderr)
return ret
def validate (xmltree, xsdURL):
"Checks if xmltree is valid wrt the supplied xml schema"
# TODO (sbigaret) explain that!
xmlschema_doc = etree.parse(xsdURL,
etree.XMLParser(no_network=False))
xmlschema = etree.XMLSchema(xmlschema_doc)
return xmlschema.validate(xmltree)
##########################################################################
# #
# GET THE VALUES #
# #
##########################################################################
def getValue(xmltree) :
try :
xmlvalue = xmltree.find("value")
if xmlvalue.find("integer") != None :
val = int(xmlvalue.find("integer").text)
elif xmlvalue.find("real") != None :
val = float(xmlvalue.find("real").text)
elif xmlvalue.find("interval") != None :
val = "INTERVAL !"
elif xmlvalue.find("rational") != None :
val = float(xmlvalue.find("rational/numerator").text)/float(xmlvalue.find("rational/denominator").text)
elif xmlvalue.find("label") != None :
val = xmlvalue.find("label").text
elif xmlvalue.find("rankedlabel") != None :
val = float(xmlvalue.find("rank").text)
elif xmlvalue.find("boolean") != None :
val = xmlvalue.find("boolean").text
elif xmlvalue.find("NA") != None :
val = "NA"
elif xmlvalue.find("image") != None :
val = "IMAGE !"
elif xmlvalue.find("imageRef") != None :
val = "IMAGEREF !"
else :
val = None
except :
val = None
return val
##########
def getValues(xmltree) :
try :
xmlvalues = xmltree.find("values")
if xmlvalues != None :
values = []
for val in xmlvalues.findall("value") :
values.append(getValue(val))
except :
values = None
return values
##########
def getNumericValue(xmltree) :
# Only returns the value if it is numeric
try :
xmlvalue = xmltree.find("value")
if xmlvalue.find("integer") != None :
val = int(xmlvalue.find("integer").text)
elif xmlvalue.find("real") != None :
val = float(xmlvalue.find("real").text)
elif xmlvalue.find("rational") != None :
val = float(xmlvalue.find("rational/numerator").text)/float(xmlvalue.find("rational/denominator").text)
elif xmlvalue.find("NA") != None :
val = "NA"
else :
val = None
except :
val = None
return val
##########
def getNumericPerformanceTableValue (xmltree) :
# Cette fonction retourne les valeurs utilisables pour un tableau de performance numerique, et met None pour toute autre valeur
try :
xmlvalue = xmltree.find("value")
if xmlvalue.find("integer") != None :
val = int(xmlvalue.find("integer").text)
elif xmlvalue.find("real") != None :
val = float(xmlvalue.find("real").text)
elif xmlvalue.find("rational") != None :
val = float(xmlvalue.find("rational/numerator").text)/float(xmlvalue.find("rational/denominator").text)
elif xmlvalue.find("rankedLabel") != None :
val = float(xmlvalue.find("rankedLabel/rank").text)
elif xmlvalue.find("boolean") != None :
if xmlvalue.find("boolean").text == "true":
val = 1
else:
val = 0
else :
val = None
except :
val = None
return val
##########
#Deprecated
def getSimpleValue (xmltree) :
# Cette fonction retourne tous les types simples, c'est a dire tous sauf les intervalles, et les images
try :
xmlvalue = xmltree.find("value")
if xmlvalue.find("integer") != None :
val = int(xmlvalue.find("integer").text)
elif xmlvalue.find("real") != None :
val = float(xmlvalue.find("real").text)
elif xmlvalue.find("rational") != None :
val = float(xmlvalue.find("rational/numerator").text)/float(xmlvalue.find("rational/denominator").text)
elif xmlvalue.find("label") != None :
val = xmlvalue.find("label").text
elif xmlvalue.find("rankedLabel") != None :
val = float(xmlvalue.find("rankedLabel/rank").text)
elif xmlvalue.find("boolean") != None :
val = xmlvalue.find("boolean").text
elif xmlvalue.find("NA") != None :
val = "NA"
else :
val = None
except :
val = None
return val
##########
def getAlternativeValue (xmltree, alternativesId, mcdaConcept=None) :
if mcdaConcept == None :
strSearch = "alternativesValues"
else :
strSearch = "alternativesValues[@mcdaConcept=\'"+mcdaConcept+"\']"
try:
alternativesValues = xmltree.xpath(strSearch)[0]
except:
return {}
values = {}
for alternativeValue in alternativesValues.findall ("./alternativeValue") :
alt = alternativeValue.find ("alternativeID").text
if alternativeId.count(alt) > 0 :
values[alt] = getValue (alternativeValue)
return values
##########
def getCriterionValue (xmltree, criteriaId, mcdaConcept=None) :
if mcdaConcept == None :
strSearch = "criteriaValues"
else :
strSearch = "criteriaValues[@mcdaConcept=\'"+mcdaConcept+"\']"
try:
criteriaValues = xmltree.xpath(strSearch)[0]
except:
return {}
if criteriaValues is None:
return {}
values = {}
for criterionValue in criteriaValues.findall("./criterionValue"):
crit = criterionValue.find ("criterionID").text
if criteriaId.count(crit) > 0 :
values[crit] = getValue (criterionValue)
return values
##########################################################################
# #
# OBTAINING A LIST OF ID #
# #
##########################################################################
def getAlternativesID (xmltree, condition="ACTIVE") :
# Retourne la liste des alternatives, selon la condition suivante : ALL, ACTIVE, INACTIVE, FICTIVE, REAL, ACTIVEREAL, ACTIVEFICTIVE
# Par defaut, uniquement les alternatives ACTIVE
# On suppose que si rien n'est precise, l'alternative est active
alternativesID = []
for listAlternatives in xmltree.findall('alternatives'):
for alternative in listAlternatives.findall('alternative'):
act = alternative.find('active')
if act == None or act.text == "true":
active = True
else:
active = False
fic = alternative.find('type')
if fic == None or fic.text == "real":
fictive = False
else:
fictive = True
if condition == "ACTIVE" and active:
alternativesID.append(str(alternative.get('id')))
elif condition == "INACTIVE" and not active:
alternativesID.append(str(alternative.get('id')))
elif condition == "REAL" and not fictive:
alternativesID.append(str(alternative.get('id')))
elif condition == "FICTIVE" and fictive:
alternativesID.append(str(alternative.get('id')))
elif condition == "ACTIVEREAL" and active and not fictive:
alternativesID.append(str(alternative.get('id')))
elif condition == "ACTIVEFICTIVE" and active and fictive:
alternativesID.append(str(alternative.get('id')))
elif condition == "ALL":
alternativesID.append(str(alternative.get('id')))
return alternativesID
##########
def getCriteriaID (xmltree, condition="ACTIVE") :
# Retourne la liste des criteres, selon la condition suivante : ALL, ACTIVE, INACTIVE
# Par defaut, uniquement les criteres ACTIVE
# On suppose que si rien n'est precise, le critre est actif
criteriaID = []
for listCriteria in xmltree.findall('criteria'):
for criterion in listCriteria.findall('criterion'):
active = criterion.find('active')
if condition == "ACTIVE" and (active == None or active.text == "true") :
criteriaID.append(str(criterion.get('id')))
elif condition == "INACTIVE" and (active != None and active.text == "false") :
criteriaID.append(str(criterion.get('id')))
elif condition == "ALL" :
criteriaID.append(str(criterion.get('id')))
return criteriaID
##########
def getAttributesID (xmltree, condition="ACTIVE") :
# Retourne la liste des attributs, selon la condition suivante : ALL, ACTIVE, INACTIVE
# Par defaut, uniquement les attributs ACTIVE
# On suppose que si rien n'est precise, le attributs est actif
attributesID = []
for listAttributes in xmltree.findall('attributes'):
for attribute in listAttributes.findall('attribute'):
active = attribute.find('active')
if condition == "ACTIVE" and (active == None or active.text == "true") :
attributesID.append(str(attribute.get('id')))
elif condition == "INACTIVE" and (active != None and active.text == "false") :
attributesID.append(str(attribute.get('id')))
elif condition == "ALL" :
attributesID.append(str(attribute.get('id')))
return attributesID
##########
def getCategoriesID (xmltree) :
# Retourne la liste des categories
categoriesId = []
for listCategories in xmltree.findall('categories'):
for category in listCategories.findall('category'):
categoriesId.append(str(category.get('id')))
return categoriesId
##########
def getProfilesID (xmltree) :
# Retourne la liste des alternatives qui servent de profils
categoriesId = []
for listCategories in xmltree.findall('categories'):
for category in listCategories.findall('category'):
categoriesId.append(str(category.get('id')))
return categoriesId
##########
def getCategoriesProfiles (xmltree_profiles, catId):
catpro = {}
for cat in catId:
catpro[cat] = {}
for xmlprofile in xmltree_profiles.findall(".//categoryProfile"):
try:
profileId = xmlprofile.find("alternativeID").text
lowercat = xmlprofile.find("limits/lowerCategory/categoryID").text
uppercat = xmlprofile.find("limits/upperCategory/categoryID").text
catpro[lowercat]["upper"] = profileId
catpro[uppercat]["lower"] = profileId
except:
return {}
return catpro
##########
def getProfilesCategories (xmltree_profiles, catId):
procat = {}
for xmlprofile in xmltree_profiles.findall(".//categoryProfile"):
try:
profileId = xmlprofile.find("alternativeID").text
lowercat = xmlprofile.find("limits/lowerCategory/categoryID").text
uppercat = xmlprofile.find("limits/upperCategory/categoryID").text
procat[profileId] = {}
procat[profileId]["upper"] = uppercat
procat[profileId]["lower"] = lowercat
except:
return {}
return procat
##########
def getCategoriesRank(xmltree, catId):
categoriesRank = {}
for cat in catId :
try :
xml_dir = xmltree.xpath(".//category[@id='"+cat+"']/rank/integer")[0] #FIXME: Always integer?
categoriesRank[cat] = int(xml_dir.text)
except :
categoriesRank[cat] = -1
return categoriesRank
##########
def getAlternativesReferences (xmltree, altId) :
# Returns the list of alternativeID given in xmltree, only if they are all present in altId (if not, it returns an empty list)
listId = []
xmlId = xmltree.find("alternativeID")
if xmlId != None :
if altId.count(xmlId.text) > 0 :
listId.append(xmlId.text)
else :
for xmlId in xmltree.findall("alternativesSet/element/alternativeID") :
if altId.count(xmlId.text) > 0 :
listId.append(xmlId.text)
else :
listId = []
break
return listId
##########
def getCriteriaReferences (xmltree, criId) :
# Returns the list of criterionID given in xmltree, only if they are all present in criId (if not, it returns an empty list)
listId = []
xmlId = xmltree.find("criterionID")
if xmlId != None :
if criId.count(xmlId.text) > 0 :
listId.append(xmlId.text)
else :
for xmlId in xmltree.findall("criteriaSet/element/criterionID") :
if criId.count(xmlId.text) > 0 :
listId.append(xmlId.text)
else :
listId = []
break
return listId
##########
def getCategoriesReferences (xmltree, catId) :
# Returns the list of categoryID given in xmltree, only if they are all present in catId (if not, it returns an empty list)
listId = []
xmlId = xmltree.find("categoryID")
if xmlId != None :
if catId.count(xmlId.text) > 0 :
listId.append(xmlId.text)
else :
for xmlId in xmltree.findall("categoriesSet/element/categoryID") :
if catId.count(xmlId.text) > 0 :
listId.append(xmlId.text)
else :
listId = []
break
return listId
##########################################################################
# #
# GET THE PERFORMANCE TABLE #
# #
##########################################################################
def getPerformanceTable (xmltree, alternativesId, criteriaId) :
perfTable = xmltree.find(".//performanceTable")
Table = {}
if perfTable != None :
allAltPerf = perfTable.findall("alternativePerformances")
for altPerf in allAltPerf :
alt = altPerf.find("alternativeID").text
Table[alt]={}
allCritPerf = altPerf.findall("performance")
for critPerf in allCritPerf :
crit = critPerf.find("criterionID").text
val = getSimpleValue(critPerf)
Table[alt][crit] = val
return Table
##########
def getNumericPerformanceTable (xmltree, alternativesId, criteriaId) :
perfTable = xmltree.find(".//performanceTable")
Table = {}
if perfTable != None :
allAltPerf = perfTable.findall("alternativePerformances")
for altPerf in allAltPerf :
alt = altPerf.find("alternativeID").text
Table[alt]={}
allCritPerf = altPerf.findall("performance")
for critPerf in allCritPerf :
crit = critPerf.find("criterionID").text
val = getNumericPerformanceTableValue(critPerf)
Table[alt][crit] = val
return Table
##########################################################################
# #
# GET THE XXX COMPARISONS #
# #
##########################################################################
def getAlternativesComparisons (xmltree, altId, mcdaConcept=None) :
#Retourne le premier alternativeComparisons trouve avec le bon MCDAConcept (si precise)
#Par la suite, retourner une liste ?
if mcdaConcept == None :
strSearch = ".//alternativesComparisons"
else :
strSearch = ".//alternativesComparisons[@mcdaConcept=\'"+mcdaConcept+"\']"
comparisons = xmltree.xpath(strSearch)[0]
if comparisons == None :
return {}
else :
datas = {}
for pair in comparisons.findall ("pairs/pair") :
init = pair.find("initial/alternativeID").text
term = pair.find("terminal/alternativeID").text
val = getNumericValue(pair)
# Only the alternatives concerned
if altId.count(init) > 0 :
if altId.count(term) > 0 :
# We check if init is still an entry in the table
if not(datas.has_key(init)) :
datas[init] = {}
datas[init][term] = val
return datas
##########
def getCriteriaComparisons (xmltree, criId, mcdaConcept=None) :
#Retourne le premier criteriaComparisons trouve avec le bon MCDAConcept (si precise)
#Par la suite, retourner une liste ?
if mcdaConcept == None :
strSearch = ".//criteriaComparisons"
else :
strSearch = ".//criteriaComparisons[@mcdaConcept=\'"+mcdaConcept+"\']"
comparisons = xmltree.xpath(strSearch)[0]
if comparisons == None :
return []
else :
datas = []
for pair in comparisons.findall ("pairs/pair") :
comp = {}
comp["initial"] = getCriteriaReferences(pair.find("initial"), criId)
comp["terminal"] = getCriteriaReferences(pair.find("terminal"), criId)
if comp["initial"] != [] and comp["terminal"] != [] :
comp["val"] = getNumericValue(pair)
datas.append(comp)
return datas
##########
def getCategoriesComparisons (xmltree, catId, mcdaConcept=None) :
#Retourne le premier categoriesComparisons trouve avec le bon MCDAConcept (si precise)
#Par la suite, retourner une liste ?
if mcdaConcept == None :
strSearch = ".//categoriesComparisons"
else :
strSearch = ".//categoriesComparisons[@mcdaConcept=\'"+mcdaConcept+"\']"
comparisons = xmltree.xpath(strSearch)[0]
if comparisons == None :
return []
else :
datas = []
for pair in comparisons.findall ("pairs/pair") :
comp = {}
comp["initial"] = getCategoriesReferences(pair.find("initial"), catId)
comp["terminal"] = getCategoriesReferences(pair.find("terminal"), catId)
if comp["initial"] != [] and comp["terminal"] != [] :
comp["val"] = getNumericValue(pair)
datas.append(comp)
return datas
##########################################################################
# #
# GET THE THRESHOLDS #
# #
##########################################################################
def getConstantThresholds (xmltree, critId) :
thresholds = {}
try:
#On suppose pour le moment que les seuils sont constants
for criterion in xmltree.findall(".//criterion") :
criterionID = criterion.get("id")
xmlthresholds = criterion.find("thresholds")
if xmlthresholds != None :
tempThresholds = {}
for xmlthreshold in xmlthresholds.findall("threshold") :
xmlVal = xmlthreshold.find("constant/real")
if xmlVal == None :
xmlVal = xmlthreshold.find("constant/integer")
if xmlVal != None :
if xmlthreshold.get("mcdaConcept") != None :
tempThresholds[xmlthreshold.get("mcdaConcept")] = float(xmlVal.text)
thresholds[criterionID] = tempThresholds
else :
thresholds[criterionID] = {}
except :
return None
return thresholds
##########################################################################
# #
# GET CRITERION SCALE INFORMATION #
# #
##########################################################################
def getCriteriaScalesTypes (xmltree, critId) :
scalesTypes = {}
for crit in critId :
try :
xml_cri = xmltree.xpath(".//criterion[@id='"+crit+"']")[0]
if xml_cri.find("scale/qualitative") != None :
scalesTypes[crit] = "qualitative"
else :
scalesTypes[crit] = "quantitative"
except :
scalesTypes[crit] = "quantitative"
return scalesTypes
##########
def getCriteriaPreferenceDirections (xmltree, critId) :
prefDir = {}
for crit in critId :
try :
xml_dir = xmltree.xpath(".//criterion[@id='"+crit+"']/scale/*/preferenceDirection")[0]
prefDir[crit] = xml_dir.text
except :
prefDir[crit] = "max"
return prefDir
##########
def getCriteriaLowerBounds (xmltree, critId) :
LB = {}
for crit in critId :
try :
xml_val = xmltree.xpath(".//criterion[@id='"+crit+"']/scale/quantitative/minimum/*")[0]
LB[crit] = float(xml_val.text)
except :
LB[crit] = None
return LB
##########
def getCriteriaUpperBounds (xmltree, critId) :
UB = {}
for crit in critId :
try :
xml_val = xmltree.xpath(".//criterion[@id='"+crit+"']/scale/quantitative/maximum/*")[0]
UB[crit] = float(xml_val.text)
except :
UB[crit] = None
return UB
##########
def getCriteriaRankedLabel (xmltree, critId) :
RL = {}
for crit in critId :
try :
xml_val = xmltree.xpath(".//criterion[@id='"+crit+"']/scale/qualitative")[0]
if xml_val == None :
RL[crit] = None
else :
RL[crit] = {}
for rankedLabel in xml_val.findall("rankedLabel") :
RL[crit][rankedLabel.find("rank").text] = rankedLabel.find("label").text
except :
RL[crit] = None
return RL
##########################################################################
# #
# GET THE PARAMETERS #
# #
##########################################################################
def getParameterByName (xmltree, paramName, paramFamilyName = None) :
try :
if paramFamilyName == None :
param = xmltree.xpath(".//parameter[@name='"+paramName+"']")[0]
else :
param = xmltree.xpath(".//methodParameters[@name=\'"+paramFamilyName+"\']/parameter[@name=\'"+paramName+"\']")[0]
if param != None :
return getValue(param)
else :
return None
except :
return None
##########
def getParametersByName (xmltree, paramName, paramFamilyName = None) :
try :
if paramFamilyName == None :
params = xmltree.xpath(".//parameters[@name='"+paramName+"']")[0]
else :
params = xmltree.xpath(".//methodParameters[@name=\'"+paramFamilyName+"\']/parameters[@name=\'"+paramName+"\']")[0]
if params != None :
paramList = []
for param in params.findall("parameter") :
paramList.append(getValue(param))
return paramList
else :
return {}
except :
return {}
##########
def getNamedParametersByName (xmltree, paramName, paramFamilyName = None) :
try :
if paramFamilyName == None :
params = xmltree.xpath(".//parameters[@name='"+paramName+"']")[0]
else :
params = xmltree.xpath(".//methodParameters[@name=\'"+paramFamilyName+"\']/parameters[@name=\'"+paramName+"\']")[0]
if params != None :
paramList = {}
for param in params.findall("parameter") :
index = param.get("name")
if index :
paramList[index] = getValue(param)
return paramList
else :
return {}
except :
return {}
##########################################################################
# #
# GET ALTERNATIVES AFFECTATION #
# #
##########################################################################
def getAlternativesAffectations(xmltree):
affectations = xmltree.find(".//alternativesAffectations")
table = {}
if affectations != None :
alts_aff = affectations.findall("alternativeAffectation")
for alt_aff in alts_aff :
alt = alt_aff.find("alternativeID").text
aff = alt_aff.find("categoryID").text
table[alt] = aff
return table
##########################################################################
# #
# WORKING WITH XMLTREE #
# #
##########################################################################
def xmlDeleteThresholds (xmltree, thresholdName = None):
# Supprime les seuils definis.
# Pour le moment, tous, il faudra apres modifier pour ne prendre que ceux s'appelant thresholdName
for xmlThreshold in xmltree.findall(".//thresholds"):
xmlThreshold.getparent().remove(xmlThreshold)
def xmlAddThresholds (xmltree, thresholdsList):
# Ajoute les seuils dans xmltree
# Syntaxe de thresholdsList : thresholds[criterion][thresholdsName] = valeur associee
for crit in thresholdsList:
# On regarde si le critere existe
try:
xmlCriterion = xmltree.xpath(".//criterion[@id='"+crit+"']")[0]
except:
# Le critere n'existe pas, on continue
# REMARQUE : on devrait lever une erreur ou au moins un warning
continue
# On regarde s'il y a un tag thresholds defini sous le critere
xmlCriterionThresholds = xmlCriterion.find("thresholds")
if xmlCriterionThresholds is None:
# On cree le tag thresholds
xmlCriterionThresholds = etree.SubElement(xmlCriterion, "thresholds")
for threshold in thresholdsList[crit]:
# On verifie si le seuil existe deja
xmlCriterionThreshold = xmlCriterionThresholds.xpath("threshold[@id='"+threshold+"']")
if xmlCriterionThreshold != []:
# le seuil existe, on le supprime
xmlCriterionThresholds.remove(xmlCriterionThreshold[0])
# On ajoute le seuil avec la valeur
xmlCriterionThreshold = etree.SubElement(xmlCriterionThresholds, "threshold")
xmlCriterionThreshold.set("id", threshold)
xmlCriterionThreshold.set("name", threshold)
xmlCriterionThreshold.set("mcdaConcept", threshold)
xmlCriterionThreshold.text = ""
xmlConstant = etree.SubElement(xmlCriterionThreshold, "constant")
xmlConstant.text = ""
xmlReal = etree.SubElement(xmlConstant, "real")
xmlReal.text = thresholdsList[crit][threshold]
def xmlWrite (xmltree, xmlFileName):
ET = etree.ElementTree (xmltree)
ET.write(xmlFileName, encoding="UTF-8")
##########################################################################
# #
# WRITE IN FILES #
# #
##########################################################################
def writeHeader (xmlfile) :
xmlfile.write ("<?xml version='1.0' encoding='UTF-8'?>\n<?xml-stylesheet type='text/xsl' href='xmcdaXSL.xsl'?>\n")
xmlfile.write("<xmcda:XMCDA xmlns:xmcda='http://www.decision-deck.org/2009/XMCDA-2.0.0' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://www.decision-deck.org/2009/XMCDA-2.0.0 http://sma.uni.lu/d2cms/xmcda/_downloads/XMCDA-2.0.0.xsd'>\n\n")
##########
def writeFooter (xmlfile) :
xmlfile.write ("\n</xmcda:XMCDA>\n")
##########
def createMessagesFile (fileName, logMess, warnMess, errorMess):
# Creating a message file
xmlfile = open(fileName, 'w')
writeHeader (xmlfile)
writeMessages (xmlfile, logMess, warnMess, errorMess)
writeFooter(xmlfile)
xmlfile.close()
##########
def writeMessages (xmlfile, logMess, warnMess, errorMess) :
xmlfile.write ("<methodMessages>\n")
for message in logMess :
xmlfile.write ("<logMessage><text><![CDATA["+message+"]]></text></logMessage>\n")
for message in warnMess :