Example #1
0
def func_2():

    for distance_id in distance_ids:
        target_exp = mapel.prepare_experiment(f'abstract_classes/{exp_id}',
                                              instance_type='ordinal',
                                              distance_id=distance_id)
        groups_pos = {}
        for name_1, name_2 in itertools.combinations(target_exp.elections, 2):
            if target_exp.distances[name_1][name_2] < 0.000001:
                name_1 = get_id(name_1)
                name_2 = get_id(name_2)
                if name_1 in groups_pos:
                    groups_pos[name_1].append(name_2)
                else:
                    if not any(name_1 in group
                               for group in groups_pos.values()):
                        groups_pos[name_1] = [name_1, name_2]

        groups_pos = [[int(name.split('_')[-1]) for name in group]
                      for group in groups_pos.values()]
        flat_groups = [item for sublist in groups_pos for item in sublist]
        for i in range(num_elections):
            if i not in flat_groups:
                groups_pos.append([i])

        for group in groups_pos:
            # for exp_id in group:
            print(group[0])
            print(target_exp.elections[f'all_{group[0]}'].
                  votes_to_bordawise_vector())

        print(distance_id, len(groups_pos))
Example #2
0
def func_7():

    mses = {
        '3x3': 100,
        '3x4': 80,
        '3x5': 60,
        '4x3': 40,
        '4x4': 20,
    }

    for exp_id in base:
        list_of_names = []
        for distance_id in distance_ids:
            experiment = mapel.prepare_experiment(
                experiment_id=f'abstract_classes/{exp_id}',
                instance_type='ordinal',
                distance_id=distance_id)

            feature_id = 'swap_distance_from_id'
            title = 'swap_distance_from_id'

            # experiment.compute_feature(feature_id=feature_id)
            # experiment.embed(algorithm='mds')
            experiment.print_map(
                feature_id=feature_id,
                title=f'{exp_id} {distance_id}',
                ms=mses[exp_id],
                adjust_single=True,
                rounding=0,
                xticklabels=['0', ' ', 'max'],
                saveas=f'equivalence/{exp_id} {distance_id}',
            )
Example #3
0
def func_correlation():

    for exp_id in base:
        list_of_names = []
        output = []
        for distance_id in distance_ids:
            experiment_id = f'abstract_classes/{exp_id}'
            names = ['swap_bf', distance_id]
            all_distances = {}

            for name in names:
                experiment = mapel.prepare_experiment(
                    experiment_id=experiment_id,
                    instance_type='ordinal',
                    distance_id=name)
                all_distances[name] = experiment.distances

            for name_1, name_2 in itertools.combinations(names, 2):
                values_x = []
                values_y = []
                empty_x = []
                empty_y = []
                for e1, e2 in itertools.combinations(all_distances[name_1], 2):

                    values_x.append(all_distances[name_1][e1][e2])
                    values_y.append(all_distances[name_2][e1][e2])

                pear = round(stats.pearsonr(values_x, values_y)[0], 4)
                output.append(f'{exp_id} {distance_id} {pear}')

        print(output)
Example #4
0
def import_experiment():
    experiment_id = 'emd-positionwise'
    instance_type = 'ordinal'
    distance_id = 'emd-positionwise'

    experiment = mapel.prepare_experiment(experiment_id=experiment_id,
                                          instance_type=instance_type,
                                          distance_id=distance_id,
                                          coordinates_names=[
                                              'emd-positionwise-paths-big-fixed-4_circle_kamada_bb_2_steps.csv',
                                              'emd-positionwise-paths-big-fixed-4_square_kamada_bb_2_steps.csv'
                                          ])

    experiment.embed(algorithm='kamada-kawai')
    experiment.print_map()
    print(calculate_stability(experiment))
Example #5
0
def eq_cl():

    # distance_id = 'l1-positionwise'
    exp_id = '5x3'
    exp = mapel.prepare_experiment(f'abstract_classes/{exp_id}',
                                   instance_type='ordinal')
    # exp.prepare_elections()

    distance_ids = [
        # 'l1-bordawise',
        'emd-bordawise',
        'emd-positionwise',
        'l1-positionwise',
        'l1-pairwise',
        # 'swap_bf'
        # 'spearman'
    ]

    for distance_id in distance_ids:
        print(distance_id)
        exp.compute_distances(distance_id=distance_id, printing=True)
Example #6
0
def func_swap():

    for exp_id in base:
        num_elections = base[exp_id]
        swap_exp = mapel.prepare_experiment(f'abstract_classes/{exp_id}',
                                            instance_type='ordinal',
                                            distance_id='swap_bf')

        feature_dict = swap_exp.distances['all_0']
        print(feature_dict)

        path = os.path.join(os.getcwd(), "experiments",
                            f'abstract_classes/{exp_id}', "features",
                            f'swap_distance_from_id.csv')
        with open(path, 'w', newline='') as csv_file:
            writer = csv.writer(csv_file, delimiter=';')
            writer.writerow(["election_id", "value"])
            writer.writerow(["all_0", "0"])
            ctr = 0
            for key in feature_dict:
                ctr += 1
                writer.writerow([key, feature_dict[key]])
Example #7
0
            max_es = []
            avg_es = []
            all_weight_spoilers = []
            all_weight_vectors = []
            all_shapley_spoilers = []
            all_shapley_vectors = []
            all_banzhaf_spoilers = []
            all_banzhaf_vectors = []
            all_borda = []

            all_alternative_weight_vectors = []
            all_alternative_shapley_vectors = []
            all_alternative_banzhaf_vectors = []

            for _ in range(precision):
                experiment = mapel.prepare_experiment()
                experiment.set_default_num_candidates(num_candidates)
                experiment.set_default_num_voters(num_voters)

                experiment.add_family(election_model=election_model,
                                      size=size,
                                      params={
                                          'num_winners': num_winners,
                                          'num_parties': num_parties,
                                          'main-phi': 0.5,
                                          'norm-phi': 0.5
                                      })

                experiment.compute_winners(method=method,
                                           num_winners=num_winners)
Example #8
0
import mapel

if __name__ == "__main__":

    distance_id = 'emd-positionwise'

    experiment = mapel.prepare_experiment(instance_type='ordinal')

    experiment.set_default_num_candidates(20)
    experiment.set_default_num_voters(100)

    experiment.add_election_family(model_id='impartial_culture',
                                   color='grey',
                                   family_id='ic',
                                   size=10)

    experiment.add_election_family(model_id='urn_model',
                                   color='black',
                                   family_id='urn',
                                   params={'alpha': 0.2},
                                   size=10)

    experiment.add_election_family(model_id='norm-mallows',
                                   color='blue',
                                   family_id='mallows',
                                   params={'norm-phi': 0.5},
                                   size=10)

    experiment.compute_distances(distance_id=distance_id)

    experiment.embed()
Example #9
0
def count_number_of_eq_classes():

    for exp_id in base:
        print("\n\n\n")
        num_elections = base[exp_id]
        # swap_exp = mapel.prepare_experiment(f'abstract_classes/{exp_id}', election_type='ordinal',
        #                                     distance_id='swap_bf')

        # groups_pos = {}
        # for name_1, name_2 in itertools.combinations(swap_exp.elections, 2):
        #     if swap_exp.distances[name_1][name_2] == 0:
        #         name_1 = get_id(name_1)
        #         name_2 = get_id(name_2)
        #         if name_1 in groups_pos:
        #             groups_pos[name_1].append(name_2)
        #         else:
        #             if not any(name_1 in group for group in groups_pos.values()):
        #                 groups_pos[name_1] = [name_1, name_2]
        # groups_pos = [[name.split('_')[-1] for name in group] for group in groups_pos.values()]
        #

        distance_ids = [
            # 'l1-bordawise',
            # 'emd-bordawise',
            # 'l1-pairwise',
            # 'l1-positionwise',
            # 'emd-positionwise',
            # 'swap_bf'
            'discrete'
        ]

        for distance_id in distance_ids:
            target_exp = mapel.prepare_experiment(f'abstract_classes/{exp_id}',
                                                  instance_type='ordinal',
                                                  distance_id=distance_id)

            groups_pos = {}
            for name_1, name_2 in itertools.combinations(
                    target_exp.elections, 2):
                # print(name_1, name_2)

                if target_exp.distances[name_1][name_2] < 0.0001:
                    # print('tmp')
                    name_1 = get_id(name_1)
                    name_2 = get_id(name_2)
                    if name_1 in groups_pos:
                        groups_pos[name_1].append(name_2)
                    else:
                        if not any(name_1 in group
                                   for group in groups_pos.values()):
                            groups_pos[name_1] = [name_1, name_2]

            groups_pos = [[int(name.split('_')[-1]) for name in group]
                          for group in groups_pos.values()]
            flat_groups = [item for sublist in groups_pos for item in sublist]
            # print(flat_groups)
            for i in range(num_elections):
                if i not in flat_groups:
                    groups_pos.append([i])
            # print(groups_pos)

            # for group in groups_pos:
            #     print(group)

            print(distance_id, len(groups_pos))
Example #10
0
import mapel

if __name__ == "__main__":

    experiment_id = 'mallows'
    distance_id = 'emd-positionwise'
    instance_type = 'ordinal'

    experiment = mapel.prepare_experiment(experiment_id=experiment_id,
                                          distance_id=distance_id,
                                          instance_type=instance_type)

    # generate elections according to map.csv file
    experiment.prepare_elections()

    # compute distances between each pair of elections
    experiment.compute_distances(distance_id=distance_id)
Example #11
0
def matrix2png(argv):
    # introduce yourself
    if len(argv) < 4:
        print("Invocation:")
        print("  python3 matrix2png num_candidates model_id reorder [param1]")
        print(
            "  reorder -- election_id of the model_id to try to resemble (e.g., ID, or AN); use org to use original order"
        )
        print("")
        exit()

    # gather arguments
    m = int(argv[1])
    n = m * m
    model = argv[2]
    tgt = argv[3]
    print("TGT:", tgt)
    if len(argv) >= 5:
        param = float(argv[4])
    else:
        param = None

    if model != "mallows":
        name = "%s_%d_%s.png" % (model, m, tgt)
    else:
        name = "%s_phi%d_%d_%s.png" % (model, param * 100, m, tgt)

    # prepare the experiment/matrix
    experiment = mapel.prepare_experiment()
    experiment.set_default_num_candidates(m)
    experiment.set_default_num_voters(n)

    # Compass Matrices
    experiment.add_election(election_model="uniformity",
                            election_id="UN",
                            color=(1, 0.5, 0.5),
                            marker="X")
    experiment.add_election(election_model="identity",
                            election_id="ID",
                            color="red",
                            marker="X")
    experiment.add_election(election_model="antagonism",
                            election_id="AN",
                            color="black",
                            marker="o")
    experiment.add_election(election_model="stratification",
                            election_id="ST",
                            color="black")

    # form the matrix
    if model != "mallows":
        experiment.add_election(election_model=model, election_id="M")
    else:
        experiment.add_election(election_model="norm-mallows_matrix",
                                params={"norm-phi": param},
                                election_id="M")
    M = experiment.elections["M"].matrix

    # get the mapping to a given election
    experiment.compute_distances()
    if tgt == "org":
        match = list(range(m))
    else:
        match = experiment.matchings[tgt]["M"]
    print(match)
    # get reversed matching
    rev_match = [0] * m
    for i in range(m):
        rev_match[match[i]] = i
    print(rev_match)

    # create the image
    img = Image.new("RGB", (m, m), color="black")
    draw = ImageDraw.Draw(img)

    MAX = 0  # highest value in the matrix
    for y in range(m):
        for x in range(m):
            MAX = max(MAX, M[y][x])

    color = lambda v: getsqrtrgb_uniform(v, MAX)

    ### print columns
    print("----")
    for x in range(m):
        print("%.2f" % x, end=" ")
    print()
    print("----")

    ### draw the matrix
    for y in range(m):
        for x in range(m):
            draw.point((x, y), fill=color(M[y][rev_match[x]]))
            print("%.2f" % M[y][rev_match[x]], end=" ")
        print()

    # save the image
    img.save(name)

    print("MAX value:", MAX)
Example #12
0
import mapel

if __name__ == "__main__":

    distance_id = 'l1-approvalwise'

    experiment = mapel.prepare_experiment(instance_type='approval')

    experiment.set_default_num_candidates(50)
    experiment.set_default_num_voters(100)

    experiment.add_election(model_id='approval_empty',
                            election_id='Empty',
                            label='_nolegend_')
    experiment.add_election(model_id='approval_full',
                            election_id='Full',
                            label='_nolegend_')
    experiment.add_election(model_id='approval_ic',
                            election_id='IC 0.5',
                            label='_nolegend_',
                            params={'p': .5})
    experiment.add_election(model_id='approval_id',
                            election_id='ID 0.5',
                            label='_nolegend_',
                            params={'p': .5})

    experiment.add_election_family(model_id='approval_ic',
                                   color='black',
                                   family_id='IC_path',
                                   params={},
                                   size=10,