Political elections, appointment, analysis and visualization in Python

Overview

rtd ci codecov pyversions pypi pypistatus license coc codestyle colab

Political elections, appointment, analysis and visualization in Python

poli-sci-kit is a Python package for political science appointment and election analysis. The goal is to provide a comprehensive tool for all methods needed to analyze and simulate election results. See the documentation for a full outline of the package including algorithms and visualization techniques.

Contents

Installation

poli-sci-kit can be downloaded from PyPI via pip or sourced directly from this repository:

pip install poli-sci-kit
git clone https://github.com/andrewtavis/poli-sci-kit.git
cd poli-sci-kit
python setup.py install
import poli_sci_kit

Appointment

appointment.methods includes functions to allocate parliamentary seats based on population or vote shares. Included methods are:

Largest Remainder: Hare, Droop, Hagenbach–Bischoff (incl Hamilton, Vinton, Hare–Niemeyer)

Highest Averages: Jefferson, Webster, Huntington-Hill

Arguments to allow allocation thresholds, minimum allocations per group, tie break conditions, and other election features are also provided. Along with deriving results for visualization and reporting, these functions allow the user to analyze outcomes given systematic or situational changes. The appointment.metrics module further provides diagnostics to analyze the results of elections, apportionments, and other political science scenarios.

A basic example of political appointment using poli-sci-kit is:

from poli_sci_kit import appointment

vote_counts = [2700, 900, 3300, 1300, 2150, 500]
seats_to_allocate = 50

# Huntington-Hill is the method used to allocate House of Representatives seats to US states
ha_allocations = appointment.methods.highest_averages(
    averaging_style="Huntington-Hill",
    shares=vote_counts,
    total_alloc=seats_to_allocate,
    alloc_threshold=None,
    min_alloc=1,
    tie_break="majority",
    majority_bonus=False,
    modifier=None,
)

ha_allocations
# [26, 9, 37, 12, 23, 5]

# The Gallagher method is a measure of absolute difference similar to summing square residuals
disproportionality = appointment.metrics.dispr_index(
    shares=vote_counts,
    allocations=ha_allocations,
    metric_type='Gallagher'
)

disproportionality
# 0.01002

We can also check that the allocations pass the quota condition:

passes_qc = appointment.checks.quota_condition(
    shares=vote_counts,
    seats=ha_allocations
)

passes_qc
# True

Allocation consistency can further be checked using dataframes of shares and seats given electoral settings. See appointment.checks and the documentation for explanations of method checks.

Plotting

poli-sci-kit provides Python only implementations of common electoral plots.

Visualizing the above results:

import matplotlib.pyplot as plt
import poli_sci_kit

# German political parties
parties = ['CDU/CSU', 'FDP', 'Greens', 'Die Linke', 'SPD', 'AfD']
party_colors = ['#000000', '#ffed00', '#64a12d', '#be3075', '#eb001f', '#009ee0']

Parliament Plots

poli_sci_kit provides implementations of both rectangular and semicircle parliament plots:

fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2)

ax1 = poli_sci_kit.plot.parliament(
    allocations=seat_allocations,
    labels=parties,
    colors=party_colors,
    style="rectangle",
    num_rows=4,
    marker_size=300,
    speaker=True,
    axis=ax1,
)

ax2 = poli_sci_kit.plot.parliament(
    allocations=seat_allocations,
    labels=parties,
    colors=party_colors,
    style="semicircle",
    num_rows=4,
    marker_size=175,
    speaker=False,
    axis=ax2,
)

plt.show()

Disproportionality Bar Plot

A novel addition to social science analysis is the disproportionality bar plot, which graphically depicts the disproportionality between expected and realized results. Bar widths are the proportion of shares (ex: votes received), and heights are the difference or relative difference between shares and allocations (ex: parliament seats received).

An example follows:

import pltviz

ax = poli_sci_kit.plot.dispr_bar(
    shares=votes,
    allocations=ha_allocations,
    labels=parties,
    colors=party_colors,
    total_shares=None,
    total_alloc=None,
    percent=True,
    axis=None,
)

handles, labels = pltviz.plot.legend.gen_elements(
    counts=[round(v / sum(votes), 4) for v in votes],
    labels=parties,
    colors=party_colors,
    size=11,
    marker="o",
    padding_indexes=None,
    order=None,
)

ax.legend(
    handles=handles,
    labels=labels,
    title="Vote Percents (bar widths)",
    title_fontsize=15,
    fontsize=11,
    ncol=2,
    loc="upper left",
    bbox_to_anchor=(0, 1),
    frameon=True,
    facecolor="#FFFFFF",
    framealpha=1,
)

ax.axes.set_title('Seat to Vote Share Disproportionality', fontsize=30)
ax.set_xlabel('Parties', fontsize=20)
ax.set_ylabel('Percent Shift', fontsize=20)

plt.show()

Examples

Examples in poli-sci-kit use publicly available Wikidata statistics sourced via the Python package wikirepo. Current examples include:

  • US HoR

    • Allocates seats to a version of the US House of Representatives that includes all US territories and Washington DC given census data, with this further being used to derive relative vote strengths of state citizens in the US presidential election
  • Global Parliament

    • Analyzes the allocation of seats in a hypothetical global parliament given the prevalence of certain countries and organizations, the distribution of seats based on Freedom House indexes, as well as disproportionality metrics

To-Do

Please see the contribution guidelines if you are interested in contributing to this project. Work that is in progress or could be implemented includes:

References

Full list of references

Comments
  • Add equations to appointment.methods docstrings

    Add equations to appointment.methods docstrings

    Equations should be added to the doc strings of largest_remainder and highest_average in poli_sci_kit.appointment.methods. They would then be rendered in the documentation for greater clarity.

    Most of these equations can be found on the Wikipedia pages for the respective methods. They should be placed in the options section of the quota_style and averaging_style parameters respectively.

    documentation help wanted good first issue 
    opened by andrewtavis 6
  • Bump urllib3 from 1.26.3 to 1.26.4

    Bump urllib3 from 1.26.3 to 1.26.4

    ⚠️ Dependabot is rebasing this PR ⚠️

    If you make any changes to it yourself then they will take precedence over the rebase.


    Bumps urllib3 from 1.26.3 to 1.26.4.

    Release notes

    Sourced from urllib3's releases.

    1.26.4

    :warning: IMPORTANT: urllib3 v2.0 will drop support for Python 2: Read more in the v2.0 Roadmap

    • Changed behavior of the default SSLContext when connecting to HTTPS proxy during HTTPS requests. The default SSLContext now sets check_hostname=True.

    If you or your organization rely on urllib3 consider supporting us via GitHub Sponsors

    Changelog

    Sourced from urllib3's changelog.

    1.26.4 (2021-03-15)

    • Changed behavior of the default SSLContext when connecting to HTTPS proxy during HTTPS requests. The default SSLContext now sets check_hostname=True.
    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 2
  • [ImgBot] Optimize images

    [ImgBot] Optimize images

    Beep boop. Your images are optimized!

    Your image file size has been reduced by 41% 🎉

    Details

    | File | Before | After | Percent reduction | |:--|:--|:--|:--| | /resources/gh_images/semicircle_parliament.png | 81.86kb | 18.55kb | 77.34% | | /resources/gh_images/rectangle_parliament.png | 9.29kb | 3.47kb | 62.65% | | /resources/poli-sci-kit_logo_transparent.png | 152.83kb | 95.31kb | 37.63% | | /resources/poli-sci-kit_logo.png | 139.30kb | 90.68kb | 34.91% | | /resources/gh_images/dispr_bar.png | 103.09kb | 77.35kb | 24.97% | | | | | | | Total : | 486.37kb | 285.36kb | 41.33% |


    Black Lives Matter | 💰 donate | 🎓 learn | ✍🏾 sign

    📝 docs | :octocat: repo | 🙋🏾 issues | 🏅 swag | 🏪 marketplace

    opened by imgbot[bot] 1
  • Bump cryptography from 3.3.1 to 3.3.2

    Bump cryptography from 3.3.1 to 3.3.2

    Bumps cryptography from 3.3.1 to 3.3.2.

    Changelog

    Sourced from cryptography's changelog.

    3.3.2 - 2021-02-07

    
    * **SECURITY ISSUE:** Fixed a bug where certain sequences of ``update()`` calls
      when symmetrically encrypting very large payloads (>2GB) could result in an
      integer overflow, leading to buffer overflows. *CVE-2020-36242*
    

    .. _v3-3-1:

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 1
  • Create concise requirement and env files

    Create concise requirement and env files

    This issue is for creating concise versions of requirements.txt and environment.yml for poli-sci-kit. It would be great if these files were created by hand with specific version numbers or generated in a way so that sub-dependencies don't always need to be updated.

    As of now both files are being created with the following commands in the package's conda virtual environment:

    pip list --format=freeze > requirements.txt  
    conda env export --no-builds | grep -v "^prefix: " > environment.yml
    

    poli-sci-kit and other obviously unneeded packages are then removed from these files before being uploaded.

    Any insights or help would be much appreciated!

    help wanted good first issue question 
    opened by andrewtavis 0
  • Add equations to appointment.metrics docstrings

    Add equations to appointment.metrics docstrings

    This issue is for adding LaTeX equations to the docstrings of all functions found in poli_sci_kit.appointment.metrics. The style should be similar to those found in poli_sci_kit.appointment.methods.

    The following is an explanation for how to write LaTeX in docstrings:

    1. In conf.py of the documentation you need the extension sphinx.ext.imgmath, which allows equations to be rendered to pngs (this has been added to poli-sci-kit's conf.py)
    2. If you want to add an equation, then as seen in the docstrings for appointment.methods you add the following:
    .. math::
        LaTeX you want rendered
    
    1. The docstring also needs to be converted to an r-sting (this is now the case for largest_remainder and highest_averages)
    2. You also need to use &= instead of = in equations

    This LaTeX editor could be used to test equations and then add them to the docstrings (remembering &= instead of =). I would be more than happy to help if one of the equations doesn't make sense, or if getting the LaTeX to work is a bit confusing :)

    Thanks for your interest in contributing!

    documentation help wanted good first issue 
    opened by andrewtavis 0
  • New appointment arguments

    New appointment arguments

    Please use this issue to suggest new arguments for poli-sci-kit.appointment.methods functions if you know of a style of appointment variable that is not yet implemented. These new arguments can then be converted into good first issues that would include the necessary codes for implementation and testing.

    Thanks for your interest in contributing!

    enhancement help wanted question 
    opened by andrewtavis 0
  • Add Adams method to appointment.methods.highest_averages

    Add Adams method to appointment.methods.highest_averages

    The Adams method, as described on Wikipedia, is another highest averages method that could be implemented. This method has been implemented in voting, but lacks the allocation conditions that poli-sci-kit provide.

    This issue would be to add this method to appointment.methods.highest_averages in a way that allows for minimum allocations, tie break conditions, majority bonus rules, and other conditional rulesets.

    enhancement help wanted good first issue 
    opened by andrewtavis 0
  • Accurate semicircle parliament plot allocations

    Accurate semicircle parliament plot allocations

    The semicircle version of the parliament plot at times doesn't put all the seats for a group in the same area. There is potentially a better method of allocating the scatterplot points in that function, or break points could be put in given parliament sizes to assure that groups have all their seats in one area of the plot.

    Fixes for this would specifically need to target poli_sci_kit.utils.gen_parl_points.

    enhancement help wanted 
    opened by andrewtavis 0
Releases(v1.0.0)
  • v1.0.0(Dec 28, 2021)

  • v0.1.2.5(Mar 24, 2021)

    Changes include:

    • Package structure has been modified for better testing and a cleaner wheel

    • Bug fixes and refactoring for cleaner code

    • Checks for code quality have been added

    • Examples now function in Google Colab

    Source code(tar.gz)
    Source code(zip)
  • v0.1.0(Feb 10, 2021)

    First stable release of poli-sci-kit

    Changes include:

    • Plotting functions for parliament allocations and seat disproportionality

    • Full documentation of the package

    • Virtual environment files

    • Bug fixes

    • Extensive testing of all modules with GH Actions and Codecov

    • Code of conduct and contribution guidelines

    Source code(tar.gz)
    Source code(zip)
  • v0.0.2.1(Dec 9, 2020)

    The minimum viable product of poli-sci-kit

    • Users are able to do political appointments using a variety of methods including largest remainder and highest average techniques

    • Users are able to analyze the results of appointments

    • Usage examples have been created

    Source code(tar.gz)
    Source code(zip)
Owner
Andrew Tavis McAllister
Data scientist, developer and designer. Humboldt University of Berlin (MS); University of Oregon (BA).
Andrew Tavis McAllister
This is a sorting visualizer made with Tkinter.

Sorting-Visualizer This is a sorting visualizer made with Tkinter. Make sure you've installed tkinter in your system to use this visualizer pip instal

Vishal Choubey 7 Jul 06, 2022
These data visualizations were created for my introductory computer science course using Python

Homework 2: Matplotlib and Data Visualization Overview These data visualizations were created for my introductory computer science course using Python

Sophia Huang 12 Oct 20, 2022
Bokeh Plotting Backend for Pandas and GeoPandas

Pandas-Bokeh provides a Bokeh plotting backend for Pandas, GeoPandas and Pyspark DataFrames, similar to the already existing Visualization feature of

Patrik Hlobil 822 Jan 07, 2023
Python ts2vg package provides high-performance algorithm implementations to build visibility graphs from time series data.

ts2vg: Time series to visibility graphs The Python ts2vg package provides high-performance algorithm implementations to build visibility graphs from t

Carlos Bergillos 26 Dec 17, 2022
daily report of @arkinvest ETF activity + data collection

ark_invest daily weekday report of @arkinvest ETF activity + data collection This script was created to: Extract and save daily csv's from ARKInvest's

T D 27 Jan 02, 2023
Render tokei's output to interactive sunburst chart.

Render tokei's output to interactive sunburst chart.

134 Dec 15, 2022
High-level geospatial data visualization library for Python.

geoplot: geospatial data visualization geoplot is a high-level Python geospatial plotting library. It's an extension to cartopy and matplotlib which m

Aleksey Bilogur 1k Jan 01, 2023
Realtime Web Apps and Dashboards for Python and R

H2O Wave Realtime Web Apps and Dashboards for Python and R New! R Language API Build and control Wave dashboards using R! New! Easily integrate AI/ML

H2O.ai 3.4k Jan 06, 2023
Geocoding library for Python.

geopy geopy is a Python client for several popular geocoding web services. geopy makes it easy for Python developers to locate the coordinates of addr

geopy 3.8k Jan 02, 2023
A concise grammar of interactive graphics, built on Vega.

Vega-Lite Vega-Lite provides a higher-level grammar for visual analysis that generates complete Vega specifications. You can find more details, docume

Vega 4k Jan 08, 2023
University of Missouri - Kansas City: CS451R: Capstone

CS451RC University of Missouri - Kansas City: CS451R: Capstone Installation cd git clone https://github.com/ala2q6/CS451RC.git cd CS451RC pip3 instal

Alex Arbuckle 1 Nov 17, 2021
The Timescale NFT Starter Kit is a step-by-step guide to get up and running with collecting, storing, analyzing and visualizing NFT data from OpenSea, using PostgreSQL and TimescaleDB.

Timescale NFT Starter Kit The Timescale NFT Starter Kit is a step-by-step guide to get up and running with collecting, storing, analyzing and visualiz

Timescale 102 Dec 24, 2022
Log visualizer for whirl-framework

Lumberjack Log visualizer for whirl-framework Установка pip install -r requirements.txt Как пользоваться python3 lumberjack.py -l путь до лога -o

Vladimir Malinovskii 2 Dec 19, 2022
OpenStats is a library built on top of streamlit that extracts data from the Github API and shows the main KPIs

Open Stats Discover and share the KPIs of your OpenSource project. OpenStats is a library built on top of streamlit that extracts data from the Github

Pere Miquel Brull 4 Apr 03, 2022
Extract data from ThousandEyes REST API and visualize it on your customized Grafana Dashboard.

ThousandEyes Grafana Dashboard Extract data from the ThousandEyes REST API and visualize it on your customized Grafana Dashboard. Deploy Grafana, Infl

Flo Pachinger 16 Nov 26, 2022
2D maze path solver visualizer implemented with python

2D maze path solver visualizer implemented with python

SS 14 Dec 21, 2022
Flow-based visual scripting for Python

A simple visual node editor for Python Ryven combines flow-based visual scripting with Python. It gives you absolute freedom for your nodes and a simp

Leon Thomm 3.1k Jan 06, 2023
Streamlit component for Let's-Plot visualization library

streamlit-letsplot This is a work-in-progress, providing a convenience function to plot charts from the Lets-Plot visualization library. Example usage

Randy Zwitch 9 Nov 03, 2022
Color maps for POV-Ray v3.7 from the Plasma, Inferno, Magma and Viridis color maps in Python's Matplotlib

POV-Ray-color-maps Color maps for POV-Ray v3.7 from the Plasma, Inferno, Magma and Viridis color maps in Python's Matplotlib. The include file Color_M

Tor Olav Kristensen 1 Apr 05, 2022
Interactive plotting for Pandas using Vega-Lite

pdvega: Vega-Lite plotting for Pandas Dataframes pdvega is a library that allows you to quickly create interactive Vega-Lite plots from Pandas datafra

Altair 342 Oct 26, 2022