gridvoting-jax 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,8 @@
1
+ Copyright 2021-2025 by Contributors:
2
+ Paul Brewer <drpaulbrewer@eaftc.com> Economic and Financial Technology Consulting LLC
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ 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.
@@ -0,0 +1,4 @@
1
+ include README.md
2
+ include LICENSE.md
3
+ include requirements.txt
4
+ recursive-include src/gridvoting_jax py.typed
@@ -0,0 +1,399 @@
1
+ Metadata-Version: 2.4
2
+ Name: gridvoting-jax
3
+ Version: 0.0.1
4
+ Summary: Spatial voting simulations on a grid with random challengers (with float32 JAX backend)
5
+ Home-page: https://github.com/drpaulbrewer/gridvoting-jax
6
+ Author: Paul Brewer
7
+ Author-email: drpaulbrewer@eaftc.com
8
+ Project-URL: Bug Tracker, https://github.com/drpaulbrewer/gridvoting-jax/issues
9
+ Project-URL: Original Project, https://github.com/drpaulbrewer/gridvoting
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.9
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: POSIX :: Linux
17
+ Classifier: Operating System :: MacOS
18
+ Classifier: Operating System :: Microsoft :: Windows
19
+ Classifier: Development Status :: 3 - Alpha
20
+ Classifier: Environment :: GPU :: NVIDIA CUDA
21
+ Classifier: Environment :: GPU
22
+ Classifier: Intended Audience :: Science/Research
23
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
24
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
25
+ Requires-Python: >=3.9
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE.md
28
+ Requires-Dist: numpy>=2.0.0
29
+ Requires-Dist: pandas>=2.2.0
30
+ Requires-Dist: scipy>=1.13.0
31
+ Requires-Dist: matplotlib>=3.8.0
32
+ Requires-Dist: jax>=0.4.20
33
+ Dynamic: license-file
34
+
35
+ # gridvoting-jax
36
+
37
+ **A JAX-powered derivative of the original [gridvoting](https://github.com/drpaulbrewer/gridvoting) project**
38
+
39
+ [![PyPI version](https://badge.fury.io/py/gridvoting-jax.svg)](https://badge.fury.io/py/gridvoting-jax)
40
+ [![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
41
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
42
+
43
+ This library provides GPU/TPU/CPU-accelerated spatial voting simulations using Google's JAX framework with float32 precision.
44
+
45
+ ## Origin and Development
46
+
47
+ This project is derived from the original `gridvoting` module, which was developed for the research publication:
48
+
49
+ > Brewer, P., Juybari, J. & Moberly, R.
50
+ > A comparison of zero- and minimal-intelligence agendas in majority-rule voting models.
51
+ > J Econ Interact Coord (2023). https://doi.org/10.1007/s11403-023-00387-8
52
+
53
+ **Migration to JAX**: The computational backend was refactored from NumPy/CuPy to JAX using Google's Antigravity AI assistant. This migration provides:
54
+ - ✨ Unified CPU/GPU/TPU support through JAX
55
+ - 🚀 Improved performance through JIT compilation
56
+ - 💾 Float32 precision for efficiency
57
+ - 🔗 Better compatibility with modern ML/AI workflows
58
+
59
+ **Original Project**: https://github.com/drpaulbrewer/gridvoting
60
+
61
+ ---
62
+
63
+ ## Quick Start
64
+
65
+ ```python
66
+ import gridvoting_jax as gv
67
+
68
+ # Create a grid
69
+ grid = gv.Grid(x0=-20, x1=20, y0=-20, y1=20)
70
+
71
+ # Define voter ideal points
72
+ voter_ideal_points = [[-15, -9], [0, 17], [15, -9]]
73
+
74
+ # Generate utility functions
75
+ utilities = grid.spatial_utilities(voter_ideal_points=voter_ideal_points)
76
+
77
+ # Create and analyze voting model
78
+ vm = gv.VotingModel(
79
+ utility_functions=utilities,
80
+ majority=2,
81
+ zi=False, # Minimal Intelligence agenda
82
+ number_of_voters=3,
83
+ number_of_feasible_alternatives=grid.len
84
+ )
85
+
86
+ vm.analyze()
87
+
88
+ # View results
89
+ print(f"Device: {gv.device_type}") # Shows 'gpu', 'tpu', or 'cpu'
90
+ print(f"Stationary distribution: {vm.stationary_distribution[:5]}...")
91
+ ```
92
+
93
+ ---
94
+
95
+ ## Installation
96
+
97
+ ### Google Colab (Recommended)
98
+ All dependencies are pre-installed! Just run:
99
+ ```python
100
+ !pip install gridvoting-jax
101
+ ```
102
+
103
+ ### Local Installation
104
+ ```bash
105
+ pip install gridvoting-jax
106
+ ```
107
+
108
+ **GPU Support**: JAX automatically detects and uses NVIDIA GPUs (CUDA) when available.
109
+
110
+ **TPU Support**: JAX automatically detects TPUs on Google Cloud.
111
+
112
+ **CPU-Only Mode**: Set environment variable `NO_GPU=1` to force CPU-only execution:
113
+ ```bash
114
+ NO_GPU=1 python your_script.py
115
+ ```
116
+
117
+ ---
118
+
119
+ ## Requirements
120
+
121
+ - Python 3.9+
122
+ - numpy >= 2.0.0
123
+ - pandas >= 2.2.0
124
+ - scipy >= 1.13.0
125
+ - matplotlib >= 3.8.0
126
+ - jax >= 0.4.20
127
+
128
+ **Google Colab**: All dependencies are pre-installed (numpy 2.0.2, pandas 2.2.2, scipy 1.16.3, matplotlib 3.10, jax 0.7).
129
+
130
+ ---
131
+
132
+ ## Performance
133
+
134
+ gridvoting-jax uses JAX's JIT compilation for high performance:
135
+
136
+ - **First run**: ~1-2s (includes JIT compilation)
137
+ - **Subsequent runs**: ~0.03-0.05s (comparable to CuPy)
138
+ - **Vectorized operations**: All computations run on GPU/TPU when available
139
+
140
+ **Benchmark** (g=20, 1681 alternatives, Nvidia 1080Ti):
141
+ - Analysis time: 0.033s (after JIT compilation)
142
+ - Test suite: 22 tests in ~16s
143
+ - Speedup: 10-30x faster than CPU-only
144
+
145
+ ---
146
+
147
+ ## Differences from Original gridvoting
148
+
149
+ This JAX version differs from the original in several ways:
150
+
151
+ | Feature | Original gridvoting | gridvoting-jax |
152
+ |---------|-------------------|----------------|
153
+ | **Backend** | NumPy/CuPy | JAX |
154
+ | **Precision** | Float64 | Float32 |
155
+ | **Solver** | Power + Algebraic | Algebraic only |
156
+ | **Tolerance** | 1e-10 | 5e-5 |
157
+ | **Device Detection** | GPU/CPU | TPU/GPU/CPU |
158
+ | **Import** | `import gridvoting` | `import gridvoting_jax` |
159
+
160
+ **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.
161
+
162
+ ---
163
+
164
+ ## Random Sequential Voting Simulations
165
+
166
+ This follows [section 2 of our research paper](https://link.springer.com/article/10.1007/s11403-023-00387-8#Sec4).
167
+
168
+ A simulation consists of:
169
+ - A sequence of times: `t=0,1,2,3,...`
170
+ - A finite feasible set of alternatives **F**
171
+ - A set of voters who have preferences over the alternatives and vote truthfully
172
+ - A rule for voting and selecting challengers
173
+ - A mapping of the set of alternatives **F** into a 2D grid
174
+
175
+ The active or status quo alternative at time t is called `f[t]`.
176
+
177
+ 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]`.
178
+
179
+ **Randomness** enters through two possible rules for choosing the challenger `c[t]`:
180
+ - **Zero Intelligence (ZI)** (`zi=True`): `c[t]` is chosen uniformly at random from **F**
181
+ - **Minimal Intelligence (MI)** (`zi=False`): `c[t]` is chosen uniformly from the status quo `f[t]` and the possible winning alternatives given `f[t]`
182
+
183
+ ---
184
+
185
+ ## API Documentation
186
+
187
+ ### class Grid
188
+
189
+ #### Constructor
190
+
191
+ ```python
192
+ gridvoting_jax.Grid(x0, x1, xstep=1, y0, y1, ystep=1)
193
+ ```
194
+
195
+ Constructs a 2D grid in x and y dimensions.
196
+
197
+ **Parameters:**
198
+ - `x0`: leftmost grid x-coordinate
199
+ - `x1`: rightmost grid x-coordinate
200
+ - `xstep=1`: optional, grid spacing in x dimension
201
+ - `y0`: lowest grid y-coordinate
202
+ - `y1`: highest grid y-coordinate
203
+ - `ystep=1`: optional, grid spacing in y dimension
204
+
205
+ **Example:**
206
+ ```python
207
+ import gridvoting_jax as gv
208
+ grid = gv.Grid(x0=-5, x1=5, y0=-7, y1=7)
209
+ ```
210
+
211
+ **Instance Properties:**
212
+ - `grid.x0, grid.x1, grid.xstep, grid.y0, grid.y1, grid.ystep` - constructor parameters
213
+ - `grid.points` - 2D numpy array of grid points in typewriter order `[[x0,y1],[x0+1,y1],...,[x1,y0]]`
214
+ - `grid.x` - 1D numpy array of x-coordinates in typewriter order
215
+ - `grid.y` - 1D numpy array of y-coordinates in typewriter order
216
+ - `grid.gshape` - natural shape `(number_of_rows, number_of_cols)`
217
+ - `grid.extent` - tuple `(x0, x1, y0, y1)` for matplotlib
218
+ - `grid.len` - number of points on the grid
219
+ - `grid.boundary` - 1D boolean array indicating boundary points
220
+
221
+ #### Methods
222
+
223
+ **`grid.spatial_utilities(voter_ideal_points, metric='sqeuclidean', scale=-1)`**
224
+
225
+ Returns utility function values for each voter at each grid point as a function of distance from an ideal point.
226
+
227
+ - `voter_ideal_points`: array of 2D coordinates `[[xv1,yv1],[xv2,yv2],...]`
228
+ - `metric`: distance metric (default `'sqeuclidean'`). See [scipy.spatial.distance.cdist](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html)
229
+
230
+ **`grid.within_box(x0=None, x1=None, y0=None, y1=None)`**
231
+
232
+ Returns 1D boolean array for testing whether grid points are in the defined box.
233
+
234
+ **`grid.within_disk(x0, y0, r, metric='euclidean')`**
235
+
236
+ Returns 1D boolean array for testing whether grid points are in the defined disk.
237
+
238
+ **`grid.within_triangle(points)`**
239
+
240
+ Returns 1D boolean array for testing whether grid points are in the defined triangle.
241
+ - `points`: shape `(3,2)` array of triangle vertices
242
+
243
+ **`grid.embedding(valid)`**
244
+
245
+ Returns an embedding function `efunc(z, fill=0.0)` that maps 1D arrays of size `valid.sum()` to arrays of size `grid.len`.
246
+
247
+ - `valid`: boolean array of length `grid.len` selecting valid grid points
248
+ - `fill`: value for invalid indices (default 0.0, use `np.nan` for plotting)
249
+
250
+ **`grid.plot(z, title=None, log=True, points=None, zoom=False, ...)`**
251
+
252
+ Creates a contour plot of values z defined on the grid.
253
+
254
+ ---
255
+
256
+ ### class VotingModel
257
+
258
+ #### Constructor
259
+
260
+ ```python
261
+ gridvoting_jax.VotingModel(
262
+ utility_functions,
263
+ number_of_voters,
264
+ number_of_feasible_alternatives,
265
+ majority,
266
+ zi
267
+ )
268
+ ```
269
+
270
+ **Parameters:**
271
+ - `utility_functions`: 2D array of shape `(number_of_voters, number_of_feasible_alternatives)`
272
+ - `number_of_voters`: integer
273
+ - `number_of_feasible_alternatives`: integer
274
+ - `majority`: integer, number of votes needed to win
275
+ - `zi`: boolean, True for Zero Intelligence, False for Minimal Intelligence
276
+
277
+ #### Methods
278
+
279
+ **`analyze()`**
280
+
281
+ Computes the transition matrix and stationary distribution.
282
+
283
+ **`what_beats(index)`**
284
+
285
+ Returns array indicating which alternatives beat the alternative at `index`.
286
+
287
+ **`what_is_beaten_by(index)`**
288
+
289
+ Returns array indicating which alternatives are beaten by the alternative at `index`.
290
+
291
+ **`summarize_in_context(grid, valid=None)`**
292
+
293
+ Calculate summary statistics for stationary distribution using grid coordinates.
294
+
295
+ **`plots(grid, voter_ideal_points, ...)`**
296
+
297
+ Creates visualization plots of the stationary distribution.
298
+
299
+ ---
300
+
301
+ ### class MarkovChainCPUGPU
302
+
303
+ #### Constructor
304
+
305
+ ```python
306
+ gridvoting_jax.MarkovChainCPUGPU(P, computeNow=True, tolerance=5e-5)
307
+ ```
308
+
309
+ **Parameters:**
310
+ - `P`: valid transition matrix (square JAX/numpy array whose rows sum to 1.0)
311
+ - `computeNow=True`: immediately compute Markov Chain properties
312
+ - `tolerance=5e-5`: tolerance for checking convergence (appropriate for float32)
313
+
314
+ #### Methods
315
+
316
+ **`solve_for_unit_eigenvector()`**
317
+
318
+ Finds the stationary distribution by solving for the unit eigenvector.
319
+
320
+ **`find_unique_stationary_distribution(tolerance=5e-5)`**
321
+
322
+ Finds the unique stationary distribution using the algebraic method.
323
+
324
+ **`diagnostic_metrics()`**
325
+
326
+ Returns dictionary of diagnostic metrics for the Markov chain.
327
+
328
+ ---
329
+
330
+ ## Testing
331
+
332
+ ### Run Tests
333
+
334
+ ```bash
335
+ # Install development dependencies
336
+ pip install -r requirements-dev.txt
337
+
338
+ # Run all tests
339
+ pytest tests/
340
+
341
+ # Run with coverage
342
+ pytest tests/ --cov=gridvoting_jax
343
+ ```
344
+
345
+ ### Google Colab
346
+
347
+ ```python
348
+ !pip install gridvoting-jax
349
+ !pytest /usr/local/lib/python3.*/dist-packages/gridvoting_jax/
350
+ ```
351
+
352
+ ---
353
+
354
+ ## License
355
+
356
+ The software is provided under the standard [MIT License](./LICENSE.md).
357
+
358
+ 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.
359
+
360
+ ---
361
+
362
+ ## Disclaimers
363
+
364
+ 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.
365
+
366
+ 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.
367
+
368
+ The [MIT License](./LICENSE.md) includes this disclaimer:
369
+
370
+ > 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.
371
+
372
+ ---
373
+
374
+ ## Research Data
375
+
376
+ 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.
377
+
378
+ ---
379
+
380
+ ## Contributing
381
+
382
+ Contributions are welcome! Please feel free to submit a Pull Request.
383
+
384
+ ---
385
+
386
+ ## Citation
387
+
388
+ If you use this software in your research, please cite the original paper:
389
+
390
+ ```bibtex
391
+ @article{brewer2023comparison,
392
+ title={A comparison of zero-and minimal-intelligence agendas in majority-rule voting models},
393
+ author={Brewer, Paul and Juybari, Jeremy and Moberly, Raymond},
394
+ journal={Journal of Economic Interaction and Coordination},
395
+ year={2023},
396
+ publisher={Springer},
397
+ doi={10.1007/s11403-023-00387-8}
398
+ }
399
+ ```