MetacouplingLLM 0.1.0__py3-none-any.whl

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.
Files changed (35) hide show
  1. metacouplingllm/__init__.py +208 -0
  2. metacouplingllm/core.py +4542 -0
  3. metacouplingllm/data/Papers.zip +0 -0
  4. metacouplingllm/data/PeriTelecoupling_clean.csv +49953 -0
  5. metacouplingllm/data/PeriTelecoupling_subset.csv +11 -0
  6. metacouplingllm/data/chunk_embeddings.manifest.json +11 -0
  7. metacouplingllm/data/chunk_embeddings.npy +0 -0
  8. metacouplingllm/data/pericoupled_adm1_edge_list.csv +8291 -0
  9. metacouplingllm/data/telecoupling_literature.bib +3498 -0
  10. metacouplingllm/knowledge/__init__.py +1 -0
  11. metacouplingllm/knowledge/adm1_pericoupling.py +591 -0
  12. metacouplingllm/knowledge/citations.py +109 -0
  13. metacouplingllm/knowledge/countries.py +557 -0
  14. metacouplingllm/knowledge/examples.py +713 -0
  15. metacouplingllm/knowledge/framework.py +717 -0
  16. metacouplingllm/knowledge/literature.py +518 -0
  17. metacouplingllm/knowledge/pericoupling.py +241 -0
  18. metacouplingllm/knowledge/rag.py +1791 -0
  19. metacouplingllm/knowledge/references.py +112 -0
  20. metacouplingllm/knowledge/websearch.py +1842 -0
  21. metacouplingllm/llm/__init__.py +1 -0
  22. metacouplingllm/llm/client.py +636 -0
  23. metacouplingllm/llm/parser.py +868 -0
  24. metacouplingllm/output/__init__.py +1 -0
  25. metacouplingllm/output/formatter.py +276 -0
  26. metacouplingllm/prompts/__init__.py +1 -0
  27. metacouplingllm/prompts/builder.py +477 -0
  28. metacouplingllm/prompts/templates.py +556 -0
  29. metacouplingllm/visualization/__init__.py +114 -0
  30. metacouplingllm/visualization/adm1_map.py +884 -0
  31. metacouplingllm/visualization/worldmap.py +1372 -0
  32. metacouplingllm-0.1.0.dist-info/METADATA +440 -0
  33. metacouplingllm-0.1.0.dist-info/RECORD +35 -0
  34. metacouplingllm-0.1.0.dist-info/WHEEL +4 -0
  35. metacouplingllm-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,884 @@
1
+ """
2
+ Subnational (ADM1) map rendering for metacoupling framework analysis.
3
+
4
+ Generates choropleth maps where first-level administrative divisions (ADM1)
5
+ are color-coded by their coupling type (intracoupling, pericoupling,
6
+ telecoupling) relative to a focal ADM1 region.
7
+
8
+ Uses **geopandas** and **matplotlib** (optional dependencies). Install
9
+ with ``pip install metacoupling[viz]``.
10
+
11
+ The base map (World Bank Admin 1 GeoPackage) can be provided by the user
12
+ or auto-downloaded on first use.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import os
18
+ import urllib.request
19
+ from dataclasses import dataclass
20
+ from pathlib import Path
21
+ from typing import TYPE_CHECKING
22
+
23
+ from metacouplingllm.knowledge.adm1_pericoupling import (
24
+ get_adm1_country,
25
+ get_adm1_info,
26
+ get_adm1_neighbors,
27
+ )
28
+
29
+ if TYPE_CHECKING:
30
+ import geopandas as gpd
31
+ import matplotlib.figure
32
+ import matplotlib.pyplot as plt
33
+
34
+
35
+ # ---------------------------------------------------------------------------
36
+ # Dependency check
37
+ # ---------------------------------------------------------------------------
38
+
39
+
40
+ def _check_dependencies() -> None:
41
+ """Raise :exc:`ImportError` with install instructions if deps are missing."""
42
+ missing: list[str] = []
43
+ try:
44
+ import geopandas # noqa: F401
45
+ except ImportError:
46
+ missing.append("geopandas")
47
+ try:
48
+ import matplotlib # noqa: F401
49
+ except ImportError:
50
+ missing.append("matplotlib")
51
+ if missing:
52
+ raise ImportError(
53
+ f"Visualization requires {', '.join(missing)}. "
54
+ f"Install with: pip install metacoupling[viz]"
55
+ )
56
+
57
+
58
+ # ---------------------------------------------------------------------------
59
+ # Color scheme
60
+ # ---------------------------------------------------------------------------
61
+
62
+
63
+ @dataclass(frozen=True)
64
+ class Adm1CouplingColors:
65
+ """Color scheme for ADM1 metacoupling maps.
66
+
67
+ Override any field to customise the palette.
68
+ """
69
+
70
+ intracoupling: str = "#D4E79E" # light yellow-green (focal region)
71
+ pericoupling: str = "#4CAF50" # bright green (adjacent regions)
72
+ telecoupling: str = "#ADD8E6" # light blue (not adjacent, any country)
73
+ na: str = "#D3D3D3" # light grey (not in database)
74
+ ocean: str = "#DCEEFB" # light water blue (oceans + Caspian)
75
+ lake: str = "#4A90D9" # medium-dark blue (lakes overlay)
76
+ border: str = "#888888" # region border lines
77
+ disputed: str = "#BFBFBF" # darker grey for disputed territories
78
+ disputed_outline: str = "#4D4D4D" # darker outline so disputes stay visible
79
+ disputed_hatch: str = "///" # matplotlib hatch pattern
80
+
81
+
82
+ DEFAULT_ADM1_COLORS = Adm1CouplingColors()
83
+
84
+
85
+ # ---------------------------------------------------------------------------
86
+ # World Bank Admin 1 GeoPackage management
87
+ # ---------------------------------------------------------------------------
88
+
89
+ _WB_BOUNDARIES_RELEASE_BASE_URL = (
90
+ "https://github.com/Hanshan-XY/wb-boundaries-data/releases/download/"
91
+ "v2025-06-17"
92
+ )
93
+ _WB_ADM1_DOWNLOAD_ENV_VAR = "METACOUPLING_ADM1_DOWNLOAD_URL"
94
+ _WB_ADM1_URL = (
95
+ f"{_WB_BOUNDARIES_RELEASE_BASE_URL}/"
96
+ "World.Bank.Official.Boundaries.-.Admin.1.gpkg"
97
+ )
98
+ _WB_ADM1_FILENAMES = (
99
+ "World Bank Official Boundaries - Admin 1.gpkg",
100
+ "World.Bank.Official.Boundaries.-.Admin.1.gpkg",
101
+ "WB_GAD_ADM1.gpkg",
102
+ "wb_adm1.gpkg",
103
+ )
104
+
105
+ _WB_ADM1_DOWNLOAD_INSTRUCTIONS = (
106
+ "The World Bank Admin 1 GeoPackage is required for ADM1 maps.\n"
107
+ "Download it from:\n"
108
+ " https://github.com/Hanshan-XY/wb-boundaries-data/releases/tag/v2025-06-17\n"
109
+ "Then pass the file path:\n"
110
+ " plot_focal_adm1_map('MEX001', shapefile='path/to/Admin 1.gpkg')"
111
+ )
112
+
113
+
114
+ def _get_adm1_cache_dir() -> Path:
115
+ """Return the directory for caching the World Bank Admin 1 GeoPackage.
116
+
117
+ Respects the ``METACOUPLING_CACHE_DIR`` environment variable.
118
+ Falls back to ``~/.cache/metacoupling``.
119
+ """
120
+ env = os.environ.get("METACOUPLING_CACHE_DIR")
121
+ if env:
122
+ return Path(env) / "wb_adm1"
123
+ return Path.home() / ".cache" / "metacoupling" / "wb_adm1"
124
+
125
+
126
+ def _get_adm1_geodataframe(
127
+ shapefile: str | Path | None = None,
128
+ ) -> gpd.GeoDataFrame:
129
+ """Load an ADM1 GeoDataFrame.
130
+
131
+ Parameters
132
+ ----------
133
+ shapefile:
134
+ Path to a user-provided GeoPackage, shapefile, or GeoJSON.
135
+ If ``None``, looks for a cached copy or raises an error with
136
+ download instructions.
137
+
138
+ Returns
139
+ -------
140
+ geopandas.GeoDataFrame
141
+ ADM1 regions with normalised ``adm1_code`` and ``iso_code`` columns.
142
+ """
143
+ import geopandas as _gpd
144
+
145
+ if shapefile is not None:
146
+ # ---- User-provided shapefile ----
147
+ world = _gpd.read_file(str(shapefile))
148
+ return _normalise_adm1_columns(world)
149
+
150
+ # ---- Look for cached copy ----
151
+ cache_dir = _get_adm1_cache_dir()
152
+
153
+ # Check for common file names in the cache directory
154
+ for fname in _WB_ADM1_FILENAMES:
155
+ cached = cache_dir / fname
156
+ if cached.exists():
157
+ world = _gpd.read_file(str(cached))
158
+ return _normalise_adm1_columns(world)
159
+
160
+ # Also check for any .gpkg file in the cache directory
161
+ if cache_dir.exists():
162
+ for gpkg in cache_dir.glob("*.gpkg"):
163
+ world = _gpd.read_file(str(gpkg))
164
+ return _normalise_adm1_columns(world)
165
+
166
+ downloaded = _download_adm1_geopackage()
167
+ if downloaded is not None and downloaded.exists():
168
+ world = _gpd.read_file(str(downloaded))
169
+ return _normalise_adm1_columns(world)
170
+
171
+ # ---- No cached file found ----
172
+ raise FileNotFoundError(
173
+ f"No World Bank Admin 1 GeoPackage found in cache "
174
+ f"({cache_dir}).\n\n{_WB_ADM1_DOWNLOAD_INSTRUCTIONS}"
175
+ )
176
+
177
+
178
+ def _download_adm1_geopackage() -> Path | None:
179
+ """Download and cache the default ADM1 GeoPackage."""
180
+ cache_dir = _get_adm1_cache_dir()
181
+ cache_dir.mkdir(parents=True, exist_ok=True)
182
+
183
+ download_url = os.environ.get(_WB_ADM1_DOWNLOAD_ENV_VAR, _WB_ADM1_URL)
184
+ filename = (
185
+ Path(download_url).name
186
+ or "World.Bank.Official.Boundaries.-.Admin.1.gpkg"
187
+ )
188
+ target = cache_dir / filename
189
+
190
+ try:
191
+ if not target.exists():
192
+ urllib.request.urlretrieve(download_url, target)
193
+ return target
194
+ except Exception:
195
+ return None
196
+
197
+
198
+ def _normalise_adm1_columns(world: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
199
+ """Normalise column names in the ADM1 GeoDataFrame.
200
+
201
+ Ensures the result has ``adm1_code`` and ``iso_code`` columns.
202
+ """
203
+ # Normalise ADM1 code column
204
+ if "adm1_code" not in world.columns:
205
+ if "ADM1CD_c" in world.columns:
206
+ world["adm1_code"] = world["ADM1CD_c"]
207
+ elif "ADM1_CODE" in world.columns:
208
+ world["adm1_code"] = world["ADM1_CODE"]
209
+ else:
210
+ raise ValueError(
211
+ "ADM1 shapefile must contain an 'ADM1CD_c' or "
212
+ "'adm1_code' column with ADM1 region codes."
213
+ )
214
+
215
+ # Normalise country ISO code column
216
+ if "iso_code" not in world.columns:
217
+ if "ISO_A3" in world.columns:
218
+ world["iso_code"] = world["ISO_A3"]
219
+ elif "ISO_A3_EH" in world.columns:
220
+ world["iso_code"] = world["ISO_A3_EH"]
221
+ else:
222
+ raise ValueError(
223
+ "ADM1 shapefile must contain an 'ISO_A3' or "
224
+ "'iso_code' column with ISO alpha-3 country codes."
225
+ )
226
+
227
+ return world
228
+
229
+
230
+ # ---------------------------------------------------------------------------
231
+ # ADM1 classification
232
+ # ---------------------------------------------------------------------------
233
+
234
+
235
+ def _classify_adm1(
236
+ focal_code: str,
237
+ focal_country: str,
238
+ neighbor_codes: set[str],
239
+ shapefile_codes: set[str],
240
+ shapefile_countries: dict[str, str],
241
+ db_countries: set[str],
242
+ mentioned_countries: set[str] | None = None,
243
+ mentioned_adm1_codes: set[str] | None = None,
244
+ ) -> dict[str, str]:
245
+ """Classify every ADM1 region in the shapefile by coupling type.
246
+
247
+ Parameters
248
+ ----------
249
+ focal_code:
250
+ ADM1 code of the focal region.
251
+ focal_country:
252
+ ISO alpha-3 code of the focal region's country.
253
+ neighbor_codes:
254
+ ADM1 codes adjacent to the focal region (from the database).
255
+ shapefile_codes:
256
+ All ADM1 codes present in the shapefile.
257
+ shapefile_countries:
258
+ Mapping of ADM1 code → ISO alpha-3 code from the shapefile.
259
+ db_countries:
260
+ Set of ISO alpha-3 codes that appear in the ADM1 database.
261
+ mentioned_countries:
262
+ When provided, only regions whose country is in this set (or
263
+ that are neighbors of the focal region) will be classified as
264
+ pericoupling/telecoupling. Regions belonging to countries
265
+ **not** in this set are classified as ``"na"`` (grey).
266
+ When ``None``, all DB countries are coloured (legacy behaviour).
267
+ mentioned_adm1_codes:
268
+ When provided, strict ADM1-level filtering is used for regions
269
+ in the focal country: only regions in this set are coloured
270
+ (pericoupling if a DB neighbor, telecoupling otherwise). All
271
+ other focal-country regions become ``"na"``. Regions in other
272
+ countries fall back to the country-level ``mentioned_countries``
273
+ filter. When ``None``, all DB neighbors are coloured
274
+ pericoupling regardless of whether they appear in the analysis.
275
+
276
+ Returns
277
+ -------
278
+ ``{adm1_code: "intracoupling"|"pericoupling"|"telecoupling"|"na"}``
279
+ """
280
+ classification: dict[str, str] = {}
281
+ for code in shapefile_codes:
282
+ if code == focal_code:
283
+ classification[code] = "intracoupling"
284
+ continue
285
+
286
+ region_country = shapefile_countries.get(code)
287
+
288
+ # STRICT MODE: when mentioned_adm1_codes is provided, apply
289
+ # the substantive-evidence filter to ALL regions, including
290
+ # cross-border DB neighbors. This prevents the LLM-hint-echo
291
+ # problem where a DB neighbor (e.g., Santa Cruz, Bolivia)
292
+ # gets coloured pericoupling even though the LLM has no
293
+ # substantive evidence of actual interaction.
294
+ if mentioned_adm1_codes is not None:
295
+ if code in mentioned_adm1_codes:
296
+ if code in neighbor_codes:
297
+ classification[code] = "pericoupling"
298
+ else:
299
+ # Mentioned but not a DB neighbor — could be same
300
+ # country (non-adjacent) or a different country.
301
+ classification[code] = "telecoupling"
302
+ else:
303
+ # Not mentioned. If the region's country is a
304
+ # mentioned country OTHER than the focal country,
305
+ # colour it as telecoupling at the country level
306
+ # (e.g., China). All other cases — including
307
+ # non-mentioned DB neighbors like Santa Cruz —
308
+ # become NA.
309
+ if (
310
+ mentioned_countries is not None
311
+ and region_country is not None
312
+ and region_country != focal_country
313
+ and region_country in mentioned_countries
314
+ ):
315
+ classification[code] = "telecoupling"
316
+ else:
317
+ classification[code] = "na"
318
+ continue
319
+
320
+ # LEGACY MODE: mentioned_adm1_codes is None — old behaviour
321
+ # (all DB neighbors coloured pericoupling regardless of
322
+ # analysis content).
323
+ if code in neighbor_codes:
324
+ classification[code] = "pericoupling"
325
+ elif mentioned_countries is not None:
326
+ # Analysis-driven mode: only color countries mentioned in analysis
327
+ if region_country and region_country in mentioned_countries:
328
+ classification[code] = "telecoupling"
329
+ else:
330
+ classification[code] = "na"
331
+ elif (
332
+ region_country == focal_country
333
+ or region_country in db_countries
334
+ ):
335
+ classification[code] = "telecoupling"
336
+ else:
337
+ classification[code] = "na"
338
+ return classification
339
+
340
+
341
+ # ---------------------------------------------------------------------------
342
+ # Map rendering
343
+ # ---------------------------------------------------------------------------
344
+
345
+
346
+ def _select_adm1_detail_countries(
347
+ focal_country: str,
348
+ neighbor_codes: set[str],
349
+ shapefile_countries: dict[str, str],
350
+ ) -> set[str]:
351
+ """Return countries that should retain ADM1 detail on the map.
352
+
353
+ ADM1 detail is reserved for the focal country and any countries that
354
+ contain pericoupled neighbor regions. Telecoupled countries that are
355
+ only referenced at country scale are rendered as dissolved country
356
+ polygons instead of full subnational mosaics.
357
+ """
358
+ detail_countries: set[str] = {focal_country}
359
+ for code in neighbor_codes:
360
+ iso = shapefile_countries.get(code)
361
+ if iso:
362
+ detail_countries.add(iso)
363
+ return detail_countries
364
+
365
+
366
+ def _dissolve_country_layer(
367
+ country_layer_raw: gpd.GeoDataFrame,
368
+ color_map: dict[str, str],
369
+ ) -> gpd.GeoDataFrame | None:
370
+ """Dissolve ADM1 regions to country polygons while preserving color.
371
+
372
+ Countries collapsed out of ADM1 detail should still keep their coupling
373
+ color on the map, so this helper aggregates the geometries and assigns
374
+ each dissolved country a single coupling class.
375
+ """
376
+ if len(country_layer_raw) == 0:
377
+ return None
378
+
379
+ coupling_priority = {
380
+ "na": 0,
381
+ "telecoupling": 1,
382
+ "pericoupling": 2,
383
+ "intracoupling": 3,
384
+ }
385
+ country_coupling: dict[str, str] = {}
386
+ for iso_code, group in country_layer_raw.groupby("iso_code"):
387
+ values = [
388
+ value for value in group["coupling"].tolist()
389
+ if isinstance(value, str)
390
+ ]
391
+ if not values:
392
+ country_coupling[iso_code] = "na"
393
+ continue
394
+ country_coupling[iso_code] = max(
395
+ values,
396
+ key=lambda value: coupling_priority.get(value, -1),
397
+ )
398
+
399
+ country_layer = country_layer_raw.dissolve(
400
+ by="iso_code",
401
+ as_index=False,
402
+ aggfunc="first",
403
+ )
404
+ country_layer["coupling"] = (
405
+ country_layer["iso_code"].map(country_coupling).fillna("na")
406
+ )
407
+ country_layer["_color"] = country_layer["coupling"].map(color_map)
408
+ return country_layer
409
+
410
+
411
+ def _get_adm1_centroid(
412
+ world: gpd.GeoDataFrame,
413
+ adm1_code: str,
414
+ ) -> tuple[float, float] | None:
415
+ """Return the representative point for an ADM1 region."""
416
+ row = world.loc[world["adm1_code"] == adm1_code]
417
+ if row.empty:
418
+ return None
419
+ geom = row.geometry.values[0]
420
+ point = geom.representative_point()
421
+ return (point.x, point.y)
422
+
423
+
424
+ def _draw_mixed_flow_arrows(
425
+ ax: object,
426
+ world: gpd.GeoDataFrame,
427
+ flows: list[dict[str, str]],
428
+ *,
429
+ focal_adm1: str | None = None,
430
+ focal_country_iso: str | None = None,
431
+ ) -> list:
432
+ """Draw ADM1 domestic arrows and country-level international arrows.
433
+
434
+ When ``focal_adm1`` and ``focal_country_iso`` are provided, flow
435
+ endpoints that resolve to the focal country are substituted with
436
+ the focal ADM1 region's centroid. This way, a flow like
437
+ "Mato Grosso, Brazil → China" starts at Mato Grosso's centroid
438
+ instead of Brazil's country centroid.
439
+ """
440
+ import re
441
+
442
+ import matplotlib.patches as mpatches
443
+ from matplotlib.patches import FancyArrowPatch
444
+
445
+ from metacouplingllm.knowledge.countries import resolve_country_code
446
+ from metacouplingllm.visualization.worldmap import (
447
+ _FLOW_ARROW_COLORS,
448
+ _FLOW_ARROW_DEFAULT_COLOR,
449
+ _get_country_centroid,
450
+ _resolve_flow_endpoints,
451
+ )
452
+
453
+ drawn_categories: dict[str, str] = {}
454
+ country_gdf = world.dissolve(by="iso_code", as_index=False)
455
+
456
+ # Pre-compute the focal ADM1 centroid once (used for substitution).
457
+ focal_adm1_xy: tuple[float, float] | None = None
458
+ if focal_adm1 and focal_country_iso:
459
+ focal_adm1_xy = _get_adm1_centroid(world, focal_adm1)
460
+
461
+ def _resolve_with_focal_substitution(
462
+ flow: dict[str, str],
463
+ ) -> tuple[
464
+ tuple[float, float] | None,
465
+ tuple[float, float] | None,
466
+ bool,
467
+ ]:
468
+ """Resolve flow endpoints, substituting focal ADM1 for focal country."""
469
+ # First, get the country-level endpoints from the shared resolver.
470
+ src_xy, tgt_xy, is_bidir = _resolve_flow_endpoints(flow, country_gdf)
471
+
472
+ if focal_adm1_xy is None or focal_country_iso is None:
473
+ return src_xy, tgt_xy, is_bidir
474
+
475
+ # Re-parse the direction to identify which endpoint (if any)
476
+ # matches the focal country, so we can swap in the ADM1 centroid.
477
+ direction = flow.get("direction", "")
478
+ if not direction:
479
+ return src_xy, tgt_xy, is_bidir
480
+
481
+ cleaned = re.sub(r"[Bb]idirectional\s*\(?", "", direction)
482
+ cleaned = cleaned.rstrip(")")
483
+ parts = re.split(r"\s*(?:→|->|=>|↔|<->|<=>)\s*", cleaned)
484
+ parts = [p.strip() for p in parts if p.strip()]
485
+ if len(parts) < 2:
486
+ return src_xy, tgt_xy, is_bidir
487
+
488
+ src_name = parts[0]
489
+ tgt_name = re.sub(r"\s*\(.*\)", "", parts[1]).strip()
490
+ src_code = resolve_country_code(src_name)
491
+ tgt_code = resolve_country_code(tgt_name)
492
+
493
+ if src_code == focal_country_iso:
494
+ src_xy = focal_adm1_xy
495
+ if tgt_code == focal_country_iso:
496
+ tgt_xy = focal_adm1_xy
497
+
498
+ return src_xy, tgt_xy, is_bidir
499
+
500
+ for i, flow in enumerate(flows):
501
+ if flow.get("source_adm1") and flow.get("target_adm1"):
502
+ src_xy = _get_adm1_centroid(world, flow["source_adm1"])
503
+ tgt_xy = _get_adm1_centroid(world, flow["target_adm1"])
504
+ is_bidir = bool(flow.get("is_bidirectional"))
505
+ else:
506
+ src_xy, tgt_xy, is_bidir = _resolve_with_focal_substitution(flow)
507
+ if src_xy is None or tgt_xy is None:
508
+ continue
509
+
510
+ category = flow.get("category", "").lower()
511
+ color = _FLOW_ARROW_COLORS.get(category, _FLOW_ARROW_DEFAULT_COLOR)
512
+ cat_label = category.title() if category else "Flow"
513
+ if cat_label not in drawn_categories:
514
+ drawn_categories[cat_label] = color
515
+
516
+ is_domestic_adm1 = bool(
517
+ flow.get("source_adm1") and flow.get("target_adm1"),
518
+ )
519
+ offset = (i * 0.3) - (len(flows) * 0.15)
520
+ base_rad = 0.28 if is_domestic_adm1 else 0.15
521
+ arrow = FancyArrowPatch(
522
+ posA=src_xy,
523
+ posB=tgt_xy,
524
+ arrowstyle="->" if not is_bidir else "<->",
525
+ connectionstyle=f"arc3,rad={base_rad + offset * 0.05}",
526
+ color=color,
527
+ linewidth=2.0,
528
+ mutation_scale=15,
529
+ zorder=5,
530
+ alpha=0.8,
531
+ )
532
+ ax.add_patch(arrow)
533
+
534
+ handles = []
535
+ for cat_label, color in drawn_categories.items():
536
+ handles.append(
537
+ mpatches.Patch(
538
+ facecolor=color,
539
+ edgecolor=color,
540
+ label=f"{cat_label} Flow",
541
+ )
542
+ )
543
+ return handles
544
+
545
+
546
+ def _render_adm1_map(
547
+ world: gpd.GeoDataFrame,
548
+ classification: dict[str, str],
549
+ colors: Adm1CouplingColors,
550
+ title: str,
551
+ figsize: tuple[float, float],
552
+ db_countries: set[str],
553
+ adm1_detail_countries: set[str] | None = None,
554
+ zoom_bounds: tuple[float, float, float, float] | None = None,
555
+ flows: list[dict[str, str]] | None = None,
556
+ mentioned_countries: set[str] | None = None,
557
+ focal_adm1: str | None = None,
558
+ focal_country_iso: str | None = None,
559
+ ) -> matplotlib.figure.Figure:
560
+ """Render the classified ADM1 map.
561
+
562
+ Only countries in ``adm1_detail_countries`` are rendered at ADM1
563
+ level. All other countries are dissolved into single country-level
564
+ polygons (no internal ADM1 boundaries), while preserving their
565
+ coupling colors.
566
+
567
+ Returns a :class:`matplotlib.figure.Figure`.
568
+ """
569
+ import geopandas as _gpd
570
+ import matplotlib.patches as mpatches
571
+ import matplotlib.pyplot as _plt
572
+
573
+ fig, ax = _plt.subplots(1, 1, figsize=figsize)
574
+
575
+ # Assign coupling type and colour to each geometry
576
+ world = world.copy()
577
+ world["coupling"] = (
578
+ world["adm1_code"].map(classification).fillna("na")
579
+ )
580
+
581
+ color_map = {
582
+ "intracoupling": colors.intracoupling,
583
+ "pericoupling": colors.pericoupling,
584
+ "telecoupling": colors.telecoupling,
585
+ "na": colors.na,
586
+ }
587
+ world["_color"] = world["coupling"].map(color_map)
588
+
589
+ # Split into two layers:
590
+ # 1) Countries to show at ADM1 level (subnational boundaries)
591
+ # 2) Countries to dissolve into country-level polygons (no internal ADM1 boundaries)
592
+ if adm1_detail_countries is None:
593
+ adm1_detail_countries = set()
594
+ adm1_mask = world["iso_code"].isin(adm1_detail_countries)
595
+ adm1_layer = world[adm1_mask]
596
+ country_layer_raw = world[~adm1_mask]
597
+
598
+ # Dissolve countries outside the ADM1-detail set to country polygons.
599
+ country_layer = _dissolve_country_layer(country_layer_raw, color_map)
600
+ if country_layer is not None and len(country_layer) > 0:
601
+ country_layer.plot(
602
+ ax=ax,
603
+ color=country_layer["_color"],
604
+ edgecolor=colors.border,
605
+ linewidth=0.3,
606
+ )
607
+
608
+ # Plot ADM1-level regions on top
609
+ if len(adm1_layer) > 0:
610
+ adm1_layer.plot(
611
+ ax=ax,
612
+ color=adm1_layer["_color"],
613
+ edgecolor=colors.border,
614
+ linewidth=0.3,
615
+ )
616
+
617
+ # Overlay disputed territories with hatching using World Bank-only
618
+ # disputed / indeterminate polygons.
619
+ disputed_gdf = _get_disputed_overlay_geodataframe(world)
620
+ if disputed_gdf is not None and len(disputed_gdf) > 0:
621
+ from metacouplingllm.visualization.worldmap import _plot_disputed_overlay
622
+
623
+ _plot_disputed_overlay(ax, disputed_gdf, colors, zorder=1.5)
624
+
625
+ # Draw flow arrows. International flows stay country-level, while
626
+ # same-country nearby flows can use ADM1-to-ADM1 centroids.
627
+ # When focal_adm1 is provided, international flows touching the
628
+ # focal country anchor on the focal ADM1 centroid instead.
629
+ flow_handles: list = []
630
+ if flows:
631
+ flow_handles = _draw_mixed_flow_arrows(
632
+ ax,
633
+ world,
634
+ flows,
635
+ focal_adm1=focal_adm1,
636
+ focal_country_iso=focal_country_iso,
637
+ )
638
+
639
+ # Zoom to focal country extent if requested
640
+ if zoom_bounds is not None:
641
+ margin = 2.0 # degrees
642
+ ax.set_xlim(zoom_bounds[0] - margin, zoom_bounds[2] + margin)
643
+ ax.set_ylim(zoom_bounds[1] - margin, zoom_bounds[3] + margin)
644
+
645
+ # Legend
646
+ legend_items = [
647
+ mpatches.Patch(
648
+ facecolor=colors.na,
649
+ edgecolor="black",
650
+ label="NA",
651
+ ),
652
+ mpatches.Patch(
653
+ facecolor=colors.intracoupling,
654
+ edgecolor="black",
655
+ label="Intracoupling (Focal Region)",
656
+ ),
657
+ mpatches.Patch(
658
+ facecolor=colors.pericoupling,
659
+ edgecolor="black",
660
+ label="Pericoupling (Adjacent)",
661
+ ),
662
+ mpatches.Patch(
663
+ facecolor=colors.telecoupling,
664
+ edgecolor="black",
665
+ label="Telecoupling (Non-Adjacent)",
666
+ ),
667
+ mpatches.Patch(
668
+ facecolor=colors.disputed,
669
+ edgecolor=colors.disputed_outline,
670
+ hatch=colors.disputed_hatch * 2,
671
+ label="Disputed / Indeterminate",
672
+ ),
673
+ ]
674
+ # Add flow arrow legend items
675
+ legend_items.extend(flow_handles)
676
+
677
+ ax.legend(
678
+ handles=legend_items,
679
+ loc="lower left",
680
+ fontsize=9,
681
+ title="Categories",
682
+ title_fontsize=10,
683
+ frameon=True,
684
+ fancybox=True,
685
+ )
686
+
687
+ ax.set_title(title, fontsize=14, fontweight="bold")
688
+ ax.set_axis_off()
689
+ ax.set_facecolor(colors.ocean)
690
+ fig.patch.set_facecolor(colors.ocean)
691
+ fig.tight_layout()
692
+
693
+ return fig
694
+
695
+
696
+ def _get_disputed_overlay_geodataframe(
697
+ world: gpd.GeoDataFrame,
698
+ ) -> gpd.GeoDataFrame | None:
699
+ """Build a disputed-territory overlay for ADM1 maps.
700
+
701
+ The World Bank ADM1 GeoPackage does not always carry separate disputed
702
+ polygons such as Western Sahara or Kashmir. Reuse the World Bank
703
+ disputed-area helper so the overlay stays aligned with the World Bank
704
+ boundary sources used elsewhere in the package.
705
+ """
706
+ try:
707
+ from metacouplingllm.visualization.worldmap import (
708
+ _get_disputed_territories_overlay,
709
+ )
710
+
711
+ return _get_disputed_territories_overlay(world.crs)
712
+ except Exception:
713
+ return None
714
+
715
+
716
+ # ---------------------------------------------------------------------------
717
+ # Public API
718
+ # ---------------------------------------------------------------------------
719
+
720
+
721
+ def plot_focal_adm1_map(
722
+ focal_adm1: str,
723
+ *,
724
+ shapefile: str | Path | None = None,
725
+ title: str | None = None,
726
+ colors: Adm1CouplingColors | None = None,
727
+ figsize: tuple[float, float] = (15, 8),
728
+ zoom_to_focal: bool = False,
729
+ mentioned_countries: set[str] | None = None,
730
+ mentioned_adm1_codes: set[str] | None = None,
731
+ flows: list[dict[str, str]] | None = None,
732
+ ) -> matplotlib.figure.Figure:
733
+ """Generate a subnational map colored by coupling type relative to a focal ADM1 region.
734
+
735
+ All ADM1 regions are classified into four categories:
736
+
737
+ - **Intracoupling** (light yellow-green): the focal ADM1 region itself.
738
+ - **Pericoupling** (bright green): regions sharing a border with the
739
+ focal region.
740
+ - **Telecoupling** (light blue): distant systems linked to the focal
741
+ region. On the map, country-level telecoupled systems are usually
742
+ dissolved to country polygons rather than showing every ADM1 boundary.
743
+ - **NA** (grey): regions not in the database.
744
+
745
+ Parameters
746
+ ----------
747
+ focal_adm1:
748
+ ADM1 code of the focal region (e.g., ``"MEX001"``).
749
+ shapefile:
750
+ Path to a World Bank Admin 1 GeoPackage (``.gpkg``), shapefile,
751
+ or GeoJSON. If ``None``, looks for a cached copy in
752
+ ``~/.cache/metacoupling/wb_adm1/``. Download the GeoPackage
753
+ from https://datacatalog.worldbank.org/search/dataset/0038272 .
754
+ title:
755
+ Custom map title. Defaults to
756
+ ``"ADM1 Metacoupling Map: {Region Name} ({Country})"``.
757
+ colors:
758
+ Custom :class:`Adm1CouplingColors` instance.
759
+ figsize:
760
+ Figure size in inches ``(width, height)``.
761
+ zoom_to_focal:
762
+ If ``True``, zoom the map to show only the focal country and
763
+ its neighbors.
764
+ mentioned_countries:
765
+ When provided (typically from a parsed LLM analysis), only
766
+ regions whose country is in this set are coloured as telecoupling.
767
+ All other distant regions are grey. The focal country is always
768
+ included automatically. When ``None``, the legacy behaviour is
769
+ used (all DB countries are coloured). This controls coloring, not
770
+ which countries keep ADM1 boundary detail.
771
+ mentioned_adm1_codes:
772
+ When provided, strict ADM1-level filtering is used for regions
773
+ in the focal country: only ADM1 regions in this set are coloured
774
+ (pericoupling if a DB neighbor, telecoupling otherwise). All
775
+ other focal-country regions become grey (NA). This prevents
776
+ non-adjacent focal-country states from being incorrectly coloured
777
+ just because the focal country is in ``mentioned_countries``.
778
+ Regions in other countries still use the country-level
779
+ ``mentioned_countries`` filter.
780
+ flows:
781
+ Optional list of parsed flow dicts (from ``ParsedAnalysis.flows``).
782
+ When provided, curved arrows are drawn on the map showing the
783
+ direction of each flow between countries and, for nearby
784
+ same-country flows, between ADM1 regions.
785
+
786
+ Returns
787
+ -------
788
+ matplotlib.figure.Figure
789
+ The rendered map. Call ``fig.savefig("map.png")`` to save.
790
+
791
+ Raises
792
+ ------
793
+ ImportError
794
+ If geopandas or matplotlib are not installed.
795
+ FileNotFoundError
796
+ If no shapefile is provided and no cached copy is available.
797
+ ValueError
798
+ If *focal_adm1* is not in the ADM1 database.
799
+
800
+ Examples
801
+ --------
802
+ >>> fig = plot_focal_adm1_map(
803
+ ... "MEX001",
804
+ ... shapefile="World Bank Official Boundaries - Admin 1.gpkg",
805
+ ... )
806
+ >>> fig.savefig("mexico_adm1.png", dpi=150, bbox_inches="tight")
807
+ """
808
+ _check_dependencies()
809
+
810
+ focal_adm1 = focal_adm1.strip()
811
+
812
+ # Get info about the focal region from the database
813
+ info = get_adm1_info(focal_adm1)
814
+ if info is None:
815
+ raise ValueError(
816
+ f"ADM1 code '{focal_adm1}' is not in the pericoupling database."
817
+ )
818
+
819
+ focal_country = info["iso_a3"]
820
+
821
+ if colors is None:
822
+ colors = DEFAULT_ADM1_COLORS
823
+
824
+ if title is None:
825
+ title = (
826
+ f"ADM1 Metacoupling Map: {info['name']} ({info['country_name']})"
827
+ )
828
+
829
+ # Get neighbors from the database
830
+ neighbor_codes = get_adm1_neighbors(focal_adm1)
831
+
832
+ # Load ADM1 shapefile
833
+ world = _get_adm1_geodataframe(shapefile=shapefile)
834
+
835
+ # Build classification
836
+ shapefile_codes = set(world["adm1_code"].dropna().unique())
837
+ shapefile_countries: dict[str, str] = dict(
838
+ zip(world["adm1_code"], world["iso_code"])
839
+ )
840
+
841
+ # Collect all countries that appear in the ADM1 database
842
+ from metacouplingllm.knowledge.adm1_pericoupling import _adm1_country, _ensure_loaded
843
+
844
+ _ensure_loaded()
845
+ assert _adm1_country is not None
846
+ db_countries = set(_adm1_country.values())
847
+
848
+ # If mentioned_countries is provided, always include the focal country
849
+ if mentioned_countries is not None:
850
+ mentioned_countries = mentioned_countries | {focal_country}
851
+
852
+ classification = _classify_adm1(
853
+ focal_adm1,
854
+ focal_country,
855
+ neighbor_codes,
856
+ shapefile_codes,
857
+ shapefile_countries,
858
+ db_countries,
859
+ mentioned_countries=mentioned_countries,
860
+ mentioned_adm1_codes=mentioned_adm1_codes,
861
+ )
862
+ adm1_detail_countries = _select_adm1_detail_countries(
863
+ focal_country,
864
+ neighbor_codes,
865
+ shapefile_countries,
866
+ )
867
+
868
+ # Compute zoom bounds if requested
869
+ zoom_bounds = None
870
+ if zoom_to_focal:
871
+ focal_mask = world["iso_code"] == focal_country
872
+ if focal_mask.any():
873
+ bounds = world[focal_mask].total_bounds # [minx, miny, maxx, maxy]
874
+ zoom_bounds = (bounds[0], bounds[1], bounds[2], bounds[3])
875
+
876
+ return _render_adm1_map(
877
+ world, classification, colors, title, figsize, db_countries,
878
+ adm1_detail_countries=adm1_detail_countries,
879
+ zoom_bounds=zoom_bounds,
880
+ flows=flows,
881
+ mentioned_countries=mentioned_countries,
882
+ focal_adm1=focal_adm1,
883
+ focal_country_iso=focal_country,
884
+ )