# gridvoting-jax

**A JAX-powered derivative of the original [gridvoting](https://github.com/drpaulbrewer/gridvoting) project**

[![PyPI version](https://img.shields.io/pypi/v/gridvoting-jax.svg)](https://pypi.org/project/gridvoting-jax/)
[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

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  
- 💾 choice of Float32 or Float64 precision
- 🔗 Better compatibility with modern ML/AI workflows

**Original Project**: https://github.com/drpaulbrewer/gridvoting

---

## Quick Start

Open a new window at https://colab.google

### Installation in Google Colab
To install, add these line at the top of the first cell:
```
!pip install gridvoting-jax
import gridvoting_jax as gv
```

Note: the pip line uses a dash '-' but the import line uses an underscore '_'

####**Float64 Precision**
By default, JAX uses 32-bit floats for faster performance. However, larger models (g>50) should
use 64-bit floats for higher accuracy and to avoid accumulation errors.

To enable 64-bit precision for higher accuracy:
```python
import gridvoting_jax as gv
gv.enable_float64()
#### All subsequent JAX operations will use float64
```

### Spatial Voting Example

```python
import gridvoting_jax as gv

# Use a pre-built example or create your own
# 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

```python
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)
To install into Google Colab, add these lines at the top of the first cell:
```
!pip install gridvoting-jax
import gridvoting_jax as gv
```

### Local Installation
If you are using your own computer, not Google Colab, then you need to install the gridvoting-jax python module.

```bash
pip install gridvoting-jax
```

Pip may work; it may not.  If pip issues an error about another system managing the python packages on your computer, then
it may be wise to create a python virtual environment so as not to create conflicts among the python packages.

### Device support

**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`:
```bash
GV_FORCE_CPU=1 python your_script.py
```

### Docker Usage

The project uses a multi-tier Docker image system hosted on GitHub Container Registry (GHCR):
- **Base Images**: JAX + CUDA
- **Release Images**: Versioned releases from PyPI (~30s builds)
- **Dev Images**: Local development with mounted source code

**Quick Start - Local Development:**
```bash
# CPU testing with your local source code
./test_docker.sh --dev --cpu tests/

# GPU testing (auto-detects CUDA 12 or 13)
./test_docker.sh --dev --gpu tests/
```

**Testing Specific Versions:**
```bash
# Test a specific release
./test_docker.sh --version=v0.9.1 --gpu

# Run BJM validation
./test_docker_bjm.sh --dev --gpu --quick
```

**Detailed Documentation:**  
See [`docs/docker.md`](docs/docker.md) for comprehensive Docker usage guide including:
- Image types and GHCR paths
- Development workflow
- CI/CD pipeline
- Troubleshooting

**Building Images Locally:**
```bash
# Build base images (one-time, slow)
docker build -f Dockerfiles/base/Dockerfile.jax-cpu -t base/cpu:local .

# Build dev images (fast)
docker build -f Dockerfiles/dev/Dockerfile.dev-cpu -t dev/cpu:local .
```

---

## Requirements

- Python 3.10+
- 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)<br>Float64 (available) |
| **Solver** | Power (Matrix) + Algebraic | Power (vector) + Algebraic |
| **Tolerance** | 1e-10 | variable, up to 1e-10 for float64 |
| **Device Detection** | GPU/CPU | TPU/GPU/CPU |
| **Import** | `import gridvoting` | `import gridvoting_jax` |

**Numerical Accuracy**: Float32 provides ~7 decimal digits of precision, which can be sufficient for some spatial voting simulations. 

---

## Random Sequential Voting Simulations

This follows [section 2 of our research paper](https://link.springer.com/article/10.1007/s11403-023-00387-8#Sec4).

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
- In a Spatial Voting Simulatoin, a mapping of the set of alternatives **F** into a 2D grid (x,y coordinates)

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 quo `f[t]` and the possible winning alternatives given `f[t]`

---

## API Documentation (v0.30.0)

The package is organized into submodules, but the public API is exposed at the top level for convenience.

```python
import gridvoting_jax as gv
```

### Core Configuration (`gv.core`)

Centralized configuration and constants.

- **`gv.enable_float64()`**: Enable 64-bit floating point precision globally for JAX
- **`gv.device_type`**: Current device type ('gpu', 'tpu', or 'cpu')
- **`gv.use_accelerator`**: Boolean indicating if GPU/TPU is available

### Geometric Components (`gv.geometry`)

#### `class Grid`

```python
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]` coordinates
- `grid.x`, `grid.y`: 1D JAX arrays of x and y coordinates
- `grid.boundary`: 1D boolean mask for boundary points
- `grid.len`: Total number of grid points

**Methods:**
- **`spatial_utilities(voter_ideal_points, metric='sqeuclidean')`**: Distance-based utility calculation
- **`within_box/disk/triangle(...)`**: Geometric query methods returning boolean masks
- **`extremes(z, valid=None)`**: Find min/max values and their locations
- **`embedding(valid)`**: Create embedding function for plotting subsets
- **`plot(z, ...)`**: Plot scalar fields on the grid using Matplotlib

#### `class PolarGrid`

```python
grid = gv.PolarGrid(radius, rstep=1, thetastep=15)
```

Constructs a 2D polar grid for spatial voting models with radial symmetry.

**Parameters:**
- `radius`: Maximum radius of the grid
- `rstep`: Radial step size (default: 1)
- `thetastep`: Angular step size in degrees (default: 15)

**Properties:**
- `grid.points`: JAX array of shape `(N, 2)` containing `[x, y]` coordinates in Cartesian space
- `grid.r`, `grid.theta`: 1D JAX arrays of radial and angular coordinates
- `grid.weights`: 1D JAX array of area-based weights for each grid cell
- `grid.len`: Total number of grid points (1 + (n_rings * n_angular_positions))

**Methods:**
- **`index(r=None, theta=None, x=None, y=None)`**: Find grid index from polar or Cartesian coordinates
- **`partition_from_rotation(angle)`**: Create partition for rotational symmetry
  - `angle=0`: Continuous rotation symmetry (SO(2)) - each ring forms a partition
  - `angle>0`: Discrete rotation symmetry (cyclic group C_n) - each ring is tiled n-fold into k partitions where n=360/angle, k=angle/thetastep
  - Angle must divide 360 and be a multiple of `thetastep`
- **`plot(z, ...)`**: Plot scalar fields using polar contour plot

**Notes:**
- Grid points are arranged in concentric rings around the origin
- The origin (r=0) is a single point
- Weights represent the area of each grid cell in state space
- Useful for models with radial or rotational symmetry

#### `class Partition`

```python
partition = gv.Partition(inverse_indices, metadata=None)
```

Wraps partition arrays with optimization metadata for lumping operations *(New in v0.46.0)*.

**Attributes:**
- `partition.inverse_indices`: JAX array of shape `(n,)` mapping states to groups (0 to k-1)
- `partition.metadata`: `PartitionMetadata` object with optimization hints
- `partition.k`: Number of groups in partition

**Methods:**
- `len(partition)`: Returns number of states
- `partition.max()`: Returns maximum group ID (for backward compatibility)

**PartitionMetadata:**
- `lazy_lumpable`: Boolean hint suggesting lazy lumping is possible
- `primary_group_size`: Expected group size (2 for reflections, None for variable)
- `exceptions`: Dict mapping group IDs to sizes for non-standard groups
- `source`: Descriptive string (e.g., "reflect_x", "rotate_0_0_120deg")

**Example:**
```python
# Partition objects are returned by partition-generating functions
partition = grid.partition_from_symmetry(['reflect_x'])

# Access inverse indices for array operations
num_groups = partition.k  # or int(partition.inverse_indices.max()) + 1
group_id = partition.inverse_indices[i]

# Check metadata
print(f"Source: {partition.metadata.source}")  # "reflect_x"
print(f"Primary group size: {partition.metadata.primary_group_size}")  # 2

# Use with lumping functions (automatically extracts inverse_indices)
lumped_mc = gv.lump(model.MarkovChain, partition)
```

### Symmetry & Dimension Reduction

Reduce computational cost by exploiting spatial symmetries.

Known issue: Practicality.  Time currently required to calculate symmetries and lumping is often higher than solution time
of the original model.

```python
import gridvoting_jax as gv
import jax.numpy as jnp
from gridvoting_jax.symmetry import suggest_symmetries

# 1. Detect Symmetries
# Suggest valid spatial symmetries for the model
symmetries = suggest_symmetries(model)
print(f"Detected: {symmetries}") 

# 2. Partition Grid
# Returns Partition object with metadata (v0.46.0)
partition = model.grid.partition_from_symmetry(['reflect_x'])
print(f"Number of groups: {partition.k}")
print(f"Source: {partition.metadata.source}")  # "reflect_x"

# 3. Lump Markov Chain
# Solve on reduced state space (e.g., 50% fewer states)
lumped_mc = gv.lump(model.MarkovChain, partition)
lumped_pi = lumped_mc.solve()

# 4. Unlump
# Map results back to full grid
stationary_distribution = gv.unlump(lumped_pi, partition)

# Verify Lumpability (optional)
# Check if partition preserves Markov property
is_valid = gv.is_lumpable(model.MarkovChain, partition)
print(f"Strongly lumpable: {is_valid}")
```

**Partition Format** *(Updated in v0.46.0)*:
- Partitions are now returned as `Partition` objects with metadata
- Access inverse indices via `.inverse_indices` attribute
- Format: `jnp.ndarray` of shape `(N,)` where `partition.inverse_indices[i]` is the group ID for state `i`
- Example: `Partition(jnp.array([0, 0, 1, 1]))` means states 0,1 are in group 0; states 2,3 are in group 1
- Backward compatible: Lumping functions accept both `Partition` objects and raw arrays

**Symmetry Types**:
- `'reflect_x'`: Reflection across x=0 (vertical line)
- `'reflect_y'`: Reflection across y=0 (horizontal line)
- `'reflect_x=c'`: Reflection across x=c (custom vertical line)
- `'reflect_y=c'`: Reflection across y=c (custom horizontal line)
- `'swap_xy'`: Diagonal reflection (x,y) ↔ (y,x)
- `('rotate', cx, cy, angle)`: Rotation by `angle` degrees around `(cx, cy)`

**Performance**:
- Singleton symmetries (single symmetry) use optimized fast path
- Multiple symmetries use general connected components algorithm
- Lumping uses fully vectorized JAX operations

### Pareto Efficiency
Finds the Pareto Optimal set (points where no other point is unanimously preferred).

```python
# Get a boolean mask for Pareto set
pareto_mask = model.Pareto

# Visualize
model.grid.plot(pareto_mask, title="Pareto Set")

# Create Unanimous Model
unanimous_model = model.unanimize()
```
### Voting Models

#### `class VotingModel`

Geometry-agnostic base voting model.

```python
vm = gv.VotingModel(
    utility_functions,
    number_of_voters,
    number_of_feasible_alternatives,
    majority,
    zi,
    weights=None  # Optional: JAX array of weights for each alternative
)
```

**Parameters:**
- `utility_functions`: JAX array of shape `(n_voters, n_alternatives)` containing utility values
- `number_of_voters`: Total number of voters
- `number_of_feasible_alternatives`: Total number of alternatives
- `majority`: Number of votes required to win
- `zi`: Boolean for Zero Intelligence (True) or Minimal Intelligence (False) challenger selection
- `weights`: *(Optional)* JAX array of shape `(n_alternatives,)` with positive weights for each alternative. When provided, challengers are selected with probability proportional to weights instead of uniformly. Useful for grids with non-uniform cell areas (e.g., `PolarGrid`)

**Methods:**
- **`analyze(solver="full_matrix_inversion")`**: Compute stationary distribution
- **`what_beats(index)`**: Returns alternatives that beat the given index
- **`summarize_in_context(grid)`**: Calculate entropy, mean, and covariance

**Properties:**
- `stationary_distribution`: Probability distribution over alternatives
- `core_exists`: Boolean indicating if a core exists
- `core_points`: Boolean mask of core points

#### `class SpatialVotingModel`

Geometry-aware spatial voting model (delegates to `VotingModel`).

```python
model = gv.SpatialVotingModel(
    voter_ideal_points,
    grid,
    number_of_voters,
    majority,
    zi
)
```

**Additional Methods:**
- **`plot_stationary_distribution(**kwargs)`**: Visualize results on grid
- **`analyze(solver="power_method", sec_per_digit=1.0, **kwargs)`** *(New in v0.10.0)*: 
  - Solvers: `"full_matrix_inversion"`, `"gmres_matrix_inversion"`, `"power_method"`, `"bifurcated_power_method"`

#### `class BudgetVotingModel`

Budget allocation voting model for dividing a fixed budget among 3 voters.

```python
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 distribution
- **`voter_utility_distribution(voter_index)`**: Probability distribution of voter payoffs
- **`giniss_distribution(granularity=0.10)`**: Probability distribution of GiniSS index
- **`plot_stationary_distribution(**kwargs)`**: Visualize on triangular simplex

**Properties:**
- `budget`: Total budget to allocate
- `u1, u2, u3`: Utility for each voter at each alternative
- `GiniSS`: Gini-like inequality index for each alternative
- `stationary_distribution`: Probability distribution over allocations

### Example Models

#### Plott's Theorem Examples

Demonstrate core existence conditions from Plott's median-in-all-directions voter theorem:

> Plott, C. R. (1967). A notion of equilibrium and its possibility under majority rule. *American Economic Review*, 57(4), 787-806.

```python
# 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)  # (cycling)
```

#### Shapes Submodule

Random and geometric configurations:

```python
# 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:

> 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

```python
# Spatial voting (Triangle 1 from BJM research)
model = gv.bjm_spatial_triangle(g=20, zi=False)

# Budget voting
model = gv.bjm_budget_triangle(budget=100, zi=False)
```

### Markov Chain (`gv.stochastic`)

#### `class MarkovChain`

```python
mc = gv.MarkovChain(P)
mc.solve(solver="full_matrix_inversion")

# With partitions for automatic lumping/unlumping
partition = model.grid.partition_from_symmetry(['reflect_x'])
mc.solve(solver="full_matrix_inversion", partitions=partition)
```

**Parameters:**
- `solver`: Strategy to use (see solver options below)
- `initial_guess`: Optional starting distribution for iterative solvers
- `partitions`: Optional JAX array for automatic Markov chain lumping/unlumping. When provided, the chain is lumped using the partition, solved on the reduced state space, then unlumped back to the original space. See [Symmetry & Dimension Reduction](#symmetry--dimension-reduction) section for details.
- `time_per_digit`: Time budget (seconds) per digit of precision for iterative solvers (default: 1.0)

> [!NOTE]
> **API Change**: The `MarkovChain` method `find_unique_stationary_distribution` has been renamed to `solve` for a more concise API aligned with scientific computing conventions.

**Dense Solvers** (constructs full transition matrix):
- **`"full_matrix_inversion"`** (default): Direct matrix inversion
  - Fastest for small grids (g≤40)
  - Memory: O(N²) where N = grid.len
  - Accuracy: Excellent (limited by float32 precision)
  - Fails: g≥80 (out of memory on some GPUs)

- **`"gmres_matrix_inversion"`**: Iterative GMRES solver
  - Memory-efficient for medium grids (g=40-60)
  - Memory: O(N²) for matrix + O(N) for solver
  - Accuracy: Excellent
  - Fails: g≥80 (out of memory on some GPUs matrix construction OOM)

- **`"power_method"`**: Power iteration
  - Memory: O(N²) for matrix + O(N) for vectors
  - Slower convergence than GMRES
  - Robust for difficult cases
  - Fails: g≥80 (out of memory on some GPUs, matrix construction OOM)

- **`"bifurcated_power_method"`**: Dual-start power iteration
  - Starts from uniform distribution and atom at middle grid point
  - Better convergence for some models
  - Same memory requirements as power_method

**Lazy Solvers** (matrix-free, for large grids):
- **`"power_method (lazy)"`**: Lazy power iteration
  - No matrix construction - computes P.T @ v on-the-fly
  - Memory: O(N) only
  - Works for g=80, g=100
  - Slower than dense but enables large grids
  - Use via: `model.analyze_lazy(solver="power_method")`

- **`"bifurcated_power_method (lazy)"`**: Lazy dual-start power iteration
  - Lazy version of bifurcated_power_method
  - Memory: O(N)
  - Use via: `model.analyze_lazy(solver="power_method", force_lazy=True)`

**Outline Solvers** *(New in v0.19.0)* (SpatialVotingModel only):
- **`"outline_and_fill"`**: Solve on coarsened grid (2x spacing), interpolate
  - Creates coarsened model with 2x grid spacing (same boundaries)
  - Solves coarsened model (4x fewer points)
  - Interpolates to original grid using sparse BCOO matrix
  - Normalizes result
  - **Fast but low accuracy** (L1 ~0.02-0.03)
  - Use case: Quick approximation or initial guess generation
  - Memory: O(N_coarse²) + O(N_fine) for interpolation

- **`"outline_and_power"`**: Outline + power_method refinement
  - Uses outline_and_fill solution as initial guess
  - Refines with power_method solver
  - **Best for large grids** - never hits OOM at g=80
  - Memory: O(N²) for dense power method
  - Accuracy: Good to Excellent (L1 ~1e-06 to 5e-04)
  - **Recommended for g=80** when GMRES fails

- **`"outline_and_gmres"`**: Outline + GMRES refinement
  - Uses outline_and_fill solution as initial guess
  - Refines with gmres_matrix_inversion
  - Excellent accuracy when memory allows
  - Memory: O(N²) for dense GMRES
  - Fails: g≥80 (GMRES OOM)
  - **Recommended for g≤60** for best accuracy

**Solver Selection Guide**:

| Grid Size | Recommended Solver | Alternative | Notes |
|-----------|-------------------|-------------|-------|
| g=20-40 | `full_matrix_inversion` | `outline_and_gmres` | Fastest, most accurate |
| g=60 | `gmres_matrix_inversion` | `outline_and_gmres` | Balance speed/memory |
| g=80 | `outline_and_power` | `power_method (lazy)` | Use outline or lazy solvers |
| g=100 | `outline_and_power` | N/A | Requires outline solver |

**Pre-computed Interpolation Matrix** :
```python
from gridvoting_jax.models.spatial import create_outline_interpolation_matrix

# Pre-compute for batch processing
C = create_outline_interpolation_matrix(model.grid, coarse_grid)

# Reuse for multiple models with same grid size
model1.analyze(solver="outline_and_fill", interpolation_matrix=C)
model2.analyze(solver="outline_and_fill", interpolation_matrix=C)
```
### Large Grid Support 

- **g=80**: Validated (L1 ~1e-08)
- **g=100**: 10,201 alternatives, uses lazy solvers + outline solvers

```python
model = gv.bjm_spatial_triangle(g=100, zi=False)
model.analyze(solver="outline_and_power")  # Recommended for large grids
```
### Datasets (`gv.datasets`)

- **`gv.datasets.fetch_bjm_spatial_voting_2022_a100()`**: Downloads BJM reference dataset

---

## Benchmarks

Run performance benchmarks to test solver speed across different grid sizes:

```python
import gridvoting_jax as gv

# Print formatted benchmark results
gv.benchmarks.run_comparison_report()

# download the reference dataset
gv.datasets.fetch_bjm_spatial_voting_2022_a100()

# compare your computed results to the published scientific record using L1 norm
gv.benchmarks.run_comparison_report()

# 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 BJM Data

You can automatically verify the library's output against the original A100 GPU replication data from the BJM research. This benchmark downloads the reference data and compares stationary distributions using the L1 norm.

```python
from gridvoting_jax.benchmarks.bjm_comparison import run_comparison_report

# Run complete comparison report
# Automatically downloads reference data to /tmp/gridvoting_bjm_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:

```python
!pip install gridvoting-jax

from gridvoting_jax.benchmarks.bjm_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

see [TESTING.md](./TESTING.md)

---

## License

The software is provided under the standard [MIT License](./LICENSE.md).

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](./LICENSE.md) 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](https://osf.io/k2phe/) 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:

```bibtex
@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}
}
```
