gerrytools 2.0.1__tar.gz → 2.0.3__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.1 → gerrytools-2.0.3}/PKG-INFO +1 -1
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/_geodataframe.py +13 -3
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/mgrp/run_container.py +51 -8
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/data/_axis_api.py +37 -5
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/data/barplot.py +1 -1
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/data/histogram.py +89 -35
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/scoring/evaluator.py +39 -20
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/scoring/metrics/_geometry.py +29 -23
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/scoring/result.py +3 -3
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/scoring/single_plan/__init__.py +2 -2
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/scoring/single_plan/_base.py +5 -4
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/scoring/single_plan/_geometry.py +23 -14
- {gerrytools-2.0.1 → gerrytools-2.0.3}/pyproject.toml +1 -1
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/tests/geometry.rs +1 -1
- {gerrytools-2.0.1 → gerrytools-2.0.3}/LICENSE +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/README.md +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/__init__.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/_election_math.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/_geometry.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/_ipython.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/_partisan_math.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/_scoring_engine.pyi +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/ben/__init__.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/ben/_graph_prep.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/ben/recorded_chain.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/colors/__init__.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/colors/_latex_table.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/colors/_sources.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/colors/_value.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/colors/core.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/colors/districtr.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/colors/latex.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/colors/seaborn.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/colors/utils.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/data/__init__.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/data/_geometry_etags.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/data/geometries.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/data/uscensus/__init__.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/data/uscensus/_api.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/data/uscensus/acs.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/data/uscensus/block_cvap.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/data/uscensus/census.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/data/uscensus/census_tables.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/data/uscensus/ptable_column_aliases.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/latex/__init__.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/latex/_colors.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/latex/_render.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/latex/_table_base.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/latex/_table_layout.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/latex/_table_options.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/latex/_table_preamble.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/latex/_text.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/latex/_tikz_plot_base.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/latex/commands.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/latex/document.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/latex/formatters.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/latex/paintball.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/latex/seatsvotes.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/latex/table.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/latex/tikz_table.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/logging.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/mgrp/__init__.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/mgrp/constraints.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/mgrp/objectives.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/mgrp/run_config.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/mgrp/runners/__init__.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/mgrp/runners/forest.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/mgrp/runners/recom.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/mgrp/runners/smc.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plan_comparison/__init__.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plan_comparison/overlap.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plan_comparison/relabel.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/__init__.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/_artist_registry.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/_axes_backed.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/_axes_state.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/_figure_io.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/_legend_mixin.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/_legend_utils.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/_rng.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/data/__init__.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/data/_annotation_api.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/data/_annotations.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/data/_arrow_renderer.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/data/_categorical_distribution_base.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/data/_gerryplot_dataclasses.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/data/_unit_square_base.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/data/boxplot.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/data/gerryplot.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/data/options.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/data/paintball.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/data/scatterplot.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/data/sealevel.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/data/seatsvotes.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/data/violin.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/geometry/__init__.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/geometry/_dot_sampling.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/geometry/_labels.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/geometry/_layers/__init__.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/geometry/_layers/_base.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/geometry/_layers/_categorical.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/geometry/_layers/_continuous.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/geometry/_layers/_marker.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/geometry/dotdensity.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/geometry/geoplot.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/geometry/geoplotbase.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/mpl/__init__.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/mpl/axis_title_style.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/mpl/geoplot_options.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/mpl/label_text_options.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/mpl/legend_options.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/mpl/marker_options.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/mpl/tick_style.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/other/__init__.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/other/subway.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/plan/__init__.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/plan/drawgraph.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/plotting/utils.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/py.typed +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/scoring/__init__.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/scoring/_manifest.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/scoring/_types.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/scoring/formulas.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/scoring/metrics/__init__.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/scoring/metrics/_base.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/gerrytools/typing.py +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/Cargo.lock +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/Cargo.toml +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/README.md +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/adjacency.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/error.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/geometry/mod.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/geometry/precise_area.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/geometry/unit_hulls.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/lib.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/metrics/area_perimeter.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/metrics/convex_hull_ratio.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/metrics/cut_edges.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/metrics/formulas.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/metrics/hull_metric.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/metrics/mod.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/metrics/polsby_popper.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/metrics/population_polygon.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/metrics/region.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/metrics/region_parts.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/metrics/region_tally.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/metrics/reock.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/metrics/schwartzberg.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/metrics/state_clipped_convex_hull_ratio.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/metrics/tally.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/python.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/scoring/delta.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/scoring/district.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/scoring/input.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/scoring/mod.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/scoring/output.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/scoring/result.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/scoring/stream.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/scoring/uniqueness.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/tests/convex_hull_ratio.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/tests/cut_edges.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/tests/district.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/tests/formulas.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/tests/input.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/tests/output.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/tests/polsby_popper.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/tests/population_polygon.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/tests/region.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/tests/region_tally.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/tests/reock.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/tests/schwartzberg.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/tests/state_clipped_convex_hull_ratio.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/tests/stream.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/tests/support.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/tests/tally.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/tests/twodelta.rs +0 -0
- {gerrytools-2.0.1 → gerrytools-2.0.3}/rust/src/tests/unit_hulls.rs +0 -0
|
@@ -77,10 +77,18 @@ def _validated_geometry_frame(
|
|
|
77
77
|
"""Transform and validate a geometry frame whose rows are already aligned."""
|
|
78
78
|
if frame.crs is None:
|
|
79
79
|
raise ValueError("geometries must have a CRS")
|
|
80
|
+
_require_valid_polygons(frame, "geometries")
|
|
81
|
+
if crs is None and frame.crs.is_geographic:
|
|
82
|
+
try:
|
|
83
|
+
crs = frame.estimate_utm_crs()
|
|
84
|
+
except (RuntimeError, ValueError) as error:
|
|
85
|
+
raise ValueError(
|
|
86
|
+
"Cannot determine a UTM CRS; supply an explicit projected CRS"
|
|
87
|
+
) from error
|
|
80
88
|
if crs is not None:
|
|
81
89
|
frame = frame.to_crs(crs)
|
|
90
|
+
_require_valid_polygons(frame, "geometries")
|
|
82
91
|
_require_projected_crs(frame, "geometry scoring")
|
|
83
|
-
_require_valid_polygons(frame, "geometries")
|
|
84
92
|
return frame
|
|
85
93
|
|
|
86
94
|
|
|
@@ -103,7 +111,8 @@ def aligned_geodataframe(
|
|
|
103
111
|
geometries (gpd.GeoDataFrame): One geometry row per graph node.
|
|
104
112
|
node_column (str | None): Optional column containing graph node identifiers.
|
|
105
113
|
crs (Any | None): Optional projected CRS to which the geometries are transformed. Without
|
|
106
|
-
this argument,
|
|
114
|
+
this argument, geographic input is projected to an estimated UTM CRS; projected input
|
|
115
|
+
retains its CRS.
|
|
107
116
|
|
|
108
117
|
Returns:
|
|
109
118
|
gpd.GeoDataFrame: An aligned copy of ``geometries``.
|
|
@@ -111,7 +120,8 @@ def aligned_geodataframe(
|
|
|
111
120
|
Raises:
|
|
112
121
|
TypeError: If ``geometries`` is not a GeoDataFrame.
|
|
113
122
|
ValueError: If identifiers are missing, duplicated, or do not match the node set; if CRS
|
|
114
|
-
information is absent or
|
|
123
|
+
information is absent or no projected CRS can be determined; or if a geometry is
|
|
124
|
+
missing, empty, or invalid.
|
|
115
125
|
"""
|
|
116
126
|
if not isinstance(geometries, gpd.GeoDataFrame):
|
|
117
127
|
raise TypeError("geometries must be a GeoDataFrame")
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
3
|
import codecs
|
|
4
|
+
import errno
|
|
4
5
|
import hashlib
|
|
5
6
|
import json
|
|
6
7
|
import logging
|
|
@@ -9,18 +10,19 @@ import sys
|
|
|
9
10
|
import tempfile
|
|
10
11
|
import warnings
|
|
11
12
|
from abc import ABC, abstractmethod
|
|
12
|
-
from collections.abc import Callable, Mapping
|
|
13
|
+
from collections.abc import Callable, Generator, Mapping
|
|
13
14
|
from contextlib import contextmanager
|
|
14
15
|
from pathlib import Path, PureWindowsPath
|
|
15
16
|
from types import TracebackType
|
|
16
|
-
from typing import ClassVar, Generic,
|
|
17
|
+
from typing import ClassVar, Generic, Protocol, TypeVar, cast, runtime_checkable
|
|
17
18
|
|
|
18
19
|
import docker.errors
|
|
20
|
+
from docker.types.daemon import CancellableStream
|
|
19
21
|
from gerrychain import Graph, Partition
|
|
20
22
|
|
|
21
23
|
logger = logging.getLogger(__name__)
|
|
22
24
|
|
|
23
|
-
DEFAULT_DOCKER_IMAGE = "mgggdev/replicate:v2.0.
|
|
25
|
+
DEFAULT_DOCKER_IMAGE = "mgggdev/replicate:v2.0.3@sha256:fe03dd8c70e72e15d50410317892c32a6b04e1d254d0a4af6f16b4a10d14768f"
|
|
24
26
|
|
|
25
27
|
BINARY_WRITERS = ("pcompress", "ben", "bendl")
|
|
26
28
|
"""Writers whose output cannot be decoded from a console stream."""
|
|
@@ -82,7 +84,7 @@ def _partial_output_path(output: Path) -> Path:
|
|
|
82
84
|
|
|
83
85
|
|
|
84
86
|
@contextmanager
|
|
85
|
-
def _preserve_outputs_on_failure(expected_files: list[str]) ->
|
|
87
|
+
def _preserve_outputs_on_failure(expected_files: list[str]) -> Generator[None, None, None]:
|
|
86
88
|
"""Hide old outputs during a rerun and preserve failed output under partial names."""
|
|
87
89
|
outputs = [Path(output) for output in expected_files]
|
|
88
90
|
backup_dirs: dict[Path, Path] = {}
|
|
@@ -149,7 +151,7 @@ def _preserve_outputs_on_failure(expected_files: list[str]) -> Iterator[None]:
|
|
|
149
151
|
|
|
150
152
|
|
|
151
153
|
@contextmanager
|
|
152
|
-
def _preserve_log_on_failure(log_file: str) ->
|
|
154
|
+
def _preserve_log_on_failure(log_file: str) -> Generator[None, None, None]:
|
|
153
155
|
"""Back up an existing log during a rerun and restore it if the rerun fails.
|
|
154
156
|
|
|
155
157
|
Unlike outputs, a failed run's fresh log is kept when there was no previous log to
|
|
@@ -729,14 +731,55 @@ class RunnerSession(Generic[RunSpecT]):
|
|
|
729
731
|
raise RuntimeError("Could not stop the abandoned streamed engine command.") from error
|
|
730
732
|
self.container = None
|
|
731
733
|
|
|
734
|
+
@staticmethod
|
|
735
|
+
def _close_exec_stream(stream: object) -> None:
|
|
736
|
+
"""Close the stream even if Docker's socket shutdown finds it disconnected."""
|
|
737
|
+
close = getattr(stream, "close", None)
|
|
738
|
+
if close is None:
|
|
739
|
+
return
|
|
740
|
+
|
|
741
|
+
try:
|
|
742
|
+
close()
|
|
743
|
+
except OSError as error:
|
|
744
|
+
if error.errno != errno.ENOTCONN:
|
|
745
|
+
raise
|
|
746
|
+
else:
|
|
747
|
+
return
|
|
748
|
+
|
|
749
|
+
if isinstance(stream, CancellableStream):
|
|
750
|
+
RunnerSession._close_disconnected_docker_stream(stream)
|
|
751
|
+
|
|
752
|
+
@staticmethod
|
|
753
|
+
def _close_disconnected_docker_stream(stream: CancellableStream) -> None:
|
|
754
|
+
"""Release Docker's response even when its private socket layout is unfamiliar."""
|
|
755
|
+
# Docker's failed shutdown skips socket.close(); release both owners.
|
|
756
|
+
# NOTE: This uses a private SDK socket layout; revisit if/when Docker fixes close().
|
|
757
|
+
response = getattr(stream, "_response", None)
|
|
758
|
+
if response is None:
|
|
759
|
+
raise RuntimeError("Docker exec stream response is unavailable; cannot finish cleanup.")
|
|
760
|
+
|
|
761
|
+
try:
|
|
762
|
+
try:
|
|
763
|
+
socket_file = response.raw._fp.fp
|
|
764
|
+
raw_socket_file = getattr(socket_file, "raw", socket_file)
|
|
765
|
+
response_socket = getattr(raw_socket_file, "sock", None)
|
|
766
|
+
if response_socket is None:
|
|
767
|
+
response_socket = raw_socket_file._sock
|
|
768
|
+
except AttributeError as error:
|
|
769
|
+
raise RuntimeError(
|
|
770
|
+
"Docker exec stream socket layout has changed; cannot finish socket cleanup."
|
|
771
|
+
) from error
|
|
772
|
+
|
|
773
|
+
response_socket.close()
|
|
774
|
+
finally:
|
|
775
|
+
response.close()
|
|
776
|
+
|
|
732
777
|
def _cleanup_exec_stream(self, stream: object, *, completed: bool) -> None:
|
|
733
778
|
"""Close a Docker exec stream and stop its container if consumption failed."""
|
|
734
779
|
primary_error = sys.exception()
|
|
735
780
|
cleanup_errors: list[Exception] = []
|
|
736
|
-
close = getattr(stream, "close", None)
|
|
737
781
|
try:
|
|
738
|
-
|
|
739
|
-
close()
|
|
782
|
+
self._close_exec_stream(stream)
|
|
740
783
|
except Exception as error:
|
|
741
784
|
cleanup_errors.append(error)
|
|
742
785
|
if not completed:
|
|
@@ -16,6 +16,7 @@ from typing import Generic, Literal, Sequence, TypeVar
|
|
|
16
16
|
import matplotlib
|
|
17
17
|
from matplotlib.axes import Axes
|
|
18
18
|
from matplotlib.text import Text
|
|
19
|
+
from matplotlib.ticker import Formatter
|
|
19
20
|
|
|
20
21
|
from gerrytools.colors import resolve_rgba
|
|
21
22
|
from gerrytools.plotting._axes_backed import deferred_axis_update
|
|
@@ -201,6 +202,21 @@ class _TitleText(_ManagedText[TitleStyle]):
|
|
|
201
202
|
return _title_snapshot(ax)
|
|
202
203
|
|
|
203
204
|
|
|
205
|
+
class _PositionLabelFormatter(Formatter):
|
|
206
|
+
"""Labels tied to fixed locations, retaining the formatter they displaced on this axis."""
|
|
207
|
+
|
|
208
|
+
def __init__(
|
|
209
|
+
self, owner: _AxisState, previous: Formatter, locations: list[float], labels: list[str]
|
|
210
|
+
) -> None:
|
|
211
|
+
super().__init__()
|
|
212
|
+
self.owner = owner
|
|
213
|
+
self.previous = previous
|
|
214
|
+
self._labels = dict(zip(locations, labels, strict=True))
|
|
215
|
+
|
|
216
|
+
def __call__(self, x: float, pos: int | None = None) -> str:
|
|
217
|
+
return self._labels.get(x, "")
|
|
218
|
+
|
|
219
|
+
|
|
204
220
|
class _AxisState:
|
|
205
221
|
"""One axis's managed configuration plus x/y-dispatching matplotlib accessors."""
|
|
206
222
|
|
|
@@ -227,7 +243,20 @@ class _AxisState:
|
|
|
227
243
|
(ax.set_xticks if self.axis == "x" else ax.set_yticks)(locations)
|
|
228
244
|
|
|
229
245
|
def set_ticklabels(self, ax: Axes, labels: list[str]) -> None:
|
|
230
|
-
|
|
246
|
+
axis = ax.xaxis if self.axis == "x" else ax.yaxis
|
|
247
|
+
previous = axis.get_major_formatter()
|
|
248
|
+
if isinstance(previous, _PositionLabelFormatter) and previous.owner is self:
|
|
249
|
+
previous = previous.previous
|
|
250
|
+
|
|
251
|
+
axis.set_major_formatter(
|
|
252
|
+
_PositionLabelFormatter(self, previous, self.get_ticks(ax), labels)
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
def restore_tick_formatter(self, ax: Axes) -> None:
|
|
256
|
+
axis = ax.xaxis if self.axis == "x" else ax.yaxis
|
|
257
|
+
current = axis.get_major_formatter()
|
|
258
|
+
if isinstance(current, _PositionLabelFormatter) and current.owner is self:
|
|
259
|
+
axis.set_major_formatter(current.previous)
|
|
231
260
|
|
|
232
261
|
def get_ticks(self, ax: Axes) -> list[float]:
|
|
233
262
|
ticks = ax.get_xticks() if self.axis == "x" else ax.get_yticks()
|
|
@@ -593,10 +622,13 @@ class _AxisApiMixin(_TitleApiMixin):
|
|
|
593
622
|
if tick_locations is None:
|
|
594
623
|
# Matplotlib will compute labels from the locator at draw time; nothing to apply.
|
|
595
624
|
return
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
625
|
+
default_labels = (
|
|
626
|
+
self._default_x_tick_labels(tick_locations) if axis.axis == "x" else None
|
|
627
|
+
)
|
|
628
|
+
if default_labels is None:
|
|
629
|
+
axis.restore_tick_formatter(self._ax)
|
|
630
|
+
else:
|
|
631
|
+
axis.set_ticklabels(self._ax, list(default_labels))
|
|
600
632
|
return
|
|
601
633
|
if tick_locations is None:
|
|
602
634
|
tick_locations = axis.get_ticks(self._ax)
|
|
@@ -229,7 +229,7 @@ class BarPlot(CategoricalDistributionPlotBase):
|
|
|
229
229
|
uniques, counts = np.unique(vals, return_counts=True)
|
|
230
230
|
# Default :g formatting can merge values beyond six significant digits.
|
|
231
231
|
heights_dict = {
|
|
232
|
-
np.format_float_positional(unique_value, trim="-"): float(count)
|
|
232
|
+
np.format_float_positional(float(unique_value), trim="-"): float(count)
|
|
233
233
|
for unique_value, count in zip(uniques, counts, strict=True)
|
|
234
234
|
}
|
|
235
235
|
self._add_bar_set(
|
|
@@ -176,6 +176,7 @@ class Histogram(GerryPlotBase):
|
|
|
176
176
|
self._show_warnings = True
|
|
177
177
|
self._bins: BinsType | None = None
|
|
178
178
|
self._bin_alignment = "edge"
|
|
179
|
+
self._bin_center_ticks: list[float] | None = None
|
|
179
180
|
self._as_density_plot = False
|
|
180
181
|
self._binwidth: float | None = None
|
|
181
182
|
|
|
@@ -204,16 +205,46 @@ class Histogram(GerryPlotBase):
|
|
|
204
205
|
|
|
205
206
|
@deferred_axis_update
|
|
206
207
|
def center_bars(self) -> None:
|
|
207
|
-
"""Center histogram
|
|
208
|
+
"""Center the histogram bars according to the bin specification.
|
|
209
|
+
|
|
210
|
+
With :meth:`set_bin_widths`, the first bin is centered on the minimum across all datasets.
|
|
211
|
+
Successive centers are one bin width apart. Each bin includes its left edge and excludes
|
|
212
|
+
its right edge. For example, with width 1, the values ``[1, 1.5, 2]`` give counts of
|
|
213
|
+
1 at center 1 and 2 at center 2.
|
|
214
|
+
|
|
215
|
+
With automatic bins or :meth:`set_bins`, the bars shift half a bin width to the left
|
|
216
|
+
for display. The original edges still determine the counts. The bins must have uniform
|
|
217
|
+
widths for centering or the plot raises ``ValueError`` when drawn.
|
|
218
|
+
"""
|
|
208
219
|
self._bin_alignment = "center"
|
|
209
220
|
|
|
221
|
+
@deferred_axis_update
|
|
222
|
+
def set_xticks_at_bin_centers(self) -> None:
|
|
223
|
+
"""Place one x-axis tick at the center of each displayed bin.
|
|
224
|
+
|
|
225
|
+
Tick locations follow the bins as datasets or bin settings change. Grouped bars share
|
|
226
|
+
one tick per bin. This replaces labels tied to previous locations with the axis's own
|
|
227
|
+
formatting. Labels explicitly hidden with ``set_xticks(labels=[])`` stay hidden.
|
|
228
|
+
To label the new positions yourself, call :meth:`set_xticks` afterward with one label
|
|
229
|
+
per bin.
|
|
230
|
+
"""
|
|
231
|
+
self._bin_center_ticks = []
|
|
232
|
+
if self._xaxis.tick_labels != [] or self._xaxis.tick_locations == []:
|
|
233
|
+
self._xaxis.tick_labels = None
|
|
234
|
+
self._xaxis.tick_locations = None
|
|
235
|
+
self._axes_state.reclaim_without_value(self._xaxis.unit_ticks)
|
|
236
|
+
|
|
237
|
+
def _default_x_tick_locations(self) -> list[float] | None:
|
|
238
|
+
return self._bin_center_ticks
|
|
239
|
+
|
|
210
240
|
@deferred_axis_update
|
|
211
241
|
def set_bins(self, bins: BinsType | None) -> None:
|
|
212
242
|
"""Set the bins for the histogram.
|
|
213
243
|
|
|
214
244
|
Bins can be specified either as an array of bin edges, an integer number of bins,
|
|
215
|
-
or a string (e.g., 'auto') to use
|
|
216
|
-
|
|
245
|
+
or a string (e.g., 'auto') to use NumPy's histogram binning strategies. Adjacent edges
|
|
246
|
+
define one bin. Each bin includes its left edge, and the final bin also includes its
|
|
247
|
+
right edge. NumPy supports the following strategies.
|
|
217
248
|
|
|
218
249
|
- ‘auto’: Minimum bin width between the ‘sturges’ and ‘fd’ estimators. Provides good
|
|
219
250
|
all-around performance.
|
|
@@ -252,8 +283,11 @@ class Histogram(GerryPlotBase):
|
|
|
252
283
|
def set_bin_widths(self, binwidth: float | None) -> None:
|
|
253
284
|
"""Set histogram bins by specifying a fixed bin width.
|
|
254
285
|
|
|
255
|
-
The
|
|
256
|
-
|
|
286
|
+
The bins start at the minimum across all datasets. Calling :meth:`center_bars` places
|
|
287
|
+
the first bin's center at that minimum instead. In either alignment, a bin includes
|
|
288
|
+
its left edge and excludes its right edge. The final edge is above the maximum so every
|
|
289
|
+
observation falls in a bin. If the width is too small to distinguish adjacent edges at the
|
|
290
|
+
scale of the data, the plot raises ``ValueError`` when drawn.
|
|
257
291
|
|
|
258
292
|
Args:
|
|
259
293
|
binwidth (float | None): Desired width of each histogram bin. If None, the
|
|
@@ -531,43 +565,52 @@ class Histogram(GerryPlotBase):
|
|
|
531
565
|
|
|
532
566
|
def _compute_bins(self) -> NDArray[np.float64]:
|
|
533
567
|
"""Compute histogram bins based on current settings and data."""
|
|
534
|
-
bins = self._bins
|
|
535
|
-
if bins is None and self._binwidth is None:
|
|
536
|
-
bins = "auto"
|
|
537
|
-
|
|
538
568
|
all_values = np.concatenate(
|
|
539
569
|
[hdata.values for hdata in chain(*self._hist_data_dict.values())]
|
|
540
570
|
)
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
571
|
+
bin_width = self._binwidth
|
|
572
|
+
if bin_width is None:
|
|
573
|
+
bins = "auto" if self._bins is None else self._bins
|
|
574
|
+
return np.histogram_bin_edges(all_values, bins=bins)
|
|
575
|
+
|
|
576
|
+
minimum, maximum = np.min(all_values), np.max(all_values)
|
|
577
|
+
first_edge = minimum - bin_width / 2 if self._bin_alignment == "center" else minimum
|
|
578
|
+
bin_count = max(1, int(np.ceil((maximum - first_edge) / bin_width)))
|
|
579
|
+
edges = first_edge + np.arange(bin_count + 1) * bin_width
|
|
580
|
+
|
|
581
|
+
if edges[-1] <= maximum:
|
|
582
|
+
edges = np.append(edges, first_edge + (bin_count + 1) * bin_width)
|
|
583
|
+
else:
|
|
584
|
+
# The span and the edges round separately. Keep the first edge above the maximum.
|
|
585
|
+
edges = edges[: np.searchsorted(edges, maximum, side="right") + 1]
|
|
546
586
|
|
|
547
587
|
if (
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
588
|
+
not np.isfinite(edges).all()
|
|
589
|
+
or not (edges[1:] > edges[:-1]).all()
|
|
590
|
+
or edges[-1] <= maximum
|
|
591
|
+
):
|
|
592
|
+
raise ValueError("The bin width must produce distinct finite edges spanning the data.")
|
|
551
593
|
|
|
552
|
-
|
|
553
|
-
return bins
|
|
594
|
+
return edges
|
|
554
595
|
|
|
555
596
|
def _display_edges(self, bin_edges: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
556
597
|
"""Bin edges shifted to where bars are drawn.
|
|
557
598
|
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
derives its x-positions from these display edges, so the alignment mode lives here only.
|
|
599
|
+
Fixed-width bins already incorporate their alignment when their edges are computed.
|
|
600
|
+
For other bin specifications, centering shifts the drawing by half a bin width.
|
|
561
601
|
"""
|
|
562
|
-
if self._bin_alignment == "center":
|
|
602
|
+
if self._bin_alignment == "center" and self._binwidth is None:
|
|
563
603
|
return bin_edges - 0.5 * (bin_edges[1] - bin_edges[0])
|
|
564
604
|
return bin_edges
|
|
565
605
|
|
|
566
|
-
def _draw_histograms(
|
|
606
|
+
def _draw_histograms(
|
|
607
|
+
self, bin_edges: NDArray[np.float64], display_edges: NDArray[np.float64]
|
|
608
|
+
) -> NDArray[np.float64]:
|
|
567
609
|
"""Draw the histograms on the plot.
|
|
568
610
|
|
|
569
611
|
Args:
|
|
570
612
|
bin_edges (NDArray[np.float64]): Shared bin edges computed once per build.
|
|
613
|
+
display_edges (NDArray[np.float64]): X-coordinates of the drawn bin edges.
|
|
571
614
|
|
|
572
615
|
Returns:
|
|
573
616
|
NDArray[np.float64]: Per-bin maximum bar-top heights across every series (stacked tops
|
|
@@ -580,7 +623,6 @@ class Histogram(GerryPlotBase):
|
|
|
580
623
|
raise ValueError(
|
|
581
624
|
"Cannot center histogram data on bin edges when bin widths are not uniform."
|
|
582
625
|
)
|
|
583
|
-
display_edges = self._display_edges(bin_edges)
|
|
584
626
|
|
|
585
627
|
for histtype, histlist in self._hist_data_dict.items():
|
|
586
628
|
hist_bottoms = np.zeros(len(bin_edges) - 1)
|
|
@@ -675,7 +717,11 @@ class Histogram(GerryPlotBase):
|
|
|
675
717
|
return max_heights
|
|
676
718
|
|
|
677
719
|
def _draw_points(
|
|
678
|
-
self,
|
|
720
|
+
self,
|
|
721
|
+
bin_edges: NDArray[np.float64],
|
|
722
|
+
display_edges: NDArray[np.float64],
|
|
723
|
+
bin_centers: NDArray[np.float64],
|
|
724
|
+
max_heights: NDArray[np.float64],
|
|
679
725
|
) -> None:
|
|
680
726
|
"""Draw the points on the histogram plot.
|
|
681
727
|
|
|
@@ -684,6 +730,8 @@ class Histogram(GerryPlotBase):
|
|
|
684
730
|
|
|
685
731
|
Args:
|
|
686
732
|
bin_edges (NDArray[np.float64]): Shared bin edges computed once per build.
|
|
733
|
+
display_edges (NDArray[np.float64]): Edges used to locate a marker at its actual x-value.
|
|
734
|
+
bin_centers (NDArray[np.float64]): Display coordinates for markers snapped to a bin.
|
|
687
735
|
max_heights (NDArray[np.float64]): Per-bin maximum bar-top heights from
|
|
688
736
|
``_draw_histograms``. Mutated in place as points stack above bars.
|
|
689
737
|
"""
|
|
@@ -694,9 +742,6 @@ class Histogram(GerryPlotBase):
|
|
|
694
742
|
_recompute_data_limits(self._ax)
|
|
695
743
|
self._ax.autoscale_view()
|
|
696
744
|
|
|
697
|
-
display_edges = self._display_edges(bin_edges)
|
|
698
|
-
bin_centers = (display_edges[:-1] + display_edges[1:]) / 2.0
|
|
699
|
-
|
|
700
745
|
def clearance_data_units(clearance_pt: float, y_top: float) -> float:
|
|
701
746
|
"""Convert a point-space clearance to y-data units at ``y_top``."""
|
|
702
747
|
px = clearance_pt * self._ax.figure.dpi / 72.0
|
|
@@ -715,11 +760,14 @@ class Histogram(GerryPlotBase):
|
|
|
715
760
|
x_positions = np.array(pointlist.values)
|
|
716
761
|
y_positions = []
|
|
717
762
|
visited_indexes = set()
|
|
763
|
+
|
|
718
764
|
placement_edges = bin_edges if pointlist.centered else display_edges
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
765
|
+
bin_indices = np.searchsorted(placement_edges, pointlist.values, side="right") - 1
|
|
766
|
+
if self._binwidth is None: # NumPy includes the last edge for these bins.
|
|
767
|
+
bin_indices[pointlist.values == placement_edges[-1]] = len(max_heights) - 1
|
|
768
|
+
|
|
769
|
+
for i, index in enumerate(bin_indices):
|
|
770
|
+
bin_idx = int(index)
|
|
723
771
|
in_range = 0 <= bin_idx < len(max_heights)
|
|
724
772
|
stack_idx = bin_idx if in_range else (-1 if bin_idx < 0 else len(max_heights))
|
|
725
773
|
height = (
|
|
@@ -768,9 +816,15 @@ class Histogram(GerryPlotBase):
|
|
|
768
816
|
"""Build the histogram plot."""
|
|
769
817
|
if sum(len(lst) for lst in self._hist_data_dict.values()) == 0:
|
|
770
818
|
raise ValueError("No histogram sets added yet.")
|
|
819
|
+
|
|
771
820
|
bin_edges = self._compute_bins()
|
|
772
|
-
|
|
773
|
-
|
|
821
|
+
display_edges = self._display_edges(bin_edges)
|
|
822
|
+
bin_centers = display_edges[:-1] + np.diff(display_edges) / 2
|
|
823
|
+
if self._bin_center_ticks is not None:
|
|
824
|
+
self._bin_center_ticks = bin_centers.tolist()
|
|
825
|
+
|
|
826
|
+
max_heights = self._draw_histograms(bin_edges, display_edges)
|
|
827
|
+
self._draw_points(bin_edges, display_edges, bin_centers, max_heights)
|
|
774
828
|
|
|
775
829
|
def _dataset_legend_handles(self) -> list[LegendHandle]:
|
|
776
830
|
"""Get legend handles for the histogram sets."""
|
|
@@ -13,12 +13,13 @@ from types import MappingProxyType
|
|
|
13
13
|
from typing import Any, Literal, TypeAlias, cast
|
|
14
14
|
from weakref import WeakSet
|
|
15
15
|
|
|
16
|
+
import gerrychain
|
|
16
17
|
import networkx as nx
|
|
17
18
|
import numpy as np
|
|
18
19
|
import pandas as pd
|
|
19
20
|
from geopandas import GeoDataFrame
|
|
20
|
-
from gerrychain import Graph as GerryGraph
|
|
21
21
|
from gerrychain import Partition
|
|
22
|
+
from gerrychain.graph import FrozenGraph
|
|
22
23
|
from pyproj import CRS
|
|
23
24
|
from tqdm.auto import tqdm
|
|
24
25
|
|
|
@@ -131,14 +132,16 @@ class _ResourceCandidate:
|
|
|
131
132
|
class PlanEvaluator:
|
|
132
133
|
"""Prepare graph and geometry resources once, then evaluate plans with engine kernels.
|
|
133
134
|
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
reordered by node identifier. Arbitrary hashable district labels are
|
|
137
|
-
and restored in the result.
|
|
135
|
+
NetworkX inputs are read lazily; RustworkX-backed GerryChain inputs are copied at construction.
|
|
136
|
+
Metric columns are prepared when first required. Sequence assignments follow construction-time
|
|
137
|
+
node order; mappings are reordered by node identifier. Arbitrary hashable district labels are
|
|
138
|
+
mapped densely for Rust and restored in the result.
|
|
138
139
|
|
|
139
140
|
Args:
|
|
140
|
-
graph (nx.Graph): An undirected, simple NetworkX
|
|
141
|
-
attributes.
|
|
141
|
+
graph (nx.Graph | gerrychain.Graph | FrozenGraph): An undirected, simple NetworkX or
|
|
142
|
+
GerryChain graph containing metric attributes. RustworkX-backed GerryChain graphs
|
|
143
|
+
are copied once using original node identifiers, in internal node-index order.
|
|
144
|
+
Assignments and geometry identifiers use those original labels.
|
|
142
145
|
geometry (GeoDataFrame | None, optional): GeoDataFrame with exactly one row per graph node.
|
|
143
146
|
The whole aligned frame is authoritative for ordinary node and region columns, except
|
|
144
147
|
that its active geometry column is reserved for geometry-backed metrics. Defaults to
|
|
@@ -146,7 +149,7 @@ class PlanEvaluator:
|
|
|
146
149
|
node_id_column (str | None, optional): Geometry-frame column containing graph node
|
|
147
150
|
identifiers. Defaults to None, which uses the GeoDataFrame index.
|
|
148
151
|
target_crs (Any | None, optional): Projected CRS used by geometry-backed metrics. Defaults
|
|
149
|
-
to None, which
|
|
152
|
+
to None, which preserves projected input or estimates UTM for geographic input.
|
|
150
153
|
|
|
151
154
|
Raises:
|
|
152
155
|
ValueError: If the graph is empty, directed, a multigraph, or otherwise incompatible with
|
|
@@ -155,12 +158,13 @@ class PlanEvaluator:
|
|
|
155
158
|
|
|
156
159
|
def __init__(
|
|
157
160
|
self,
|
|
158
|
-
graph: nx.Graph,
|
|
161
|
+
graph: nx.Graph | gerrychain.Graph | FrozenGraph,
|
|
159
162
|
*,
|
|
160
163
|
geometry: GeoDataFrame | None = None,
|
|
161
164
|
node_id_column: str | None = None,
|
|
162
165
|
target_crs: Any | None = None,
|
|
163
166
|
) -> None:
|
|
167
|
+
graph = _normalize_graph(graph)
|
|
164
168
|
if graph.is_directed():
|
|
165
169
|
raise ValueError("graph must be undirected")
|
|
166
170
|
if graph.is_multigraph():
|
|
@@ -181,7 +185,7 @@ class PlanEvaluator:
|
|
|
181
185
|
self._graph = graph
|
|
182
186
|
self._geometry_source: _GeometrySource | None = None
|
|
183
187
|
self._edge_labels: frozenset[frozenset[Hashable]] | None = None
|
|
184
|
-
self._verified_partition_graphs: WeakSet[
|
|
188
|
+
self._verified_partition_graphs: WeakSet[gerrychain.Graph] = WeakSet()
|
|
185
189
|
self._metrics: list[tuple[str, _MetricBase]] = []
|
|
186
190
|
self._resources: _PreparedResources | None = None
|
|
187
191
|
self._preparing: _ResourceCandidate | None = None
|
|
@@ -223,7 +227,8 @@ class PlanEvaluator:
|
|
|
223
227
|
geometry (GeoDataFrame): Frame containing one row per graph node.
|
|
224
228
|
node_id_column (str | None, optional): Column containing graph node identifiers.
|
|
225
229
|
Defaults to None, which uses the frame index.
|
|
226
|
-
target_crs (Any | None, optional): Projected CRS for geometry metrics. Defaults to None
|
|
230
|
+
target_crs (Any | None, optional): Projected CRS for geometry metrics. Defaults to None,
|
|
231
|
+
preserving projected input or estimating UTM for geographic input.
|
|
227
232
|
|
|
228
233
|
Returns:
|
|
229
234
|
PlanEvaluator: This evaluator, for chained registration.
|
|
@@ -1093,6 +1098,10 @@ def _merge_ensemble_result(
|
|
|
1093
1098
|
installed.append(destination)
|
|
1094
1099
|
|
|
1095
1100
|
existing_manifest["metrics"] = merged
|
|
1101
|
+
if staged_result.summary.unique_plans is not None:
|
|
1102
|
+
summary = cast("dict[str, object]", existing_manifest["summary"])
|
|
1103
|
+
summary["unique_plans"] = staged_result.summary.unique_plans
|
|
1104
|
+
summary["unique_districts"] = staged_result.summary.unique_districts
|
|
1096
1105
|
_write_run_manifest(output, existing_manifest)
|
|
1097
1106
|
except BaseException:
|
|
1098
1107
|
for destination in reversed(installed):
|
|
@@ -1217,27 +1226,37 @@ def _node_order_json(node_order: tuple[Hashable, ...]) -> str | None:
|
|
|
1217
1226
|
return None
|
|
1218
1227
|
|
|
1219
1228
|
|
|
1220
|
-
def
|
|
1221
|
-
"""
|
|
1222
|
-
source
|
|
1229
|
+
def _normalize_graph(source: nx.Graph | gerrychain.Graph | FrozenGraph) -> nx.Graph:
|
|
1230
|
+
"""Normalize scoring graphs without losing original labels or parallel edges."""
|
|
1231
|
+
if isinstance(source, FrozenGraph):
|
|
1232
|
+
source = source.graph
|
|
1233
|
+
if isinstance(source, nx.Graph):
|
|
1234
|
+
return source
|
|
1235
|
+
if not isinstance(source, gerrychain.Graph):
|
|
1236
|
+
raise TypeError("graph must be a NetworkX or GerryChain graph")
|
|
1237
|
+
if source.is_nx_graph():
|
|
1238
|
+
return source.get_nx_graph()
|
|
1239
|
+
|
|
1223
1240
|
graph = nx.Graph()
|
|
1224
1241
|
internal_nodes = []
|
|
1225
1242
|
for internal in source.node_indices:
|
|
1226
1243
|
if not isinstance(internal, numbers.Integral):
|
|
1227
|
-
raise ValueError("
|
|
1244
|
+
raise ValueError("GerryChain graph must use integer internal node identifiers")
|
|
1228
1245
|
internal_nodes.append(int(internal))
|
|
1229
1246
|
for internal in sorted(internal_nodes):
|
|
1230
1247
|
original = source.original_nx_node_id_for_internal_node_id(internal)
|
|
1248
|
+
if original in graph:
|
|
1249
|
+
raise ValueError("GerryChain graph original node identifiers must be unique")
|
|
1231
1250
|
data = dict(source.node_data(internal))
|
|
1232
1251
|
data.pop("__networkx_node__", None)
|
|
1233
1252
|
graph.add_node(original, **data)
|
|
1234
1253
|
for edge in source.edge_indices:
|
|
1235
1254
|
left, right = source.get_edge_from_edge_id(edge)
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
)
|
|
1255
|
+
left = source.original_nx_node_id_for_internal_node_id(left)
|
|
1256
|
+
right = source.original_nx_node_id_for_internal_node_id(right)
|
|
1257
|
+
if graph.has_edge(left, right):
|
|
1258
|
+
raise ValueError("graph must be simple, not a multigraph")
|
|
1259
|
+
graph.add_edge(left, right, **dict(source.edge_data(edge)))
|
|
1241
1260
|
return graph
|
|
1242
1261
|
|
|
1243
1262
|
|