def get_input_data(input_dir):
    file_names = (
        'alternatives.xml',
        'categoriesProfiles.xml',
        'criteria.xml',
        'performanceTable.xml',
        'profilesPerformanceTable.xml',
    )
    trees = get_trees(input_dir, file_names)

    alternatives = px.getAlternativesID(trees['alternatives'])
    criteria = px.getCriteriaID(trees['criteria'])
    pref_directions = px.getCriteriaPreferenceDirections(trees['criteria'], criteria)
    thresholds = px.getConstantThresholds(trees['criteria'], criteria)
    performances = px.getPerformanceTable(trees['performanceTable'], None, None)
    categories_profiles = get_categories_profiles_central(trees['categoriesProfiles'])
    profiles_performance_table = px.getPerformanceTable(
        trees['profilesPerformanceTable'], None, None
    )

    ret = {
        'alternatives': alternatives,
        'categories_profiles': categories_profiles,
        'criteria': criteria,
        'performances': performances,
        'pref_directions': pref_directions,
        'profiles_performance_table': profiles_performance_table,
        'thresholds': thresholds,
    }
    return ret
def get_input_data(input_dir):
    file_names = (
        'alternatives.xml',
        'categoriesProfiles.xml',
        'criteria.xml',
        'performanceTable.xml',
        'profilesPerformanceTable.xml',
        'weights.xml',
    )
    trees = get_trees(input_dir, file_names)

    alternatives = px.getAlternativesID(trees['alternatives'])
    criteria = px.getCriteriaID(trees['criteria'])
    pref_directions = px.getCriteriaPreferenceDirections(trees['criteria'], criteria)
    thresholds = px.getConstantThresholds(trees['criteria'], criteria)
    weights = px.getCriterionValue(trees['weights'], criteria)
    performances = px.getPerformanceTable(trees['performanceTable'], None, None)
    categories_profiles = get_categories_profiles_central(trees['categoriesProfiles'])
    profiles_performance_table = px.getPerformanceTable(trees['profilesPerformanceTable'],
                                                        None, None)

    ret = {
        'alternatives': alternatives,
        'categories_profiles': categories_profiles,
        'criteria': criteria,
        'performances': performances,
        'pref_directions': pref_directions,
        'profiles_performance_table': profiles_performance_table,
        'thresholds': thresholds,
        'weights': weights,
    }
    return ret
def get_input_data(input_dir):
    file_names = (
        'alternatives.xml',
        'performanceTable.xml',
        'categoriesProfiles.xml',
        'criteria.xml',
        'profilesPerformanceTable.xml',
    )
    trees = get_trees(input_dir, file_names)

    alternatives = px.getAlternativesID(trees['alternatives'])
    criteria = px.getCriteriaID(trees['criteria'])
    pref_directions = px.getCriteriaPreferenceDirections(trees['criteria'], criteria)
    thresholds = px.getConstantThresholds(trees['criteria'], criteria)
    performances = px.getPerformanceTable(trees['performanceTable'], None, None)
    profiles_performance_table = px.getPerformanceTable(trees['profilesPerformanceTable'], None, None)
    cp_tree = trees['categoriesProfiles']
    # we need only categories profiles' names
    categories_profiles = [p for p in cp_tree.xpath('//categoriesProfiles//alternativeID/text()')]

    ret = {
        'alternatives': alternatives,
        'categories_profiles': categories_profiles,
        'criteria': criteria,
        'performances': performances,
        'pref_directions': pref_directions,
        'profiles_performance_table': profiles_performance_table,
        'thresholds': thresholds,
    }
    return ret
def get_input_data(input_dir):
    file_names = (
        'alternatives.xml',
        'criteria.xml',
        'interactions.xml',
        'method_parameters.xml',
        'performance_table.xml',
        'weights.xml',
    )
    trees = get_trees(input_dir, file_names)

    alternatives = px.getAlternativesID(trees['alternatives'])
    criteria = px.getCriteriaID(trees['criteria'])
    pref_directions = px.getCriteriaPreferenceDirections(trees['criteria'], criteria)
    thresholds = px.getConstantThresholds(trees['criteria'], criteria)
    weights = px.getCriterionValue(trees['weights'], criteria)
    performances = px.getPerformanceTable(trees['performance_table'], 1, 1)
    interactions = get_criteria_interactions(trees['interactions'], criteria)

    check_net_balance(interactions, weights)
    z_function = px.getParameterByName(trees['method_parameters'], 'z_function')

    ret = {
        'alternatives': alternatives,
        'criteria': criteria,
        'interactions': interactions,
        'performances': performances,
        'pref_directions': pref_directions,
        'thresholds': thresholds,
        'weights': weights,
        'z_function': z_function,
    }
    return ret
Пример #5
0
def get_input_data(input_dir):
    file_names = (
        'alternatives.xml',
        'criteria.xml',
        'interactions.xml',
        'method_parameters.xml',
        'performance_table.xml',
        'weights.xml',
    )
    trees = get_trees(input_dir, file_names)

    alternatives = px.getAlternativesID(trees['alternatives'])
    criteria = px.getCriteriaID(trees['criteria'])
    pref_directions = px.getCriteriaPreferenceDirections(
        trees['criteria'], criteria)
    thresholds = px.getConstantThresholds(trees['criteria'], criteria)
    weights = px.getCriterionValue(trees['weights'], criteria)
    performances = px.getPerformanceTable(trees['performance_table'], 1, 1)
    interactions = get_criteria_interactions(trees['interactions'], criteria)

    check_net_balance(interactions, weights)
    z_function = px.getParameterByName(trees['method_parameters'],
                                       'z_function')

    ret = {
        'alternatives': alternatives,
        'criteria': criteria,
        'interactions': interactions,
        'performances': performances,
        'pref_directions': pref_directions,
        'thresholds': thresholds,
        'weights': weights,
        'z_function': z_function,
    }
    return ret
Пример #6
0
def get_input_data(input_dir):
    file_names = (
        'alternatives.xml',
        'performanceTable.xml',
        'categoriesProfiles.xml',
        'criteria.xml',
        'profilesPerformanceTable.xml',
    )
    trees = get_trees(input_dir, file_names)

    alternatives = px.getAlternativesID(trees['alternatives'])
    criteria = px.getCriteriaID(trees['criteria'])
    pref_directions = px.getCriteriaPreferenceDirections(
        trees['criteria'], criteria)
    thresholds = px.getConstantThresholds(trees['criteria'], criteria)
    performances = px.getPerformanceTable(trees['performanceTable'], None,
                                          None)
    profiles_performance_table = px.getPerformanceTable(
        trees['profilesPerformanceTable'], None, None)
    cp_tree = trees['categoriesProfiles']
    # we need only categories profiles' names
    categories_profiles = [
        p for p in cp_tree.xpath('//categoriesProfiles//alternativeID/text()')
    ]

    ret = {
        'alternatives': alternatives,
        'categories_profiles': categories_profiles,
        'criteria': criteria,
        'performances': performances,
        'pref_directions': pref_directions,
        'profiles_performance_table': profiles_performance_table,
        'thresholds': thresholds,
    }
    return ret
Пример #7
0
def parse_xmcda_files(in_weights, in_hierarchy, in_concorlevel, in_criteria, in_alternatives, in_performances):
    xml_crit = px.parseValidate(in_criteria)
    xml_alt = px.parseValidate(in_alternatives)
    xml_pt = px.parseValidate(in_performances)
    xml_weight = px.parseValidate(in_weights)
    xml_hierarchy = px.parseValidate(in_hierarchy)
    xml_concordance = px.parseValidate(in_concorlevel)
    if xml_crit == None:
        raise ValueError, ["Invalid criteria file"]
    if xml_alt == None:
        raise ValueError, ["Invalid alternative file"]
    if xml_pt == None:
        raise ValueError, ["Invalid performance table file"]
    if xml_weight == None:
        raise ValueError, ["Invalid weight file"]
    if xml_hierarchy == None:
        raise ValueError, ["Invalid assignment file"]
    if xml_concordance == None:
        raise ValueError, ["Invalid concordance file"]

    try:
        alternatives_ids = px.getAlternativesID(xml_alt)
        criteria_ids = px.getCriteriaID(xml_crit)
        performance_table = px.getPerformanceTable(xml_pt, alternatives_ids, criteria_ids)
        criteriaWeight = px.getCriterionValue(xml_weight, criteria_ids, 'Importance')
        preferenceDirections = px.getCriteriaPreferenceDirections(xml_crit, criteria_ids)
        hierarchyArray = get_hierarchy_array(xml_hierarchy)
        criteria_thresholds = px.getConstantThresholds(xml_crit, criteria_ids)
        concordanceCutLev = get_criterion_concordance_cutting_level_value(xml_concordance, 'Concordance')
    except:
        raise ValueError, ["Failed to parse one or more file"]
        return

    return alternatives_ids, criteria_ids, performance_table, criteriaWeight, preferenceDirections, hierarchyArray, criteria_thresholds, concordanceCutLev
def get_input_data(input_dir):
    file_names = (
        'alternatives.xml',
        'performanceTable.xml',
        'categoriesProfiles.xml',
        'criteria.xml',
        'profilesPerformanceTable.xml',
        'weights.xml',
    )
    trees = get_trees(input_dir, file_names)

    alternatives = px.getAlternativesID(trees['alternatives'])
    criteria = px.getCriteriaID(trees['criteria'])
    pref_directions = px.getCriteriaPreferenceDirections(
        trees['criteria'], criteria)
    thresholds = px.getConstantThresholds(trees['criteria'], criteria)
    weights = px.getCriterionValue(trees['weights'], criteria)
    performances = px.getPerformanceTable(trees['performanceTable'], 1, 1)

    # we can't assume that categories will be always available as a separate
    # input file, therefore it's better to extract them from categoriesProfiles
    cp_tree = trees['categoriesProfiles']
    categories = list(
        set(cp_tree.xpath('//categoriesProfiles//limits//categoryID/text()')))
    # since we just need names of categories profiles, it's better to get them like below
    # - otherwise, to get 'full' categories profiles, we should use this:
    # categories_profiles = px.getCategoriesProfiles(trees['categoriesProfiles'], categories)
    categories_profiles = [
        p for p in cp_tree.xpath('//categoriesProfiles//alternativeID/text()')
    ]
    # last two args to getPerformanceTable are not used at all anyway...
    profiles_performance_table = px.getPerformanceTable(
        trees['profilesPerformanceTable'], None, None)

    ret = {
        'alternatives': alternatives,
        'categories_profiles': categories_profiles,
        'criteria': criteria,
        'performances': performances,
        'pref_directions': pref_directions,
        'profiles_performance_table': profiles_performance_table,
        'thresholds': thresholds,
        'weights': weights,
    }
    return ret
def get_input_data(input_dir):
    file_names = (
        'alternatives.xml',
        'performanceTable.xml',
        'categoriesProfiles.xml',
        'criteria.xml',
        'profilesPerformanceTable.xml',
        'weights.xml',
    )
    trees = get_trees(input_dir, file_names)

    alternatives = px.getAlternativesID(trees['alternatives'])
    criteria = px.getCriteriaID(trees['criteria'])
    pref_directions = px.getCriteriaPreferenceDirections(trees['criteria'], criteria)
    thresholds = px.getConstantThresholds(trees['criteria'], criteria)
    weights = px.getCriterionValue(trees['weights'], criteria)
    performances = px.getPerformanceTable(trees['performanceTable'], 1, 1)

    # we can't assume that categories will be always available as a separate
    # input file, therefore it's better to extract them from categoriesProfiles
    cp_tree = trees['categoriesProfiles']
    categories = list(set(cp_tree.xpath('//categoriesProfiles//limits//categoryID/text()')))
    # since we just need names of categories profiles, it's better to get them like below
    # - otherwise, to get 'full' categories profiles, we should use this:
    # categories_profiles = px.getCategoriesProfiles(trees['categoriesProfiles'], categories)
    categories_profiles = [p for p in cp_tree.xpath('//categoriesProfiles//alternativeID/text()')]
    # last two args to getPerformanceTable are not used at all anyway...
    profiles_performance_table = px.getPerformanceTable(trees['profilesPerformanceTable'], None, None)

    ret = {
        'alternatives': alternatives,
        'categories_profiles': categories_profiles,
        'criteria': criteria,
        'performances': performances,
        'pref_directions': pref_directions,
        'profiles_performance_table': profiles_performance_table,
        'thresholds': thresholds,
        'weights': weights,
    }
    return ret
def get_input_data(input_dir):
    file_names = (
        'alternatives.xml',
        'criteria.xml',
        'performanceTable.xml',
    )
    trees = get_trees(input_dir, file_names)

    criteria = px.getCriteriaID(trees['criteria'])
    pref_directions = px.getCriteriaPreferenceDirections(
        trees['criteria'], criteria)
    thresholds = px.getConstantThresholds(trees['criteria'], criteria)
    performances = px.getPerformanceTable(trees['performanceTable'], None,
                                          None)

    ret = {
        'criteria': criteria,
        'performances': performances,
        'pref_directions': pref_directions,
        'thresholds': thresholds,
    }
    return ret
def main(argv=None):
	if argv is None:
		argv = sys.argv
	
	parser = OptionParser()
	
	parser.add_option("-i", "--in", dest="in_dir")
	parser.add_option("-o", "--out", dest="out_dir")
	
	(options, args) = parser.parse_args(argv[1:])
	
	in_dir = options.in_dir
	out_dir = options.out_dir
	
	# Creating lists for error and log messages
	errorList = []
	logList = []
	
	# If some mandatory input files are missing
	if not os.path.isfile (in_dir+"/alternatives.xml") or not os.path.isfile (in_dir+"/criteria.xml") or not os.path.isfile (in_dir+"/alternativesComparisons.xml") or not os.path.isfile (in_dir+"/performanceTable.xml") :
		errorList.append("Some input files are missing")
	
	else :
		
		maxWeight = 0
		
		if os.path.isfile (in_dir+"/maxWeight.xml") :
			xmltree_maxWeight = PyXMCDA.parseValidate(in_dir+"/maxWeight.xml")
			if xmltree_maxWeight == None :
				errorList.append ("maxWeight file can't be validated.")
			else :
				maxWeight = PyXMCDA.getParameterByName (xmltree_maxWeight, "maxWeight")
				if not isinstance(maxWeight,int) :
					errorList.append ("maxWeight value should be a strictly positive integer")
				else :
					if maxWeight <= 0 :
						errorList.append ("maxWeightvalue should be a strictly positive integer")
			
			
		xmltree_alternatives = PyXMCDA.parseValidate(in_dir+"/alternatives.xml")
		xmltree_criteria = PyXMCDA.parseValidate(in_dir+"/criteria.xml")
		xmltree_altComparisons = PyXMCDA.parseValidate(in_dir+"/alternativesComparisons.xml")
		xmltree_perfTable = PyXMCDA.parseValidate(in_dir+"/performanceTable.xml")
		
		if xmltree_alternatives == None :
			errorList.append("The alternatives file can't be validated.")
		if xmltree_criteria == None :
			errorList.append("The criteria file can't be validated.")
		if xmltree_perfTable == None :
			errorList.append("The performance table file can't be validated.")
		if xmltree_altComparisons == None :
			errorList.append("The alternatives comparisons file can't be validated.")
	
		if not errorList :
		
			alternativesId = PyXMCDA.getAlternativesID(xmltree_alternatives)
			criteriaId = PyXMCDA.getCriteriaID(xmltree_criteria)
			perfTable = PyXMCDA.getPerformanceTable(xmltree_perfTable, alternativesId, criteriaId)
			thresholds = PyXMCDA.getConstantThresholds (xmltree_criteria, criteriaId)
			altComparisons = PyXMCDA.getAlternativesComparisons (xmltree_altComparisons, alternativesId)
			
			criComparisons = {}
			if os.path.isfile (in_dir+"/criteriaComparisons.xml") :
				xmltree_criComparisons = PyXMCDA.parseValidate(in_dir+"/criteriaComparisons.xml")
				if xmltree_criComparisons == None :
					errorList.append ("criteriaComparisons file can't be validated")
				else :
					criComparisons = PyXMCDA.getCriteriaComparisons (xmltree_criComparisons, criteriaId)
			
			criLB = {}
			if os.path.isfile (in_dir+"/criteriaLowerBounds.xml") :
				xmltree_criLB = PyXMCDA.parseValidate(in_dir+"/criteriaLowerBounds.xml")
				if xmltree_criLB == None :
					errorList.append ("criteriaLowerBounds file can't be validated")
				else :
					criLB = PyXMCDA.getCriterionValue (xmltree_criLB, criteriaId)
					
			criUB = {}
			if os.path.isfile (in_dir+"/criteriaUpperBounds.xml") :
				xmltree_criUB = PyXMCDA.parseValidate(in_dir+"/criteriaUpperBounds.xml")
				if xmltree_criUB == None :
					errorList.append ("criteriaUpperBounds file can't be validated")
				else :
					criUB = PyXMCDA.getCriterionValue (xmltree_criUB, criteriaId)
					
			
			if not alternativesId :
				errorList.append("No alternatives found. Is your alternatives file correct ?")
			if not criteriaId :
				errorList.append("No criteria found. Is your criteria file correct ?")
			if not perfTable :
				errorList.append("No performance table found. Is your performance table file correct ?")
			#if not altComparisons :
			#	errorList.append("No alternatives comparisons found. Is your file correct ?")
			if not thresholds :
				errorList.append("Problem when retrieving the thresholds. The thresholds need to be constant.")
		
	if not errorList :
	
		p = subprocess.Popen(['ampl'], shell=False, bufsize=0,stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
		
		# We write in the pipe the first part of the ampl file
		file = open ("amplRoadef2010_model.txt", 'r')
		p.stdin.write(file.read()) 
		p.stdin.write("\n")
		
		lib_ampl_reverse.create_ampl_reverse_data (p.stdin, alternativesId, criteriaId, perfTable, altComparisons, thresholds, maxWeight, criComparisons, criLB, criUB)
		
		file = open ("amplRoadef2010_solve.txt", 'r')
		p.stdin.write(file.read())
		p.stdin.write("\n")
		p.stdin.flush()
		
		# Calling CPlex for solving MILP
		output,stderr = p.communicate()
		status = p.returncode
		
		# We check the correct resolution
		if status == 0  and not stderr :
			
			if PyXMCDA.getStringPart(output, "nolicense") == "" :
			
				if PyXMCDA.getStringPart(output, "infeasible") != "infeasible" :
							
					# We create the criteriaWeights file
					fileWeights = open(out_dir+"/criteriaWeights.xml", 'w')
					PyXMCDA.writeHeader (fileWeights)
					fileWeights.write (PyXMCDA.getStringPart(output, "criteriaValues"))	
					logList.append("Execution ok")
					logList.append(PyXMCDA.getStringPart(output, "slackSum")) 
					logList.append(PyXMCDA.getCleanedStringPart(output, "CPLexInfos"))
					PyXMCDA.writeFooter(fileWeights)
					fileWeights.close()
				
				else :
					errorList.append ("Infeasible problem.")
					errorList.append (PyXMCDA.getStringPart(output, "CPLexInfos"))
								
			else :
				errorList.append ("No license available.")
				errorList.append (PyXMCDA.getStringPart(output, "CPLexInfos"))
			
		else :
			errorList.append ("CPlex is unable to solve the problem.")
			errorList.append ("CPlex returned status : " + str(status))
			errorList.append (stderr)
		
	
	
	# Creating log and error file, messages.xml
	fileMessages = open(out_dir+"/messages.xml", 'w')
	PyXMCDA.writeHeader (fileMessages)
	
	if not errorList :
		PyXMCDA.writeLogMessages (fileMessages, logList)
	else :
		PyXMCDA.writeErrorMessages (fileMessages, errorList)
		
	PyXMCDA.writeFooter(fileMessages)
	fileMessages.close()
Пример #12
0
def main(argv=None):
	if argv is None:
		argv = sys.argv
	
	parser = OptionParser()
	
	parser.add_option("-i", "--in", dest="in_dir")
	parser.add_option("-o", "--out", dest="out_dir")
	
	(options, args) = parser.parse_args(argv[1:])
	
	in_dir = options.in_dir
	out_dir = options.out_dir
	
	# Creating a list for error messages
	errorList = []
	
	# If some mandatory input files are missing
	if not os.path.isfile (in_dir+"/alternatives.xml") or not os.path.isfile (in_dir+"/criteria.xml") or not os.path.isfile (in_dir+"/criteriaWeights.xml") or not os.path.isfile (in_dir+"/performanceTable.xml") :
		errorList.append("Some input files are missing")
	
	else :
		
		# We parse all the mandatory input files
		xmltree_alternatives = PyXMCDA.parseValidate(in_dir+"/alternatives.xml")
		xmltree_criteria = PyXMCDA.parseValidate(in_dir+"/criteria.xml")
		xmltree_weights = PyXMCDA.parseValidate(in_dir+"/criteriaWeights.xml")
		xmltree_perfTable = PyXMCDA.parseValidate(in_dir+"/performanceTable.xml")
		
		# We check if all madatory input files are valid
		if xmltree_alternatives == None :
			errorList.append("The alternatives file can't be validated.")
		if xmltree_criteria == None :
			errorList.append("The criteria file can't be validated.")
		if xmltree_perfTable == None :
			errorList.append("The performance table file can't be validated.")
		if xmltree_weights == None :
			errorList.append("The criteria weights file can't be validated.")
		
		if not errorList :
		
			alternativesId = PyXMCDA.getAlternativesID(xmltree_alternatives)
			criteriaId = PyXMCDA.getCriteriaID(xmltree_criteria)
			perfTable = PyXMCDA.getPerformanceTable(xmltree_perfTable, alternativesId, criteriaId)
			thresholds = PyXMCDA.getConstantThresholds (xmltree_criteria, criteriaId)
			weights = PyXMCDA.getCriterionValue (xmltree_weights, criteriaId)
		
			if not alternativesId :
				errorList.append("No alternatives found. Is your alternatives file correct ?")
			if not criteriaId :
				errorList.append("No criteria found. Is your criteria file correct ?")
			if not perfTable :
				errorList.append("No performance table found. Is your performance table file correct ?")
			if not weights :
				errorList.append("No weights found. Is your weights file correct ?")
	
	
	if not errorList :
	
		# We check if a criterion weight is defined for all the active criteria
		for crit in criteriaId :
			if not weights.has_key(crit) :
				errorList.append("There is no defined weight for criterion "+crit+".")
		
		
	if not errorList :
		
		# We compute the weighted sum for all the active alternatives
		fileAltValues = open(out_dir+"/alternativesValues.xml", 'w')
		PyXMCDA.writeHeader (fileAltValues)
		
		fileAltValues.write ("<alternativesValues>\n")
		
		for alt in alternativesId :
		
			fileAltValues.write("<alternativeValue><alternativeID>"+alt+"</alternativeID><value>")
			sum = 0.0
			errorAlt = False
	
			for crit in criteriaId :
				
				try :
					sum = sum + weights[crit] * perfTable[alt][crit]
				except :
					errorList.append("No evaluation found for alternative "+alt+" on criterion "+crit+" in the performance table.")
					errorAlt = True
		
			if not errorAlt :	
				fileAltValues.write ("<real>"+str(sum)+"</real></value></alternativeValue>\n")
			else :
				fileAltValues.write ("<NA>not available</NA></value></alternativeValue>\n")
			
		fileAltValues.write ("</alternativesValues>")
		
		PyXMCDA.writeFooter(fileAltValues)
		fileAltValues.close()
	
	# Creating log and error file, messages.xml
	fileMessages = open(out_dir+"/messages.xml", 'w')
	PyXMCDA.writeHeader (fileMessages)
	
	if not errorList :
	
		PyXMCDA.writeLogMessages (fileMessages, ["Execution ok"])
	else :
		PyXMCDA.writeErrorMessages (fileMessages, errorList)
		
	PyXMCDA.writeFooter(fileMessages)
	fileMessages.close()
def main(argv=None):
	if argv is None:
		argv = sys.argv
	
	parser = OptionParser()
	
	parser.add_option("-i", "--in", dest="in_dir")
	parser.add_option("-o", "--out", dest="out_dir")
	
	(options, args) = parser.parse_args(argv[1:])
	
	in_dir = options.in_dir
	out_dir = options.out_dir
	
	# Creating a list for error messages
	errorList = []
	
	# If some mandatory input files are missing
	if not os.path.isfile (in_dir+"/alternatives.xml") or not os.path.isfile (in_dir+"/criteria.xml") or not os.path.isfile (in_dir+"/criteriaWeights.xml") or not os.path.isfile (in_dir+"/performanceTable.xml") :
		errorList.append("Some input files are missing")
	
	else :
		
		# We parse all the mandatory input files
		xmltree_alternatives = PyXMCDA.parseValidate(in_dir+"/alternatives.xml")
		xmltree_criteria = PyXMCDA.parseValidate(in_dir+"/criteria.xml")
		xmltree_weights = PyXMCDA.parseValidate(in_dir+"/criteriaWeights.xml")
		xmltree_perfTable = PyXMCDA.parseValidate(in_dir+"/performanceTable.xml")
		
		# We check if all madatory input files are valid
		if xmltree_alternatives == None :
			errorList.append("The alternatives file can't be validated.")
		if xmltree_criteria == None :
			errorList.append("The criteria file can't be validated.")
		if xmltree_perfTable == None :
			errorList.append("The performance table file can't be validated.")
		if xmltree_weights == None :
			errorList.append("The criteria weights file can't be validated.")
		
		# By default, the valuation domain is fixed to [0,1]	
		minValDomain = 0
		maxValDomain = 1
		
		# If a valuation domain input file has been provided
		if os.path.isfile (in_dir+"/valuationDomain.xml") :
		
			xmltree_valuation = PyXMCDA.parseValidate(in_dir+"/valuationDomain.xml")
			if xmltree_valuation == None :
				errorList.append ("valuationDomain file can't be validated.")
				
			else :
			
				minValDomain = PyXMCDA.getParameterByName (xmltree_valuation, "min", "valuationDomain")
				maxValDomain = PyXMCDA.getParameterByName (xmltree_valuation, "max", "valuationDomain")
				
				# We check the validity of the parameters
				if not isinstance(minValDomain,float) and not isinstance(minValDomain,int) :
					errorList.append ("min value should be an integer or a real")
				if not isinstance(maxValDomain,float) and not isinstance(maxValDomain,int) :
					errorList.append ("max value should be an integer or a real")
					
				if not errorList :
					if minValDomain >= maxValDomain :
						errorList.append ("The max value should be strictly greater than the min value")
	
		if not errorList :
		
			alternativesId = PyXMCDA.getAlternativesID(xmltree_alternatives)
			criteriaId = PyXMCDA.getCriteriaID(xmltree_criteria)
			perfTable = PyXMCDA.getPerformanceTable(xmltree_perfTable, alternativesId, criteriaId)
			thresholds = PyXMCDA.getConstantThresholds (xmltree_criteria, criteriaId)
			weights = PyXMCDA.getCriterionValue (xmltree_weights, criteriaId)
		
			if not alternativesId :
				errorList.append("No alternatives found. Is your alternatives file correct ?")
			if not criteriaId :
				errorList.append("No criteria found. Is your criteria file correct ?")
			if not perfTable :
				errorList.append("No performance table found. Is your performance table file correct ?")
			if not weights :
				errorList.append("No weights found. Is your weights file correct ?")
		
	if not errorList :
	
		# We compute the weight sum (only the weights associated to active criteria)
		sumWeights = 0.0
		
		for crit in criteriaId :
			try :
				sumWeights = sumWeights + weights[crit]
			except :
				errorList.append("There is no defined weight for criterion "+crit+".")
		
	if not errorList :
		
		# We recover the criteria preference directions
		criteriaDir = PyXMCDA.getCriteriaPreferenceDirections (xmltree_criteria, criteriaId)
	
		# We compute the alternative comparisons values
		fileAltValues = open(out_dir+"/alternativesComparisons.xml", 'w')
		PyXMCDA.writeHeader (fileAltValues)
		
		fileAltValues.write ("\t<alternativesComparisons>\n\t\t<pairs>\n")
		
		ElemOut = PyXMCDA.getRubisElementaryOutranking (alternativesId, criteriaId, perfTable, thresholds)
		
		for alt1 in alternativesId :
			for alt2 in alternativesId :
			
				fileAltValues.write("\t\t\t<pair>\n\t\t\t\t<initial><alternativeID>"+alt1+"</alternativeID></initial>\n\t\t\t\t<terminal><alternativeID>"+alt2+"</alternativeID></terminal>\n")
				
				# Verifier s'il manque des valeurs !!! try expect
				#fileAltValues.write ("\t\t\t\t<value><NA>not available</NA></value>\n\t\t\t</pair>\n")
				sum = 0.0
				
				for crit in criteriaId :
					
					sum += ElemOut[alt1][alt2][crit] * weights[crit]
					
				sum = sum/sumWeights
				
				# La valeur est entre 0 et 1, on la met dans le bon intervalle
				sum = (maxValDomain - minValDomain)*sum + minValDomain
				
				fileAltValues.write ("\t\t\t\t<value><real>"+str(sum)+"</real></value>\n\t\t\t</pair>\n")
					
			
		fileAltValues.write ("\t\t</pairs>\n\t</alternativesComparisons>\n")
			
		PyXMCDA.writeFooter(fileAltValues)
		fileAltValues.close()
	
	# Creating log and error file, messages.xml
	fileMessages = open(out_dir+"/messages.xml", 'w')
	PyXMCDA.writeHeader (fileMessages)
	
	if not errorList :
	
		PyXMCDA.writeLogMessages (fileMessages, ["Execution ok"])
	else :
		PyXMCDA.writeErrorMessages (fileMessages, errorList)
		
	PyXMCDA.writeFooter(fileMessages)
	fileMessages.close()
Пример #14
0
def main(argv=None):
    if argv is None:
        argv = sys.argv

    parser = OptionParser()

    parser.add_option("-i", "--in", dest="in_dir")
    parser.add_option("-o", "--out", dest="out_dir")

    (options, args) = parser.parse_args(argv[1:])

    in_dir = options.in_dir
    out_dir = options.out_dir

    # Creating a list for error messages
    errorList = []

    # If some mandatory input files are missing
    if (
        not os.path.isfile(in_dir + "/alternatives.xml")
        or not os.path.isfile(in_dir + "/criteria.xml")
        or not os.path.isfile(in_dir + "/criteriaWeights.xml")
        or not os.path.isfile(in_dir + "/performanceTable.xml")
    ):
        errorList.append("Some input files are missing")

    else:

        # We parse all the mandatory input files
        xmltree_alternatives = PyXMCDA.parseValidate(in_dir + "/alternatives.xml")
        xmltree_criteria = PyXMCDA.parseValidate(in_dir + "/criteria.xml")
        xmltree_weights = PyXMCDA.parseValidate(in_dir + "/criteriaWeights.xml")
        xmltree_perfTable = PyXMCDA.parseValidate(in_dir + "/performanceTable.xml")

        # We check if all madatory input files are valid
        if xmltree_alternatives == None:
            errorList.append("The alternatives file can't be validated.")
        if xmltree_criteria == None:
            errorList.append("The criteria file can't be validated.")
        if xmltree_perfTable == None:
            errorList.append("The performance table file can't be validated.")
        if xmltree_weights == None:
            errorList.append("The criteria weights file can't be validated.")

            # By default, the valuation domain is fixed to [0,1]
        minValDomain = 0
        maxValDomain = 1

        # If a valuation domain input file has been provided
        if os.path.isfile(in_dir + "/valuationDomain.xml"):

            xmltree_valuation = PyXMCDA.parseValidate(in_dir + "/valuationDomain.xml")
            if xmltree_valuation == None:
                errorList.append("valuationDomain file can't be validated.")

            else:

                minValDomain = PyXMCDA.getParameterByName(xmltree_valuation, "min", "valuationDomain")
                maxValDomain = PyXMCDA.getParameterByName(xmltree_valuation, "max", "valuationDomain")

                # We check the validity of the parameters
                if not isinstance(minValDomain, float) and not isinstance(minValDomain, int):
                    errorList.append("min value should be an integer or a real")
                if not isinstance(maxValDomain, float) and not isinstance(maxValDomain, int):
                    errorList.append("max value should be an integer or a real")

                if not errorList:
                    if minValDomain >= maxValDomain:
                        errorList.append("The max value should be strictly greater than the min value")

        if not errorList:

            alternativesId = PyXMCDA.getAlternativesID(xmltree_alternatives)
            criteriaId = PyXMCDA.getCriteriaID(xmltree_criteria)
            perfTable = PyXMCDA.getPerformanceTable(xmltree_perfTable, alternativesId, criteriaId)
            thresholds = PyXMCDA.getConstantThresholds(xmltree_criteria, criteriaId)
            weights = PyXMCDA.getCriterionValue(xmltree_weights, criteriaId)

            if not alternativesId:
                errorList.append("No alternatives found. Is your alternatives file correct ?")
            if not criteriaId:
                errorList.append("No criteria found. Is your criteria file correct ?")
            if not perfTable:
                errorList.append("No performance table found. Is your performance table file correct ?")
            if not weights:
                errorList.append("No weights found. Is your weights file correct ?")

    if not errorList:

        # We compute the weight sum (only the weights associated to active criteria)
        sumWeights = 0.0

        for crit in criteriaId:
            try:
                sumWeights = sumWeights + weights[crit]
            except:
                errorList.append("There is no defined weight for criterion " + crit + ".")

    if not errorList:

        # We recover the criteria preference directions
        # criteriaDir = PyXMCDA.getCriteriaPreferenceDirections (xmltree_criteria, criteriaId)
        # Plus necessaire

        # We compute the alternative comparisons values
        fileAltValues = open(out_dir + "/alternativesComparisons.xml", "w")
        PyXMCDA.writeHeader(fileAltValues)

        # We write some information about the generated file
        fileAltValues.write(
            "\t<projectReference>\n\t\t<title>Rubis outranking relation</title>\n\t\t<version>"
            + VERSION
            + "</version>\n\t\t<author>ws_PyXMCDA suite (TV)</author>\n\t</projectReference>\n\n"
        )

        fileAltValues.write("\t<alternativesComparisons>\n\t\t<pairs>\n")

        # ATTENTION Solution rustine
        # On retourne ici le tableau de perf pour les criteres a minimiser
        # Devra etre fait par le getRubisElementaryOutranking
        criteriaDir = PyXMCDA.getCriteriaPreferenceDirections(xmltree_criteria, criteriaId)
        for crit in criteriaId:
            if criteriaDir[crit] == "min":
                for alt in alternativesId:
                    perfTable[alt][crit] = -perfTable[alt][crit]

        ElemOut = PyXMCDA.getRubisElementaryOutranking(alternativesId, criteriaId, perfTable, thresholds)

        tabVetos = PyXMCDA.getVetos(alternativesId, criteriaId, perfTable, thresholds)

        for alt1 in alternativesId:
            for alt2 in alternativesId:

                fileAltValues.write(
                    "\t\t\t<pair>\n\t\t\t\t<initial><alternativeID>"
                    + alt1
                    + "</alternativeID></initial>\n\t\t\t\t<terminal><alternativeID>"
                    + alt2
                    + "</alternativeID></terminal>\n"
                )

                # Verifier s'il manque des valeurs !!! try expect
                # fileAltValues.write ("\t\t\t\t<value><NA>not available</NA></value>\n\t\t\t</pair>\n")
                sum = 0.0
                isVeto = 0
                isWeakVeto = 0

                for crit in criteriaId:

                    sum += ElemOut[alt1][alt2][crit] * weights[crit]

                    # On verifie si un veto est leve
                    if (
                        tabVetos.has_key(alt1)
                        and tabVetos[alt1].has_key(alt2)
                        and tabVetos[alt1][alt2].has_key(crit)
                        and tabVetos[alt1][alt2][crit] == 1
                    ):
                        isVeto = 1

                        # On verifie si un veto faible est leve
                    if (
                        tabVetos.has_key(alt1)
                        and tabVetos[alt1].has_key(alt2)
                        and tabVetos[alt1][alt2].has_key(crit)
                        and tabVetos[alt1][alt2][crit] == 0.5
                    ):
                        isWeakVeto = 1

                sum = sum / sumWeights

                if isVeto == 1:
                    # On utilise le veto classique, qui met la valeur minimale
                    sum = 0.0
                elif isWeakVeto == 1 and sum > 0.5:
                    # Un veto faible est leve
                    sum = 0.5

                    # La valeur est entre 0 et 1, on la met dans le bon intervalle
                sum = (maxValDomain - minValDomain) * sum + minValDomain

                fileAltValues.write("\t\t\t\t<value><real>" + str(sum) + "</real></value>\n\t\t\t</pair>\n")

        fileAltValues.write("\t\t</pairs>\n\t</alternativesComparisons>\n")

        PyXMCDA.writeFooter(fileAltValues)
        fileAltValues.close()

        # Creating log and error file, messages.xml
    fileMessages = open(out_dir + "/messages.xml", "w")
    PyXMCDA.writeHeader(fileMessages)

    if not errorList:

        PyXMCDA.writeLogMessages(fileMessages, ["Execution ok"])
    else:
        PyXMCDA.writeErrorMessages(fileMessages, errorList)

    PyXMCDA.writeFooter(fileMessages)
    fileMessages.close()
def main(argv=None):
	if argv is None:
		argv = sys.argv
	
	parser = OptionParser()
	
	parser.add_option("-i", "--in", dest="in_dir")
	parser.add_option("-o", "--out", dest="out_dir")
	
	(options, args) = parser.parse_args(argv[1:])
	
	in_dir = options.in_dir
	out_dir = options.out_dir
	
	# Creating lists for error and log messages
	errorList = []
	logList = []
	
	# If some mandatory input files are missing
	if not os.path.isfile (in_dir+"/alternatives.xml") or not os.path.isfile (in_dir+"/criteria.xml") or not os.path.isfile (in_dir+"/performanceTable.xml"):
		errorList.append("Some input files are missing")
	
	else:
			
		xmltree_alternatives = PyXMCDA.parseValidate(in_dir+"/alternatives.xml")
		xmltree_criteria = PyXMCDA.parseValidate(in_dir+"/criteria.xml")
		xmltree_perfTable = PyXMCDA.parseValidate(in_dir+"/performanceTable.xml")
		
		if xmltree_alternatives == None:
			errorList.append("The alternatives file can't be validated.")
		if xmltree_criteria == None:
			errorList.append("The criteria file can't be validated.")
		if xmltree_perfTable == None:
			errorList.append("The performance table file can't be validated.")

		if not errorList:
		
			alternativesId = PyXMCDA.getAlternativesID(xmltree_alternatives)
			criteriaId = PyXMCDA.getCriteriaID(xmltree_criteria)
			perfTable = PyXMCDA.getPerformanceTable(xmltree_perfTable, alternativesId, criteriaId)
			thresholds = PyXMCDA.getConstantThresholds (xmltree_criteria, criteriaId)
		
			if not alternativesId:
				errorList.append("No alternatives found. Is your alternatives file correct ?")
			if not criteriaId:
				errorList.append("No criteria found. Is your criteria file correct ?")
			if not perfTable:
				errorList.append("No performance table found. Is your performance table file correct ?")
		
	if not errorList:
	
		ElemOut = PyXMCDA.getRubisElementaryOutranking (alternativesId, criteriaId, perfTable, thresholds)
		
		# Adding thresholds equals to 0 when they are not defined
		for crit in criteriaId:
			if not thresholds.has_key(crit):
				thresholds[crit] = {}
			if not thresholds[crit].has_key("indifference"):
				thresholds[crit]["indifference"] = 0
			if not thresholds[crit].has_key("preference"):
				thresholds[crit]["preference"] = 0
				
		# Creating the table for min and max thresholds
		thresholdsBounds = {}
		
		for crit in criteriaId:
			thresholdsBounds[crit] = {}
			thresholdsBounds[crit]["ind"] = {}
			thresholdsBounds[crit]["ind"]["min"] = 0.0
			thresholdsBounds[crit]["pre"] = {}
			thresholdsBounds[crit]["pre"]["min"] = 0.0
			
			for alt1 in alternativesId:
				for alt2 in alternativesId:
					if alt1 != alt2:
						if perfTable[alt1][crit] < perfTable[alt2][crit]:
							if ElemOut[alt1][alt2][crit] == 1:
								if perfTable[alt2][crit] - perfTable[alt1][crit] > thresholdsBounds[crit]["ind"]["min"]:
									thresholdsBounds[crit]["ind"]["min"] = perfTable[alt2][crit] - perfTable[alt1][crit]
								if perfTable[alt2][crit] - perfTable[alt1][crit] > thresholdsBounds[crit]["pre"]["min"]:
									thresholdsBounds[crit]["pre"]["min"] = perfTable[alt2][crit] - perfTable[alt1][crit]
							elif ElemOut[alt1][alt2][crit] == 0.5:
								if perfTable[alt2][crit] - perfTable[alt1][crit] > thresholdsBounds[crit]["pre"]["min"]:
									thresholdsBounds[crit]["pre"]["min"] = perfTable[alt2][crit] - perfTable[alt1][crit]
								if not thresholdsBounds[crit]["ind"].has_key("max") or perfTable[alt2][crit] - perfTable[alt1][crit] < thresholdsBounds[crit]["ind"]["max"]:
									thresholdsBounds[crit]["ind"]["max"] = perfTable[alt2][crit] - perfTable[alt1][crit]
							else:
								if not thresholdsBounds[crit]["ind"].has_key("max") or perfTable[alt2][crit] - perfTable[alt1][crit] < thresholdsBounds[crit]["ind"]["max"]:
									thresholdsBounds[crit]["ind"]["max"] = perfTable[alt2][crit] - perfTable[alt1][crit]
								if not thresholdsBounds[crit]["pre"].has_key("max") or perfTable[alt2][crit] - perfTable[alt1][crit] < thresholdsBounds[crit]["pre"]["max"]:
									thresholdsBounds[crit]["pre"]["max"] = perfTable[alt2][crit] - perfTable[alt1][crit]

		# Creating criteriaThresholdsBounds file
		fileThresholds = open(out_dir+"/criteriaThresholdsBounds.xml",'w')
		PyXMCDA.writeHeader(fileThresholds)
		
		# We write some information about the generated file
		fileThresholds.write ("\t<projectReference>\n\t\t<title>Thresholds Sensitivity Analysis (TSA)</title>\n\t\t<version>"+VERSION+"</version>\n\t\t<author>ws_PyXMCDA suite (TV)</author>\n\t</projectReference>\n\n")
	
		# Writing the indLowerBounds
		fileThresholds.write("<criteriaValues mcdaConcept='indLowerBounds'>\n")
		for crit in criteriaId:
			if thresholdsBounds[crit]["ind"].has_key("min"):
				fileThresholds.write("<criterionValue><criterionID>"+crit+"</criterionID><value><real>"+str(thresholdsBounds[crit]["ind"]["min"])+"</real></value></criterionValue>\n")
		fileThresholds.write("</criteriaValues>\n\n")
		
		# Writing the indUpperBounds
		fileThresholds.write("<criteriaValues mcdaConcept='indUpperBounds'>\n")
		for crit in criteriaId:
			if thresholdsBounds[crit]["ind"].has_key("max"):
				fileThresholds.write("<criterionValue><criterionID>"+crit+"</criterionID><value><real>"+str(thresholdsBounds[crit]["ind"]["max"])+"</real></value></criterionValue>\n")
		fileThresholds.write("</criteriaValues>\n\n")
		
		# Writing the indLowerBounds
		fileThresholds.write("<criteriaValues mcdaConcept='prefLowerBounds'>\n")
		for crit in criteriaId:
			if thresholdsBounds[crit]["pre"].has_key("min"):
				fileThresholds.write("<criterionValue><criterionID>"+crit+"</criterionID><value><real>"+str(thresholdsBounds[crit]["pre"]["min"])+"</real></value></criterionValue>\n")
		fileThresholds.write("</criteriaValues>\n\n")
		
		# Writing the preUpperBounds
		fileThresholds.write("<criteriaValues mcdaConcept='prefUpperBounds'>\n")
		for crit in criteriaId:
			if thresholdsBounds[crit]["pre"].has_key("max"):
				fileThresholds.write("<criterionValue><criterionID>"+crit+"</criterionID><value><real>"+str(thresholdsBounds[crit]["pre"]["max"])+"</real></value></criterionValue>\n")
		fileThresholds.write("</criteriaValues>\n\n")
		
		PyXMCDA.writeFooter(fileThresholds)
		fileThresholds.close()
			
	# Creating log and error file, messages.xml
	fileMessages = open(out_dir+"/messages.xml", 'w')
	PyXMCDA.writeHeader (fileMessages)
	
	if not errorList:
		logList.append("Execution ok")
		PyXMCDA.writeLogMessages (fileMessages, logList)
	else:
		PyXMCDA.writeErrorMessages (fileMessages, errorList)
		
	PyXMCDA.writeFooter(fileMessages)
	fileMessages.close()