0
# Graph Operations
1
2
Create and manipulate geographic graphs representing electoral districts, precincts, or other geographic units. GerryChain extends NetworkX graphs with geographic capabilities and adjacency operations.
3
4
## Capabilities
5
6
### Graph Creation
7
8
Create graphs from shapefiles, GeoDataFrames, or existing NetworkX graphs with geographic data and adjacency relationships.
9
10
```python { .api }
11
class Graph:
12
@classmethod
13
def from_file(
14
cls,
15
filename: str,
16
adjacency: str = "rook"
17
) -> "Graph":
18
"""
19
Create a Graph from a shapefile or GeoJSON file.
20
21
Parameters:
22
- filename (str): Path to shapefile (.shp) or GeoJSON file
23
- adjacency (str): Adjacency type - "rook" or "queen"
24
25
Returns:
26
Graph: New graph with geographic data and adjacency edges
27
"""
28
29
@classmethod
30
def from_geodataframe(
31
cls,
32
dataframe,
33
adjacency: str = "rook"
34
) -> "Graph":
35
"""
36
Create a Graph from a GeoPandas GeoDataDF.
37
38
Parameters:
39
- dataframe (GeoDataFrame): GeoPandas dataframe with geometry
40
- adjacency (str): Adjacency type - "rook" or "queen"
41
42
Returns:
43
Graph: New graph with geographic data and adjacency edges
44
"""
45
46
@classmethod
47
def from_networkx(cls, graph) -> "Graph":
48
"""
49
Create a Graph from an existing NetworkX graph.
50
51
Parameters:
52
- graph: NetworkX graph object
53
54
Returns:
55
Graph: New GerryChain Graph wrapping the NetworkX graph
56
"""
57
58
@classmethod
59
def from_json(cls, json_file: str) -> "Graph":
60
"""
61
Load a Graph from a JSON file.
62
63
Parameters:
64
- json_file (str): Path to JSON file
65
66
Returns:
67
Graph: Loaded graph
68
"""
69
```
70
71
Usage example:
72
```python
73
from gerrychain import Graph
74
75
# From shapefile
76
graph = Graph.from_file("precincts.shp", adjacency="queen")
77
78
# From GeoDataFrame
79
import geopandas as gpd
80
gdf = gpd.read_file("districts.geojson")
81
graph = Graph.from_geodataframe(gdf, adjacency="rook")
82
```
83
84
### Data Operations
85
86
Join additional data to graph nodes and create lookup mappings for efficient data access.
87
88
```python { .api }
89
def join(self, other_dataframe, columns: List[str] = None) -> None:
90
"""
91
Join additional data to graph nodes.
92
93
Parameters:
94
- other_dataframe (DataFrame): Data to join to graph nodes
95
- columns (List[str], optional): Specific columns to join
96
97
Returns:
98
None: Modifies graph in place
99
"""
100
101
def lookup(self, key: str, target_column: str) -> Dict:
102
"""
103
Create a lookup mapping from key column to target column.
104
105
Parameters:
106
- key (str): Column name to use as lookup key
107
- target_column (str): Column name for lookup values
108
109
Returns:
110
Dict: Mapping from key values to target values
111
"""
112
113
def to_json(
114
self,
115
json_file: str,
116
*,
117
include_geometries_as_geojson: bool = False
118
) -> None:
119
"""
120
Save graph to JSON file.
121
122
Parameters:
123
- json_file (str): Path to output JSON file
124
- include_geometries_as_geojson (bool): Whether to include geometries as GeoJSON
125
126
Returns:
127
None: Saves graph to file
128
"""
129
130
def issue_warnings(self) -> None:
131
"""
132
Check graph for common issues and warn about problems.
133
134
Returns:
135
None: Prints warnings to console
136
"""
137
```
138
139
Usage example:
140
```python
141
import pandas as pd
142
143
# Join election data
144
election_data = pd.read_csv("election_results.csv")
145
graph.join(election_data, columns=["SEN18D", "SEN18R"])
146
147
# Create lookup for population by district
148
pop_lookup = graph.lookup("GEOID", "population")
149
```
150
151
### Graph Inspection
152
153
Access graph structure, node data, and adjacency relationships.
154
155
```python { .api }
156
def neighbors(self, node_id: NodeId) -> List[NodeId]:
157
"""
158
Get neighbors of a specific node.
159
160
Parameters:
161
- node_id (NodeId): ID of the node
162
163
Returns:
164
List[NodeId]: List of neighboring node IDs
165
"""
166
```
167
168
### Geographic Operations
169
170
Handle coordinate reference systems and geometric transformations for spatial analysis.
171
172
```python { .api }
173
def reprojected(geometry, crs_from: str, crs_to: str):
174
"""
175
Reproject geometric data between coordinate reference systems.
176
177
Parameters:
178
- geometry: Geometric data to reproject
179
- crs_from (str): Source CRS (e.g., "EPSG:4326")
180
- crs_to (str): Target CRS (e.g., "EPSG:3857")
181
182
Returns:
183
Reprojected geometry
184
"""
185
186
class GeometryError(Exception):
187
"""Raised when geometric operations fail."""
188
```
189
190
### Adjacency Management
191
192
Add and modify adjacency relationships between geographic units.
193
194
```python { .api }
195
def add_edges_from_file(graph: Graph, filename: str) -> None:
196
"""
197
Add adjacency edges from an external file.
198
199
Parameters:
200
- graph (Graph): Graph to modify
201
- filename (str): Path to adjacency file
202
203
Returns:
204
None: Modifies graph in place
205
"""
206
207
def neighbors_of_component(graph: Graph, component: Set[NodeId]) -> Set[NodeId]:
208
"""
209
Find all neighbors of a connected component.
210
211
Parameters:
212
- graph (Graph): The graph
213
- component (Set[NodeId]): Set of nodes forming a component
214
215
Returns:
216
Set[NodeId]: Set of neighboring nodes outside the component
217
"""
218
219
def neighbors_of_node(graph: Graph, node_id: NodeId) -> Set[NodeId]:
220
"""
221
Find neighbors of a single node.
222
223
Parameters:
224
- graph (Graph): The graph
225
- node_id (NodeId): ID of the node
226
227
Returns:
228
Set[NodeId]: Set of neighboring node IDs
229
"""
230
```
231
232
## Types
233
234
```python { .api }
235
NodeId = Union[int, str] # Graph node identifier
236
AdjacencyType = Literal["rook", "queen"] # Spatial adjacency types
237
```