def run(self):
        pt_sorted = SortedPerformanceTable(self.pt)

        meta = MetaMRSortPop3(self.nmodels, self.criteria, self.categories,
                              pt_sorted, self.aa)

        self.mutex.lock()
        self.results.append(meta.metas[0].model.copy())
        self.fitness.append(meta.metas[0].ca)
        self.mutex.unlock()
        self.emit(QtCore.SIGNAL('update(int)'), 0)

        for i in range(1, self.niter + 1):
            if self.is_stopped() is True:
                break

            model, ca = meta.optimize(self.nmeta)

            self.mutex.lock()
            self.results.append(model.copy())
            self.fitness.append(ca)
            self.mutex.unlock()

            self.emit(QtCore.SIGNAL('update(int)'), i)

            if ca == 1:
                break
Example #2
0
def test_heur_mrsort_init_profiles(seed, na, nc, ncat, pcerrors):
    # Generate an ELECTRE TRI model and assignment examples
    model = generate_random_mrsort_model(nc, ncat, seed)
    model2 = model.copy()
    model3 = model.copy()

    # Generate a first set of alternatives
    a = generate_alternatives(na)
    pt = generate_random_performance_table(a, model.criteria)

    # Compute assignments
    aa = model.pessimist(pt)

    # Initialize the second model with random generated profiles
    b = model.categories_profiles.get_ordered_profiles()
    model2.bpt = generate_random_profiles(b, model2.criteria)

    # Run the heuristic
    cats = model.categories_profiles.to_categories()
    pt_sorted = SortedPerformanceTable(pt)
    heur = HeurMRSortInitProfiles(model3, pt_sorted, aa)
    heur.solve()

    # Learn the weights and cut threshold
    cps = model.categories_profiles

    lp_weights = LpMRSortWeights(model2, pt, aa)
    lp_weights.solve()

    lp_weights = LpMRSortWeights(model3, pt, aa)
    lp_weights.solve()

    # Compute the classification accuracy
    aa2 = model2.pessimist(pt)
    aa3 = model3.pessimist(pt)

    ca2 = compute_ca(aa, aa2)
    ca3 = compute_ca(aa, aa3)

    # Save all infos in test_result class
    t = test_result("%s-%d-%d-%d-%g" % (seed, na, nc, ncat, pcerrors))

    # Input params
    t['seed'] = seed
    t['na'] = na
    t['nc'] = nc
    t['ncat'] = ncat
    t['pcerrors'] = pcerrors

    # Output params
    t['ca_rdom'] = ca2
    t['ca_heur'] = ca3

    return t
    def one_test(self, seed, na, nc, ncat, ca_expected):
        model = generate_random_mrsort_model(nc, ncat, seed)
        a = generate_alternatives(na)
        pt = generate_random_performance_table(a, model.criteria)

        aa = model.pessimist(pt)

        pt_sorted = SortedPerformanceTable(pt)
        heur = HeurMRSortInitProfiles(model, pt_sorted, aa)
        heur.solve()

        aa2 = model.pessimist(pt)

        ca = compute_ca(aa, aa2)

        self.assertEqual(ca, ca_expected)
def run_meta_mr(pipe, criteria, categories, worst, best, nmodels, niter, nmeta,
                pt, aa):
    pt_sorted = SortedPerformanceTable(pt)

    meta = MetaMRSortPop3(nmodels, criteria, categories, pt_sorted, aa)

    ca = meta.metas[0].meta.good / len(aa)
    pipe.send([meta.metas[0].model, ca])

    for i in range(1, niter + 1):
        model, ca = meta.optimize(nmeta)
        pipe.send([model, ca])
        if ca == 1:
            break

    pipe.close()
Example #5
0
def run_metaheuristic(pipe,
                      model,
                      pt,
                      aa,
                      algo,
                      n,
                      use_heur=False,
                      worst=None,
                      best=None):

    random.seed(0)
    pt_sorted = SortedPerformanceTable(pt)

    if use_heur is True:
        heur = HeurMRSortInitProfiles(model, pt_sorted, aa)
        heur.solve()
    else:
        model.bpt = generate_random_profiles(model.profiles,
                                             model.criteria,
                                             worst=worst,
                                             best=best)

    if algo == "Meta 3":
        meta = MetaMRSortProfiles3(model, pt_sorted, aa)
    elif algo == "Meta 4":
        meta = MetaMRSortProfiles4(model, pt_sorted, aa)
    else:
        print("Invalid algorithm %s" % algo)
        pipe.close()
        return

    f = compute_ca(aa, meta.aa)

    pipe.send([model.copy(), f])

    for i in range(1, n + 1):
        meta.optimize()
        f = compute_ca(aa, meta.aa)

        pipe.send([model.copy(), f])

        if f == 1:
            break

    pipe.close()
    def one_test(self, seed, na, nc, ncat, max_loop, n):
        model = generate_random_mrsort_model(nc, ncat, seed)
        a = generate_alternatives(na)
        pt = generate_random_performance_table(a, model.criteria)

        aa = model.pessimist(pt)

        model2 = model.copy()
        bids = model2.categories_profiles.get_ordered_profiles()
        model2.bpt = generate_random_profiles(bids, model.criteria)

        pt_sorted = SortedPerformanceTable(pt)

        meta = MetaMRSortProfiles4(model2, pt_sorted, aa)

        for i in range(1, max_loop + 1):
            ca = meta.optimize()
            if ca == 1:
                break

        aa2 = model2.pessimist(pt)

        self.assertEqual(i, n)
        self.assertEqual(aa, aa2)
    model.cv.display(criterion_ids=cids)
    print("lambda: %.7s" % model.lbda)
    model.vpt.id = "veto"
    model.vpt.display(criterion_ids=cids)
    model.veto_weights.display(criterion_ids=cids)
    print("veto lambda: %.7s" % model.veto_lbda)
    print("number of possible coalitions: %d" %
          compute_number_of_winning_coalitions(model.cv, model.lbda))

    model2 = model.copy()
    model2.vpt = generate_random_veto_profiles(model2, worst)
    print('Original random profiles')
    print('========================')
    model2.vpt.display(criterion_ids=cids)

    pt_sorted = SortedPerformanceTable(pt)
    meta = MetaMRSortVetoProfiles5(model2, pt_sorted, aa)

    t1 = time.time()

    i = 0
    for i in range(0, 101):
        f = meta.good / meta.na
        print('%d: fitness: %g' % (i, f))
        model2.bpt.display(criterion_ids=cids)
        if f == 1:
            break

        f = meta.optimize()

    t2 = time.time()
    from pymcda.generate import generate_random_profiles
    from pymcda.pt_sorted import SortedPerformanceTable
    from pymcda.utils import compute_ca
    from pymcda.utils import compute_winning_and_loosing_coalitions
    from pymcda.utils import display_coalitions
    from pymcda.learning.lp_mrsort_weights import LpMRSortWeights
    from pymcda.ui.graphic import display_electre_tri_models

    model = generate_random_mrsort_model(10, 3, 17)
    winning, loosing = compute_winning_and_loosing_coalitions(
        model.cv, model.lbda)
    print("Number of coalitions: %d" % len(winning))

    a = generate_alternatives(1000)
    pt = generate_random_performance_table(a, model.criteria)
    sorted_pt = SortedPerformanceTable(pt)

    aa = model.pessimist(pt)

    for cat in model.categories_profiles.get_ordered_categories():
        pc = len(aa.get_alternatives_in_category(cat)) / len(aa) * 100
        print("Percentage of alternatives in %s: %g %%" % (cat, pc))

    # Learn the weights with random generated profiles
    for i in range(10):
        model2 = model.copy()
        b = model.categories_profiles.get_ordered_profiles()
        model2.bpt = generate_random_profiles(b, model2.criteria)

        lp_weights = LpMRSortWeights(model2, pt, aa)
        lp_weights.solve()
Example #9
0
def run_test(seed, data, pclearning, nloop, nmodels, nmeta):
    random.seed(seed)
    global aaa
    global allm
    global fct_ca
    global LOO

    # Separate learning data and test data
    if LOO:
        pt_learning, pt_test = data.pt.split_LOO(seed)
    else:
        pt_learning, pt_test = data.pt.split(2, [pclearning, 100 - pclearning])
    aa_learning = data.aa.get_subset(pt_learning.keys())
    aa_test = data.aa.get_subset(pt_test.keys())

    #import pdb; pdb.set_trace()

    # Initialize a random model
    cat_profiles = generate_categories_profiles(data.cats)
    worst = data.pt.get_worst(data.c)
    best = data.pt.get_best(data.c)
    b = generate_alternatives(len(data.cats) - 1, 'b')
    bpt = None
    cvs = None
    lbda = None

    model = MRSort(data.c, cvs, bpt, lbda, cat_profiles)
    # if LOO:
    #     print(data.c, cvs, bpt, lbda, cat_profiles)
    #     print(model.categories_profiles.to_categories())
    #     print(model.categories)        
    #     import pdb; pdb.set_trace()

    # Run the metaheuristic
    t1 = time.time()

    pt_sorted = SortedPerformanceTable(pt_learning)

    # Algorithm
    meta = meta_mrsort(nmodels, model.criteria,
                       model.categories_profiles.to_categories(),
                       pt_sorted, aa_learning,
                       seed = seed * 100)
    # if LOO:
    #     print(nmodels, model.criteria,
    #                    model.categories_profiles.to_categories(),
    #                    pt_sorted, aa_learning)
        #import pdb; pdb.set_trace()
#lp_weights = lp_weights,
#heur_profiles = heur_profiles,
#lp_veto_weights = lp_veto_weights,
#heur_veto_profiles = heur_veto_profiles,

    for i in range(0, nloop):
        model, ca_learning, all_models = meta.optimize(nmeta, fct_ca)
        #import pdb; pdb.set_trace()

        if ca_learning == 1:
            break

    t_total = time.time() - t1

    aa_learning2 = model.pessimist(pt_learning)
    
    ca_learning = compute_ca(aa_learning, aa_learning2)
    ca_learning_good = compute_ca_good(aa_learning, aa_learning2)
    #import pdb; pdb.set_trace()
    auc_learning = model.auc(aa_learning, pt_learning)

    diff_learning = compute_confusion_matrix(aa_learning, aa_learning2,
                                           model.categories)

    # Compute CA of test setting
    
    if len(aa_test) > 0:
        aa_test2 = model.pessimist(pt_test)
        ca_test = compute_ca(aa_test, aa_test2)
        ca_test_good = compute_ca_good(aa_test, aa_test2)
        auc_test = model.auc(aa_test, pt_test)
        diff_test = compute_confusion_matrix(aa_test, aa_test2,
                                           model.categories)
        #import pdb; pdb.set_trace()

    else:
        ca_test = 0
        auc_test = 0
        ncat = len(data.cats)
        diff_test = OrderedDict([((a, b), 0) for a in model.categories \
                                             for b in model.categories])

    # Compute CA of whole set
    aa2 = model.pessimist(data.pt)
    ca = compute_ca(data.aa, aa2)
    ca_good = compute_ca_good(data.aa, aa2)
    auc = model.auc(data.aa, data.pt)
    diff_all = compute_confusion_matrix(data.aa, aa2, model.categories)

    t = test_result("%s-%d-%d-%d-%d-%d" % (data.name, seed, nloop, nmodels,
                                           nmeta, pclearning))

    model.id = 'learned'
    aa_learning.id, aa_test.id = 'learning_set', 'test_set'
    pt_learning.id, pt_test.id = 'learning_set', 'test_set'
    save_to_xmcda("%s/%s.bz2" % (directory, t.test_name),
                  model, aa_learning, aa_test, pt_learning, pt_test)

    t['seed'] = seed
    t['na'] = len(data.a)
    t['nc'] = len(data.c)
    t['ncat'] = len(data.cats)
    t['pclearning'] = pclearning
    t['nloop'] = nloop
    t['nmodels'] = nmodels
    t['nmeta'] = nmeta
    t['na_learning'] = len(aa_learning)
    t['na_test'] = len(aa_test)
    t['ca_learning'] = ca_learning
    t['ca_test'] = ca_test
    t['ca_all'] = ca    
    t['ca_learning_good'] = ca_learning_good
    t['ca_test_good'] = ca_test_good
    t['ca_all_good'] = ca_good
    t['auc_learning'] = auc_learning
    t['auc_test'] = auc_test
    t['auc_all'] = auc

    # import pdb; pdb.set_trace()
    aaa[seed]=dict()
    aaa[seed]['id'] = seed
    aaa[seed]['learning_asgmt_id'] = [i.id for i in aa_learning]
    aaa[seed]['learning_asgmt'] = [i.category_id for i in aa_learning]
    aaa[seed]['learning_asgmt2'] = [i.category_id for i in aa_learning2]        
    aaa[seed]['test_asgmt_id'] = [i.id for i in aa_test]
    aaa[seed]['test_asgmt'] = [i.category_id for i in aa_test]
    aaa[seed]['test_asgmt2'] = [i.category_id for i in aa_test2]
    aaa[seed]['criteria'] =  [i for i,j in model.criteria.items()]
    aaa[seed]['criteria_weights'] = [str(i.value) for i in model.cv.values()]
    aaa[seed]['profiles_values'] = [str(model.bpt['b1'].performances[i]) for i,j in model.criteria.items()]
    aaa[seed]['lambda'] = model.lbda
    #[model.bpt['b1'].performances[i] for i,j in model.criteria.items()]


    allm[seed]=dict()
    allm[seed]['id'] = seed
    current_model = 0
    allm[seed]['mresults'] = dict()
    for all_model in list(all_models)[1:]:
        current_model += 1 # skipping the 1rst model already treated
        allm[seed]['mresults'][current_model] = ["",""]
        aa_learning2_allm = all_model.model.pessimist(pt_learning)
        ca_learning_allm = compute_ca(aa_learning, aa_learning2_allm)
        ca_learning_good_allm = compute_ca_good(aa_learning, aa_learning2_allm)
        auc_learning_allm = all_model.model.auc(aa_learning, pt_learning)
        # diff_learning_allm = compute_confusion_matrix(aa_learning, aa_learning2_allm,
        #                                        all_model.model.categories)
        # Compute CA of test setting
        if len(aa_test) > 0:
            aa_test2_allm = all_model.model.pessimist(pt_test)
            ca_test_allm = compute_ca(aa_test, aa_test2_allm)
            ca_test_good_allm = compute_ca_good(aa_test, aa_test2_allm)
            auc_test_allm = all_model.model.auc(aa_test, pt_test)
            # diff_test_allm = compute_confusion_matrix(aa_test, aa_test2_allm,
            #                                    all_model.categories)
        else:
            ca_test_allm = 0
            auc_test_allm = 0
            ncat_allm = len(data.cats)
            # diff_test_allm = OrderedDict([((a, b), 0) for a in all_model.categories \
            #                                      for b in all_model.model.categories])
        # Compute CA of whole set
        aa2_allm = all_model.model.pessimist(data.pt)
        ca_allm = compute_ca(data.aa, aa2_allm)
        ca_good_allm = compute_ca_good(data.aa, aa2_allm)
        auc_allm = all_model.model.auc(data.aa, data.pt)
        #diff_all_allm = compute_confusion_matrix(data.aa, aa2_allm, all_model.model.categories) 
        allm[seed]['mresults'][current_model][0] = 'na_learning,na_test,ca_learning,ca_test,ca_all,ca_learning_good,ca_test_good,ca_all_good,auc_learning,auc_test,auc_all'
        allm[seed]['mresults'][current_model][1] =  str(len(aa_learning)) + "," + str(len(aa_test)) + "," + str(ca_learning_allm) +  "," + str(ca_test_allm) +  "," + str(ca_allm) + "," + str(ca_learning_good_allm) + "," + str(ca_test_good_allm) + "," + str(ca_good_allm) +  "," + str(auc_learning_allm) + "," + str(auc_test_allm) +  "," + str(auc_allm)
        #allm[seed]['mresults'][current_model][1] =
        #all_model.model.bpt['b1'].performances
        #all_model.model.cv.values()
        #import pdb; pdb.set_trace()

        # allm[seed][current_model]['na_learning'] = len(aa_learning)
        # allm[seed][current_model]['na_test'] = len(na_test)
        # allm[seed][current_model]['ca_learning'] = ca_learning_allm
        # allm[seed][current_model]['ca_test'] = ca_test_allm
        # allm[seed][current_model]['ca_all'] = ca_allm     
        # allm[seed][current_model]['ca_learning_good'] = ca_learning_good_allm
        # allm[seed][current_model]['ca_test_good'] = ca_test_good_allm
        # allm[seed][current_model]['ca_all_good'] = ca_good_allm
        # allm[seed][current_model]['auc_learning'] = auc_learning_allm
        # allm[seed][current_model]['auc_test'] = auc_test_allm
        # allm[seed][current_model]['auc_all'] = auc_allm


    for k, v in diff_learning.items():
        t['learn_%s_%s' % (k[0], k[1])] = v
    for k, v in diff_test.items():
        t['test_%s_%s' % (k[0], k[1])] = v
    for k, v in diff_all.items():
        t['all_%s_%s' % (k[0], k[1])] = v

    t['t_total'] = t_total

    return t
def run_test(seed, data, pclearning, nloop, nmodels, nmeta):
    random.seed(seed)

    # Separate learning data and test data
    pt_learning, pt_test = data.pt.split(2, [pclearning, 100 - pclearning])
    aa_learning = data.aa.get_subset(pt_learning.keys())
    aa_test = data.aa.get_subset(pt_test.keys())

    # Initialize a random model
    cat_profiles = generate_categories_profiles(data.cats)
    worst = data.pt.get_worst(data.c)
    best = data.pt.get_best(data.c)
    b = generate_alternatives(len(data.cats) - 1, 'b')
    bpt = None
    cvs = None
    lbda = None

    model = MRSort(data.c, cvs, bpt, lbda, cat_profiles)

    # Run the metaheuristic
    t1 = time.time()

    pt_sorted = SortedPerformanceTable(pt_learning)

    # Algorithm
    meta = meta_mrsort(nmodels,
                       model.criteria,
                       model.categories_profiles.to_categories(),
                       pt_sorted,
                       aa_learning,
                       seed=seed * 100)
    #lp_weights = lp_weights,
    #heur_profiles = heur_profiles,
    #lp_veto_weights = lp_veto_weights,
    #heur_veto_profiles = heur_veto_profiles,

    for i in range(0, nloop):
        model, ca_learning = meta.optimize(nmeta)

        if ca_learning == 1:
            break

    t_total = time.time() - t1

    aa_learning2 = model.pessimist(pt_learning)
    ca_learning = compute_ca(aa_learning, aa_learning2)
    auc_learning = model.auc(aa_learning, pt_learning)
    diff_learning = compute_confusion_matrix(aa_learning, aa_learning2,
                                             model.categories)

    # Compute CA of test setting
    if len(aa_test) > 0:
        aa_test2 = model.pessimist(pt_test)
        ca_test = compute_ca(aa_test, aa_test2)
        auc_test = model.auc(aa_test, pt_test)
        diff_test = compute_confusion_matrix(aa_test, aa_test2,
                                             model.categories)

    else:
        ca_test = 0
        auc_test = 0
        ncat = len(data.cats)
        diff_test = OrderedDict([((a, b), 0) for a in model.categories \
                                             for b in model.categories])

    # Compute CA of whole set
    aa2 = model.pessimist(data.pt)
    ca = compute_ca(data.aa, aa2)
    auc = model.auc(data.aa, data.pt)
    diff_all = compute_confusion_matrix(data.aa, aa2, model.categories)

    t = test_result("%s-%d-%d-%d-%d-%d" %
                    (data.name, seed, nloop, nmodels, nmeta, pclearning))

    model.id = 'learned'
    aa_learning.id, aa_test.id = 'learning_set', 'test_set'
    pt_learning.id, pt_test.id = 'learning_set', 'test_set'
    save_to_xmcda("%s/%s.bz2" % (directory, t.test_name), model, aa_learning,
                  aa_test, pt_learning, pt_test)

    t['seed'] = seed
    t['na'] = len(data.a)
    t['nc'] = len(data.c)
    t['ncat'] = len(data.cats)
    t['pclearning'] = pclearning
    t['nloop'] = nloop
    t['nmodels'] = nmodels
    t['nmeta'] = nmeta
    t['na_learning'] = len(aa_learning)
    t['na_test'] = len(aa_test)
    t['ca_learning'] = ca_learning
    t['ca_test'] = ca_test
    t['ca_all'] = ca
    t['auc_learning'] = auc_learning
    t['auc_test'] = auc_test
    t['auc_all'] = auc

    for k, v in diff_learning.items():
        t['learn_%s_%s' % (k[0], k[1])] = v
    for k, v in diff_test.items():
        t['test_%s_%s' % (k[0], k[1])] = v
    for k, v in diff_all.items():
        t['all_%s_%s' % (k[0], k[1])] = v

    t['t_total'] = t_total

    return t
Example #11
0
def test_meta_electre_tri_global(seed, na, nc, ncat, ns, na_gen, pcerrors,
                                 max_oloops, nmodels, max_loops):

    # Generate a random UTADIS model
    model = generate_random_avfsort_model(nc, ncat, ns, ns, seed)
    cats = model.cat_values.get_ordered_categories()

    # Generate a set of alternatives
    a = generate_alternatives(na)
    pt = generate_random_performance_table(a, model.criteria)
    aa = model.get_assignments(pt)

    # Add errors in assignment examples
    aa_err = aa.copy()
    aa_erroned = add_errors_in_assignments(aa_err, cats, pcerrors / 100)

    # Sort the performance table
    pt_sorted = SortedPerformanceTable(pt)

    t1 = time.time()

    # Perform at max oloops on the set of metas
    meta = MetaMRSortPop3(nmodels, model.criteria,
                          model.cat_values.to_categories(), pt_sorted, aa_err)
    ca2_iter = [meta.metas[0].ca] + [1] * (max_loops)

    nloops = 0
    for i in range(0, max_loops):
        model2, ca2 = meta.optimize(max_oloops)

        ca2_iter[i + 1] = ca2
        nloops += 1

        if ca2 == 1:
            break

    t_total = time.time() - t1

    # Determine the number of erroned alternatives badly assigned
    aa2 = model2.pessimist(pt)

    ok_errors = ok2_errors = ok = 0
    for alt in a:
        if aa(alt.id) == aa2(alt.id):
            if alt.id in aa_erroned:
                ok_errors += 1
            ok += 1

        if aa_err(alt.id) == aa2(alt.id) and alt.id in aa_erroned:
            ok2_errors += 1

    total = len(a)
    ca2_errors = ok2_errors / total
    ca_best = ok / total
    ca_errors = ok_errors / total

    # Generate alternatives for the generalization
    a_gen = generate_alternatives(na_gen)
    pt_gen = generate_random_performance_table(a_gen, model.criteria)
    aa_gen = model.get_assignments(pt_gen)
    aa_gen2 = model2.pessimist(pt_gen)
    ca_gen = compute_ca(aa_gen, aa_gen2)

    # Save all infos in test_result class
    t = test_result(
        "%s-%d-%d-%d-%d-%g-%d-%d-%d" %
        (seed, na, nc, ncat, na_gen, pcerrors, max_loops, nmodels, max_oloops))

    # Input params
    t['seed'] = seed
    t['na'] = na
    t['nc'] = nc
    t['ncat'] = ncat
    t['ns'] = ns
    t['na_gen'] = na_gen
    t['pcerrors'] = pcerrors
    t['max_loops'] = max_loops
    t['nmodels'] = nmodels
    t['max_oloops'] = max_oloops

    # Ouput params
    t['ca_best'] = ca_best
    t['ca_errors'] = ca_errors
    t['ca2_best'] = ca2
    t['ca2_errors'] = ca2_errors
    t['ca_gen'] = ca_gen
    t['nloops'] = nloops
    t['t_total'] = t_total

    t['ca2_iter'] = ca2_iter

    return t
Example #12
0
def mrsort_meta_inference(indir, outdir):
    if indir is None or not os.path.isdir(indir):
        log_error("Invalid input directory (%s)" % indir)
        return 1

    if outdir is None or not os.path.isdir(outdir):
        log_error("Invalid output directory (%s)" % outdir)
        return 1

    model, assignments, pt, params = parse_input_files(indir)

    if model is None or assignments is None or pt is None or params is None:
        log_error("Error while parsing input files")
        write_message_error(outdir + '/messages.xml')
        return 1

    if 'solver' in params:
        solver = params['solver'].value
    else:
        solver = DEFAULT_SOLVER

    if solver not in SOLVERS_LIST:
        log_error("Invalid solver selected (%s)" % solver)
        write_message_error(outdir + '/messages.xml')
        return 1

    os.environ["SOLVER"] = solver

    if 'nmodels' in params:
        nmodels = params['nmodels'].value
    else:
        log_error("Invalid number of models (nmodels)")
        write_message_error(outdir + '/messages.xml')
        return 1

    if 'niter_meta' in params:
        niter_meta = params['niter_meta'].value
    else:
        log_error("Invalid number of iterations (niter_meta)")
        write_message_error(outdir + '/messages.xml')
        return 1

    if 'niter_heur' in params:
        niter_heur = params['niter_heur'].value
    else:
        log_error("Invalid number of iterations (niter_heur)")
        write_message_error(outdir + '/messages.xml')
        return 1

    try:
        pt_sorted = SortedPerformanceTable(pt)
        meta = MetaMRSortPop3(nmodels, model.criteria,
                              model.categories_profiles.to_categories(),
                              pt_sorted, assignments)
        for i in range(niter_meta):
            model, ca = meta.optimize(niter_heur)

        assignments2 = model.get_assignments(pt)
        compat = get_compat_alternatives(assignments, assignments2)
        compat = to_alternatives(compat)
        msg_solver = "Solver: %s" % solver
        msg_ca = "CA: %g" % (len(compat) / len(assignments))

        profiles = to_alternatives(model.categories_profiles.keys())
        xmcda_lbda = lambda_to_xmcda(model.lbda)

        write_xmcda_file(outdir + '/lambda.xml', xmcda_lbda)
        write_xmcda_file(outdir + '/cat_profiles.xml',
                         model.categories_profiles.to_xmcda())
        write_xmcda_file(outdir + '/crit_weights.xml', model.cv.to_xmcda())
        write_xmcda_file(outdir + '/profiles_perfs.xml', model.bpt.to_xmcda())
        write_xmcda_file(outdir + '/compatible_alts.xml', compat.to_xmcda())

        write_message_ok(outdir + '/messages.xml', [msg_solver, msg_ca])
    except:
        log_error("Cannot solve problem")
        log_error(traceback.format_exc())
        write_message_error(outdir + '/messages.xml')

    return 0
Example #13
0
t1 = time.time()

if algo == 'meta_mrsort':
    heur_init_profiles = HeurMRSortInitProfiles
    lp_weights = LpMRSortWeights
    heur_profiles = MetaMRSortProfiles4
elif algo == 'meta_mrsortc':
    heur_init_profiles = HeurMRSortInitProfiles
    lp_weights = LpMRSortMobius
    heur_profiles = MetaMRSortProfilesChoquet

if algo == 'meta_mrsort' or algo == 'meta_mrsortc':
    model_type = 'mrsort'
    cat_profiles = generate_categories_profiles(data.cats)
    model = MRSort(data.c, None, None, None, cat_profiles)
    pt_sorted = SortedPerformanceTable(data.pt)

    meta = MetaMRSortPop3(nmodels, model.criteria,
                          model.categories_profiles.to_categories(), pt_sorted,
                          data.aa, heur_init_profiles, lp_weights,
                          heur_profiles)

    for i in range(0, nloop):
        model, ca_learning = meta.optimize(nmeta)
        print(ca_learning)
        if ca_learning == 1:
            break
elif algo == 'mip_mrsort':
    model_type = 'mrsort'
    cat_profiles = generate_categories_profiles(data.cats)
    model = MRSort(data.c, None, None, None, cat_profiles)
def test_meta_electre_tri_global(seed, na, nc, ncat, na_gen, pcerrors,
                                 max_oloops, nmodels, max_loops):

    # Generate a random ELECTRE TRI BM model
    if random_model_type == 'mrsort':
        model = generate_random_mrsort_model(nc, ncat, seed)
    elif random_model_type == 'ncs':
        model = generate_random_mrsort_choquet_model(nc, ncat, 2, seed)
    elif random_model_type == 'mrsortcv':
        model = generate_random_mrsort_model_with_coalition_veto2(
            nc, ncat, seed)

    # Generate a set of alternatives
    a = generate_alternatives(na)
    pt = generate_random_performance_table(a, model.criteria)
    aa = model.pessimist(pt)

    # Add errors in assignment examples
    aa_err = aa.copy()
    categories = model.categories_profiles.to_categories()
    aa_erroned = add_errors_in_assignments_proba(aa_err, model.categories,
                                                 pcerrors / 100)
    na_err = len(aa_erroned)

    # Sort the performance table
    pt_sorted = SortedPerformanceTable(pt)

    meta = algo(nmodels, model.criteria, categories, pt_sorted, aa)
    metas_sorted = meta.sort_models()
    ca2_iter = [metas_sorted[0].ca] + [1] * (max_loops)

    t1 = time.time()

    for i in range(0, max_loops):
        model2, ca2_best = meta.optimize(max_oloops)
        ca2_iter[i + 1] = ca2_best
        if ca2_best == 1:
            break

    nloops = i + 1

    t_total = time.time() - t1

    aa2 = model2.pessimist(pt)

    ok_errors = ok2_errors = ok = 0
    for alt in a:
        if aa(alt.id) == aa2(alt.id):
            if alt.id in aa_erroned:
                ok_errors += 1
            ok += 1

        if aa_err(alt.id) == aa2(alt.id) and alt.id in aa_erroned:
            ok2_errors += 1

    total = len(a)
    ca2_errors = ok2_errors / total
    ca_best = ok / total
    ca_errors = ok_errors / total

    # Generate alternatives for the generalization
    a_gen = generate_alternatives(na_gen)
    pt_gen = generate_random_performance_table(a_gen, model.criteria)
    aa_gen = model.pessimist(pt_gen)
    aa_gen2 = model2.pessimist(pt_gen)
    ca_gen = compute_ca(aa_gen, aa_gen2)

    aa_gen_err = aa_gen.copy()
    aa_gen_erroned = add_errors_in_assignments_proba(aa_gen_err,
                                                     model.categories,
                                                     pcerrors / 100)
    aa_gen2 = model2.pessimist(pt_gen)
    ca_gen_err = compute_ca(aa_gen_err, aa_gen2)

    # Save all infos in test_result class
    t = test_result(
        "%s-%d-%d-%d-%d-%g-%d-%d-%d" %
        (seed, na, nc, ncat, na_gen, pcerrors, max_loops, nmodels, max_oloops))

    model.id = 'initial'
    model2.id = 'learned'
    pt.id, pt_gen.id = 'learning_set', 'test_set'
    save_to_xmcda("%s/%s.bz2" % (directory, t.test_name), model, model2, pt,
                  pt_gen)

    # Input params
    t['seed'] = seed
    t['na'] = na
    t['nc'] = nc
    t['ncat'] = ncat
    t['na_gen'] = na_gen
    t['pcerrors'] = pcerrors
    t['max_loops'] = max_loops
    t['nmodels'] = nmodels
    t['max_oloops'] = max_oloops

    # Ouput params
    t['na_err'] = na_err
    t['ca_best'] = ca_best
    t['ca_errors'] = ca_errors
    t['ca2_best'] = ca2_best
    t['ca2_errors'] = ca2_errors
    t['ca_gen'] = ca_gen
    t['ca_gen_err'] = ca_gen_err
    t['nloops'] = nloops
    t['t_total'] = t_total

    t['ca2_iter'] = ca2_iter

    return t
def test_meta_electre_tri_profiles(seed, na, nc, ncat, na_gen, pcerrors,
                                   max_loops):
    # Generate an ELECTRE TRI model and assignment examples
    model = generate_random_mrsort_model(nc, ncat, seed)
    model2 = model.copy()

    # Generate a first set of alternatives
    a = generate_alternatives(na)
    pt = generate_random_performance_table(a, model.criteria)

    aa = model.pessimist(pt)

    # Initiate model with random profiles
    model2.bpt = generate_random_profiles(model.profiles, model.criteria)

    # Add errors in assignment examples
    aa_err = aa.copy()
    aa_erroned = add_errors_in_assignments(aa_err, model.categories,
                                           pcerrors / 100)

    # Sort the performance table
    pt_sorted = SortedPerformanceTable(pt)

    t1 = time.time()

    # Run the algorithm
    meta = algo(model2, pt_sorted, aa_err)

    ca2_iter = [1] * (max_loops + 1)
    aa2 = model2.pessimist(pt)
    ca2 = compute_ca(aa_err, aa2)
    ca2_best = ca2
    best_bpt = model2.bpt.copy()
    ca2_iter[0] = ca2
    nloops = 0

    for k in range(max_loops):
        if ca2_best == 1:
            break

        meta.optimize()
        nloops += 1

        aa2 = meta.aa
        ca2 = compute_ca(aa_err, aa2)

        ca2_iter[k + 1] = ca2

        if ca2 > ca2_best:
            ca2_best = ca2
            best_bpt = model2.bpt.copy()

    t_total = time.time() - t1

    # Determine the number of erroned alternatives badly assigned
    model2.bpt = best_bpt
    aa2 = model2.pessimist(pt)

    ok = ok_errors = ok2_errors = 0
    for alt in a:
        if aa_err(alt.id) == aa2(alt.id) and alt.id in aa_erroned:
            ok2_errors += 1

        if aa(alt.id) == aa2(alt.id):
            if alt.id in aa_erroned:
                ok_errors += 1
            ok += 1

    total = len(a)
    ca_best = ok / total
    ca_best_errors = ok_errors / total
    ca2_best_errors = ok2_errors / total

    # Generate alternatives for the generalization
    a_gen = generate_alternatives(na_gen)
    pt_gen = generate_random_performance_table(a_gen, model.criteria)
    aa_gen = model.pessimist(pt_gen)
    aa_gen2 = model2.pessimist(pt_gen)
    ca_gen = compute_ca(aa_gen, aa_gen2)

    # Save all infos in test_result class
    t = test_result("%s-%d-%d-%d-%d-%g-%d" %
                    (seed, na, nc, ncat, na_gen, pcerrors, max_loops))

    # Input params
    t['seed'] = seed
    t['na'] = na
    t['nc'] = nc
    t['ncat'] = ncat
    t['na_gen'] = na_gen
    t['pcerrors'] = pcerrors
    t['max_loops'] = max_loops

    # Ouput params
    t['ca_best'] = ca_best
    t['ca_best_errors'] = ca_best_errors
    t['ca2_best'] = ca2_best
    t['ca2_best_errors'] = ca2_best_errors
    t['ca_gen'] = ca_gen
    t['nloops'] = nloops
    t['t_total'] = t_total

    t['ca2_iter'] = ca2_iter

    return t