Beispiel #1
0
 def get_credibility(*args, **kwargs):
     alternatives = px.getAlternativesID(trees['alternatives'])
     comparison_with = kwargs.get('comparison_with')
     if not comparison_with:
         comparison_with = px.getParameterByName(
             trees['method_parameters'],
             'comparison_with',
         )
     if comparison_with in ('boundary_profiles', 'central_profiles'):
         categories_profiles = _get_categories_profiles(
             trees['categories_profiles'],
             comparison_with,
         )
     else:
         categories_profiles = None
     eliminate_cycles_method = px.getParameterByName(
         trees.get('method_parameters'),
         'eliminate_cycles_method',
     )
     tree = trees.get('credibility')
     if eliminate_cycles_method == 'cut_weakest' and tree is None:
         raise InputDataError(
             "'cut_weakest' option requires credibility as an additional "
             "input (apart from outranking)."
         )
     credibility = _get_alternatives_comparisons(
         tree,
         alternatives,
         categories_profiles=categories_profiles,
     )
     return credibility  # NoneType, Vividict
def get_input_data(input_dir):
    file_names = (
        'alternatives.xml',
        'categories.xml',
        'categoriesProfiles.xml',
        'credibility.xml',
        'method_parameters.xml',
    )
    trees = get_trees(input_dir, file_names)

    alternatives = px.getAlternativesID(trees['alternatives'])
    categories = px.getCategoriesID(trees['categories'])
    categories_rank = px.getCategoriesRank(trees['categories'], categories)
    categories_profiles = get_categories_profiles_central(trees['categoriesProfiles'])
    credibility = getAlternativesComparisons(trees['credibility'], alternatives,
                                             categories_profiles)
    cut_threshold = px.getParameterByName(trees['method_parameters'], 'cut_threshold')
    check_cut_threshold(cut_threshold)

    ret = {
        'alternatives': alternatives,
        'categories_rank': categories_rank,
        'categories_profiles': categories_profiles,
        'credibility': credibility,
        'cut_threshold': cut_threshold,
    }
    return ret
def get_input_data(input_dir):
    file_names = (
        'alternatives.xml',
        'method_parameters.xml',
        'outranking.xml',
    )
    trees = get_trees(input_dir, file_names)

    alternatives = px.getAlternativesID(trees['alternatives'])
    alternatives.sort()
    outranking = get_intersection_distillation(trees['outranking'],
                                               alternatives)
    if outranking == None:
        outranking = px.getAlternativesComparisons(trees['outranking'],
                                                   alternatives)
    eliminate_cycles_method = px.getParameterByName(trees['method_parameters'],
                                                    'eliminate_cycles_method')
    if eliminate_cycles_method not in ['aggregate', 'cut_weakest']:
        raise RuntimeError("Invalid/missing method for cycle elimination.")
    cut_threshold = px.getParameterByName(trees['method_parameters'],
                                          'cut_threshold')
    check_cut_threshold(cut_threshold)

    ret = {
        'alternatives': alternatives,
        'cut_threshold': cut_threshold,
        'eliminate_cycles_method': eliminate_cycles_method,
        'outranking': outranking,
    }
    return ret
def get_input_data(input_dir):
    file_names = (
        'alternatives.xml',
        'method_parameters.xml',
        'outranking.xml',
    )
    trees = get_trees(input_dir, file_names)

    alternatives = px.getAlternativesID(trees['alternatives'])
    alternatives.sort()
    outranking = get_intersection_distillation(trees['outranking'], alternatives)
    if outranking == None:
        outranking = px.getAlternativesComparisons(trees['outranking'], alternatives)
    eliminate_cycles_method = px.getParameterByName(trees['method_parameters'],
                                                    'eliminate_cycles_method')
    if eliminate_cycles_method not in ['aggregate', 'cut_weakest']:
        raise RuntimeError("Invalid/missing method for cycle elimination.")
    cut_threshold = px.getParameterByName(trees['method_parameters'], 'cut_threshold')
    check_cut_threshold(cut_threshold)

    ret = {
        'alternatives': alternatives,
        'cut_threshold': cut_threshold,
        'eliminate_cycles_method': eliminate_cycles_method,
        'outranking': outranking,
    }
    return ret
Beispiel #5
0
 def get_credibility(*args, **kwargs):
     alternatives = px.getAlternativesID(trees['alternatives'])
     comparison_with = kwargs.get('comparison_with')
     if not comparison_with:
         comparison_with = px.getParameterByName(
             trees['method_parameters'],
             'comparison_with',
         )
     if comparison_with in ('boundary_profiles', 'central_profiles'):
         categories_profiles = _get_categories_profiles(
             trees['categories_profiles'],
             comparison_with,
         )
     else:
         categories_profiles = None
     eliminate_cycles_method = px.getParameterByName(
         trees.get('method_parameters'),
         'eliminate_cycles_method',
     )
     tree = trees.get('credibility')
     if eliminate_cycles_method == 'cut_weakest' and tree is None:
         raise InputDataError(
             "'cut_weakest' option requires credibility as an additional "
             "input (apart from outranking)."
         )
     credibility = _get_alternatives_comparisons(
         tree,
         alternatives,
         categories_profiles=categories_profiles,
     )
     return credibility  # NoneType, Vividict
Beispiel #6
0
 def writeAlternativeComparision(self, filename, comparisionMx, comparisionType=None):
     outfile = open(filename, 'w')
     px.writeHeader(outfile)
     for key, item in comparisionMx.items() :
         if self.criteria.has_key(key.name):
             outfile.write('\t<alternativesComparisons mcdaConcept="Pairwise comparison">\n')
             if comparisionType != None :
                 outfile.write("\t\t<comparisonType>%s</comparisonType>\n" % comparisionType)
             outfile.write("\t\t<criterionID>%s</criterionID>\n" % key.name)
             outfile.write('\t\t<pairs>\n')
             for key1, item1 in item.items():
                 for key2, item2 in item1.items():
                     outfile.write("""\t\t\t<pair>
             <initial>
                 <alternativeID>%s</alternativeID>
             </initial>
             <terminal>
                 <alternativeID>%s</alternativeID>
             </terminal>
             <value>
                 <real>%s</real>
             </value>
         </pair>\n""" % (key1, key2, item2))
             outfile.write('\t\t</pairs>\n')
             outfile.write('\t</alternativesComparisons>\n')
         else:
             pass
     px.writeFooter(outfile)
     outfile.close()
Beispiel #7
0
 def get_discordance(*args, **kwargs):
     alternatives = px.getAlternativesID(trees['alternatives'])
     comparison_with = px.getParameterByName(
         trees['method_parameters'],
         'comparison_with',
     )
     if kwargs.get('use_partials') is not None:
         use_partials = kwargs.get('use_partials')
     else:
         parameter = px.getParameterByName(
             trees['method_parameters'],
             'use_partials',
         )
         use_partials = True if parameter == 'true' else False
     if comparison_with in ('boundary_profiles', 'central_profiles'):
         categories_profiles = _get_categories_profiles(
             trees['categories_profiles'],
             comparison_with,
         )
     else:
         categories_profiles = None
     discordance = _get_alternatives_comparisons(
         trees['discordance'],
         alternatives,
         categories_profiles=categories_profiles,
         use_partials=use_partials,
     )
     return discordance  # Vividict
Beispiel #8
0
def write_xmcda_content(filename, content=None):
    outfile = open(filename, 'w')
    px.writeHeader(outfile)
    if content != None:
        outfile.write(content)
    px.writeFooter(outfile)
    outfile.close()
def output_criteria(filename, criteria_ids, xml_crit):
    oldCriteriaIDs = px.getCriteriaID(xml_crit)
    trivial = trivialCopy(xml_crit, oldCriteriaIDs)
    #critScale = px.getCriteriaScalesTypes(xml_crit, oldCriteriaIDs)
    #critThresholds = px.getConstantThresholds(xml_crit, oldCriteriaIDs)
    #critPreference = px.getCriteriaPreferenceDirections(xml_crit, oldCriteriaIDs)

    outfile = open(filename, 'w')
    px.writeHeader(outfile)
    outfile.write('  <criteria>\n')
    for id in sorted(criteria_ids):
        oldID = getOriginalName(id)
        if not oldID in oldCriteriaIDs:
            pass
            #outfile.write('''
        #<criterion id="%s" name="%s"/>
        #''' % (id,id))
        else:
            #print trivial
            #print oldID
            outfile.write('''
        <criterion id="%s" name="%s">\n%s
        </criterion>''' % (id, id, trivial[oldID]))
    outfile.write('  </criteria>\n')
    px.writeFooter(outfile)
    outfile.close()
def write_xmcda_content(filename, content=None):
    outfile = open(filename, "w")
    px.writeHeader(outfile)
    if content != None:
        outfile.write(content)
    px.writeFooter(outfile)
    outfile.close()
def get_input_data(input_dir):
    file_names = (
        'alternatives.xml',
        'concordance.xml',
        'method_parameters.xml',
        'discordance_binary.xml',
    )
    trees = get_trees(input_dir, file_names)

    alternatives = px.getAlternativesID(trees['alternatives'])
    # we can also get alternatives from 'concordance.xml', therefore 'alternatives.xml'
    # can be optional - like here:
    # alternatives = list(set([i.text for i in trees['concordance'].findall(".//alternativeID")]))
    concordance = px.getAlternativesComparisons(trees['concordance'], alternatives)
    discordance_binary = px.getAlternativesComparisons(trees['discordance_binary'], alternatives)
    cut_threshold = px.getParameterByName(trees['method_parameters'], 'cut_threshold')
    check_cut_threshold(cut_threshold)

    ret = {
        'alternatives': alternatives,
        'concordance': concordance,
        'cut_threshold': cut_threshold,
        'discordance_binary': discordance_binary,
    }
    return ret
def get_input_data(input_dir):
    file_names = (
        'alternatives.xml',
        'categoriesProfiles.xml',
        'credibility.xml',
        'method_parameters.xml',
    )
    trees = get_trees(input_dir, file_names)

    alternatives = px.getAlternativesID(trees['alternatives'])
    cp_tree = trees['categoriesProfiles']
    categories = list(
        set(cp_tree.xpath('//categoriesProfiles//limits//categoryID/text()')))
    categories_profiles = px.getCategoriesProfiles(trees['categoriesProfiles'],
                                                   categories)
    profiles_names = [
        p for p in cp_tree.xpath('//categoriesProfiles//alternativeID/text()')
    ]
    credibility = getAlternativesComparisons(trees['credibility'],
                                             alternatives, profiles_names)
    cut_threshold = px.getParameterByName(trees['method_parameters'],
                                          'cut_threshold')
    check_cut_threshold(cut_threshold)

    ret = {
        'alternatives': alternatives,
        'categories_profiles': categories_profiles,
        'credibility': credibility,
        'cut_threshold': cut_threshold,
    }
    return ret
Beispiel #13
0
 def get_discordance(*args, **kwargs):
     alternatives = px.getAlternativesID(trees['alternatives'])
     comparison_with = px.getParameterByName(
         trees['method_parameters'],
         'comparison_with',
     )
     if kwargs.get('use_partials') is not None:
         use_partials = kwargs.get('use_partials')
     else:
         parameter = px.getParameterByName(
             trees['method_parameters'],
             'use_partials',
         )
         use_partials = True if parameter == 'true' else False
     if comparison_with in ('boundary_profiles', 'central_profiles'):
         categories_profiles = _get_categories_profiles(
             trees['categories_profiles'],
             comparison_with,
         )
     else:
         categories_profiles = None
     discordance = _get_alternatives_comparisons(
         trees['discordance'],
         alternatives,
         categories_profiles=categories_profiles,
         use_partials=use_partials,
     )
     return discordance  # Vividict
Beispiel #14
0
 def get_pref_directions(*args, **kwargs):
     criteria = px.getCriteriaID(trees['criteria'])
     pref_directions = px.getCriteriaPreferenceDirections(
         trees['criteria'],
         criteria,
     )
     return pref_directions  # dict
def output_criteria(filename, criteria_ids, xml_crit):
    oldCriteriaIDs = px.getCriteriaID(xml_crit)
    trivial = trivialCopy(xml_crit, oldCriteriaIDs)
    # critScale = px.getCriteriaScalesTypes(xml_crit, oldCriteriaIDs)
    # critThresholds = px.getConstantThresholds(xml_crit, oldCriteriaIDs)
    # critPreference = px.getCriteriaPreferenceDirections(xml_crit, oldCriteriaIDs)

    outfile = open(filename, "w")
    px.writeHeader(outfile)
    outfile.write("  <criteria>\n")
    for id in sorted(criteria_ids):
        oldID = getOriginalName(id)
        if not oldID in oldCriteriaIDs:
            pass
            # outfile.write('''
        # <criterion id="%s" name="%s"/>
        #''' % (id,id))
        else:
            # print trivial
            # print oldID
            outfile.write(
                """
        <criterion id="%s" name="%s">\n%s
        </criterion>"""
                % (id, id, trivial[oldID])
            )
    outfile.write("  </criteria>\n")
    px.writeFooter(outfile)
    outfile.close()
Beispiel #16
0
 def get_pref_directions(*args, **kwargs):
     criteria = px.getCriteriaID(trees['criteria'])
     pref_directions = px.getCriteriaPreferenceDirections(
         trees['criteria'],
         criteria,
     )
     return pref_directions  # dict
def get_input_data(input_dir):
    file_names = (
        'alternatives.xml',
        'concordance.xml',
        'method_parameters.xml',
        'discordance_binary.xml',
    )
    trees = get_trees(input_dir, file_names)

    alternatives = px.getAlternativesID(trees['alternatives'])
    # we can also get alternatives from 'concordance.xml', therefore 'alternatives.xml'
    # can be optional - like here:
    # alternatives = list(set([i.text for i in trees['concordance'].findall(".//alternativeID")]))
    concordance = px.getAlternativesComparisons(trees['concordance'],
                                                alternatives)
    discordance_binary = px.getAlternativesComparisons(
        trees['discordance_binary'], alternatives)
    cut_threshold = px.getParameterByName(trees['method_parameters'],
                                          'cut_threshold')
    check_cut_threshold(cut_threshold)

    ret = {
        'alternatives': alternatives,
        'concordance': concordance,
        'cut_threshold': cut_threshold,
        'discordance_binary': discordance_binary,
    }
    return ret
Beispiel #18
0
 def get_weights(*args, **kwargs):
     criteria = px.getCriteriaID(trees['criteria'])
     if len(criteria) == 0:
         msg = ("File 'criteria.xml' doesn't contain valid data for this "
                "method.")
         raise InputDataError(msg)
     weights = px.getCriterionValue(trees['weights'], criteria)
     return weights  # dict
def output_criteria(filename, criteria_ids):
    outfile = open(filename, 'w')
    px.writeHeader(outfile)
    outfile.write('  <criteria>\n')
    for id in criteria_ids:
        outfile.write('    <criterion id="%s" />\n' % id)
    outfile.write('  </criteria>\n')
    px.writeFooter(outfile)
    outfile.close()
Beispiel #20
0
def output_criteria(filename, criteria_ids):
    outfile = open(filename, 'w')
    px.writeHeader(outfile)
    outfile.write('  <criteria>\n')
    for id in criteria_ids:
        outfile.write('    <criterion id="%s" />\n' % id)
    outfile.write('  </criteria>\n')
    px.writeFooter(outfile)
    outfile.close()
Beispiel #21
0
 def get_weights(*args, **kwargs):
     criteria = px.getCriteriaID(trees['criteria'])
     if len(criteria) == 0:
         msg = (
             "File 'criteria.xml' doesn't contain valid data for this "
             "method."
         )
         raise InputDataError(msg)
     weights = px.getCriterionValue(trees['weights'], criteria)
     return weights  # dict
Beispiel #22
0
def create_messages_file(log_msg, err_msg, out_dir):
    with open(os.path.join(out_dir, 'messages.xml'), 'w') as f:
        px.writeHeader(f)
        if err_msg:
            px.writeErrorMessages(f, err_msg)
        elif log_msg:
            px.writeLogMessages(f, log_msg)
        else:
            px.writeErrorMessages(f, ('Neither log nor error messages have been supplied.',))
        px.writeFooter(f)
Beispiel #23
0
 def get_reinforcement_factors(*args, **kwargs):
     criteria = px.getCriteriaID(trees['criteria'])
     factors = {}
     for c in criteria:
         rf = px.getCriterionValue(trees['reinforcement_factors'], c,
                                   'reinforcement_factors')
         if len(rf) == 0:
             continue
         if rf.get(c) <= 1:
             msg = ("Reinforcement factor for criterion '{}' should be "
                    "higher than 1.0 (ideally between 1.2 and 1.5).")
             raise InputDataError(msg)
         factors.update(rf)
     return factors  # dict
def makeSelection(in_selected, in_outranking, out_outranking):
    xml_outranking = px.parseValidate(in_outranking)
    xml_selected = px.parseValidate(in_selected)
    if xml_selected == None:
        raise ValueError, "Invalid selected file"
    if xml_outranking == None:
        raise ValueError, "Invalid xml_outranking file"

    onCriterion = px.getParameterByName(xml_selected, 'selectedCriterion')
    alternativesComparisions = getAlternativesComparisonsAtCriteria(xml_outranking)

    if not alternativesComparisions.has_key(onCriterion):
        raise ValueError, 'Invalid selected criterion'
    writeAlternativeComparisionOnCriterion(out_outranking, alternativesComparisions, onCriterion, 'outranks')
Beispiel #25
0
def get_input_data(input_dir):
    file_names = (
        'alternatives.xml',
        'categoriesProfiles.xml',
        'concordance.xml',
        'discordances.xml',
    )
    trees = get_trees(input_dir, file_names)

    alternatives = px.getAlternativesID(trees['alternatives'])
    categories_profiles = get_categories_profiles_central(
        trees['categoriesProfiles'])
    concordance = getAlternativesComparisons(trees['concordance'],
                                             alternatives, categories_profiles)
    discordances = getAlternativesComparisons(trees['discordances'],
                                              alternatives,
                                              categories_profiles,
                                              partials=True)

    ret = {
        'alternatives': alternatives,
        'categories_profiles': categories_profiles,
        'concordance': concordance,
        'discordances': discordances,
    }
    return ret
Beispiel #26
0
 def get_interactions(*args, **kwargs):
     criteria = px.getCriteriaID(trees['criteria'])
     interactions = _get_criteria_interactions(
         trees['interactions'],
         criteria,
     )
     return interactions  # dict
Beispiel #27
0
 def get_profiles_performance_table(*args, **kwargs):
     comparison_with = px.getParameterByName(
         trees['method_parameters'],
         'comparison_with',
     )
     if comparison_with in ('boundary_profiles', 'central_profiles'):
         tree = trees.get('profiles_performance_table')
         if tree is None:
             msg = ("Missing profiles performance table (did you forget "
                    "to provide 'profiles_performance_table.xml' file?).")
             raise InputDataError(msg)
         profiles_performance_table = px.getPerformanceTable(
             tree, None, None)
     else:
         profiles_performance_table = None
     return profiles_performance_table  # NoneType, dict
def get_input_data(input_dir):
    file_names = (
        'alternatives.xml',
        'categoriesProfiles.xml',
        'concordance.xml',
        'discordances.xml',
    )
    trees = get_trees(input_dir, file_names)

    alternatives = px.getAlternativesID(trees['alternatives'])
    cp_tree = trees['categoriesProfiles']
    # we need only categories profiles' names
    categories_profiles = [
        p for p in cp_tree.xpath('//categoriesProfiles//alternativeID/text()')
    ]
    concordance = getAlternativesComparisons(trees['concordance'],
                                             alternatives, categories_profiles)
    discordances = getAlternativesComparisons(trees['discordances'],
                                              alternatives,
                                              categories_profiles,
                                              partials=True)

    ret = {
        'alternatives': alternatives,
        'categories_profiles': categories_profiles,
        'concordance': concordance,
        'discordances': discordances,
    }
    return ret
Beispiel #29
0
def output_criteriaValues(filename, criteria_ids, mcdaConcept, parents):
    outfile = open(filename, 'w')
    px.writeHeader(outfile)
    outfile.write('  <%s>' % mcdaConcept)
    outfile.write('''
    <description>
      <comment>A hierarchy of criteria</comment>
    </description>''')

    xmlparents = [xml_value_label % v for v in criteria_ids]

    outfile.write(make_tree('', parents, criteria_ids))

    outfile.write('\n  </%s>\n' % mcdaConcept)
    px.writeFooter(outfile)
    outfile.close()
Beispiel #30
0
 def get_interactions(*args, **kwargs):
     criteria = px.getCriteriaID(trees['criteria'])
     interactions = _get_criteria_interactions(
         trees['interactions'],
         criteria,
     )
     return interactions  # dict
Beispiel #31
0
 def get_profiles_performance_table(*args, **kwargs):
     comparison_with = px.getParameterByName(
         trees['method_parameters'],
         'comparison_with',
     )
     if comparison_with in ('boundary_profiles', 'central_profiles'):
         tree = trees.get('profiles_performance_table')
         if tree is None:
             msg = (
                 "Missing profiles performance table (did you forget "
                 "to provide 'profiles_performance_table.xml' file?)."
             )
             raise InputDataError(msg)
         profiles_performance_table = px.getPerformanceTable(tree, None, None)
     else:
         profiles_performance_table = None
     return profiles_performance_table  # NoneType, dict
def check_weights(xml_weights, hierarchyArray, outfile):
    ret = ""
    weights = px.getCriterionValue(xml_weights,
                                   [(getOriginalName(v))
                                    for v, k in hierarchyArray.items()],
                                   'Importance')
    weights = calculate_new_weights(weights, hierarchyArray)
    output_criteriaValues(outfile, weights, 'Importance')
Beispiel #33
0
 def _sort_profiles (category_profiles, categories_names, rank_tree):
     sortedCategories = {}
     categories_rank = px.getCategoriesRank(rank_tree, categories_names)
     for category in categories_rank:
         sortedCategories[categories_rank[category]] = {}
         sortedCategories[categories_rank[category]]["classes"] = category_profiles[category]
         sortedCategories[categories_rank[category]]["id"] = category
     return sortedCategories
def output_criteriaValues(filename, criteria_ids, mcdaConcept, parents):
    outfile = open(filename, 'w')
    px.writeHeader(outfile)
    outfile.write('  <%s>' % mcdaConcept)
    outfile.write('''
    <description>
      <comment>A hierarchy of criteria</comment>
    </description>''')


    xmlparents = [ xml_value_label % v for v in criteria_ids ]

    outfile.write(make_tree('', parents, criteria_ids))

    outfile.write('\n  </%s>\n' % mcdaConcept)
    px.writeFooter(outfile)
    outfile.close()
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
Beispiel #36
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
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
Beispiel #38
0
 def get_cut_threshold(*args, **kwargs):
     cut_threshold = px.getParameterByName(
         trees['method_parameters'],
         'cut_threshold',
     )
     if cut_threshold is None or not (0 <= float(cut_threshold) <= 1):
         raise InputDataError("'cut_threshold' should be in range [0, 1] "
                              "(most commonly used values are 0.6 or 0.7).")
     return cut_threshold  # float
Beispiel #39
0
 def get_reinforcement_factors(*args, **kwargs):
     criteria = px.getCriteriaID(trees['criteria'])
     factors = {}
     for c in criteria:
         rf = px.getCriterionValue(
             trees['reinforcement_factors'],
             c,
             'reinforcement_factors'
         )
         if len(rf) == 0:
             continue
         if rf.get(c) <= 1:
             msg = (
                 "Reinforcement factor for criterion '{}' should be "
                 "higher than 1.0 (ideally between 1.2 and 1.5)."
             )
             raise InputDataError(msg)
         factors.update(rf)
     return factors  # dict
def check_concordance(xml_concordance, hierarchyArray, outfile):
    ret = ""
    concordances = px.getCriterionValue(xml_concordance,
                                        [(getOriginalName(v))
                                         for v, k in hierarchyArray.items()],
                                        'Concordance')
    if concordances.__len__() > 0:
        concordances = calculate_new_concordance(concordances, hierarchyArray)
        output_criteriaValues(outfile, concordances, 'Concordance')
    else:
        check = px.getParameterByName(xml_concordance, 'percentage',
                                      'concordanceLevel')
        if check != None:
            content = """
    <methodParameters name="concordanceLevel">
        <parameter name="percentage">
            <value><real>%f</real></value>
        </parameter>
    </methodParameters>""" % check
            write_xmcda_content(outfile, content)
def output_criteriaValues(filename, weights, mcdaConcept):
    outfile = open(filename, 'w')
    px.writeHeader(outfile)
    outfile.write('  <criteriaValues mcdaConcept="%s">' % mcdaConcept)

    try:
        xmlWeights = [xml_value_real % k for v, k in weights.items()]
    except ValueError:
        xmlWeights = [xml_value_label % k for v, k in weights.items()]

    for id, weight in map(None, weights, xmlWeights):
        outfile.write("""
    <criterionValue>
      <criterionID>%s</criterionID>
%s
    </criterionValue>
""" % (id, weight))
    outfile.write('  </criteriaValues>\n')
    px.writeFooter(outfile)
    outfile.close()
Beispiel #42
0
 def get_cut_threshold(*args, **kwargs):
     cut_threshold = px.getParameterByName(
         trees['method_parameters'],
         'cut_threshold',
     )
     if cut_threshold is None or not (0 <= float(cut_threshold) <= 1):
         raise InputDataError(
             "'cut_threshold' should be in range [0, 1] "
             "(most commonly used values are 0.6 or 0.7)."
         )
     return cut_threshold  # float
Beispiel #43
0
 def get_profiles_categories(*args, **kwargs):
     #profilesCategories = px.getProfilesCategories(trees['categories_profiles'], None)
     comparison_with = kwargs.get('comparison_with')
     if comparison_with is None:
         comparison_with = px.getParameterByName(
             trees['method_parameters'],
             'comparison_with',
         )
     if comparison_with in ('boundary_profiles', 'central_profiles'):
         profilesCategories = _get_profiles_categories(trees['categories_profiles'], comparison_with, trees['categories'])
     return profilesCategories
Beispiel #44
0
 def get_categories_profiles(*args, **kwargs):
     comparison_with = kwargs.get('comparison_with')
     if comparison_with is None:
         comparison_with = px.getParameterByName(
             trees['method_parameters'],
             'comparison_with',
         )
     categories_profiles = _get_categories_profiles(
         trees.get('categories_profiles'),
         comparison_with,
     )
     return categories_profiles  # NoneType, dict, list
Beispiel #45
0
 def get_categories_profiles(*args, **kwargs):
     comparison_with = kwargs.get('comparison_with')
     if comparison_with is None:
         comparison_with = px.getParameterByName(
             trees['method_parameters'],
             'comparison_with',
         )
     categories_profiles = _get_categories_profiles(
         trees.get('categories_profiles'),
         comparison_with,
     )
     return categories_profiles  # NoneType, dict, list
def check_concordance(xml_concordance, hierarchyArray, outfile):
    ret = ""
    concordances = px.getCriterionValue(
        xml_concordance, [(getOriginalName(v)) for v, k in hierarchyArray.items()], "Concordance"
    )
    if concordances.__len__() > 0:
        concordances = calculate_new_concordance(concordances, hierarchyArray)
        output_criteriaValues(outfile, concordances, "Concordance")
    else:
        check = px.getParameterByName(xml_concordance, "percentage", "concordanceLevel")
        if check != None:
            content = (
                """
    <methodParameters name="concordanceLevel">
        <parameter name="percentage">
            <value><real>%f</real></value>
        </parameter>
    </methodParameters>"""
                % check
            )
            write_xmcda_content(outfile, content)
Beispiel #47
0
def get_trees(input_dir, file_names):
    trees = {}
    for f in file_names:
        file_name = os.path.join(input_dir, f)
        if not os.path.isfile(file_name):
            raise RuntimeError("Problem with input file: '{}'.".format(f))
        tree = None
        tree = px.parseValidate(file_name)
        if tree is None:
            raise RuntimeError("Validation error with file: '{}'.".format(f))
        trees.update({os.path.splitext(f)[0]: tree})
    return trees
def output_distillation(filename, alternativesID, concept="downwars distillation", atCriterion="Root"):
    outfile = open(filename, "w")
    if compatibleWith2_0_0 != None:
        px.writeHeader(outfile, "2.0.0")
    else:
        px.writeHeader(outfile)
        outfile.write(
            "\t<description>\n\t\t<comment>%s on criterion: %s</comment>\n\t</description>\n" % (concept, atCriterion)
        )

    outfile.write('    <alternativesValues mcdaConcept="%s">\n' % concept)
    for id, val in sorted(alternativesID.items(), key=lambda alt: alt[1], reverse=True):
        # for id, val in criteria_ids.items():
        outfile.write(
            """
            <alternativeValue>
                <alternativeID>%s</alternativeID>
                <value>
                    <real>%s</real>
                </value>
            </alternativeValue>"""
            % (id, val)
        )
    outfile.write("\n    </alternativesValues>\n")
    px.writeFooter(outfile)
    outfile.close()
def makeDistilation(
    in_selected, in_alternatives, in_credibility, out_descending, out_ascending, out_medianPreorder, out_final
):
    xml_alternatives = px.parseValidate(in_alternatives)
    xml_selected = px.parseValidate(in_selected)
    xml_alternatives = px.parseValidate(in_alternatives)
    xml_credibility = px.parseValidate(in_credibility)
    if xml_selected == None:
        raise ValueError, "Invalid selected file"
    if xml_alternatives == None:
        raise ValueError, "Invalid alternative file"
    if xml_credibility == None:
        raise ValueError, "Invalid credibility file"

    onCriterion = px.getParameterByName(xml_selected, "selectedCriterion")
    alternativesID = px.getAlternativesID(xml_alternatives)
    alternativesComparisions = getAlternativesComparisonsAtCriteria(xml_credibility, alternativesID)

    if not alternativesComparisions.has_key(onCriterion):
        raise ValueError, "Invalid selected criterion"

    distillation = Distillation(alternativesID, alternativesComparisions[onCriterion])

    output_distillation(out_ascending, distillation.downwards(), "downward distillation", onCriterion)
    output_distillation(out_descending, distillation.upwards(), "upward distillation", onCriterion)
    output_distillation(out_medianPreorder, distillation.medianPreorder(), "median Preorder", onCriterion)

    writeAlternativeComparision(out_final, distillation.intersectionUpDowns, "outranks", onCriterion)
def writeAlternativeComparisionOnCriterion(filename, comparisionMx, criterion, comparisionType=None):
    compatibleWith2_0_0 = True
    outfile = open(filename, 'w')
    if compatibleWith2_0_0 :
        px.writeHeader(outfile, '2.0.0')
        writeCriterion = None
    else:
        px.writeHeader(outfile)
        writeCriterion = criterion #definicja jakiego kryterium dotyczny dane porównanie dopiero w standardzie 2_2_1
    #for key, item in comparisionMx.items() :
    outfile.write('\t<alternativesComparisons mcdaConcept="Pairwise comparison">\n')
    if comparisionType != None :
        outfile.write("\t\t<comparisonType>%s</comparisonType>\n" % comparisionType)
    if writeCriterion != None:
        outfile.write("\t\t<criterionID>%s</criterionID>\n" % writeCriterion)
    outfile.write('\t\t<pairs>\n')
    for key1, item1 in comparisionMx[criterion].items():
        for key2, item2 in item1.items():
            outfile.write("""\t\t\t<pair>
            <initial>
                <alternativeID>%s</alternativeID>
            </initial>
            <terminal>
                <alternativeID>%s</alternativeID>
            </terminal>
            <value>
                %s
            </value>
        </pair>\n""" % (key1, key2, correctType(item2)))
    outfile.write('\t\t</pairs>\n')
    outfile.write('\t</alternativesComparisons>\n')
    px.writeFooter(outfile)
    outfile.close()
Beispiel #51
0
def output_distillation(filename,
                        alternativesID,
                        concept='downwars distillation',
                        atCriterion='Root'):
    outfile = open(filename, 'w')
    if compatibleWith2_0_0 != None:
        px.writeHeader(outfile, '2.0.0')
    else:
        px.writeHeader(outfile)
        outfile.write(
            '\t<description>\n\t\t<comment>%s on criterion: %s</comment>\n\t</description>\n'
            % (concept, atCriterion))

    outfile.write('    <alternativesValues mcdaConcept="%s">\n' % concept)
    for id, val in sorted(alternativesID.items(),
                          key=lambda alt: alt[1],
                          reverse=True):
        #for id, val in criteria_ids.items():
        outfile.write('''
            <alternativeValue>
                <alternativeID>%s</alternativeID>
                <value>
                    <real>%s</real>
                </value>
            </alternativeValue>''' % (id, val))
    outfile.write('\n    </alternativesValues>\n')
    px.writeFooter(outfile)
    outfile.close()
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',
        '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
Beispiel #54
0
 def get_concordance(*args, **kwargs):
     alternatives = px.getAlternativesID(trees['alternatives'])
     comparison_with = px.getParameterByName(
         trees['method_parameters'],
         'comparison_with',
     )
     if comparison_with in ('boundary_profiles', 'central_profiles'):
         categories_profiles = _get_categories_profiles(
             trees['categories_profiles'],
             comparison_with,
         )
         concordance = _get_alternatives_comparisons(
             trees['concordance'],
             alternatives,
             categories_profiles,
         )
     else:
         concordance = px.getAlternativesComparisons(
             trees['concordance'],
             alternatives,
         )
     return concordance  # Vividict, dict
Beispiel #55
0
 def get_cv_crossed(*args, **kwargs):
     # 'cv_crossed' stands for 'counter-veto crossed'
     alternatives = px.getAlternativesID(trees['alternatives'])
     comparison_with = px.getParameterByName(
         trees['method_parameters'],
         'comparison_with',
     )
     if comparison_with in ('boundary_profiles', 'central_profiles'):
         categories_profiles = _get_categories_profiles(
             trees['categories_profiles'],
             comparison_with,
         )
     else:
         categories_profiles = None
     cv_crossed = _get_alternatives_comparisons(
         trees['counter_veto_crossed'],
         alternatives,
         categories_profiles=categories_profiles,
         use_partials=True,
         mcda_concept='counterVetoCrossed',
     )
     return cv_crossed  # Vividict
def check_criteria_hierarchy(
    in_weights, in_hierarchy, in_concorlevel, in_criteria, out_criteria, out_weights, out_hierarchy, out_concorlevel
):
    weights_xmltree = px.parseValidate(in_weights)
    hierarchy_xmtree = px.parseValidate(in_hierarchy)
    concordance_xmltree = px.parseValidate(in_concorlevel)
    criteria_xmltree = px.parseValidate(in_criteria)

    if weights_xmltree == None:
        raise ValueError, "Invalid weights file"
    if hierarchy_xmtree == None:
        raise ValueError, "Invalid hierarchy file"
    if concordance_xmltree == None:
        raise ValueError, "Invalid concordance level file"
    if criteria_xmltree == None:
        raise ValueError, "Invalid criterioa file"

    hierarchyArray = check_hierarchy(hierarchy_xmtree, out_hierarchy)
    check_weights(weights_xmltree, hierarchyArray, out_weights)
    check_concordance(concordance_xmltree, hierarchyArray, out_concorlevel)
    output_criteria(out_criteria, [(v) for v, k in hierarchyArray.items()], criteria_xmltree)
    return None