Package: poli-sci-kit
Political elections, appointment, analysis and visualization in Pythonpoli-sci-kitis 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 thedocumentationfor a full outline of the package including algorithms and visualization techniques.ContentsInstallationAppointmentPlottingParliament PlotsDisproportionality Bar PlotExamplesTo-DoInstallation⇧poli-sci-kit can be downloaded from PyPI via pip or sourced directly from this repository:pipinstallpoli-sci-kitgitclonehttps://github.com/andrewtavis/poli-sci-kit.gitcdpoli-sci-kit
pythonsetup.pyinstallimportpoli_sci_kitAppointment⇧appointment.methodsincludes 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-HillArguments 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. Theappointment.metricsmodule 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:frompoli_sci_kitimportappointmentvote_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 statesha_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]We can then compute various metrics to derive disproportionality:# The Gallagher method is a measure of absolute difference similar to summing square residualsdisproportionality=appointment.metrics.dispr_index(shares=vote_counts,allocations=ha_allocations,metric_type='Gallagher')disproportionality# 0.01002We can also check that the allocations pass thequota condition:passes_qc=appointment.checks.quota_condition(shares=vote_counts,seats=ha_allocations)passes_qc# TrueAllocation consistency can further be checked using dataframes of shares and seats given electoral settings. Seeappointment.checksandthe documentationfor explanations of method checks.Plotting⇧poli-sci-kit provides Python only implementations of common electoral plots.Visualizing the above results:importmatplotlib.pyplotaspltimportpoli_sci_kit# German political partiesparties=['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 semicircleparliament 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 thedisproportionality 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:importpltvizax=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)forvinvotes],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 packagewikirepo. Current examples include:US HoR(Open in Colab)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 electionGlobal Parliament(Open in Colab)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 metricsTo-Do⇧Please see thecontribution guidelinesif you are interested in contributing to this project. Work that is in progress or could be implemented includes:Adding theAdams methodtoappointment.methods.highest_averages(see issue)Deriving further needed arguments to assure that all current and historic appointment systems can be simulated using poli-sci-kit (see issue)Potentially indexing preset versions ofappointment.methodsthat coincide with the systems used by governments around the worldThis would allow quick comparisons of actual systems with variationsAdding methods such as quadratic voting to poli-sci-kit to allow for preference based simulationsCreating, improving and sharingexamplesImprovingtestsfor greatercode coverageReferencesFull list of referencesvotingbycrflynn(License)https://blogs.reading.ac.uk/readingpolitics/2015/06/29/electoral-disproportionality-what-is-it-and-how-should-we-measure-it/Balinski, M. L., and Young, H. P. (1982). Fair Representation: Meeting the Ideal of One Man, One Vote. New Haven, London: Yale University Press.Karpov, A. (2008). "Measurement of disproportionality in proportional representation systems". Mathematical and Computer Modelling, Vol. 48, pp. 1421-1438. URL:https://www.sciencedirect.com/science/article/pii/S0895717708001933.Kohler, U., and Zeh, J. (2012). “Apportionment methods”. The Stata Journal, Vol. 12, No. 3, pp. 375–392. URL:https://journals.sagepub.com/doi/pdf/10.1177/1536867X1201200303.Taagepera, R., and Grofman, B. (2003). "Mapping the Indices of Seats-Votes Disproportionality and Inter-Election Volatility". Party Politics, Vol. 9, No. 6, pp. 659–677. URL:https://escholarship.org/content/qt0m9912ff/qt0m9912ff.pdf.