Spatial voting simulations on a grid with random challengers (with float32 JAX backend)
Project description
gridvoting-jax
A JAX-powered derivative of the original gridvoting project
This library provides GPU/TPU/CPU-accelerated spatial voting simulations using Google's JAX framework with float32 precision.
Origin and Development
This project is derived from the original gridvoting module, which was developed for the research publication:
Brewer, P., Juybari, J. & Moberly, R.
A comparison of zero- and minimal-intelligence agendas in majority-rule voting models.
J Econ Interact Coord (2023). https://doi.org/10.1007/s11403-023-00387-8
Migration to JAX: The computational backend was refactored from NumPy/CuPy to JAX using Google's Antigravity AI assistant. This migration provides:
- ✨ Unified CPU/GPU/TPU support through JAX
- 🚀 Improved performance through JIT compilation
- 💾 Float32 precision for efficiency
- 🔗 Better compatibility with modern ML/AI workflows
Original Project: https://github.com/drpaulbrewer/gridvoting
Quick Start
Spatial Voting Example
import gridvoting_jax as gv
# Use a pre-built example or create your own
# Triangle 1 from Brewer, Juybari & Moberly (2023)
# Voter ideal points: [[-15, -9], [0, 17], [15, -9]]
# https://doi.org/10.1007/s11403-023-00387-8
model = gv.bjm_spatial_triangle(g=20, zi=False)
model.analyze()
print(f"Device: {gv.device_type}") # Shows 'gpu', 'tpu', or 'cpu'
print(f"Core exists: {model.core_exists}")
print(f"Stationary distribution: {model.stationary_distribution[:5]}...")
Budget Voting Example (New in v0.9.0)
import gridvoting_jax as gv
# Create budget voting model (divide $100 among 3 voters)
model = gv.BudgetVotingModel(budget=100, zi=False)
model.analyze()
print(f"Alternatives: {model.number_of_alternatives}") # 5151
print(f"GiniSS inequality: {model.GiniSS[:5]}...")
# Get voter utility distributions
utility_values, probabilities = model.voter_utility_distribution(voter_index=0)
# Get GiniSS inequality distribution
gini_values, gini_probs = model.giniss_distribution(granularity=0.10)
Installation
Google Colab (Recommended)
All dependencies are pre-installed! Just run:
!pip install gridvoting-jax
Local Installation
pip install gridvoting-jax
GPU Support: JAX automatically detects and uses NVIDIA GPUs (CUDA) when available. An Nvidia A100 works well if you have one, but even an old 2017 gaming Nvidia 1080Ti will run some models.
TPU Support: JAX automatically detects TPUs on Google Cloud. TPUs we tried have been quirky with this code.
CPU Support: Should run with most CPUs. It will fall back to CPU mode if a GPU or TPU is not detected. RAM >=32GB is useful for some tasks.
CPU-Only Mode: If you have a GPU or TPU but want to force CPU-only execution, set environment variable GV_FORCE_CPU=1:
GV_FORCE_CPU=1 python your_script.py
Docker Usage
The project includes Dockerfiles for building CPU and GPU images.
Building Docker Images:
# Build CPU image
docker build -f docker/Dockerfile.cpu -t gridvoting-jax-cpu .
# Build GPU image
docker build -f docker/Dockerfile.gpu -t gridvoting-jax-gpu .
Testing Docker Images:
A test_docker.sh script is provided to run a quick test inside the Docker containers.
To execute:
./test_docker.sh
Run OSF Benchmarks
To run the full suite of OSF comparison benchmarks using the pre-built Docker images (GHCR):
./test_docker_osf.sh
This script automatically detects GPU availability and runs both Float32 and Float64 benchmarks.
Using Pre-built Docker Images
The project provides pre-built Docker images with all dependencies and OSF benchmark data included.
CPU Image:
# Run python shell
docker run --rm -it ghcr.io/[user]/gridvoting-jax-cpu python3
# Run OSF Benchmark
docker run --rm ghcr.io/[user]/gridvoting-jax-cpu run_osf_benchmark
GPU Image:
# Run python shell with GPU access
docker run --rm --gpus all -it ghcr.io/[user]/gridvoting-jax-all python3
# Run OSF Benchmark
docker run --rm --gpus all ghcr.io/[user]/gridvoting-jax-all run_osf_benchmark
Float64 Precision: By default, JAX uses 32-bit floats for better GPU performance. To enable 64-bit precision for higher accuracy:
import gridvoting_jax as gv
gv.enable_float64()
# All subsequent JAX operations will use float64
Requirements
- Python 3.9+
- numpy >= 2.0.0
- matplotlib >= 3.8.0
- jax >= 0.4.20
- chex >= 0.1.0
Google Colab: All dependencies are pre-installed (numpy 2.0.2, matplotlib 3.10, jax 0.7).
Note: pandas and scipy are NOT required. gridvoting-jax uses only JAX for numerical operations.
Performance
Under review
Differences from Original gridvoting
This JAX version differs from the original in several ways:
| Feature | Original gridvoting | gridvoting-jax |
|---|---|---|
| Backend | NumPy/CuPy | JAX |
| Precision | Float64 | Float32 (default) Float64 (available) |
| Solver | Power + Algebraic | Algebraic only |
| Tolerance | 1e-10 | 5e-5 |
| Device Detection | GPU/CPU | TPU/GPU/CPU |
| Import | import gridvoting |
import gridvoting_jax |
Numerical Accuracy: Float32 provides ~7 decimal digits of precision, which is sufficient for many spatial voting simulations.
Random Sequential Voting Simulations
This follows section 2 of our research paper.
A simulation consists of:
- A sequence of times:
t=0,1,2,3,... - A finite feasible set of alternatives F
- A set of voters who have preferences over the alternatives and vote truthfully
- A rule for voting and selecting challengers
- A mapping of the set of alternatives F into a 2D grid
The active or status quo alternative at time t is called f[t].
At each t, there is a majority-rule vote between alternative f[t] and a challenger alternative c[t]. The winner of that vote becomes the next status quo f[t+1].
Randomness enters through two possible rules for choosing the challenger c[t]:
- Zero Intelligence (ZI) (
zi=True):c[t]is chosen uniformly at random from F - Minimal Intelligence (MI) (
zi=False):c[t]is chosen uniformly from the status quof[t]and the possible winning alternatives givenf[t]
API Documentation (v0.9.0)
The package is organized into submodules, but the public API is exposed at the top level for convenience.
import gridvoting_jax as gv
Core Configuration (gv.core)
Centralized configuration and constants.
gv.enable_float64(): Enable 64-bit floating point precision globally for JAXgv.TOLERANCE: Default tolerance for floating-point comparisons (5e-5 for float32)gv.device_type: Current device type ('gpu', 'tpu', or 'cpu')gv.use_accelerator: Boolean indicating if GPU/TPU is available
Spatial Components (gv.spatial)
class Grid
grid = gv.Grid(x0, x1, xstep=1, y0, y1, ystep=1)
Constructs a 2D grid for spatial voting models.
Properties:
grid.points: JAX array of shape(N, 2)containing[x, y]coordinatesgrid.x,grid.y: 1D JAX arrays of x and y coordinatesgrid.boundary: 1D boolean mask for boundary pointsgrid.len: Total number of grid points
Methods:
spatial_utilities(voter_ideal_points, metric='sqeuclidean'): Distance-based utility calculationwithin_box/disk/triangle(...): Geometric query methods returning boolean masksextremes(z, valid=None): Find min/max values and their locationsembedding(valid): Create embedding function for plotting subsetsplot(z, ...): Plot scalar fields on the grid using Matplotlib
Voting Models
class VotingModel
Geometry-agnostic base voting model.
vm = gv.VotingModel(
utility_functions,
number_of_voters,
number_of_feasible_alternatives,
majority,
zi
)
Methods:
analyze(solver="full_matrix_inversion"): Compute stationary distributionwhat_beats(index): Returns alternatives that beat the given indexsummarize_in_context(grid): Calculate entropy, mean, and covariance
Properties:
stationary_distribution: Probability distribution over alternativescore_exists: Boolean indicating if a core existscore_points: Boolean mask of core points
class SpatialVotingModel
Geometry-aware spatial voting model (delegates to VotingModel).
model = gv.SpatialVotingModel(
voter_ideal_points,
grid,
number_of_voters,
majority,
zi
)
Additional Methods:
plot_stationary_distribution(**kwargs): Visualize results on grid
class BudgetVotingModel (New in v0.9.0)
Budget allocation voting model for dividing a fixed budget among 3 voters.
model = gv.BudgetVotingModel(budget=100, zi=False)
Features:
- Feasible set forms triangular simplex:
x + y <= budget - Number of alternatives:
(budget+1)*(budget+2)//2 - Utility functions:
u1=x,u2=y,u3=budget-x-y - GiniSS inequality index: scaled to [0,1]
- Symmetry property:
π[x,y] ≈ π[y,x]
Methods:
analyze(solver="full_matrix_inversion"): Compute stationary distributionvoter_utility_distribution(voter_index): Probability distribution of voter payoffsginiss_distribution(granularity=0.10): Probability distribution of GiniSS indexplot_stationary_distribution(**kwargs): Visualize on triangular simplex
Properties:
budget: Total budget to allocateu1, u2, u3: Utility for each voter at each alternativeGiniSS: Gini-like inequality index for each alternativestationary_distribution: Probability distribution over allocations
Example Models (New in v0.9.0)
Plott's Theorem Examples
Demonstrate core existence conditions from Plott's median voter theorem:
Plott, C. R. (1967). A notion of equilibrium and its possibility under majority rule. American Economic Review, 57(4), 787-806.
# Core existence examples
model = gv.core1(g=20, zi=False) # 5 voters on horizontal line
model = gv.core2(g=20, zi=False) # 5 voters on vertical line
model = gv.core3(g=20, zi=False) # 5 voters on diagonal
model = gv.core4(g=20, zi=False) # 4 corners + center
model = gv.ring_with_central_core(g=20, r=10, voters=7) # Ring + center
# No-core example
model = gv.nocore_triangle(g=20, zi=False) # Equilateral triangle (cycling)
Shapes Submodule
Random and geometric configurations:
# Random triangle
model = gv.shapes.random_triangle(g=20, within=10, zi=False)
# Ring of voters (must be odd)
model = gv.shapes.ring(g=20, r=10, voters=5, round_ideal_points=True)
BJM Research Examples
Examples from published research:
Brewer, P., Juybari, J. & Moberly, R. (2023). A comparison of zero- and minimal-intelligence agendas in majority-rule voting models. Journal of Economic Interaction and Coordination. https://doi.org/10.1007/s11403-023-00387-8
# Spatial voting (Triangle 1 from OSF)
model = gv.bjm_spatial_triangle(g=20, zi=False)
# Budget voting
model = gv.bjm_budget_triangle(budget=100, zi=False)
Markov Chain (gv.dynamics)
class MarkovChain
mc = gv.MarkovChain(P, tolerance=5e-5)
mc.find_unique_stationary_distribution(solver="full_matrix_inversion")
Solvers:
"full_matrix_inversion": Direct matrix inversion (default)"gmres_matrix_inversion": Iterative GMRES solver"power_method": Power iteration method"grid_upscaling": Spatial upscaling (SpatialVotingModel only)
Datasets (gv.datasets)
gv.datasets.fetch_osf_spatial_voting_2022_a100(): Downloads OSF reference dataset
Benchmarks
Run performance benchmarks to test solver speed across different grid sizes:
import gridvoting_jax as gv
# Print formatted benchmark results
gv.benchmarks.performance()
# Get results as dictionary for programmatic use
results = gv.benchmarks.performance(dict=True)
print(f"Device: {results['device']}")
print(f"JAX version: {results['jax_version']}")
for test in results['results']:
print(f"{test['test_case']}: {test['time_seconds']:.4f}s")
Benchmark Test Cases:
- Grid sizes: g=20, g=40, g=60
- Voting modes: ZI (Zero Intelligence) and MI (Minimal Intelligence)
- 6 test cases total
Replication & Verification against OSF Data
You can automatically verify the library's output against the original A100 GPU replication data deposited on OSF. This benchmark downloads the reference data and compares stationary distributions using the L1 norm.
from gridvoting_jax.benchmarks.osf_comparison import run_comparison_report
# Run complete comparison report
# Automatically downloads reference data to /tmp/gridvoting_osf_cache
report = run_comparison_report()
# Or test specific configurations
# report = run_comparison_report([(20, False)]) # g=20, MI mode
Google Colab Usage
In a Colab notebook, you can run the full verification suite in a single cell:
!pip install gridvoting-jax
from gridvoting_jax.benchmarks.osf_comparison import run_comparison_report
# Run all 8 replication configurations (g=20, 40, 60, 80)
report = run_comparison_report()
This compares your computer's simulation results to the published scientific record.
Testing
Run Tests
# Install development dependencies
pip install -r requirements-dev.txt
# Run all tests (43 tests in v0.9.0)
pytest tests/
# Skip slow tests
pytest tests/ -m "not slow"
# Run only slow tests (benchmark test)
pytest tests/ -m slow
# Run with coverage
pytest tests/ --cov=gridvoting_jax -m "not slow"
Test Coverage (v0.9.0):
- Budget voting: 7 tests (symmetry, ZI/MI modes, distributions)
- Plott's theorem examples: 3 tests (core existence/absence)
- Shapes: 4 tests (random triangles, rings)
- BJM examples: 3 tests (OSF validation)
- Core functionality: 26 tests (grid, voting, solvers)
Test Markers:
@pytest.mark.slow: Long-running tests (benchmarks)- Use
-m "not slow"to skip slow tests during development
Google Colab
!pip install gridvoting-jax
!pytest /usr/local/lib/python3.*/dist-packages/gridvoting_jax/
License
The software is provided under the standard MIT License.
You are welcome to try the software, read it, copy it, adapt it to your needs, and redistribute your adaptations. If you change the software, be sure to change the module name so that others know it is not the original. See the LICENSE file for more details.
Disclaimers
The software is provided in the hope that it may be useful to others, but it is not a full-featured turnkey system for conducting arbitrary voting simulations. Additional coding is required to define a specific simulation.
Automated tests exist and run on GitHub Actions. However, this cannot guarantee that the software is free of bugs or defects or that it will run on your computer without adjustments.
The MIT License includes this disclaimer:
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Research Data
Code specific to the spatial voting and budget voting portions of our research publication -- as well as output data -- is deposited at: OSF Dataset for A comparison of zero and minimal Intelligence agendas in majority rule voting models and is freely available.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Citation
If you use this software in your research, please cite the original paper:
@article{brewer2023comparison,
title={A comparison of zero-and minimal-intelligence agendas in majority-rule voting models},
author={Brewer, Paul and Juybari, Jeremy and Moberly, Raymond},
journal={Journal of Economic Interaction and Coordination},
year={2023},
publisher={Springer},
doi={10.1007/s11403-023-00387-8}
}
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file gridvoting_jax-0.9.1.tar.gz.
File metadata
- Download URL: gridvoting_jax-0.9.1.tar.gz
- Upload date:
- Size: 52.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
10e254ead2b9e9d90537714ad258aa188bb8127fd068d1ad1a6619ebef0a3e24
|
|
| MD5 |
8882fd5df9f04e6a104b8b93a5475a36
|
|
| BLAKE2b-256 |
f4d9a60b8056b8f39aee4f1279a8c4218153a464ad82ef50eaced3c820b93f2d
|
Provenance
The following attestation bundles were made for gridvoting_jax-0.9.1.tar.gz:
Publisher:
python-publish.yml on DrPaulBrewer/gridvoting-jax
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
gridvoting_jax-0.9.1.tar.gz -
Subject digest:
10e254ead2b9e9d90537714ad258aa188bb8127fd068d1ad1a6619ebef0a3e24 - Sigstore transparency entry: 774992828
- Sigstore integration time:
-
Permalink:
DrPaulBrewer/gridvoting-jax@29a6f99c2f366d285e98ebf7a3f4fffe5a3a8937 -
Branch / Tag:
refs/tags/v0.9.1 - Owner: https://github.com/DrPaulBrewer
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@29a6f99c2f366d285e98ebf7a3f4fffe5a3a8937 -
Trigger Event:
release
-
Statement type:
File details
Details for the file gridvoting_jax-0.9.1-py3-none-any.whl.
File metadata
- Download URL: gridvoting_jax-0.9.1-py3-none-any.whl
- Upload date:
- Size: 44.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d7b9454a309bf2b521aba878ff5d792e509b457e891a6e86e6e293a1a055e099
|
|
| MD5 |
9e68e178996343b25c4026f2fd46844a
|
|
| BLAKE2b-256 |
66882bd71191dd0d664c3472581af8c6e384a3402d60b53b1be0bf17b91c2c8d
|
Provenance
The following attestation bundles were made for gridvoting_jax-0.9.1-py3-none-any.whl:
Publisher:
python-publish.yml on DrPaulBrewer/gridvoting-jax
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
gridvoting_jax-0.9.1-py3-none-any.whl -
Subject digest:
d7b9454a309bf2b521aba878ff5d792e509b457e891a6e86e6e293a1a055e099 - Sigstore transparency entry: 774992831
- Sigstore integration time:
-
Permalink:
DrPaulBrewer/gridvoting-jax@29a6f99c2f366d285e98ebf7a3f4fffe5a3a8937 -
Branch / Tag:
refs/tags/v0.9.1 - Owner: https://github.com/DrPaulBrewer
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@29a6f99c2f366d285e98ebf7a3f4fffe5a3a8937 -
Trigger Event:
release
-
Statement type: