gerrytools 1.2.0__tar.gz → 2.0.0__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.
- gerrytools-2.0.0/PKG-INFO +134 -0
- gerrytools-2.0.0/README.md +90 -0
- gerrytools-2.0.0/gerrytools/__init__.py +5 -0
- gerrytools-2.0.0/gerrytools/_election_math.py +184 -0
- gerrytools-2.0.0/gerrytools/_geodataframe.py +127 -0
- gerrytools-2.0.0/gerrytools/_geometry.py +47 -0
- gerrytools-2.0.0/gerrytools/_ipython.py +25 -0
- gerrytools-2.0.0/gerrytools/_partisan_math.py +145 -0
- gerrytools-2.0.0/gerrytools/_scoring_engine.pyi +147 -0
- gerrytools-2.0.0/gerrytools/ben/__init__.py +74 -0
- gerrytools-2.0.0/gerrytools/ben/_graph_prep.py +182 -0
- gerrytools-2.0.0/gerrytools/ben/recorded_chain.py +964 -0
- gerrytools-2.0.0/gerrytools/colors/__init__.py +55 -0
- gerrytools-2.0.0/gerrytools/colors/_latex_table.py +786 -0
- gerrytools-2.0.0/gerrytools/colors/_sources.py +224 -0
- gerrytools-2.0.0/gerrytools/colors/_value.py +296 -0
- gerrytools-2.0.0/gerrytools/colors/core.py +148 -0
- gerrytools-2.0.0/gerrytools/colors/districtr.py +138 -0
- gerrytools-2.0.0/gerrytools/colors/latex.py +170 -0
- gerrytools-2.0.0/gerrytools/colors/seaborn.py +81 -0
- gerrytools-2.0.0/gerrytools/colors/utils.py +200 -0
- gerrytools-2.0.0/gerrytools/data/__init__.py +15 -0
- gerrytools-2.0.0/gerrytools/data/_geometry_etags.py +625 -0
- gerrytools-2.0.0/gerrytools/data/geometries.py +200 -0
- gerrytools-2.0.0/gerrytools/data/uscensus/__init__.py +50 -0
- gerrytools-2.0.0/gerrytools/data/uscensus/_api.py +375 -0
- gerrytools-2.0.0/gerrytools/data/uscensus/acs.py +574 -0
- gerrytools-2.0.0/gerrytools/data/uscensus/block_cvap.py +580 -0
- gerrytools-2.0.0/gerrytools/data/uscensus/census.py +134 -0
- gerrytools-2.0.0/gerrytools/data/uscensus/census_tables.py +671 -0
- gerrytools-2.0.0/gerrytools/data/uscensus/ptable_column_aliases.py +628 -0
- gerrytools-2.0.0/gerrytools/latex/__init__.py +53 -0
- gerrytools-2.0.0/gerrytools/latex/_colors.py +276 -0
- gerrytools-2.0.0/gerrytools/latex/_render.py +287 -0
- gerrytools-2.0.0/gerrytools/latex/_table_base.py +909 -0
- gerrytools-2.0.0/gerrytools/latex/_table_layout.py +477 -0
- gerrytools-2.0.0/gerrytools/latex/_table_options.py +90 -0
- gerrytools-2.0.0/gerrytools/latex/_table_preamble.py +177 -0
- gerrytools-2.0.0/gerrytools/latex/_text.py +31 -0
- gerrytools-2.0.0/gerrytools/latex/_tikz_plot_base.py +513 -0
- gerrytools-2.0.0/gerrytools/latex/commands.py +265 -0
- gerrytools-2.0.0/gerrytools/latex/document.py +510 -0
- gerrytools-2.0.0/gerrytools/latex/formatters.py +597 -0
- gerrytools-2.0.0/gerrytools/latex/paintball.py +530 -0
- gerrytools-2.0.0/gerrytools/latex/seatsvotes.py +699 -0
- gerrytools-2.0.0/gerrytools/latex/table.py +123 -0
- gerrytools-2.0.0/gerrytools/latex/tikz_table.py +390 -0
- gerrytools-2.0.0/gerrytools/logging.py +119 -0
- gerrytools-2.0.0/gerrytools/mgrp/__init__.py +38 -0
- gerrytools-2.0.0/gerrytools/mgrp/constraints.py +723 -0
- gerrytools-2.0.0/gerrytools/mgrp/objectives.py +720 -0
- gerrytools-2.0.0/gerrytools/mgrp/run_config.py +211 -0
- gerrytools-2.0.0/gerrytools/mgrp/run_container.py +1010 -0
- gerrytools-2.0.0/gerrytools/mgrp/runners/forest.py +245 -0
- gerrytools-2.0.0/gerrytools/mgrp/runners/recom.py +954 -0
- gerrytools-2.0.0/gerrytools/mgrp/runners/smc.py +271 -0
- gerrytools-2.0.0/gerrytools/plan_comparison/__init__.py +22 -0
- gerrytools-2.0.0/gerrytools/plan_comparison/overlap.py +199 -0
- gerrytools-2.0.0/gerrytools/plan_comparison/relabel.py +416 -0
- gerrytools-2.0.0/gerrytools/plotting/__init__.py +98 -0
- gerrytools-2.0.0/gerrytools/plotting/_artist_registry.py +56 -0
- gerrytools-2.0.0/gerrytools/plotting/_axes_backed.py +209 -0
- gerrytools-2.0.0/gerrytools/plotting/_axes_state.py +741 -0
- gerrytools-2.0.0/gerrytools/plotting/_figure_io.py +137 -0
- gerrytools-2.0.0/gerrytools/plotting/_legend_mixin.py +280 -0
- gerrytools-2.0.0/gerrytools/plotting/_legend_utils.py +69 -0
- gerrytools-2.0.0/gerrytools/plotting/_rng.py +38 -0
- gerrytools-2.0.0/gerrytools/plotting/data/__init__.py +59 -0
- gerrytools-2.0.0/gerrytools/plotting/data/_annotation_api.py +723 -0
- gerrytools-2.0.0/gerrytools/plotting/data/_annotations.py +122 -0
- gerrytools-2.0.0/gerrytools/plotting/data/_arrow_renderer.py +637 -0
- gerrytools-2.0.0/gerrytools/plotting/data/_axis_api.py +822 -0
- gerrytools-2.0.0/gerrytools/plotting/data/_categorical_distribution_base.py +639 -0
- gerrytools-2.0.0/gerrytools/plotting/data/_gerryplot_dataclasses.py +517 -0
- gerrytools-2.0.0/gerrytools/plotting/data/_unit_square_base.py +442 -0
- gerrytools-2.0.0/gerrytools/plotting/data/barplot.py +373 -0
- gerrytools-2.0.0/gerrytools/plotting/data/boxplot.py +650 -0
- gerrytools-2.0.0/gerrytools/plotting/data/gerryplot.py +419 -0
- gerrytools-2.0.0/gerrytools/plotting/data/histogram.py +806 -0
- gerrytools-2.0.0/gerrytools/plotting/data/options.py +734 -0
- gerrytools-2.0.0/gerrytools/plotting/data/paintball.py +377 -0
- gerrytools-2.0.0/gerrytools/plotting/data/scatterplot.py +306 -0
- gerrytools-2.0.0/gerrytools/plotting/data/sealevel.py +540 -0
- gerrytools-2.0.0/gerrytools/plotting/data/seatsvotes.py +495 -0
- gerrytools-2.0.0/gerrytools/plotting/data/violin.py +203 -0
- gerrytools-2.0.0/gerrytools/plotting/geometry/__init__.py +17 -0
- gerrytools-2.0.0/gerrytools/plotting/geometry/_dot_sampling.py +206 -0
- gerrytools-2.0.0/gerrytools/plotting/geometry/_labels.py +273 -0
- gerrytools-2.0.0/gerrytools/plotting/geometry/_layers/__init__.py +20 -0
- gerrytools-2.0.0/gerrytools/plotting/geometry/_layers/_base.py +234 -0
- gerrytools-2.0.0/gerrytools/plotting/geometry/_layers/_categorical.py +228 -0
- gerrytools-2.0.0/gerrytools/plotting/geometry/_layers/_continuous.py +294 -0
- gerrytools-2.0.0/gerrytools/plotting/geometry/_layers/_marker.py +190 -0
- gerrytools-2.0.0/gerrytools/plotting/geometry/dotdensity.py +708 -0
- gerrytools-2.0.0/gerrytools/plotting/geometry/geoplot.py +651 -0
- gerrytools-2.0.0/gerrytools/plotting/geometry/geoplotbase.py +858 -0
- gerrytools-2.0.0/gerrytools/plotting/mpl/__init__.py +37 -0
- gerrytools-2.0.0/gerrytools/plotting/mpl/axis_title_style.py +170 -0
- gerrytools-2.0.0/gerrytools/plotting/mpl/geoplot_options.py +84 -0
- gerrytools-2.0.0/gerrytools/plotting/mpl/label_text_options.py +329 -0
- gerrytools-2.0.0/gerrytools/plotting/mpl/legend_options.py +71 -0
- gerrytools-2.0.0/gerrytools/plotting/mpl/marker_options.py +142 -0
- gerrytools-2.0.0/gerrytools/plotting/mpl/tick_style.py +76 -0
- gerrytools-2.0.0/gerrytools/plotting/other/__init__.py +3 -0
- gerrytools-2.0.0/gerrytools/plotting/other/subway.py +449 -0
- gerrytools-2.0.0/gerrytools/plotting/plan/__init__.py +5 -0
- gerrytools-2.0.0/gerrytools/plotting/plan/drawgraph.py +112 -0
- gerrytools-2.0.0/gerrytools/plotting/utils.py +355 -0
- gerrytools-2.0.0/gerrytools/scoring/__init__.py +175 -0
- gerrytools-2.0.0/gerrytools/scoring/_manifest.py +379 -0
- gerrytools-2.0.0/gerrytools/scoring/_types.py +159 -0
- gerrytools-2.0.0/gerrytools/scoring/evaluator.py +1314 -0
- gerrytools-2.0.0/gerrytools/scoring/formulas.py +933 -0
- gerrytools-2.0.0/gerrytools/scoring/metrics/__init__.py +908 -0
- gerrytools-2.0.0/gerrytools/scoring/metrics/_base.py +162 -0
- gerrytools-2.0.0/gerrytools/scoring/metrics/_geometry.py +841 -0
- gerrytools-2.0.0/gerrytools/scoring/result.py +1250 -0
- gerrytools-2.0.0/gerrytools/scoring/single_plan/__init__.py +1131 -0
- gerrytools-2.0.0/gerrytools/scoring/single_plan/_base.py +140 -0
- gerrytools-2.0.0/gerrytools/scoring/single_plan/_geometry.py +488 -0
- gerrytools-2.0.0/gerrytools/typing.py +146 -0
- gerrytools-2.0.0/pyproject.toml +152 -0
- gerrytools-2.0.0/rust/Cargo.lock +2276 -0
- gerrytools-2.0.0/rust/Cargo.toml +34 -0
- gerrytools-2.0.0/rust/README.md +106 -0
- gerrytools-2.0.0/rust/src/adjacency.rs +64 -0
- gerrytools-2.0.0/rust/src/error.rs +581 -0
- gerrytools-2.0.0/rust/src/geometry/mod.rs +783 -0
- gerrytools-2.0.0/rust/src/geometry/precise_area.rs +155 -0
- gerrytools-2.0.0/rust/src/geometry/unit_hulls.rs +181 -0
- gerrytools-2.0.0/rust/src/lib.rs +34 -0
- gerrytools-2.0.0/rust/src/metrics/area_perimeter.rs +113 -0
- gerrytools-2.0.0/rust/src/metrics/convex_hull_ratio.rs +153 -0
- gerrytools-2.0.0/rust/src/metrics/cut_edges.rs +241 -0
- gerrytools-2.0.0/rust/src/metrics/formulas.rs +761 -0
- gerrytools-2.0.0/rust/src/metrics/hull_metric.rs +305 -0
- gerrytools-2.0.0/rust/src/metrics/mod.rs +30 -0
- gerrytools-2.0.0/rust/src/metrics/polsby_popper.rs +381 -0
- gerrytools-2.0.0/rust/src/metrics/population_polygon.rs +769 -0
- gerrytools-2.0.0/rust/src/metrics/region.rs +442 -0
- gerrytools-2.0.0/rust/src/metrics/region_parts.rs +363 -0
- gerrytools-2.0.0/rust/src/metrics/region_tally.rs +263 -0
- gerrytools-2.0.0/rust/src/metrics/reock.rs +309 -0
- gerrytools-2.0.0/rust/src/metrics/schwartzberg.rs +128 -0
- gerrytools-2.0.0/rust/src/metrics/state_clipped_convex_hull_ratio.rs +243 -0
- gerrytools-2.0.0/rust/src/metrics/tally.rs +197 -0
- gerrytools-2.0.0/rust/src/python.rs +886 -0
- gerrytools-2.0.0/rust/src/scoring/delta.rs +137 -0
- gerrytools-2.0.0/rust/src/scoring/district.rs +117 -0
- gerrytools-2.0.0/rust/src/scoring/input.rs +286 -0
- gerrytools-2.0.0/rust/src/scoring/mod.rs +694 -0
- gerrytools-2.0.0/rust/src/scoring/output.rs +1110 -0
- gerrytools-2.0.0/rust/src/scoring/result.rs +108 -0
- gerrytools-2.0.0/rust/src/scoring/stream.rs +447 -0
- gerrytools-2.0.0/rust/src/scoring/uniqueness.rs +250 -0
- gerrytools-2.0.0/rust/src/tests/convex_hull_ratio.rs +130 -0
- gerrytools-2.0.0/rust/src/tests/cut_edges.rs +253 -0
- gerrytools-2.0.0/rust/src/tests/district.rs +32 -0
- gerrytools-2.0.0/rust/src/tests/formulas.rs +226 -0
- gerrytools-2.0.0/rust/src/tests/geometry.rs +667 -0
- gerrytools-2.0.0/rust/src/tests/input.rs +131 -0
- gerrytools-2.0.0/rust/src/tests/output.rs +530 -0
- gerrytools-2.0.0/rust/src/tests/polsby_popper.rs +239 -0
- gerrytools-2.0.0/rust/src/tests/population_polygon.rs +487 -0
- gerrytools-2.0.0/rust/src/tests/region.rs +503 -0
- gerrytools-2.0.0/rust/src/tests/region_tally.rs +183 -0
- gerrytools-2.0.0/rust/src/tests/reock.rs +523 -0
- gerrytools-2.0.0/rust/src/tests/schwartzberg.rs +52 -0
- gerrytools-2.0.0/rust/src/tests/state_clipped_convex_hull_ratio.rs +322 -0
- gerrytools-2.0.0/rust/src/tests/stream.rs +1190 -0
- gerrytools-2.0.0/rust/src/tests/support.rs +31 -0
- gerrytools-2.0.0/rust/src/tests/tally.rs +121 -0
- gerrytools-2.0.0/rust/src/tests/twodelta.rs +108 -0
- gerrytools-2.0.0/rust/src/tests/unit_hulls.rs +126 -0
- gerrytools-1.2.0/MANIFEST.in +0 -1
- gerrytools-1.2.0/PKG-INFO +0 -165
- gerrytools-1.2.0/README.md +0 -153
- gerrytools-1.2.0/gerrytools/__init__.py +0 -27
- gerrytools-1.2.0/gerrytools/ben/__init__.py +0 -37
- gerrytools-1.2.0/gerrytools/ben/binary_ensemble.py +0 -244
- gerrytools-1.2.0/gerrytools/ben/docker_manager.py +0 -28
- gerrytools-1.2.0/gerrytools/ben/parse.py +0 -345
- gerrytools-1.2.0/gerrytools/ben/reben.py +0 -616
- gerrytools-1.2.0/gerrytools/data/AssignmentCompressor.py +0 -306
- gerrytools-1.2.0/gerrytools/data/URLs.py +0 -58
- gerrytools-1.2.0/gerrytools/data/__init__.py +0 -32
- gerrytools-1.2.0/gerrytools/data/acs.py +0 -331
- gerrytools-1.2.0/gerrytools/data/census.py +0 -265
- gerrytools-1.2.0/gerrytools/data/estimatecvap.py +0 -420
- gerrytools-1.2.0/gerrytools/data/fetch.py +0 -240
- gerrytools-1.2.0/gerrytools/data/geometries.py +0 -47
- gerrytools-1.2.0/gerrytools/data/remap.py +0 -93
- gerrytools-1.2.0/gerrytools/geometry/__init__.py +0 -34
- gerrytools-1.2.0/gerrytools/geometry/compactness.py +0 -153
- gerrytools-1.2.0/gerrytools/geometry/dataframe.py +0 -36
- gerrytools-1.2.0/gerrytools/geometry/dissolve.py +0 -229
- gerrytools-1.2.0/gerrytools/geometry/dualgraph.py +0 -52
- gerrytools-1.2.0/gerrytools/geometry/optimize.py +0 -502
- gerrytools-1.2.0/gerrytools/geometry/unitmap.py +0 -72
- gerrytools-1.2.0/gerrytools/geometry/updater.py +0 -35
- gerrytools-1.2.0/gerrytools/mgrp/__init__.py +0 -21
- gerrytools-1.2.0/gerrytools/mgrp/run_container.py +0 -397
- gerrytools-1.2.0/gerrytools/mgrp/runners/forest.py +0 -162
- gerrytools-1.2.0/gerrytools/mgrp/runners/recom.py +0 -211
- gerrytools-1.2.0/gerrytools/mgrp/runners/smc.py +0 -195
- gerrytools-1.2.0/gerrytools/plotting/__init__.py +0 -41
- gerrytools-1.2.0/gerrytools/plotting/annotation.py +0 -108
- gerrytools-1.2.0/gerrytools/plotting/bins.py +0 -47
- gerrytools-1.2.0/gerrytools/plotting/boxplot.py +0 -110
- gerrytools-1.2.0/gerrytools/plotting/choropleth.py +0 -149
- gerrytools-1.2.0/gerrytools/plotting/colors.py +0 -165
- gerrytools-1.2.0/gerrytools/plotting/districtnumbers.py +0 -51
- gerrytools-1.2.0/gerrytools/plotting/drawgraph.py +0 -72
- gerrytools-1.2.0/gerrytools/plotting/drawplan.py +0 -70
- gerrytools-1.2.0/gerrytools/plotting/gifs.py +0 -88
- gerrytools-1.2.0/gerrytools/plotting/histogram.py +0 -158
- gerrytools-1.2.0/gerrytools/plotting/latexcolors.json +0 -1
- gerrytools-1.2.0/gerrytools/plotting/multidimensional.py +0 -78
- gerrytools-1.2.0/gerrytools/plotting/scatterplot.py +0 -137
- gerrytools-1.2.0/gerrytools/plotting/sealevel.py +0 -73
- gerrytools-1.2.0/gerrytools/plotting/utils.py +0 -8
- gerrytools-1.2.0/gerrytools/plotting/violin.py +0 -116
- gerrytools-1.2.0/gerrytools/scoring/__init__.py +0 -75
- gerrytools-1.2.0/gerrytools/scoring/contiguity.py +0 -50
- gerrytools-1.2.0/gerrytools/scoring/demographics.py +0 -41
- gerrytools-1.2.0/gerrytools/scoring/partisan.py +0 -173
- gerrytools-1.2.0/gerrytools/scoring/population.py +0 -36
- gerrytools-1.2.0/gerrytools/scoring/scores.py +0 -771
- gerrytools-1.2.0/gerrytools/scoring/splits.py +0 -182
- gerrytools-1.2.0/gerrytools/scoring/types.py +0 -32
- gerrytools-1.2.0/gerrytools/utilities/JSON.py +0 -96
- gerrytools-1.2.0/gerrytools/utilities/__init__.py +0 -8
- gerrytools-1.2.0/gerrytools/utilities/rename.py +0 -37
- gerrytools-1.2.0/gerrytools.egg-info/PKG-INFO +0 -165
- gerrytools-1.2.0/gerrytools.egg-info/SOURCES.txt +0 -66
- gerrytools-1.2.0/gerrytools.egg-info/requires.txt +0 -28
- gerrytools-1.2.0/gerrytools.egg-info/top_level.txt +0 -1
- gerrytools-1.2.0/setup.cfg +0 -4
- gerrytools-1.2.0/setup.py +0 -55
- {gerrytools-1.2.0 → gerrytools-2.0.0}/LICENSE +0 -0
- {gerrytools-1.2.0 → gerrytools-2.0.0}/gerrytools/mgrp/runners/__init__.py +0 -0
- /gerrytools-1.2.0/gerrytools.egg-info/dependency_links.txt → /gerrytools-2.0.0/gerrytools/py.typed +0 -0
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: gerrytools
|
|
3
|
+
Version: 2.0.0
|
|
4
|
+
Classifier: Programming Language :: Python :: 3
|
|
5
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
6
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
7
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
8
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
9
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
10
|
+
Requires-Dist: networkx>=3.6.1
|
|
11
|
+
Requires-Dist: gerrychain>=1.0.0
|
|
12
|
+
Requires-Dist: binary-ensemble==2.0.0
|
|
13
|
+
Requires-Dist: pandas>=3.0.5
|
|
14
|
+
Requires-Dist: scipy>=1.17.1
|
|
15
|
+
Requires-Dist: numpy>=2.4.6
|
|
16
|
+
Requires-Dist: pyarrow>=25.0.0
|
|
17
|
+
Requires-Dist: geopandas>=1.1.4
|
|
18
|
+
Requires-Dist: pyogrio>=0.13.0 ; python_full_version >= '3.14'
|
|
19
|
+
Requires-Dist: pyproj>=3.7.2
|
|
20
|
+
Requires-Dist: shapely>=2.1.2
|
|
21
|
+
Requires-Dist: matplotlib>=3.11.1
|
|
22
|
+
Requires-Dist: seaborn>=0.13.2
|
|
23
|
+
Requires-Dist: us>=3.2.0
|
|
24
|
+
Requires-Dist: httpx>=0.28.1
|
|
25
|
+
Requires-Dist: frozendict>=2.4.7
|
|
26
|
+
Requires-Dist: tqdm>=4.70.0
|
|
27
|
+
Requires-Dist: joblib>=1.5.3
|
|
28
|
+
Requires-Dist: furo>=2025.12.19 ; extra == 'docs'
|
|
29
|
+
Requires-Dist: myst-nb>=1.4.0 ; extra == 'docs'
|
|
30
|
+
Requires-Dist: sphinx>=9.0.4 ; extra == 'docs'
|
|
31
|
+
Requires-Dist: sphinx-autobuild>=2025.8.25 ; extra == 'docs'
|
|
32
|
+
Requires-Dist: sphinx-copybutton>=0.5.2 ; extra == 'docs'
|
|
33
|
+
Requires-Dist: sphinx-design>=0.7.0 ; extra == 'docs'
|
|
34
|
+
Requires-Dist: docker>=7.2.0 ; extra == 'mgrp'
|
|
35
|
+
Provides-Extra: docs
|
|
36
|
+
Provides-Extra: mgrp
|
|
37
|
+
License-File: LICENSE
|
|
38
|
+
Summary: Tools for processing and visualizing districting plans.
|
|
39
|
+
Author-email: Data and Democracy Research Initiative <code@mggg.org>
|
|
40
|
+
License-Expression: BSD-3-Clause
|
|
41
|
+
Requires-Python: >=3.11
|
|
42
|
+
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
|
|
43
|
+
|
|
44
|
+
# gerrytools
|
|
45
|
+
|
|
46
|
+
[](https://github.com/mggg/gerrytools/actions/workflows/tests.yml)
|
|
47
|
+
[](https://badge.fury.io/py/gerrytools)
|
|
48
|
+
[](https://gerrytools.readthedocs.io/en/latest/)
|
|
49
|
+
[](https://data-democracy.org)
|
|
50
|
+
[](https://docs.astral.sh/ruff/)
|
|
51
|
+
|
|
52
|
+
A companion to [GerryChain](https://github.com/mggg/GerryChain), GerryTools provides tools for
|
|
53
|
+
retrieving redistricting data, recording and scoring ensembles, comparing districting plans, and
|
|
54
|
+
producing publication-ready figures and tables. It is developed by the
|
|
55
|
+
[Data and Democracy Research Initiative](https://data-democracy.org) and distributed under the
|
|
56
|
+
[3-Clause BSD License](https://opensource.org/licenses/BSD-3-Clause).
|
|
57
|
+
|
|
58
|
+
## Installation
|
|
59
|
+
|
|
60
|
+
GerryTools requires Python 3.11 or newer. Published wheels include the compiled scoring engine;
|
|
61
|
+
building from source requires a stable Rust toolchain and a C++ compiler.
|
|
62
|
+
|
|
63
|
+
To install GerryTools from [PyPI](https://pypi.org/project/gerrytools/), run:
|
|
64
|
+
|
|
65
|
+
```console
|
|
66
|
+
pip install gerrytools
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
The `gerrytools.ben` API is included in the base installation. To use the Docker-backed ensemble
|
|
70
|
+
runners in `gerrytools.mgrp`, install the optional dependency:
|
|
71
|
+
|
|
72
|
+
```console
|
|
73
|
+
pip install "gerrytools[mgrp]"
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
The runners also require Docker Desktop, Docker Engine, or another compatible daemon. See the
|
|
77
|
+
[Docker documentation](https://gerrytools.readthedocs.io/en/latest/topics/docker/) for platform
|
|
78
|
+
requirements and setup instructions.
|
|
79
|
+
|
|
80
|
+
## Usage
|
|
81
|
+
|
|
82
|
+
GerryTools is organized into public modules that can be used independently or together:
|
|
83
|
+
|
|
84
|
+
- **`gerrytools.data`** retrieves decennial Census and American Community Survey tables, estimates
|
|
85
|
+
block-level citizen voting-age population, and downloads processed 2020 geographic products.
|
|
86
|
+
|
|
87
|
+
- **`gerrytools.plan_comparison`** compares plans by population or area, finds optimal district
|
|
88
|
+
relabelings, and measures population dispersion.
|
|
89
|
+
|
|
90
|
+
- **`gerrytools.plotting`** provides composable statistical and geographic plot builders that work
|
|
91
|
+
with Matplotlib figures and axes.
|
|
92
|
+
|
|
93
|
+
- **`gerrytools.colors`** provides named colors, district palettes, color conversion, and
|
|
94
|
+
Matplotlib and seaborn colormaps.
|
|
95
|
+
|
|
96
|
+
- **`gerrytools.mgrp`** runs Rust ReCom, Forest ReCom, Sequential Monte Carlo, and optimization
|
|
97
|
+
workflows through a versioned Docker image.
|
|
98
|
+
|
|
99
|
+
- **`gerrytools.ben`** records GerryChain runs as self-describing BENDL files and reconstructs
|
|
100
|
+
recorded partitions for lookup, subsampling, and analysis.
|
|
101
|
+
|
|
102
|
+
- **`gerrytools.scoring`** prepares graph and geometry resources once, evaluates plans with the
|
|
103
|
+
compiled Rust scoring engine, and provides one-shot functions and array formulas.
|
|
104
|
+
|
|
105
|
+
- **`gerrytools.latex`** builds LaTeX documents and tables plus TikZ-native paintball and
|
|
106
|
+
seats-votes figures.
|
|
107
|
+
|
|
108
|
+
See the [module guides](https://gerrytools.readthedocs.io/en/latest/user/intro/) for examples and
|
|
109
|
+
the [API reference](https://gerrytools.readthedocs.io/en/latest/api/) for signatures and parameters.
|
|
110
|
+
|
|
111
|
+
## Contributing
|
|
112
|
+
|
|
113
|
+
GerryTools is an active project, and has multiple contributors. If you'd like to contribute, here
|
|
114
|
+
are a few house rules:
|
|
115
|
+
|
|
116
|
+
1. Install `task` and `uv`, then run `task setup` from the repository root. Use
|
|
117
|
+
`task --list-all` to see the available development workflows.
|
|
118
|
+
|
|
119
|
+
1. Run `task check` before opening a pull request. Use `task format` for Ruff formatting and
|
|
120
|
+
import sorting, `task lint` for Ruff linting, `task test` for the test suite, and `task docs`
|
|
121
|
+
to build the documentation locally.
|
|
122
|
+
|
|
123
|
+
1. **Write tests.** All changes, major or minor, **must** be accompanied by testing code. Code and
|
|
124
|
+
tests will be immediately reviewed by Lab maintainers.
|
|
125
|
+
|
|
126
|
+
1. Test coverage must stay **at least** the same; this can be checked by running
|
|
127
|
+
`uv run pytest --cov=gerrytools --cov-report=term-missing` after the tests are added to
|
|
128
|
+
`tests/`.
|
|
129
|
+
|
|
130
|
+
1. **Write documentation.** Document public APIs and non-obvious invariants. Prefer clear names
|
|
131
|
+
and focused functions over comments that merely restate the code.
|
|
132
|
+
|
|
133
|
+
We look forward to your contributions!
|
|
134
|
+
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# gerrytools
|
|
2
|
+
|
|
3
|
+
[](https://github.com/mggg/gerrytools/actions/workflows/tests.yml)
|
|
4
|
+
[](https://badge.fury.io/py/gerrytools)
|
|
5
|
+
[](https://gerrytools.readthedocs.io/en/latest/)
|
|
6
|
+
[](https://data-democracy.org)
|
|
7
|
+
[](https://docs.astral.sh/ruff/)
|
|
8
|
+
|
|
9
|
+
A companion to [GerryChain](https://github.com/mggg/GerryChain), GerryTools provides tools for
|
|
10
|
+
retrieving redistricting data, recording and scoring ensembles, comparing districting plans, and
|
|
11
|
+
producing publication-ready figures and tables. It is developed by the
|
|
12
|
+
[Data and Democracy Research Initiative](https://data-democracy.org) and distributed under the
|
|
13
|
+
[3-Clause BSD License](https://opensource.org/licenses/BSD-3-Clause).
|
|
14
|
+
|
|
15
|
+
## Installation
|
|
16
|
+
|
|
17
|
+
GerryTools requires Python 3.11 or newer. Published wheels include the compiled scoring engine;
|
|
18
|
+
building from source requires a stable Rust toolchain and a C++ compiler.
|
|
19
|
+
|
|
20
|
+
To install GerryTools from [PyPI](https://pypi.org/project/gerrytools/), run:
|
|
21
|
+
|
|
22
|
+
```console
|
|
23
|
+
pip install gerrytools
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
The `gerrytools.ben` API is included in the base installation. To use the Docker-backed ensemble
|
|
27
|
+
runners in `gerrytools.mgrp`, install the optional dependency:
|
|
28
|
+
|
|
29
|
+
```console
|
|
30
|
+
pip install "gerrytools[mgrp]"
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
The runners also require Docker Desktop, Docker Engine, or another compatible daemon. See the
|
|
34
|
+
[Docker documentation](https://gerrytools.readthedocs.io/en/latest/topics/docker/) for platform
|
|
35
|
+
requirements and setup instructions.
|
|
36
|
+
|
|
37
|
+
## Usage
|
|
38
|
+
|
|
39
|
+
GerryTools is organized into public modules that can be used independently or together:
|
|
40
|
+
|
|
41
|
+
- **`gerrytools.data`** retrieves decennial Census and American Community Survey tables, estimates
|
|
42
|
+
block-level citizen voting-age population, and downloads processed 2020 geographic products.
|
|
43
|
+
|
|
44
|
+
- **`gerrytools.plan_comparison`** compares plans by population or area, finds optimal district
|
|
45
|
+
relabelings, and measures population dispersion.
|
|
46
|
+
|
|
47
|
+
- **`gerrytools.plotting`** provides composable statistical and geographic plot builders that work
|
|
48
|
+
with Matplotlib figures and axes.
|
|
49
|
+
|
|
50
|
+
- **`gerrytools.colors`** provides named colors, district palettes, color conversion, and
|
|
51
|
+
Matplotlib and seaborn colormaps.
|
|
52
|
+
|
|
53
|
+
- **`gerrytools.mgrp`** runs Rust ReCom, Forest ReCom, Sequential Monte Carlo, and optimization
|
|
54
|
+
workflows through a versioned Docker image.
|
|
55
|
+
|
|
56
|
+
- **`gerrytools.ben`** records GerryChain runs as self-describing BENDL files and reconstructs
|
|
57
|
+
recorded partitions for lookup, subsampling, and analysis.
|
|
58
|
+
|
|
59
|
+
- **`gerrytools.scoring`** prepares graph and geometry resources once, evaluates plans with the
|
|
60
|
+
compiled Rust scoring engine, and provides one-shot functions and array formulas.
|
|
61
|
+
|
|
62
|
+
- **`gerrytools.latex`** builds LaTeX documents and tables plus TikZ-native paintball and
|
|
63
|
+
seats-votes figures.
|
|
64
|
+
|
|
65
|
+
See the [module guides](https://gerrytools.readthedocs.io/en/latest/user/intro/) for examples and
|
|
66
|
+
the [API reference](https://gerrytools.readthedocs.io/en/latest/api/) for signatures and parameters.
|
|
67
|
+
|
|
68
|
+
## Contributing
|
|
69
|
+
|
|
70
|
+
GerryTools is an active project, and has multiple contributors. If you'd like to contribute, here
|
|
71
|
+
are a few house rules:
|
|
72
|
+
|
|
73
|
+
1. Install `task` and `uv`, then run `task setup` from the repository root. Use
|
|
74
|
+
`task --list-all` to see the available development workflows.
|
|
75
|
+
|
|
76
|
+
1. Run `task check` before opening a pull request. Use `task format` for Ruff formatting and
|
|
77
|
+
import sorting, `task lint` for Ruff linting, `task test` for the test suite, and `task docs`
|
|
78
|
+
to build the documentation locally.
|
|
79
|
+
|
|
80
|
+
1. **Write tests.** All changes, major or minor, **must** be accompanied by testing code. Code and
|
|
81
|
+
tests will be immediately reviewed by Lab maintainers.
|
|
82
|
+
|
|
83
|
+
1. Test coverage must stay **at least** the same; this can be checked by running
|
|
84
|
+
`uv run pytest --cov=gerrytools --cov-report=term-missing` after the tests are added to
|
|
85
|
+
`tests/`.
|
|
86
|
+
|
|
87
|
+
1. **Write documentation.** Document public APIs and non-obvious invariants. Prefer clear names
|
|
88
|
+
and focused functions over comments that merely restate the code.
|
|
89
|
+
|
|
90
|
+
We look forward to your contributions!
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"""Shared electoral math for the plotting (Matplotlib) and latex (TikZ) backends.
|
|
2
|
+
|
|
3
|
+
Pure functions over plain arrays and sequences, imported by both backends so the math cannot
|
|
4
|
+
drift between them. Values are kept at full float precision; each emitter owns whatever
|
|
5
|
+
formatting or rounding its output format requires.
|
|
6
|
+
|
|
7
|
+
This module owns shared plotting and LaTeX transformations only. Partisan and election scoring
|
|
8
|
+
formulas belong in ``gerrytools.scoring``.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from numbers import Integral
|
|
14
|
+
from typing import Iterable, Sequence
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
|
|
18
|
+
from gerrytools import _partisan_math
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _validated_opposition_counts(pov_counts: np.ndarray, total_counts: np.ndarray) -> np.ndarray:
|
|
22
|
+
"""Validate aligned, positive totals and return per-district opposition counts.
|
|
23
|
+
|
|
24
|
+
Raises:
|
|
25
|
+
ValueError: If the arrays do not align, contain nonpositive totals, or a district's
|
|
26
|
+
party-of-interest count exceeds its total.
|
|
27
|
+
"""
|
|
28
|
+
if pov_counts.shape != total_counts.shape:
|
|
29
|
+
raise ValueError("pov_counts and total_counts must have the same shape.")
|
|
30
|
+
if np.any(total_counts <= 0):
|
|
31
|
+
raise ValueError("total_counts must be positive for all districts.")
|
|
32
|
+
if np.any(pov_counts > total_counts):
|
|
33
|
+
raise ValueError("pov_counts cannot exceed total_counts.")
|
|
34
|
+
return total_counts - pov_counts
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def seats_votes_curve_values(
|
|
38
|
+
pov_counts: np.ndarray, total_counts: np.ndarray
|
|
39
|
+
) -> tuple[list[float], list[float]]:
|
|
40
|
+
"""Compute standard uniform-swing seats-votes step-curve positions.
|
|
41
|
+
|
|
42
|
+
The district shares and turnout-weighted overall share use the arithmetic shared with
|
|
43
|
+
:mod:`gerrytools.scoring.formulas`, treating ``total - pov`` as the opposition tally.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
pov_counts (np.ndarray): Per-district party-of-interest vote totals.
|
|
47
|
+
total_counts (np.ndarray): Per-district total vote totals.
|
|
48
|
+
|
|
49
|
+
Returns:
|
|
50
|
+
tuple[list[float], list[float]]: Vote-share breakpoints (x) and seat-share breakpoints
|
|
51
|
+
(y, ``0..1`` stepped by district rank).
|
|
52
|
+
|
|
53
|
+
Raises:
|
|
54
|
+
ValueError: If the arrays do not align, contain nonpositive totals, or a district's
|
|
55
|
+
party-of-interest count exceeds its total.
|
|
56
|
+
"""
|
|
57
|
+
opposition_counts = _validated_opposition_counts(pov_counts, total_counts)
|
|
58
|
+
vote_shares = _partisan_math.district_vote_shares(pov_counts, opposition_counts)
|
|
59
|
+
overall_percent = float(_partisan_math.overall_vote_share(pov_counts, opposition_counts))
|
|
60
|
+
breakpoints = _partisan_math.swing_breakpoints(vote_shares, overall_percent)
|
|
61
|
+
vote_share_shift_positions = [0.0] + sorted(map(float, breakpoints)) + [1.0]
|
|
62
|
+
|
|
63
|
+
n_seats = len(vote_shares)
|
|
64
|
+
seat_shares_shift_positions = [0.0] + list(map(float, np.arange(n_seats + 1) / n_seats))
|
|
65
|
+
return vote_share_shift_positions, seat_shares_shift_positions
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def overall_election_point(pov_counts: np.ndarray, total_counts: np.ndarray) -> tuple[float, float]:
|
|
69
|
+
"""Compute the overall election-result point ``(vote share, seat share)``.
|
|
70
|
+
|
|
71
|
+
The vote share is the party-of-interest share of all votes cast; the seat share is the
|
|
72
|
+
fraction of districts the party strictly wins. Both use the arithmetic shared with
|
|
73
|
+
:mod:`gerrytools.scoring.formulas`, with ``total - pov`` as the opposition tally.
|
|
74
|
+
|
|
75
|
+
Args:
|
|
76
|
+
pov_counts (np.ndarray): Per-district party-of-interest vote totals.
|
|
77
|
+
total_counts (np.ndarray): Per-district total vote totals.
|
|
78
|
+
|
|
79
|
+
Returns:
|
|
80
|
+
tuple[float, float]: The ``(vote share, seat share)`` marker position.
|
|
81
|
+
|
|
82
|
+
Raises:
|
|
83
|
+
ValueError: If the arrays do not align, contain nonpositive totals, or a district's
|
|
84
|
+
party-of-interest count exceeds its total.
|
|
85
|
+
"""
|
|
86
|
+
opposition_counts = _validated_opposition_counts(pov_counts, total_counts)
|
|
87
|
+
total_vote_share = float(_partisan_math.overall_vote_share(pov_counts, opposition_counts))
|
|
88
|
+
total_seat_share = float(np.mean(_partisan_math.district_wins(pov_counts, opposition_counts)))
|
|
89
|
+
return total_vote_share, total_seat_share
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def normalize_paintball_data(
|
|
93
|
+
voteshares: Sequence[float],
|
|
94
|
+
seats: Sequence[float],
|
|
95
|
+
total_seats: int | None = None,
|
|
96
|
+
) -> tuple[list[float], list[float]]:
|
|
97
|
+
"""Validate and normalize incoming vote-share and seat data for a paintball plot.
|
|
98
|
+
|
|
99
|
+
``voteshares`` values must lie in [0, 1]. ``seats`` values are either interpreted directly
|
|
100
|
+
as seat shares in [0, 1] (when ``total_seats`` is None), or as seat counts normalized by
|
|
101
|
+
``total_seats`` (when provided), and the resulting shares must also lie in [0, 1].
|
|
102
|
+
|
|
103
|
+
Args:
|
|
104
|
+
voteshares (Sequence[float]): Vote-share values in ``[0, 1]``.
|
|
105
|
+
seats (Sequence[float]): Seat-share values in ``[0, 1]`` or raw seat counts.
|
|
106
|
+
total_seats (int | None, optional): Total seats used to normalize raw seat counts.
|
|
107
|
+
Defaults to None.
|
|
108
|
+
|
|
109
|
+
Returns:
|
|
110
|
+
tuple[list[float], list[float]]: Normalized vote-share and seat-share vectors.
|
|
111
|
+
|
|
112
|
+
Raises:
|
|
113
|
+
ValueError: If lengths mismatch, inputs are empty, ``total_seats`` is not a positive
|
|
114
|
+
integer, or normalized values are out of range.
|
|
115
|
+
"""
|
|
116
|
+
if len(voteshares) != len(seats):
|
|
117
|
+
raise ValueError("vote_share_data and seats_data must have the same length.")
|
|
118
|
+
if len(voteshares) == 0:
|
|
119
|
+
raise ValueError("vote_share_data and seats_data must have at least one element.")
|
|
120
|
+
|
|
121
|
+
normalized_voteshares = [float(vote_share) for vote_share in voteshares]
|
|
122
|
+
if not all(0.0 <= vote_share <= 1.0 for vote_share in normalized_voteshares):
|
|
123
|
+
raise ValueError("All vote-share values must be in [0, 1].")
|
|
124
|
+
|
|
125
|
+
if total_seats is None:
|
|
126
|
+
normalized_seatshares = [float(seat_value) for seat_value in seats]
|
|
127
|
+
else:
|
|
128
|
+
if (
|
|
129
|
+
isinstance(total_seats, bool)
|
|
130
|
+
or not isinstance(total_seats, Integral)
|
|
131
|
+
or total_seats <= 0
|
|
132
|
+
):
|
|
133
|
+
raise ValueError("total_seats must be a positive integer when provided.")
|
|
134
|
+
normalized_seatshares = [float(seat_value) / total_seats for seat_value in seats]
|
|
135
|
+
|
|
136
|
+
if not all(0.0 <= seat_share <= 1.0 for seat_share in normalized_seatshares):
|
|
137
|
+
raise ValueError("All seat-share values must be in [0, 1].")
|
|
138
|
+
|
|
139
|
+
return normalized_voteshares, normalized_seatshares
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def paintball_coordinates(
|
|
143
|
+
voteshares: Sequence[float], seatshares: Sequence[float]
|
|
144
|
+
) -> tuple[list[float], list[float]]:
|
|
145
|
+
"""Return direct ``(vote share, seat share)`` paintball coordinates.
|
|
146
|
+
|
|
147
|
+
Args:
|
|
148
|
+
voteshares (Sequence[float]): Vote-share values in ``[0, 1]``.
|
|
149
|
+
seatshares (Sequence[float]): Seat-share values in ``[0, 1]``.
|
|
150
|
+
|
|
151
|
+
Returns:
|
|
152
|
+
tuple[list[float], list[float]]: Vote-share x-coordinates and seat-share y-coordinates.
|
|
153
|
+
"""
|
|
154
|
+
return list(voteshares), list(seatshares)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def horizontal_hull_vertices(
|
|
158
|
+
points: Iterable[tuple[float, float]],
|
|
159
|
+
) -> list[tuple[float, float]]:
|
|
160
|
+
"""Compute the horizontal hull polygon vertices for a set of points.
|
|
161
|
+
|
|
162
|
+
For each distinct y value the hull keeps the minimum and maximum x. Vertices are returned as
|
|
163
|
+
the left side (minimum x, ascending y) followed by the right side (maximum x, descending y),
|
|
164
|
+
ready to close into a polygon.
|
|
165
|
+
|
|
166
|
+
Args:
|
|
167
|
+
points (Iterable[tuple[float, float]]): The ``(x, y)`` points to hull.
|
|
168
|
+
|
|
169
|
+
Returns:
|
|
170
|
+
list[tuple[float, float]]: Hull vertices in drawing order.
|
|
171
|
+
"""
|
|
172
|
+
y_to_minmax_x: dict[float, tuple[float, float]] = {}
|
|
173
|
+
for x_coord, y_coord in points:
|
|
174
|
+
if y_coord not in y_to_minmax_x:
|
|
175
|
+
y_to_minmax_x[y_coord] = (x_coord, x_coord)
|
|
176
|
+
continue
|
|
177
|
+
|
|
178
|
+
min_x, max_x = y_to_minmax_x[y_coord]
|
|
179
|
+
y_to_minmax_x[y_coord] = (min(min_x, x_coord), max(max_x, x_coord))
|
|
180
|
+
|
|
181
|
+
sorted_y = sorted(y_to_minmax_x)
|
|
182
|
+
left_side = [(y_to_minmax_x[y_val][0], y_val) for y_val in sorted_y]
|
|
183
|
+
right_side = [(y_to_minmax_x[y_val][1], y_val) for y_val in reversed(sorted_y)]
|
|
184
|
+
return left_side + right_side
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""Shared GeoDataFrame alignment and validation helpers."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Hashable, Iterable
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
import geopandas as gpd
|
|
7
|
+
import numpy as np
|
|
8
|
+
import pandas as pd
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _object_index(values: Iterable[Hashable], name: str) -> pd.Index:
|
|
12
|
+
"""Build an object index without expanding tuple-valued identifiers."""
|
|
13
|
+
labels = tuple(values)
|
|
14
|
+
if not any(isinstance(label, tuple) for label in labels):
|
|
15
|
+
return pd.Index(labels, name=name)
|
|
16
|
+
array = np.empty(len(labels), dtype=object)
|
|
17
|
+
array[:] = labels
|
|
18
|
+
return pd.Index(array, name=name)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _require_projected_crs(frame: gpd.GeoDataFrame, context: str) -> None:
|
|
22
|
+
"""Require a projected CRS so downstream measurements are planar."""
|
|
23
|
+
crs = frame.crs
|
|
24
|
+
if crs is None or not crs.is_projected:
|
|
25
|
+
raise ValueError(f"{context} requires a projected CRS")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _require_valid_polygons(frame: gpd.GeoDataFrame, name: str) -> None:
|
|
29
|
+
"""Reject missing, empty, invalid, or non-polygonal geometries."""
|
|
30
|
+
geometry = frame.geometry
|
|
31
|
+
if geometry.isna().any():
|
|
32
|
+
raise ValueError(f"{name} cannot contain missing geometries")
|
|
33
|
+
if geometry.is_empty.any():
|
|
34
|
+
raise ValueError(f"{name} cannot contain empty geometries")
|
|
35
|
+
if not geometry.is_valid.all():
|
|
36
|
+
raise ValueError(f"{name} geometries must be topologically valid")
|
|
37
|
+
if not geometry.geom_type.isin(("Polygon", "MultiPolygon")).all():
|
|
38
|
+
raise ValueError(f"{name} must contain only Polygon or MultiPolygon geometries")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _alignment_positions(
|
|
42
|
+
node_order: Iterable[Hashable],
|
|
43
|
+
geometry_nodes: Iterable[Hashable],
|
|
44
|
+
*,
|
|
45
|
+
target_name: str = "node_order",
|
|
46
|
+
) -> tuple[int, ...]:
|
|
47
|
+
"""Return geometry row positions in node order after validating identifiers."""
|
|
48
|
+
nodes = _object_index(node_order, "node")
|
|
49
|
+
if nodes.empty:
|
|
50
|
+
raise ValueError("node_order cannot be empty")
|
|
51
|
+
if nodes.has_duplicates:
|
|
52
|
+
raise ValueError("node_order cannot contain duplicate identifiers")
|
|
53
|
+
if nodes.isna().any():
|
|
54
|
+
raise ValueError("node_order cannot contain missing identifiers")
|
|
55
|
+
|
|
56
|
+
geometry_index = _object_index(geometry_nodes, "node")
|
|
57
|
+
if geometry_index.has_duplicates:
|
|
58
|
+
raise ValueError("geometry node identifiers must be unique")
|
|
59
|
+
if geometry_index.isna().any():
|
|
60
|
+
raise ValueError("geometry node identifiers cannot be missing")
|
|
61
|
+
|
|
62
|
+
missing = nodes[~nodes.isin(geometry_index)].tolist()
|
|
63
|
+
unexpected = geometry_index[~geometry_index.isin(nodes)].tolist()
|
|
64
|
+
if missing or unexpected:
|
|
65
|
+
raise ValueError(
|
|
66
|
+
f"geometry node identifiers must exactly match {target_name}; "
|
|
67
|
+
f"missing={missing!r}, unexpected={unexpected!r}"
|
|
68
|
+
)
|
|
69
|
+
return tuple(int(value) for value in geometry_index.get_indexer(nodes))
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _validated_geometry_frame(
|
|
73
|
+
frame: gpd.GeoDataFrame,
|
|
74
|
+
*,
|
|
75
|
+
crs: Any | None = None,
|
|
76
|
+
) -> gpd.GeoDataFrame:
|
|
77
|
+
"""Transform and validate a geometry frame whose rows are already aligned."""
|
|
78
|
+
if frame.crs is None:
|
|
79
|
+
raise ValueError("geometries must have a CRS")
|
|
80
|
+
if crs is not None:
|
|
81
|
+
frame = frame.to_crs(crs)
|
|
82
|
+
_require_projected_crs(frame, "geometry scoring")
|
|
83
|
+
_require_valid_polygons(frame, "geometries")
|
|
84
|
+
return frame
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def aligned_geodataframe(
|
|
88
|
+
node_order: Iterable[Hashable],
|
|
89
|
+
geometries: gpd.GeoDataFrame,
|
|
90
|
+
*,
|
|
91
|
+
node_column: str | None = None,
|
|
92
|
+
crs: Any | None = None,
|
|
93
|
+
) -> gpd.GeoDataFrame:
|
|
94
|
+
"""Return a validated projected GeoDataFrame in graph-node order.
|
|
95
|
+
|
|
96
|
+
Geometry rows are always matched to graph nodes by identifier. When ``node_column`` is
|
|
97
|
+
omitted, the GeoDataFrame index is the identifier. Supplying a GeoDataFrame whose current
|
|
98
|
+
order happens to match the graph is not enough unless its index also contains the node ids.
|
|
99
|
+
|
|
100
|
+
Args:
|
|
101
|
+
node_order (Iterable[Hashable]): Graph node identifiers in the order expected by the scoring
|
|
102
|
+
engine.
|
|
103
|
+
geometries (gpd.GeoDataFrame): One geometry row per graph node.
|
|
104
|
+
node_column (str | None): Optional column containing graph node identifiers.
|
|
105
|
+
crs (Any | None): Optional projected CRS to which the geometries are transformed. Without
|
|
106
|
+
this argument, ``geometries`` must already use a projected CRS.
|
|
107
|
+
|
|
108
|
+
Returns:
|
|
109
|
+
gpd.GeoDataFrame: An aligned copy of ``geometries``.
|
|
110
|
+
|
|
111
|
+
Raises:
|
|
112
|
+
TypeError: If ``geometries`` is not a GeoDataFrame.
|
|
113
|
+
ValueError: If identifiers are missing, duplicated, or do not match the node set; if CRS
|
|
114
|
+
information is absent or geographic; or if a geometry is missing, empty, or invalid.
|
|
115
|
+
"""
|
|
116
|
+
if not isinstance(geometries, gpd.GeoDataFrame):
|
|
117
|
+
raise TypeError("geometries must be a GeoDataFrame")
|
|
118
|
+
|
|
119
|
+
if node_column is None:
|
|
120
|
+
geometry_nodes = _object_index(geometries.index, "node")
|
|
121
|
+
else:
|
|
122
|
+
if node_column not in geometries.columns:
|
|
123
|
+
raise ValueError(f"geometries does not contain node column {node_column!r}")
|
|
124
|
+
geometry_nodes = _object_index(geometries[node_column], "node")
|
|
125
|
+
|
|
126
|
+
positions = _alignment_positions(node_order, geometry_nodes)
|
|
127
|
+
return _validated_geometry_frame(geometries.iloc[list(positions)].copy(), crs=crs)
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Shared geometry helpers for the plotting and latex modules."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def line_segment_through_unit_square(
|
|
9
|
+
slope: float, *, round_to: int | None = None
|
|
10
|
+
) -> tuple[float, float, float, float]:
|
|
11
|
+
"""Compute line endpoints inside the unit square for a line through ``(0.5, 0.5)``.
|
|
12
|
+
|
|
13
|
+
Args:
|
|
14
|
+
slope (float): Slope of the line.
|
|
15
|
+
round_to (int | None, optional): Decimal places used to round each
|
|
16
|
+
coordinate, or None for no rounding. The TikZ emitters round to
|
|
17
|
+
keep the generated LaTeX compact. Defaults to None.
|
|
18
|
+
|
|
19
|
+
Returns:
|
|
20
|
+
tuple[float, float, float, float]: Endpoints in ``(x0, y0, x1, y1)`` order.
|
|
21
|
+
|
|
22
|
+
Raises:
|
|
23
|
+
ValueError: If ``slope`` is NaN.
|
|
24
|
+
"""
|
|
25
|
+
# NaN fails both the isinf and abs comparisons, which would silently yield NaN endpoints.
|
|
26
|
+
if math.isnan(slope):
|
|
27
|
+
raise ValueError("slope cannot be NaN")
|
|
28
|
+
if math.isinf(slope):
|
|
29
|
+
starting_x, starting_y = 0.5, 0.0
|
|
30
|
+
ending_x, ending_y = 0.5, 1.0
|
|
31
|
+
elif abs(slope) >= 1:
|
|
32
|
+
# Steep lines exit through the top and bottom edges.
|
|
33
|
+
starting_x, starting_y = 0.5 - (0.5 / slope), 0.0
|
|
34
|
+
ending_x, ending_y = 0.5 + (0.5 / slope), 1.0
|
|
35
|
+
else:
|
|
36
|
+
# Shallow lines (including slope 0) exit through the side edges.
|
|
37
|
+
starting_x, starting_y = 0.0, 0.5 - (0.5 * slope)
|
|
38
|
+
ending_x, ending_y = 1.0, 0.5 + (0.5 * slope)
|
|
39
|
+
|
|
40
|
+
if round_to is None:
|
|
41
|
+
return (starting_x, starting_y, ending_x, ending_y)
|
|
42
|
+
return (
|
|
43
|
+
round(starting_x, round_to),
|
|
44
|
+
round(starting_y, round_to),
|
|
45
|
+
round(ending_x, round_to),
|
|
46
|
+
round(ending_y, round_to),
|
|
47
|
+
)
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Internal IPython/Jupyter environment detection.
|
|
2
|
+
|
|
3
|
+
Single home for the "are we inside a live Jupyter kernel?" check used by the
|
|
4
|
+
plotting and latex modules to decide whether to suppress implicit figure
|
|
5
|
+
display or render inline output.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def in_jupyter_kernel() -> bool:
|
|
12
|
+
"""Return True iff running inside a live Jupyter kernel.
|
|
13
|
+
|
|
14
|
+
A plain IPython terminal session has an interactive shell but no
|
|
15
|
+
``kernel`` attribute, so this returns False there — as it does in any
|
|
16
|
+
ordinary Python process, including environments where IPython is not
|
|
17
|
+
installed.
|
|
18
|
+
"""
|
|
19
|
+
try: # pragma: no cover - only reachable inside a live IPython session
|
|
20
|
+
from IPython.core.getipython import get_ipython
|
|
21
|
+
|
|
22
|
+
interactive_shell = get_ipython()
|
|
23
|
+
except Exception: # pragma: no cover - IPython missing or shell lookup failed
|
|
24
|
+
return False
|
|
25
|
+
return interactive_shell is not None and getattr(interactive_shell, "kernel", None) is not None
|