Exemplo n.º 1
0
def test_signed_partisan_scores_are_positive_if_first_party_has_advantage(
    mock_election
):
    eg = efficiency_gap(mock_election)
    mm = mean_median(mock_election)
    pb = partisan_bias(mock_election)

    assert eg > 0 and mm > 0 and pb > 0
Exemplo n.º 2
0
    for elect in range(num_elections):
        f.write(
            election_names[elect]
            + "District Percentages"
            + str(
                sorted(initial_partition[election_names[elect]].percents("First"))
            )
        )
        f.write("\n")
        f.write("\n")

        f.write(
            election_names[elect]
            + "Mean-Median :"
            + str(mean_median(initial_partition[election_names[elect]]))
        )

        f.write("\n")
        f.write("\n")

        f.write(
            election_names[elect]
            + "Efficiency Gap :"
            + str(efficiency_gap(initial_partition[election_names[elect]]))
        )

        f.write("\n")
        f.write("\n")

        f.write(
Exemplo n.º 3
0
votesSenW = []
mmP12 = []
mmP16 = []
mmSenW = []
egP12 = []
egP16 = []
egSenW = []
hmsP12 = []
hmsP16 = []
hmsSenW = []

splits = []

t = 0
for part in chain:
    splits.append(num_splits(part))
    pop_vec.append(sorted(list(part["population"].values())))
    cut_vec.append(len(part["cut_edges"]))
    votesP12.append(sorted(part["PRES12"].percents("Democratic")))
    votesP16.append(sorted(part["PRES16"].percents("Democratic")))
    votesSenW.append(sorted(part["SENW101216"].percents("Democratic")))
    mmP12.append(mean_median(part["PRES12"]))
    mmP16.append(mean_median(part["PRES16"]))
    mmSenW.append(mean_median(part["SENW101216"]))
    egP12.append(efficiency_gap(part["PRES12"]))
    egP16.append(efficiency_gap(part["PRES16"]))
    egSenW.append(efficiency_gap(part["SENW101216"]))
    hmsP12.append(part["PRES12"].percents("Democratic"))
    hmsP16.append(part["PRES16"].percents("Democratic"))
    hmsSenW.append(part["SENW101216"].percents("Democratic"))
Exemplo n.º 4
0
def chain(iterations):
    idef = random.randint(1, 10000)
    graph = Graph.from_json("./PA_VTD.json")

    election = Election("SEN12", {"Dem": "USS12D", "Rep": "USS12R"})

    initial_partition = GeographicPartition(graph,
                                            assignment="2011_PLA_1",
                                            updaters={
                                                "cut_edges":
                                                cut_edges,
                                                "population":
                                                Tally("TOT_POP",
                                                      alias="population"),
                                                "SEN12":
                                                election
                                            })

    ideal_population = sum(
        initial_partition["population"].values()) / len(initial_partition)

    # We use functools.partial to bind the extra parameters (pop_col, pop_target, epsilon, node_repeats)
    # of the recom proposal.

    proposal = partial(recom,
                       pop_col="TOT_POP",
                       pop_target=ideal_population,
                       epsilon=0.02,
                       node_repeats=2)

    chain = MarkovChain(proposal=proposal,
                        constraints=[republican_constraint],
                        accept=contiguous,
                        initial_state=initial_partition,
                        total_steps=iterations + 100)

    count = 0
    metrics = []
    boundary_nodes = []
    boundary_weighted = []
    for partition in chain.with_progress_bar():
        mm = mean_median(partition["SEN12"])
        p = pp(partition)
        bias = partisan_bias(partition["SEN12"])
        gini = partisan_gini(partition["SEN12"])
        gap = efficiency_gap(partition["SEN12"])
        cut = len(partition["cut_edges"])
        if count >= 100:
            metrics.append((mm, p, bias, gini, gap, cut))
            nodes = [0] * 8921
            bnodes = [0] * 8921
            for edge in partition["cut_edges"]:
                nodes[edge[0]] = 1
                nodes[edge[1]] = 1
                bnodes[edge[0]] += 1
                bnodes[edge[1]] += 1
            boundary_nodes.append(nodes)
            boundary_weighted.append(bnodes)
        if count % 100 == 0:
            print(idef, count, mm, p, bias, gini, gap, cut,
                  partition["SEN12"].wins("Rep"))
        count += 1

    return metrics, boundary_nodes, boundary_weighted
Exemplo n.º 5
0
def chain(iterations):
    idef = random.randint(1, 10000)
    graph = Graph.from_json("../data/PA_init/PA_VTD.json")

    election = Election("SEN12", {"Dem": "USS12D", "Rep": "USS12R"})

    initial_partition = GeographicPartition(
        graph,
        assignment="2011_PLA_1",
        updaters={
            "cut_edges": cut_edges,
            "population": Tally("TOT_POP", alias="population"),
            "SEN12": election
        }
    )

    ideal_population = sum(initial_partition["population"].values()) / len(initial_partition)

    # We use functools.partial to bind the extra parameters (pop_col, pop_target, epsilon, node_repeats)
    # of the recom proposal.

    proposal = partial(recom,
                       pop_col="TOT_POP",
                       pop_target=ideal_population,
                       epsilon=0.02,
                       node_repeats=2
                      )

    chain = MarkovChain(
            proposal=proposal,
            constraints=[],
            accept=contiguous,
            initial_state=initial_partition,
            total_steps=85*iterations + 17000
        )

    count = 0
    metrics = []
    boundary_nodes = []
    boundary_weighted = []
    for partition in chain.with_progress_bar(): 
        mm = mean_median(partition["SEN12"])
        p = pp(partition)
        bias = partisan_bias(partition["SEN12"])
        gini = partisan_gini(partition["SEN12"])
        gap = efficiency_gap(partition["SEN12"])
        cut = len(partition["cut_edges"])
        if count >= 17000:
            if count % 85 == 0: 
                metrics.append((mm, p, bias, gini, gap, cut, partition["SEN12"].wins("Rep")))
                nodes = [0]*8921
                bnodes = [0]*8921
                for edge in partition["cut_edges"]:
                    nodes[edge[0]] = 1
                    nodes[edge[1]] = 1
                    bnodes[edge[0]] += 1
                    bnodes[edge[1]] += 1
                boundary_nodes.append(nodes)
                boundary_weighted.append(bnodes)

                assign = {i: partition.assignment[i] for i in partition.assignment}
                shape["CD"] = shape.index.map(assign)
                this_map = shape.dissolve(by='CD')
                this_map.plot(color='white', edgecolor='black')
                plt.axis('off')
                fig = plt.gcf()
                fig.set_size_inches((15,9), forward=False)
                fig.savefig("../images/PA_neutral/" + str(idef) + str(int((count-17000)/85)+1) + ".png", dpi=600, bbox_inches="tight", pad_inches=0)

                plt.close()

            if count % 8500 == 0: 
                print(idef, count, mm, p, bias, gini, gap, cut, partition["SEN12"].wins("Rep"))
        else:
            if count%1000 == 0:
                print(idef, "Mixing...... Iteration", count, "/17000")
        count += 1

    return metrics, boundary_nodes, boundary_weighted, idef
Exemplo n.º 6
0
rsw = []
rmm = []
reg = []
rce = []

expectednumberseats = 0

for part in recom_chain:
    rsw.append(part["Pink-Purple"].wins("Pink"))
    # Caluculate number of ties
    ties = (part["Pink-Purple"].wins("Pink") +
            part["Pink-Purple"].wins("Purple") - k)
    # Calculate number of pink seats won, add to expected value
    expectednumberseats += part["Pink-Purple"].wins("Pink") - ties / 2
    rmm.append(mean_median(part["Pink-Purple"]))
    reg.append(efficiency_gap(part["Pink-Purple"]))
    rce.append(len(part["cut_edges"]))
    # plt.figure()
    # nx.draw(
    #     graph,
    #     pos={x: x for x in graph.nodes()},
    #     node_color=[dict(part.assignment)[x] for x in graph.nodes()],
    #     node_size=ns,
    #     node_shape="s",
    #     cmap="tab20",
    # )
    # plt.savefig(f"./Figures/recom_{part['step_num']:02d}.png")
    # plt.close()

expectednumberseats = expectednumberseats / numIters
Exemplo n.º 7
0
        for elect in range(num_elections):

            f.write("RIGHT SET OF BVAPS: " + str(sorted(temp3)))

            f.write("\n")
            f.write("\n")

            f.write(election_names[elect] + "District Percentages" + str(
                sorted(initial_partition[election_names[elect]].percents(
                    "First"))))
            f.write("\n")
            f.write("\n")

            f.write(election_names[elect] + "Mean-Median :" +
                    str(mean_median(initial_partition[election_names[elect]])))

            f.write("\n")
            f.write("\n")

            f.write(
                election_names[elect] + "Efficiency Gap :" +
                str(efficiency_gap(initial_partition[election_names[elect]])))

            f.write("\n")
            f.write("\n")

            f.write(
                election_names[elect] + "How Many Seats :" +
                str(initial_partition[election_names[elect]].wins("First")))
Exemplo n.º 8
0
def test_mean_median_has_right_value(mock_election):
    mm = mean_median(mock_election)

    assert abs(mm - 0.15) < 0.00001
Exemplo n.º 9
0
def test_signed_partisan_scores_point_the_same_way(mock_election):
    eg = efficiency_gap(mock_election)
    mm = mean_median(mock_election)
    pb = partisan_bias(mock_election)

    assert (eg > 0 and mm > 0 and pb > 0) or (eg < 0 and mm < 0 and pb < 0)