Esempio n. 1
0
def run_pa(plan, total_steps=10000000):
    partition, chain = set_up_chain(plan, total_steps)

    scores = {
        key: value
        for election in elections
        for key, value in get_scores(election).items()
    }

    # scores['Distance_From_Ideal_Population'] = distance_from_ideal_population

    scores['L_minus_1_Polsby-Popper'] = L_minus_1_polsby_popper

    initial_scores = {key: score(partition) for key, score in scores.items()}

    table = pipe_to_table(chain, scores)

    pathlib.Path(f"./plots/{plan}/{now}").mkdir(parents=True, exist_ok=True)

    for score in scores:
        plt.hist(table[score], bins=50)
        plt.title(score.replace('_', ' '))
        plt.axvline(x=initial_scores[score], color='r')
        plt.savefig(f"./plots/{plan}/{now}/{score}.svg")
        plt.close()

    metadata = {'plan': plan, 'total_steps': total_steps}

    report = {
        key: p_value_report(key, table[key], initial_scores[key])
        for key in scores if key != 'L_minus_1_Polsby-Popper'
    }

    return {**metadata, 'p_value_report': report}
Esempio n. 2
0
def main():
    initial_partition = PA_partition()

    chain = BasicChain(initial_partition, total_steps=10000)

    scores = {
        'Mean-Median':
        functools.partial(mean_median, proportion_column_name='VoteA%'),
        'Mean-Thirdian':
        functools.partial(mean_thirdian, proportion_column_name='VoteA%'),
        'Efficiency Gap':
        functools.partial(efficiency_gap, col1='VoteA', col2='VoteB'),
    }

    initial_scores = {
        key: score(initial_partition)
        for key, score in scores.items()
    }

    table = pipe_to_table(chain, scores)

    return {
        key: p_value_report(key, table[key], initial_scores[key])
        for key in scores
    }
Esempio n. 3
0
def main():
    initial_partition = PA_partition()

    chain = BasicChain(initial_partition, total_steps=10000)

    scores = {
        'Mean-Median': functools.partial(mean_median, proportion_column_name='VoteA%'),
        'Mean-Thirdian': functools.partial(mean_thirdian, proportion_column_name='VoteA%'),
        'Efficiency Gap': functools.partial(efficiency_gap, col1='VoteA', col2='VoteB'),
        'L1 Reciprocal Polsby-Popper': L1_reciprocal_polsby_popper
    }

    initial_scores = {key: score(initial_partition) for key, score in scores.items()}

    table = pipe_to_table(chain, scores)

    fig, axes = plt.subplots(2, 2)

    quadrants = {
        'Mean-Median': (0, 0),
        'Mean-Thirdian': (0, 1),
        'Efficiency Gap': (1, 0),
        'L1 Reciprocal Polsby-Popper': (1, 1)
    }

    for key in scores:
        quadrant = quadrants[key]
        axes[quadrant].hist(table[key], bins=50)
        axes[quadrant].set_title(key)
        axes[quadrant].axvline(x=initial_scores[key], color='r')
    plt.show()
Esempio n. 4
0
def main():
    # Get the data, set the number of steps, and denote the column header
    # containing vote data.
    datapath = "./Prorated/Prorated.shp"
    graphpath = "./graphs/utah.json"
    steps = int(sys.argv[-1])
    r_header = "R"
    d_header = "D"

    # Generate a dataframe, graph, and then combine the two.
    df = gpd.read_file(datapath)
    graph = construct_graph(graphpath)
    add_data_to_graph(df, graph, [r_header, d_header], id_col="GEOID10")

    # Get the discrict assignment and add updaters.
    assignment = dict(
        zip(graph.nodes(), [graph.node[x]["CD"] for x in graph.nodes()]))
    updaters = {
        **votes_updaters([r_header, d_header]), "population":
        Tally("POP10", alias="population"),
        "perimeters":
        perimeters,
        "exterior_boundaries":
        exterior_boundaries,
        "interior_boundaries":
        interior_boundaries,
        "boundary_nodes":
        boundary_nodes,
        "cut_edges":
        cut_edges,
        "areas":
        Tally("ALAND10", alias="areas"),
        "polsby_popper":
        polsby_popper,
        "cut_edges_by_part":
        cut_edges_by_part
    }

    # Create an initial partition and a Pennsylvania-esque chain run.
    initial_partition = Partition(graph, assignment, updaters)
    validator = Validator(
        [refuse_new_splits, no_vanishing_districts, single_flip_contiguous])
    chain = MarkovChain(propose_random_flip,
                        validator,
                        always_accept,
                        initial_partition,
                        total_steps=steps)

    # Pick the scores we want to track.
    scores = {
        "Mean-Median":
        functools.partial(mean_median, proportion_column_name=r_header + "%"),
        "Mean-Thirdian":
        functools.partial(mean_thirdian,
                          proportion_column_name=d_header + "%"),
        "Efficiency Gap":
        functools.partial(efficiency_gap, col1=r_header, col2=d_header),
        "L1 Reciprocal Polsby-Popper":
        L1_reciprocal_polsby_popper
    }

    # Set initial scores, then allow piping and plotting things.
    initial_scores = {
        key: score(initial_partition)
        for key, score in scores.items()
    }
    table = pipe_to_table(chain, scores)
    fig, axes = plt.subplots(2, 2)

    # Configuring where the plots go.
    quadrants = {
        "Mean-Median": (0, 0),
        "Mean-Thirdian": (0, 1),
        "Efficiency Gap": (1, 0),
        "L1 Reciprocal Polsby-Popper": (1, 1)
    }

    # Plotting things!
    for key in scores:
        quadrant = quadrants[key]
        axes[quadrant].hist(table[key], bins=50)
        axes[quadrant].set_title(key)
        axes[quadrant].axvline(x=initial_scores[key], color="r")

    # Show the histogram.
    plt.savefig(f"./output/histograms/{steps}.png")
Esempio n. 5
0
    'Mean-Thirdian':
    functools.partial(mean_thirdian, proportion_column_name=vote_col1 + "%"),
    'Efficiency Gap':
    functools.partial(efficiency_gap, col1=vote_col1, col2=vote_col2),
    'L1 Reciprocal Polsby-Popper':
    L1_reciprocal_polsby_popper
}

initial_scores = {
    key: score(initial_partition)
    for key, score in scores.items()
}

table = pipe_to_table(chain,
                      scores,
                      display=True,
                      display_frequency=100,
                      bin_frequency=1)

# Histogram Plotting
hist_path = "chain_histogram3.png"

hist_of_table_scores(table, scores, outputFile=hist_path, num_bins=50)

print("plotted histograms")

# Trace Plotting
trace_path = "chain_traces3.png"

trace_of_table_scores(table, scores, outputFile=trace_path)
Esempio n. 6
0
def main():

    #graph = construct_graph_from_file("/Users/caranix/Desktop/Alaska_Chain/AK_data.shp", geoid_col="DISTRICT")

    with open('./alaska_graph.json') as f:
        data = json.load(f)
    graph = networkx.readwrite.json_graph.adjacency_graph(data)

    df = gp.read_file(
        "/Users/caranix/Desktop/Alaska_Chain/AK_data.shp"
    )  #    assignment = dict(zip(graph.nodes(), [graph.node[x]['HOUSEDIST'] for x in graph.nodes()]))
    add_data_to_graph(df,
                      graph, [
                          'join_Distr', 'POPULATION', 'join_Dem', 'join_Rep',
                          'perc_Dem', 'perc_Rep', 'AREA'
                      ],
                      id_col='DISTRICT')
    data = json.dumps(networkx.readwrite.json_graph.adjacency_data(graph))
    with open('./alaska_graph.json', 'w') as f:
        f.write(data)

    assignment = dict(
        zip(graph.nodes(),
            [graph.node[x]['join_Distr'] for x in graph.nodes()]))

    updaters = {
        'population':
        Tally('POPULATION', alias='population'),
        'cut_edges':
        cut_edges,
        'cut_edges_by_part':
        cut_edges_by_part,
        **votes_updaters(['join_Dem', 'join_Rep'], election_name='12'), 'perimeters':
        perimeters,
        'exterior_boundaries':
        exterior_boundaries,
        'boundary_nodes':
        boundary_nodes,
        'cut_edges':
        cut_edges,
        'areas':
        Tally('AREA', alias='areas'),
        'polsby_popper':
        polsby_popper
    }

    p = Partition(graph, assignment, updaters)
    print("Starting Chain")

    chain = BasicChain(p, 1000000)
    allAssignments = {0: chain.state.assignment}
    for step in chain:
        allAssignments[chain.counter + 1] = step.flips
    # print(mean_median(step, 'join_Dem%'))

# with open("chain_outputnew.json", "w") as f:
#     f.write(json.dumps(allAssignments))

#efficiency_gap(p)

# mean_median(p, 'join_Dem%')

    scores = {
        'Mean-Median':
        functools.partial(mean_median, proportion_column_name='join_Dem%'),
        'Mean-Thirdian':
        functools.partial(mean_thirdian, proportion_column_name='join_Dem%'),
        'Efficiency Gap':
        functools.partial(efficiency_gap, col1='join_Dem', col2='join_Rep'),
        'L1 Reciprocal Polsby-Popper':
        L1_reciprocal_polsby_popper
    }

    initial_scores = {key: score(p) for key, score in scores.items()}

    table = pipe_to_table(chain, scores)

    fig, axes = plt.subplots(2, 2)

    quadrants = {
        'Mean-Median': (0, 0),
        'Mean-Thirdian': (0, 1),
        'Efficiency Gap': (1, 0),
        'L1 Reciprocal Polsby-Popper': (1, 1)
    }

    for key in scores:
        quadrant = quadrants[key]
        axes[quadrant].hist(table[key], bins=50)
        axes[quadrant].set_title(key)
        axes[quadrant].axvline(x=initial_scores[key], color='r')
    plt.show()
    '''