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
import gridvoting_jax as gv
# Create a grid
grid = gv.Grid(x0=-20, x1=20, y0=-20, y1=20)
# Define voter ideal points
voter_ideal_points = [[-15, -9], [0, 17], [15, -9]]
# Generate utility functions
utilities = grid.spatial_utilities(voter_ideal_points=voter_ideal_points)
# Create and analyze voting model
vm = gv.VotingModel(
utility_functions=utilities,
majority=2,
zi=False, # Minimal Intelligence agenda
number_of_voters=3,
number_of_feasible_alternatives=grid.len
)
vm.analyze()
# View results
print(f"Device: {gv.device_type}") # Shows 'gpu', 'tpu', or 'cpu'
print(f"Stationary distribution: {vm.stationary_distribution[:5]}...")
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.
TPU Support: JAX automatically detects TPUs on Google Cloud.
CPU-Only Mode: Set environment variable GV_FORCE_CPU=1 to force CPU-only execution:
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
gridvoting-jax uses JAX's JIT compilation for high performance:
- First run: ~1-2s (includes JIT compilation)
- Subsequent runs: ~0.03-0.05s (comparable to CuPy)
- Vectorized operations: All computations run on GPU/TPU when available
Benchmark (g=20, 1681 alternatives, Nvidia 1080Ti):
- Analysis time: 0.033s (after JIT compilation)
- Test suite: 23 tests in ~80s (including slow benchmark test)
- Speedup: 10-30x faster than CPU-only
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 |
| 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 spatial voting simulations. Tolerance of 5e-5 ensures robust convergence on grids up to 60x60.
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
class Grid
Constructor
gridvoting_jax.Grid(x0, x1, xstep=1, y0, y1, ystep=1)
Constructs a 2D grid in x and y dimensions.
Parameters:
x0: leftmost grid x-coordinatex1: rightmost grid x-coordinatexstep=1: optional, grid spacing in x dimensiony0: lowest grid y-coordinatey1: highest grid y-coordinateystep=1: optional, grid spacing in y dimension
Example:
import gridvoting_jax as gv
grid = gv.Grid(x0=-5, x1=5, y0=-7, y1=7)
Instance Properties:
grid.x0, grid.x1, grid.xstep, grid.y0, grid.y1, grid.ystep- constructor parametersgrid.points- 2D numpy array of grid points in typewriter order[[x0,y1],[x0+1,y1],...,[x1,y0]]grid.x- 1D numpy array of x-coordinates in typewriter ordergrid.y- 1D numpy array of y-coordinates in typewriter ordergrid.gshape- natural shape(number_of_rows, number_of_cols)grid.extent- tuple(x0, x1, y0, y1)for matplotlibgrid.len- number of points on the gridgrid.boundary- 1D boolean array indicating boundary points
Methods
grid.spatial_utilities(voter_ideal_points, metric='sqeuclidean', scale=-1)
Returns utility function values for each voter at each grid point as a function of distance from an ideal point.
voter_ideal_points: array of 2D coordinates[[xv1,yv1],[xv2,yv2],...]metric: distance metric (default'sqeuclidean'). See scipy.spatial.distance.cdist
grid.within_box(x0=None, x1=None, y0=None, y1=None)
Returns 1D boolean array for testing whether grid points are in the defined box.
grid.within_disk(x0, y0, r, metric='euclidean')
Returns 1D boolean array for testing whether grid points are in the defined disk.
grid.within_triangle(points)
Returns 1D boolean array for testing whether grid points are in the defined triangle.
points: shape(3,2)array of triangle vertices
grid.embedding(valid)
Returns an embedding function efunc(z, fill=0.0) that maps 1D arrays of size valid.sum() to arrays of size grid.len.
valid: boolean array of lengthgrid.lenselecting valid grid pointsfill: value for invalid indices (default 0.0, usenp.nanfor plotting)
grid.plot(z, title=None, log=True, points=None, zoom=False, ...)
Creates a contour plot of values z defined on the grid.
class VotingModel
Constructor
gridvoting_jax.VotingModel(
utility_functions,
number_of_voters,
number_of_feasible_alternatives,
majority,
zi
)
Parameters:
utility_functions: 2D array of shape(number_of_voters, number_of_feasible_alternatives)number_of_voters: integernumber_of_feasible_alternatives: integermajority: integer, number of votes needed to winzi: boolean, True for Zero Intelligence, False for Minimal Intelligence
Methods
analyze()
Computes the transition matrix and stationary distribution.
what_beats(index)
Returns array indicating which alternatives beat the alternative at index.
what_is_beaten_by(index)
Returns array indicating which alternatives are beaten by the alternative at index.
summarize_in_context(grid, valid=None)
Calculate summary statistics for stationary distribution using grid coordinates.
plots(grid, voter_ideal_points, ...)
Creates visualization plots of the stationary distribution.
class MarkovChainCPUGPU
Constructor
gridvoting_jax.MarkovChainCPUGPU(P, computeNow=True, tolerance=5e-5)
Parameters:
P: valid transition matrix (square JAX/numpy array whose rows sum to 1.0)computeNow=True: immediately compute Markov Chain propertiestolerance=5e-5: tolerance for checking convergence (appropriate for float32)
Methods
solve_for_unit_eigenvector()
Finds the stationary distribution by solving for the unit eigenvector.
find_unique_stationary_distribution(tolerance=5e-5)
Finds the unique stationary distribution using the algebraic method.
diagnostic_metrics()
Returns dictionary of diagnostic metrics for the Markov chain.
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 ensures your simulation results match the published scientific record.
Testing
Run Tests
# Install development dependencies
pip install -r requirements-dev.txt
# Run all tests (23 tests, ~80s)
pytest tests/
# Skip slow tests (22 tests, ~15s)
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 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.3.1.tar.gz.
File metadata
- Download URL: gridvoting_jax-0.3.1.tar.gz
- Upload date:
- Size: 31.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c776b5dcbb933a4335b1c05b3fb167ce7a92d7494c1e7e659f8355ee70f51571
|
|
| MD5 |
725d3a9def4c4ae15b8ee88fb7e1a313
|
|
| BLAKE2b-256 |
5e799bfbe173295e7cb426cf6b22d16f24a0e431ef6f893609ad1d0383bbcf34
|
Provenance
The following attestation bundles were made for gridvoting_jax-0.3.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.3.1.tar.gz -
Subject digest:
c776b5dcbb933a4335b1c05b3fb167ce7a92d7494c1e7e659f8355ee70f51571 - Sigstore transparency entry: 773937010
- Sigstore integration time:
-
Permalink:
DrPaulBrewer/gridvoting-jax@8172ab7472d5b49ac330a8bbe40e204ce9aeaeed -
Branch / Tag:
refs/tags/v0.3.1 - Owner: https://github.com/DrPaulBrewer
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@8172ab7472d5b49ac330a8bbe40e204ce9aeaeed -
Trigger Event:
release
-
Statement type:
File details
Details for the file gridvoting_jax-0.3.1-py3-none-any.whl.
File metadata
- Download URL: gridvoting_jax-0.3.1-py3-none-any.whl
- Upload date:
- Size: 22.7 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 |
094694fb926d1404ea75c31069ed7f93e09e5fbf391cefa914ad1b51ddcbdf09
|
|
| MD5 |
614340297eb74777dc7c95404736f7bb
|
|
| BLAKE2b-256 |
569406f8dc59c6d527907d63d6c058449b9efa09e6495ce39e58c1a01ade7e22
|
Provenance
The following attestation bundles were made for gridvoting_jax-0.3.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.3.1-py3-none-any.whl -
Subject digest:
094694fb926d1404ea75c31069ed7f93e09e5fbf391cefa914ad1b51ddcbdf09 - Sigstore transparency entry: 773937019
- Sigstore integration time:
-
Permalink:
DrPaulBrewer/gridvoting-jax@8172ab7472d5b49ac330a8bbe40e204ce9aeaeed -
Branch / Tag:
refs/tags/v0.3.1 - Owner: https://github.com/DrPaulBrewer
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@8172ab7472d5b49ac330a8bbe40e204ce9aeaeed -
Trigger Event:
release
-
Statement type: