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,1372 @@
1
+ """
2
+ World map rendering for metacoupling framework analysis.
3
+
4
+ Generates choropleth maps where countries are color-coded by their coupling
5
+ type (intracoupling, pericoupling, telecoupling) relative to a focal country.
6
+
7
+ Uses **geopandas** and **matplotlib** (optional dependencies). Install
8
+ with ``pip install metacoupling[viz]``.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ import re
15
+ import urllib.request
16
+ import zipfile
17
+ from dataclasses import dataclass
18
+ from pathlib import Path
19
+ from typing import TYPE_CHECKING
20
+
21
+ from metacouplingllm.knowledge.countries import (
22
+ ISO_ALPHA3_NAMES,
23
+ get_country_name,
24
+ resolve_country_code,
25
+ )
26
+ from metacouplingllm.knowledge.pericoupling import (
27
+ PairCouplingType,
28
+ get_pericoupled_neighbors,
29
+ lookup_pericoupling,
30
+ )
31
+
32
+ if TYPE_CHECKING:
33
+ import geopandas as gpd
34
+ import matplotlib.figure
35
+ import matplotlib.pyplot as plt
36
+
37
+ from metacouplingllm.llm.parser import ParsedAnalysis
38
+
39
+
40
+ # ---------------------------------------------------------------------------
41
+ # Dependency check
42
+ # ---------------------------------------------------------------------------
43
+
44
+
45
+ def _check_dependencies() -> None:
46
+ """Raise :exc:`ImportError` with install instructions if deps are missing."""
47
+ missing: list[str] = []
48
+ try:
49
+ import geopandas # noqa: F401
50
+ except ImportError:
51
+ missing.append("geopandas")
52
+ try:
53
+ import matplotlib # noqa: F401
54
+ except ImportError:
55
+ missing.append("matplotlib")
56
+ if missing:
57
+ raise ImportError(
58
+ f"Visualization requires {', '.join(missing)}. "
59
+ f"Install with: pip install metacoupling[viz]"
60
+ )
61
+
62
+
63
+ # ---------------------------------------------------------------------------
64
+ # Color scheme
65
+ # ---------------------------------------------------------------------------
66
+
67
+
68
+ @dataclass(frozen=True)
69
+ class CouplingColors:
70
+ """Color scheme for metacoupling world maps.
71
+
72
+ Override any field to customise the palette.
73
+ """
74
+
75
+ intracoupling: str = "#D4E79E" # light yellow-green (focal country)
76
+ pericoupling: str = "#4CAF50" # bright green (adjacent)
77
+ telecoupling: str = "#ADD8E6" # light blue (distant)
78
+ na: str = "#D3D3D3" # light grey (unknown / not in DB)
79
+ ocean: str = "#DCEEFB" # light water blue (oceans + Caspian)
80
+ lake: str = "#4A90D9" # medium-dark blue (lakes overlay)
81
+ border: str = "#888888" # country border lines
82
+ disputed: str = "#BFBFBF" # darker grey for disputed territories
83
+ disputed_outline: str = "#4D4D4D" # darker outline so disputes stay visible
84
+ disputed_hatch: str = "///" # matplotlib hatch pattern
85
+
86
+
87
+ DEFAULT_COLORS = CouplingColors()
88
+
89
+
90
+ # ---------------------------------------------------------------------------
91
+ # World Bank boundary data management
92
+ # ---------------------------------------------------------------------------
93
+
94
+ _WORLD_BANK_ADM0_ENV_VAR = "METACOUPLING_ADM0_SHAPEFILE"
95
+ _WORLD_BANK_ADM0_DOWNLOAD_ENV_VAR = "METACOUPLING_ADM0_DOWNLOAD_URL"
96
+ _WORLD_BANK_NDLSA_ENV_VAR = "METACOUPLING_NDLSA_SHAPEFILE"
97
+ _WORLD_BANK_NDLSA_DOWNLOAD_ENV_VAR = "METACOUPLING_NDLSA_DOWNLOAD_URL"
98
+ _WORLD_BANK_ADM0_FILENAMES = (
99
+ "World Bank Official Boundaries - Admin 0_all_layers.gpkg",
100
+ "World Bank Official Boundaries - Admin 0.gpkg",
101
+ "World.Bank.Official.Boundaries.-.Admin.0_all_layers.gpkg",
102
+ "World.Bank.Official.Boundaries.-.Admin.0.gpkg",
103
+ )
104
+ _WORLD_BANK_NDLSA_FILENAMES = (
105
+ "World Bank Official Boundaries - NDLSA.gpkg",
106
+ "World.Bank.Official.Boundaries.-.NDLSA.gpkg",
107
+ )
108
+ _WORLD_BANK_ADM0_SHAPEFILE_NAME = "WB_countries_Admin0_10m.shp"
109
+ _WORLD_BANK_BOUNDARIES_RELEASE_BASE_URL = (
110
+ "https://github.com/Hanshan-XY/wb-boundaries-data/releases/download/"
111
+ "v2025-06-17"
112
+ )
113
+ _WORLD_BANK_ADM0_RELEASE_URL = (
114
+ f"{_WORLD_BANK_BOUNDARIES_RELEASE_BASE_URL}/"
115
+ "World.Bank.Official.Boundaries.-.Admin.0_all_layers.gpkg"
116
+ )
117
+ _WORLD_BANK_ADM0_FALLBACK_DOWNLOAD_URL = (
118
+ "https://datacatalogfiles.worldbank.org/ddh-published/0038272/"
119
+ "DR0046659/wb_countries_admin0_10m.zip"
120
+ )
121
+ _WORLD_BANK_NDLSA_RELEASE_URL = (
122
+ f"{_WORLD_BANK_BOUNDARIES_RELEASE_BASE_URL}/"
123
+ "World.Bank.Official.Boundaries.-.NDLSA.gpkg"
124
+ )
125
+ _WORLD_BANK_ADM0_DOWNLOAD_FILENAME = (
126
+ "World.Bank.Official.Boundaries.-.Admin.0_all_layers.gpkg"
127
+ )
128
+ _WORLD_BANK_ADM0_FALLBACK_DOWNLOAD_FILENAME = "wb_countries_admin0_10m.zip"
129
+ _WORLD_BANK_NDLSA_DOWNLOAD_FILENAME = (
130
+ "World.Bank.Official.Boundaries.-.NDLSA.gpkg"
131
+ )
132
+ _WORLD_BANK_NDLSA_STATUS = "Non-determined legal status area"
133
+
134
+ # Mapping from shapefile ISO codes to this package's codes.
135
+ # The pericoupling DB sometimes uses older or non-standard codes.
136
+ _ISO_CODE_FIXES: dict[str, str] = {
137
+ "ROU": "ROM", # Romania
138
+ "COD": "ZAR", # Democratic Republic of the Congo
139
+ "TLS": "TMP", # Timor-Leste / East Timor
140
+ "SRB": "YUG", # Serbia (package uses YUG for former Yugoslavia/Serbia)
141
+ }
142
+
143
+
144
+ def _get_shapefile_cache_dir() -> Path:
145
+ """Return the directory for caching map boundary files.
146
+
147
+ Respects the ``METACOUPLING_CACHE_DIR`` environment variable.
148
+ Falls back to ``~/.cache/metacoupling``.
149
+ """
150
+ env = os.environ.get("METACOUPLING_CACHE_DIR")
151
+ if env:
152
+ return Path(env)
153
+ return Path.home() / ".cache" / "metacoupling"
154
+
155
+
156
+ def _get_adm0_cache_dir() -> Path:
157
+ """Return the cache directory for World Bank ADM0 downloads."""
158
+ return _get_shapefile_cache_dir() / "wb_adm0"
159
+
160
+
161
+ def _get_ndlsa_cache_dir() -> Path:
162
+ """Return the cache directory for World Bank NDLSA downloads."""
163
+ return _get_shapefile_cache_dir() / "wb_ndlsa"
164
+
165
+
166
+ def _iter_world_bank_ndlsa_candidates() -> list[Path]:
167
+ """Return likely local paths for a World Bank NDLSA GeoPackage."""
168
+ env_path = os.environ.get(_WORLD_BANK_NDLSA_ENV_VAR)
169
+ cache_dir = _get_shapefile_cache_dir()
170
+ ndlsa_cache_dir = _get_ndlsa_cache_dir()
171
+ cwd = Path.cwd()
172
+ search_roots = (
173
+ cwd,
174
+ cwd / "data",
175
+ cwd / "data" / "shapefiles",
176
+ Path.home() / "Downloads",
177
+ cache_dir,
178
+ cache_dir / "world_bank",
179
+ ndlsa_cache_dir,
180
+ )
181
+
182
+ candidates: list[Path] = []
183
+ if env_path:
184
+ candidates.append(Path(env_path).expanduser())
185
+
186
+ for root in search_roots:
187
+ for filename in _WORLD_BANK_NDLSA_FILENAMES:
188
+ candidates.append(root / filename)
189
+
190
+ unique: list[Path] = []
191
+ seen: set[str] = set()
192
+ for candidate in candidates:
193
+ resolved = os.path.normcase(str(candidate))
194
+ if resolved in seen:
195
+ continue
196
+ seen.add(resolved)
197
+ unique.append(candidate)
198
+ return unique
199
+
200
+
201
+ def _find_cached_world_bank_ndlsa() -> Path | None:
202
+ """Return a cached World Bank NDLSA path if available."""
203
+ cache_dir = _get_ndlsa_cache_dir()
204
+ if not cache_dir.exists():
205
+ return None
206
+
207
+ for filename in _WORLD_BANK_NDLSA_FILENAMES:
208
+ candidate = cache_dir / filename
209
+ if candidate.exists():
210
+ return candidate
211
+
212
+ generic_gpkg = next(cache_dir.rglob("*.gpkg"), None)
213
+ if generic_gpkg is not None:
214
+ return generic_gpkg
215
+
216
+ return None
217
+
218
+
219
+ def _iter_world_bank_adm0_candidates() -> list[Path]:
220
+ """Return likely local paths for a World Bank ADM0 GeoPackage."""
221
+ env_path = os.environ.get(_WORLD_BANK_ADM0_ENV_VAR)
222
+ cache_dir = _get_shapefile_cache_dir()
223
+ adm0_cache_dir = _get_adm0_cache_dir()
224
+ cwd = Path.cwd()
225
+ search_roots = (
226
+ cwd,
227
+ cwd / "data",
228
+ cwd / "data" / "shapefiles",
229
+ Path.home() / "Downloads",
230
+ cache_dir,
231
+ cache_dir / "world_bank",
232
+ adm0_cache_dir,
233
+ )
234
+
235
+ candidates: list[Path] = []
236
+ if env_path:
237
+ candidates.append(Path(env_path).expanduser())
238
+
239
+ for root in search_roots:
240
+ for filename in _WORLD_BANK_ADM0_FILENAMES:
241
+ candidates.append(root / filename)
242
+
243
+ unique: list[Path] = []
244
+ seen: set[str] = set()
245
+ for candidate in candidates:
246
+ resolved = os.path.normcase(str(candidate))
247
+ if resolved in seen:
248
+ continue
249
+ seen.add(resolved)
250
+ unique.append(candidate)
251
+ return unique
252
+
253
+
254
+ def _find_cached_world_bank_adm0() -> Path | None:
255
+ """Return a cached World Bank ADM0 basemap path if available."""
256
+ cache_dir = _get_adm0_cache_dir()
257
+ if not cache_dir.exists():
258
+ return None
259
+
260
+ for filename in _WORLD_BANK_ADM0_FILENAMES:
261
+ candidate = cache_dir / filename
262
+ if candidate.exists():
263
+ return candidate
264
+
265
+ shp_candidate = next(
266
+ cache_dir.rglob(_WORLD_BANK_ADM0_SHAPEFILE_NAME),
267
+ None,
268
+ )
269
+ if shp_candidate is not None:
270
+ return shp_candidate
271
+
272
+ generic_shp = next(cache_dir.rglob("*.shp"), None)
273
+ if generic_shp is not None:
274
+ return generic_shp
275
+
276
+ generic_gpkg = next(cache_dir.rglob("*.gpkg"), None)
277
+ if generic_gpkg is not None:
278
+ return generic_gpkg
279
+
280
+ return None
281
+
282
+
283
+ def _download_world_bank_ndlsa() -> Path | None:
284
+ """Download and cache the default World Bank NDLSA GeoPackage."""
285
+ cached = _find_cached_world_bank_ndlsa()
286
+ if cached is not None:
287
+ return cached
288
+
289
+ cache_dir = _get_ndlsa_cache_dir()
290
+ cache_dir.mkdir(parents=True, exist_ok=True)
291
+ download_url = os.environ.get(
292
+ _WORLD_BANK_NDLSA_DOWNLOAD_ENV_VAR,
293
+ _WORLD_BANK_NDLSA_RELEASE_URL,
294
+ )
295
+ filename = Path(download_url).name or _WORLD_BANK_NDLSA_DOWNLOAD_FILENAME
296
+ target_path = cache_dir / filename
297
+
298
+ try:
299
+ if not target_path.exists():
300
+ urllib.request.urlretrieve(download_url, target_path)
301
+ return target_path
302
+ except Exception:
303
+ return None
304
+
305
+
306
+ def _download_world_bank_adm0_basemap() -> Path | None:
307
+ """Download and cache the default World Bank ADM0 basemap.
308
+
309
+ The current first-run download target is the GitHub-hosted
310
+ ``Admin 0_all_layers`` GeoPackage mirror. If that fails, this falls back
311
+ to the official World Bank ``wb_countries_admin0_10m.zip`` resource.
312
+ If all download attempts fail, ``None`` is returned so the caller can
313
+ fall back gracefully.
314
+ """
315
+ cached = _find_cached_world_bank_adm0()
316
+ if cached is not None:
317
+ return cached
318
+
319
+ cache_dir = _get_adm0_cache_dir()
320
+ cache_dir.mkdir(parents=True, exist_ok=True)
321
+ override_url = os.environ.get(_WORLD_BANK_ADM0_DOWNLOAD_ENV_VAR)
322
+ sources: list[tuple[str, str]] = []
323
+ if override_url:
324
+ filename = Path(override_url).name or _WORLD_BANK_ADM0_DOWNLOAD_FILENAME
325
+ sources.append((override_url, filename))
326
+ else:
327
+ sources.extend([
328
+ (_WORLD_BANK_ADM0_RELEASE_URL, _WORLD_BANK_ADM0_DOWNLOAD_FILENAME),
329
+ (
330
+ _WORLD_BANK_ADM0_FALLBACK_DOWNLOAD_URL,
331
+ _WORLD_BANK_ADM0_FALLBACK_DOWNLOAD_FILENAME,
332
+ ),
333
+ ])
334
+
335
+ for download_url, filename in sources:
336
+ target_path = cache_dir / filename
337
+ try:
338
+ if not target_path.exists():
339
+ urllib.request.urlretrieve(download_url, target_path)
340
+
341
+ if download_url.lower().endswith(".zip"):
342
+ with zipfile.ZipFile(target_path, "r") as zf:
343
+ zf.extractall(cache_dir)
344
+
345
+ cached = _find_cached_world_bank_adm0()
346
+ if cached is not None:
347
+ return cached
348
+ except Exception:
349
+ continue
350
+
351
+ return None
352
+
353
+
354
+ def _resolve_world_basemap_path(
355
+ *,
356
+ custom_shapefile: str | Path | None = None,
357
+ adm0_shapefile: str | Path | None = None,
358
+ ) -> Path | None:
359
+ """Resolve the preferred country-level basemap path.
360
+
361
+ Resolution order:
362
+
363
+ 1. ``custom_shapefile`` for fully custom user-provided boundaries.
364
+ 2. ``adm0_shapefile`` for an explicit World Bank ADM0 file.
365
+ 3. A locally available World Bank ADM0 GeoPackage discovered in common
366
+ directories such as ``Downloads`` or the metacoupling cache.
367
+ 4. ``None`` when no World Bank ADM0 file is available locally.
368
+ """
369
+ if custom_shapefile is not None:
370
+ return Path(custom_shapefile).expanduser()
371
+
372
+ if adm0_shapefile is not None:
373
+ return Path(adm0_shapefile).expanduser()
374
+
375
+ for candidate in _iter_world_bank_adm0_candidates():
376
+ if candidate.exists():
377
+ return candidate
378
+
379
+ cached = _find_cached_world_bank_adm0()
380
+ if cached is not None:
381
+ return cached
382
+
383
+ return None
384
+
385
+
386
+ def _extract_world_bank_disputed_rows(
387
+ world: gpd.GeoDataFrame,
388
+ ) -> gpd.GeoDataFrame | None:
389
+ """Extract disputed / indeterminate rows from a World Bank layer."""
390
+ if "WB_STATUS" not in world.columns:
391
+ return None
392
+
393
+ disputed = world[
394
+ world["WB_STATUS"] == _WORLD_BANK_NDLSA_STATUS
395
+ ].copy()
396
+ if len(disputed) == 0:
397
+ return None
398
+ return disputed
399
+
400
+
401
+ def _load_world_bank_ndlsa_geodataframe() -> gpd.GeoDataFrame | None:
402
+ """Load World Bank NDLSA polygons from a local or downloaded GeoPackage."""
403
+ import geopandas as _gpd
404
+
405
+ source_path = None
406
+ for candidate in _iter_world_bank_ndlsa_candidates():
407
+ if candidate.exists():
408
+ source_path = candidate
409
+ break
410
+
411
+ if source_path is None:
412
+ source_path = _find_cached_world_bank_ndlsa()
413
+
414
+ if source_path is None:
415
+ source_path = _download_world_bank_ndlsa()
416
+
417
+ if source_path is None or not source_path.exists():
418
+ return None
419
+
420
+ try:
421
+ ndlsa = _gpd.read_file(str(source_path))
422
+ except Exception:
423
+ return None
424
+
425
+ if "iso_code" not in ndlsa.columns:
426
+ if "ISO_A3" in ndlsa.columns:
427
+ ndlsa["iso_code"] = ndlsa["ISO_A3"]
428
+ elif "ISO_A3_EH" in ndlsa.columns:
429
+ ndlsa["iso_code"] = ndlsa["ISO_A3_EH"]
430
+
431
+ if "iso_code" in ndlsa.columns:
432
+ ndlsa["iso_code"] = ndlsa["iso_code"].replace(_ISO_CODE_FIXES)
433
+
434
+ return ndlsa
435
+
436
+
437
+ def _get_world_geodataframe(
438
+ custom_shapefile: str | Path | None = None,
439
+ adm0_shapefile: str | Path | None = None,
440
+ ) -> gpd.GeoDataFrame:
441
+ """Load a world-countries GeoDataFrame.
442
+
443
+ By default, this function prefers a locally available World Bank ADM0
444
+ file (for example ``Admin 0_all_layers.gpkg`` in ``Downloads`` or the
445
+ metacoupling cache). If none is found, it tries to auto-download the
446
+ hosted ``Admin 0_all_layers`` mirror, then the official World Bank
447
+ ``wb_countries_admin0_10m.zip`` basemap into the cache. If
448
+ *custom_shapefile* or *adm0_shapefile* is provided, that file is loaded
449
+ instead.
450
+
451
+ Parameters
452
+ ----------
453
+ custom_shapefile:
454
+ Path to a user-provided shapefile (``.shp``), GeoJSON, or
455
+ GeoPackage. The file must have a column named ``ISO_A3`` or
456
+ ``iso_code`` with ISO alpha-3 country codes.
457
+ adm0_shapefile:
458
+ Path to a World Bank ADM0 GeoPackage to use for country maps.
459
+ Ignored when *custom_shapefile* is provided.
460
+
461
+ Returns
462
+ -------
463
+ geopandas.GeoDataFrame
464
+ World countries with a normalised ``iso_code`` column that matches
465
+ this package's ISO alpha-3 conventions.
466
+ """
467
+ import geopandas as _gpd
468
+
469
+ source_path = _resolve_world_basemap_path(
470
+ custom_shapefile=custom_shapefile,
471
+ adm0_shapefile=adm0_shapefile,
472
+ )
473
+
474
+ if source_path is None and custom_shapefile is None and adm0_shapefile is None:
475
+ source_path = _download_world_bank_adm0_basemap()
476
+
477
+ if source_path is None or not source_path.exists():
478
+ raise FileNotFoundError(
479
+ "Country-level maps require World Bank ADM0 boundary data. "
480
+ "metacoupling looks for a local 'Admin 0_all_layers.gpkg' and "
481
+ "then tries the hosted GitHub mirror and official World Bank "
482
+ "Admin 0 10m download."
483
+ )
484
+
485
+ world = _gpd.read_file(str(source_path))
486
+ if "iso_code" not in world.columns:
487
+ if "ISO_A3" in world.columns:
488
+ world["iso_code"] = world["ISO_A3"]
489
+ elif "ISO_A3_EH" in world.columns:
490
+ world["iso_code"] = world["ISO_A3_EH"]
491
+ else:
492
+ raise ValueError(
493
+ "Custom shapefile must contain an 'ISO_A3' or "
494
+ "'iso_code' column with ISO alpha-3 country codes."
495
+ )
496
+ world["iso_code"] = world["iso_code"].replace(_ISO_CODE_FIXES)
497
+ return world
498
+
499
+
500
+ def _get_disputed_territories_overlay(
501
+ target_crs: object | None = None,
502
+ base_world: gpd.GeoDataFrame | None = None,
503
+ ) -> gpd.GeoDataFrame | None:
504
+ """Return disputed-area polygons for map overlays.
505
+
506
+ The overlay is sourced only from World Bank data:
507
+
508
+ 1. ``base_world`` rows marked with ``WB_STATUS = Non-determined legal
509
+ status area`` when available.
510
+ 2. A local or downloaded World Bank ``NDLSA.gpkg`` file.
511
+ 3. A local or downloaded World Bank ``Admin 0_all_layers.gpkg`` file
512
+ when it contains NDLSA rows.
513
+ """
514
+ disputed = None
515
+
516
+ if base_world is not None:
517
+ disputed = _extract_world_bank_disputed_rows(base_world)
518
+
519
+ if disputed is None:
520
+ disputed = _load_world_bank_ndlsa_geodataframe()
521
+
522
+ if disputed is None:
523
+ try:
524
+ adm0_world = _get_world_geodataframe()
525
+ except Exception:
526
+ adm0_world = None
527
+ if adm0_world is not None:
528
+ disputed = _extract_world_bank_disputed_rows(adm0_world)
529
+
530
+ if disputed is None or len(disputed) == 0:
531
+ return None
532
+
533
+ if target_crs is not None and disputed.crs is not None:
534
+ try:
535
+ if disputed.crs != target_crs:
536
+ disputed = disputed.to_crs(target_crs)
537
+ except Exception:
538
+ pass
539
+
540
+ return disputed
541
+
542
+
543
+ def _plot_disputed_overlay(
544
+ ax,
545
+ disputed_gdf: gpd.GeoDataFrame | None,
546
+ colors: CouplingColors,
547
+ *,
548
+ zorder: float,
549
+ ) -> None:
550
+ """Draw disputed polygons with a visible hatch/outline overlay."""
551
+ if disputed_gdf is None or len(disputed_gdf) == 0:
552
+ return
553
+
554
+ disputed_gdf.plot(
555
+ ax=ax,
556
+ color=colors.disputed,
557
+ edgecolor="none",
558
+ alpha=0.22,
559
+ zorder=zorder,
560
+ )
561
+ disputed_gdf.plot(
562
+ ax=ax,
563
+ facecolor="none",
564
+ edgecolor=colors.disputed_outline,
565
+ hatch=colors.disputed_hatch * 2,
566
+ linewidth=0.7,
567
+ zorder=zorder + 0.05,
568
+ )
569
+
570
+
571
+ # ---------------------------------------------------------------------------
572
+ # Country classification
573
+ # ---------------------------------------------------------------------------
574
+
575
+
576
+ def _classify_countries(
577
+ focal_code: str,
578
+ pericoupled_codes: set[str],
579
+ shapefile_codes: set[str],
580
+ db_codes: set[str],
581
+ mentioned_codes: set[str] | None = None,
582
+ ) -> dict[str, str]:
583
+ """Classify every country in the shapefile by coupling type.
584
+
585
+ Parameters
586
+ ----------
587
+ focal_code:
588
+ ISO code of the focal (intracoupling) country.
589
+ pericoupled_codes:
590
+ Codes of countries pericoupled with the focal country.
591
+ shapefile_codes:
592
+ All ISO codes present in the shapefile.
593
+ db_codes:
594
+ All ISO codes known to this package (from ``ISO_ALPHA3_NAMES``).
595
+ mentioned_codes:
596
+ When provided, only countries in this set (or that are pericoupled
597
+ with the focal country) will be classified as telecoupling.
598
+ Countries not in this set are classified as ``"na"`` (grey).
599
+ When ``None``, all DB countries are coloured (legacy behaviour).
600
+
601
+ Returns
602
+ -------
603
+ ``{iso_code: "intracoupling"|"pericoupling"|"telecoupling"|"na"}``
604
+ """
605
+ classification: dict[str, str] = {}
606
+ for code in shapefile_codes:
607
+ if code == focal_code:
608
+ classification[code] = "intracoupling"
609
+ elif code in pericoupled_codes:
610
+ classification[code] = "pericoupling"
611
+ elif mentioned_codes is not None:
612
+ # Analysis-driven mode: only color countries mentioned in analysis
613
+ if code in mentioned_codes:
614
+ classification[code] = "telecoupling"
615
+ else:
616
+ classification[code] = "na"
617
+ elif code in db_codes:
618
+ classification[code] = "telecoupling"
619
+ else:
620
+ classification[code] = "na"
621
+ return classification
622
+
623
+
624
+ # ---------------------------------------------------------------------------
625
+ # Map rendering
626
+ # ---------------------------------------------------------------------------
627
+
628
+
629
+ _FLOW_ARROW_COLORS: dict[str, str] = {
630
+ "matter": "#E53935", # red
631
+ "material": "#E53935", # alias
632
+ "capital": "#1E88E5", # blue
633
+ "financial": "#1E88E5", # alias
634
+ "information": "#FDD835", # yellow
635
+ "energy": "#FB8C00", # orange
636
+ "people": "#8E24AA", # purple
637
+ "organisms": "#43A047", # green
638
+ }
639
+
640
+ _FLOW_ARROW_DEFAULT_COLOR = "#555555"
641
+
642
+
643
+ def _get_country_centroid(
644
+ world: gpd.GeoDataFrame, iso_code: str,
645
+ ) -> tuple[float, float] | None:
646
+ """Return the (x, y) centroid for a country by ISO code.
647
+
648
+ Some countries (e.g., GBR) have multiple rows in the shapefile —
649
+ one for the mainland and one for overseas territories (e.g., British
650
+ Sovereign Base Areas on Cyprus). Naively using the first row's
651
+ representative point would place the centroid on Cyprus instead of
652
+ Great Britain. We avoid this by merging all matching geometries
653
+ with ``unary_union`` and then using the representative point of the
654
+ **largest polygon** in the result.
655
+ """
656
+ rows = world.loc[world["iso_code"] == iso_code]
657
+ if rows.empty:
658
+ return None
659
+ # union_all() is the non-deprecated replacement for unary_union
660
+ # (geopandas >= 1.0). Fall back to unary_union for older versions.
661
+ if hasattr(rows.geometry, "union_all"):
662
+ combined = rows.geometry.union_all()
663
+ else:
664
+ combined = rows.geometry.unary_union
665
+ if combined.geom_type == "MultiPolygon":
666
+ # Pick the largest polygon — this is the mainland, not overseas
667
+ # territories or exclaves.
668
+ largest = max(combined.geoms, key=lambda p: p.area)
669
+ pt = largest.representative_point()
670
+ else:
671
+ pt = combined.representative_point()
672
+ return (pt.x, pt.y)
673
+
674
+
675
+ def _resolve_flow_endpoints(
676
+ flow: dict[str, str],
677
+ world: gpd.GeoDataFrame,
678
+ ) -> tuple[
679
+ tuple[float, float] | None,
680
+ tuple[float, float] | None,
681
+ bool,
682
+ ]:
683
+ """Resolve source and target centroids from a flow's direction string.
684
+
685
+ Returns ``(source_xy, target_xy, is_bidirectional)``.
686
+ """
687
+ direction = flow.get("direction", "")
688
+ if not direction:
689
+ return None, None, False
690
+
691
+ is_bidir = "bidirectional" in direction.lower() or "↔" in direction
692
+
693
+ # Extract country names from the direction string
694
+ # Patterns: "Brazil → China", "Bidirectional (Brazil ↔ China)"
695
+ # Remove "Bidirectional" wrapper
696
+ cleaned = re.sub(r"[Bb]idirectional\s*\(?", "", direction)
697
+ cleaned = cleaned.rstrip(")")
698
+
699
+ # Split on arrows
700
+ parts = re.split(r"\s*(?:→|->|=>|↔|<->|<=>)\s*", cleaned)
701
+ parts = [p.strip() for p in parts if p.strip()]
702
+
703
+ if len(parts) < 2:
704
+ return None, None, is_bidir
705
+
706
+ src_name = parts[0]
707
+ tgt_name = parts[1]
708
+
709
+ # Handle multi-target: "Brazil → China (and other importers)"
710
+ tgt_name = re.sub(r"\s*\(.*\)", "", tgt_name).strip()
711
+
712
+ src_code = resolve_country_code(src_name)
713
+ tgt_code = resolve_country_code(tgt_name)
714
+
715
+ if not src_code or not tgt_code:
716
+ return None, None, is_bidir
717
+
718
+ src_xy = _get_country_centroid(world, src_code)
719
+ tgt_xy = _get_country_centroid(world, tgt_code)
720
+
721
+ return src_xy, tgt_xy, is_bidir
722
+
723
+
724
+ def _draw_flow_arrows(
725
+ ax: object,
726
+ world: gpd.GeoDataFrame,
727
+ flows: list[dict[str, str]],
728
+ ) -> list:
729
+ """Draw curved flow arrows on the map axes.
730
+
731
+ Returns legend handles for flow categories.
732
+ """
733
+ import matplotlib.patches as mpatches
734
+ from matplotlib.patches import FancyArrowPatch
735
+
736
+ drawn_categories: dict[str, str] = {} # category → color
737
+
738
+ # Group flows by (source, target) pair so overlapping arrows between
739
+ # the same country pair are spread apart with increasing curvature.
740
+ pair_counts: dict[tuple, int] = {}
741
+
742
+ for flow in flows:
743
+ src_xy, tgt_xy, is_bidir = _resolve_flow_endpoints(flow, world)
744
+ if src_xy is None or tgt_xy is None:
745
+ continue
746
+
747
+ category = flow.get("category", "").lower()
748
+ color = _FLOW_ARROW_COLORS.get(category, _FLOW_ARROW_DEFAULT_COLOR)
749
+
750
+ # Track for legend
751
+ cat_label = category.title() if category else "Flow"
752
+ if cat_label not in drawn_categories:
753
+ drawn_categories[cat_label] = color
754
+
755
+ # Compute offset for arrows between the same country pair.
756
+ # Use a canonical key (sorted endpoints) so A→B and B→A share
757
+ # the same offset sequence but curve on opposite sides.
758
+ pair_key = (
759
+ min(src_xy, tgt_xy),
760
+ max(src_xy, tgt_xy),
761
+ )
762
+ slot = pair_counts.get(pair_key, 0)
763
+ pair_counts[pair_key] = slot + 1
764
+
765
+ # Alternate positive/negative curvature so forward and reverse
766
+ # arrows separate visually. Base radius 0.15, each additional
767
+ # arrow in the same pair adds 0.10 curvature.
768
+ base_rad = 0.15 + slot * 0.10
769
+ # Reverse arrows (tgt_xy < src_xy canonically) get negative rad
770
+ # to curve on the opposite side.
771
+ if src_xy > tgt_xy:
772
+ base_rad = -base_rad
773
+
774
+ # Draw curved arrow
775
+ arrow = FancyArrowPatch(
776
+ posA=src_xy,
777
+ posB=tgt_xy,
778
+ arrowstyle="->" if not is_bidir else "<->",
779
+ connectionstyle=f"arc3,rad={base_rad}",
780
+ color=color,
781
+ linewidth=2.0,
782
+ mutation_scale=15,
783
+ zorder=5,
784
+ alpha=0.8,
785
+ )
786
+ ax.add_patch(arrow)
787
+
788
+ # Build flow legend handles
789
+ handles = []
790
+ for cat_label, color in drawn_categories.items():
791
+ handles.append(
792
+ mpatches.FancyArrowPatch(
793
+ (0, 0), (1, 0),
794
+ arrowstyle="->",
795
+ color=color,
796
+ linewidth=2,
797
+ )
798
+ if False # placeholder — use Line2D instead for legend
799
+ else mpatches.Patch(facecolor=color, edgecolor=color, label=f"{cat_label} Flow")
800
+ )
801
+ return handles
802
+
803
+
804
+ def _render_map(
805
+ world: gpd.GeoDataFrame,
806
+ classification: dict[str, str],
807
+ colors: CouplingColors,
808
+ title: str,
809
+ figsize: tuple[float, float],
810
+ flows: list[dict[str, str]] | None = None,
811
+ ) -> matplotlib.figure.Figure:
812
+ """Render the classified world map.
813
+
814
+ Parameters
815
+ ----------
816
+ world:
817
+ World GeoDataFrame with ``iso_code`` column.
818
+ classification:
819
+ Mapping of ISO codes to coupling type.
820
+ colors:
821
+ Color scheme.
822
+ title:
823
+ Map title.
824
+ figsize:
825
+ Figure size.
826
+ flows:
827
+ Optional list of parsed flow dicts. When provided, curved arrows
828
+ are drawn on the map showing the direction of each flow.
829
+
830
+ Returns a :class:`matplotlib.figure.Figure`.
831
+ """
832
+ import matplotlib.patches as mpatches
833
+ import matplotlib.pyplot as _plt
834
+
835
+ fig, ax = _plt.subplots(1, 1, figsize=figsize)
836
+
837
+ # Assign coupling type and colour to each geometry
838
+ world = world.copy()
839
+ world["coupling"] = (
840
+ world["iso_code"].map(classification).fillna("na")
841
+ )
842
+
843
+ color_map = {
844
+ "intracoupling": colors.intracoupling,
845
+ "pericoupling": colors.pericoupling,
846
+ "telecoupling": colors.telecoupling,
847
+ "na": colors.na,
848
+ }
849
+ world["_color"] = world["coupling"].map(color_map)
850
+
851
+ # Plot all countries
852
+ world.plot(
853
+ ax=ax,
854
+ color=world["_color"],
855
+ edgecolor=colors.border,
856
+ linewidth=0.5,
857
+ )
858
+
859
+ # Overlay disputed territories with hatching using the raw disputed
860
+ # polygons so they remain visible even when the main world layer has
861
+ # been dissolved or merged.
862
+ disputed_gdf = _get_disputed_territories_overlay(world.crs, world)
863
+ _plot_disputed_overlay(ax, disputed_gdf, colors, zorder=3)
864
+
865
+ # Draw flow arrows if flows are provided
866
+ flow_handles: list = []
867
+ if flows:
868
+ flow_handles = _draw_flow_arrows(ax, world, flows)
869
+
870
+ # Legend — coupling categories
871
+ legend_items = [
872
+ mpatches.Patch(
873
+ facecolor=colors.na,
874
+ edgecolor="black",
875
+ label="NA",
876
+ ),
877
+ mpatches.Patch(
878
+ facecolor=colors.intracoupling,
879
+ edgecolor="black",
880
+ label="Intracoupling Countries",
881
+ ),
882
+ mpatches.Patch(
883
+ facecolor=colors.pericoupling,
884
+ edgecolor="black",
885
+ label="Pericoupling Countries",
886
+ ),
887
+ mpatches.Patch(
888
+ facecolor=colors.telecoupling,
889
+ edgecolor="black",
890
+ label="Telecoupling Countries",
891
+ ),
892
+ mpatches.Patch(
893
+ facecolor=colors.disputed,
894
+ edgecolor=colors.disputed_outline,
895
+ hatch=colors.disputed_hatch * 2,
896
+ label="Disputed / Indeterminate",
897
+ ),
898
+ ]
899
+
900
+ # Add flow arrow legend items
901
+ legend_items.extend(flow_handles)
902
+
903
+ ax.legend(
904
+ handles=legend_items,
905
+ loc="lower left",
906
+ fontsize=10,
907
+ title="Categories",
908
+ title_fontsize=11,
909
+ frameon=True,
910
+ fancybox=True,
911
+ )
912
+
913
+ ax.set_title(title, fontsize=14, fontweight="bold")
914
+ ax.set_axis_off()
915
+ ax.set_facecolor(colors.ocean)
916
+ fig.patch.set_facecolor(colors.ocean)
917
+ fig.tight_layout()
918
+
919
+ return fig
920
+
921
+
922
+ # ---------------------------------------------------------------------------
923
+ # Public API — Function 1: Database-only map
924
+ # ---------------------------------------------------------------------------
925
+
926
+
927
+ def plot_focal_country_map(
928
+ focal_country: str,
929
+ *,
930
+ title: str | None = None,
931
+ colors: CouplingColors | None = None,
932
+ figsize: tuple[float, float] = (15, 8),
933
+ custom_shapefile: str | Path | None = None,
934
+ adm0_shapefile: str | Path | None = None,
935
+ mentioned_countries: set[str] | None = None,
936
+ ) -> matplotlib.figure.Figure:
937
+ """Generate a world map colored by coupling type relative to a focal country.
938
+
939
+ All countries in the pericoupling database are classified:
940
+
941
+ - **Intracoupling** (light yellow-green): the focal country itself.
942
+ - **Pericoupling** (bright green): countries geographically adjacent to
943
+ the focal country according to the database.
944
+ - **Telecoupling** (light blue): countries that are in the database but
945
+ are geographically distant from the focal country.
946
+ - **NA** (grey): countries not in the database.
947
+
948
+ Parameters
949
+ ----------
950
+ focal_country:
951
+ Country name or ISO alpha-3 code (e.g., ``"Mexico"`` or ``"MEX"``).
952
+ title:
953
+ Custom map title. Defaults to ``"Metacoupling Map: {Country Name}"``.
954
+ colors:
955
+ Custom :class:`CouplingColors` instance. Defaults to the standard
956
+ metacoupling palette.
957
+ figsize:
958
+ Figure size in inches ``(width, height)``.
959
+ custom_shapefile:
960
+ Path to a user-provided shapefile (``.shp``), GeoJSON, or
961
+ GeoPackage to use instead of the default World Bank ADM0 data
962
+ source. The file must contain an ``ISO_A3`` or ``iso_code``
963
+ column. When provided, this takes precedence over
964
+ *adm0_shapefile*.
965
+ adm0_shapefile:
966
+ Path to a World Bank ADM0 GeoPackage for country maps. If omitted,
967
+ metacoupling tries to discover a local ``Admin 0_all_layers.gpkg``
968
+ automatically, then auto-downloads the hosted
969
+ ``Admin 0_all_layers`` mirror and official World Bank Admin 0 10m
970
+ basemap if needed.
971
+ mentioned_countries:
972
+ When provided (typically from a parsed LLM analysis), only
973
+ countries in this set are coloured as telecoupling.
974
+ All other distant countries are grey. The focal country is always
975
+ included automatically. When ``None``, the legacy behaviour is
976
+ used (all DB countries are coloured).
977
+
978
+ Returns
979
+ -------
980
+ matplotlib.figure.Figure
981
+ The rendered map. Call ``fig.savefig("map.png")`` to save.
982
+
983
+ Raises
984
+ ------
985
+ ImportError
986
+ If geopandas or matplotlib are not installed.
987
+ ValueError
988
+ If *focal_country* cannot be resolved to an ISO code.
989
+
990
+ Examples
991
+ --------
992
+ >>> fig = plot_focal_country_map("Mexico")
993
+ >>> fig.savefig("mexico_metacoupling.png", dpi=150, bbox_inches="tight")
994
+
995
+ >>> # Use a custom base map
996
+ >>> fig = plot_focal_country_map("China", custom_shapefile="my_countries.shp")
997
+ """
998
+ _check_dependencies()
999
+
1000
+ # Resolve focal country
1001
+ focal_code = resolve_country_code(focal_country)
1002
+ if focal_code is None:
1003
+ raise ValueError(
1004
+ f"Could not resolve '{focal_country}' to an ISO country code."
1005
+ )
1006
+
1007
+ if colors is None:
1008
+ colors = DEFAULT_COLORS
1009
+
1010
+ if title is None:
1011
+ title = f"Metacoupling Map: {get_country_name(focal_code)}"
1012
+
1013
+ # Get pericoupled neighbors from the database
1014
+ pericoupled = get_pericoupled_neighbors(focal_code)
1015
+
1016
+ # Load world shapefile
1017
+ world = _get_world_geodataframe(
1018
+ custom_shapefile=custom_shapefile,
1019
+ adm0_shapefile=adm0_shapefile,
1020
+ )
1021
+
1022
+ # Classify every country
1023
+ shapefile_codes = set(world["iso_code"].dropna().unique())
1024
+ db_codes = set(ISO_ALPHA3_NAMES.keys())
1025
+
1026
+ # If mentioned_countries is provided, always include the focal country
1027
+ if mentioned_countries is not None:
1028
+ mentioned_countries = mentioned_countries | {focal_code}
1029
+
1030
+ classification = _classify_countries(
1031
+ focal_code, pericoupled, shapefile_codes, db_codes,
1032
+ mentioned_codes=mentioned_countries
1033
+ )
1034
+
1035
+ return _render_map(world, classification, colors, title, figsize, flows=None)
1036
+
1037
+
1038
+ # ---------------------------------------------------------------------------
1039
+ # Public API — Function 2: Analysis-based map
1040
+ # ---------------------------------------------------------------------------
1041
+
1042
+
1043
+ def _extract_countries_from_analysis(
1044
+ parsed: ParsedAnalysis,
1045
+ ) -> dict[str, str | None]:
1046
+ """Extract country names from a parsed analysis and resolve their codes.
1047
+
1048
+ Returns ``{role: iso_code_or_None}`` for focal, adjacent, sending,
1049
+ receiving, and spillover. Only returns one code per role (the first
1050
+ resolved).
1051
+ """
1052
+ result: dict[str, str | None] = {}
1053
+ role_texts: dict[str, list[str]] = {
1054
+ "focal": [],
1055
+ "adjacent": [],
1056
+ "sending": [],
1057
+ "receiving": [],
1058
+ "spillover": [],
1059
+ }
1060
+ for _, section in parsed.iter_coupling_sections():
1061
+ for entry in section.systems:
1062
+ role = entry.get("role", "").strip().lower()
1063
+ scope = entry.get("system_scope", "").strip().lower()
1064
+ map_role = "adjacent" if scope == "adjacent" else role
1065
+ if map_role not in role_texts:
1066
+ continue
1067
+ for key in ("name", "geographic_scope"):
1068
+ value = entry.get(key, "")
1069
+ if value:
1070
+ role_texts[map_role].append(value)
1071
+
1072
+ for role in ("focal", "adjacent", "sending", "receiving", "spillover"):
1073
+ # Try each text for a country match
1074
+ code: str | None = None
1075
+ for text in role_texts[role]:
1076
+ code = resolve_country_code(text)
1077
+ if code:
1078
+ break
1079
+ # Scan sub-chunks
1080
+ for chunk in re.split(r"[,;/()]+", text):
1081
+ chunk = chunk.strip()
1082
+ if chunk:
1083
+ code = resolve_country_code(chunk)
1084
+ if code:
1085
+ break
1086
+ if code:
1087
+ break
1088
+ result[role] = code
1089
+
1090
+ return result
1091
+
1092
+
1093
+ def _extract_all_analysis_countries(
1094
+ parsed: ParsedAnalysis,
1095
+ ) -> dict[str, set[str]]:
1096
+ """Extract **all** country codes mentioned in the analysis per role.
1097
+
1098
+ Unlike :func:`_extract_countries_from_analysis` (one code per role),
1099
+ this function returns *all* codes found in each role's text, as well
1100
+ as countries mentioned in the coupling classification and flows.
1101
+
1102
+ Returns
1103
+ -------
1104
+ ``{role: {iso_codes}}`` where role is ``"sending"``, ``"receiving"``,
1105
+ ``"spillover"``, ``"focal"``, ``"adjacent"``, or ``"other"`` (for
1106
+ countries found outside role-specific system entries).
1107
+ """
1108
+ role_codes: dict[str, set[str]] = {
1109
+ "focal": set(),
1110
+ "adjacent": set(),
1111
+ "sending": set(),
1112
+ "receiving": set(),
1113
+ "spillover": set(),
1114
+ "other": set(),
1115
+ }
1116
+
1117
+ # --- Systems: scan all text fields for country names ---
1118
+ for _, section in parsed.iter_coupling_sections():
1119
+ for entry in section.systems:
1120
+ role = entry.get("role", "").strip().lower()
1121
+ scope = entry.get("system_scope", "").strip().lower()
1122
+ map_role = "adjacent" if scope == "adjacent" else role
1123
+ if map_role not in role_codes:
1124
+ map_role = "other"
1125
+ for key, value in entry.items():
1126
+ if key in {"role", "system_scope"}:
1127
+ continue
1128
+ if isinstance(value, str) and value:
1129
+ _scan_text_for_countries(value, role_codes[map_role])
1130
+
1131
+ # --- Flows: direction strings often contain country names ---
1132
+ for flow in parsed.iter_flow_entries():
1133
+ direction = flow.get("direction", "")
1134
+ if direction:
1135
+ _scan_text_for_countries(direction, role_codes["other"])
1136
+ desc = flow.get("description", "")
1137
+ if desc:
1138
+ _scan_text_for_countries(desc, role_codes["other"])
1139
+
1140
+ # --- Coupling classification ---
1141
+ if parsed.coupling_classification:
1142
+ _scan_text_for_countries(
1143
+ parsed.coupling_classification, role_codes["other"],
1144
+ )
1145
+
1146
+ # --- Cross-coupling interactions / research gaps / grouped content ---
1147
+ for item in parsed.cross_coupling_interactions:
1148
+ if item:
1149
+ _scan_text_for_countries(item, role_codes["other"])
1150
+ for gap in parsed.research_gaps:
1151
+ if gap:
1152
+ _scan_text_for_countries(gap, role_codes["other"])
1153
+ for kind in ("causes", "effects"):
1154
+ for _section_name, _category, item in parsed.iter_category_items(kind):
1155
+ if item:
1156
+ _scan_text_for_countries(item, role_codes["other"])
1157
+
1158
+ return role_codes
1159
+
1160
+
1161
+ def _collect_analysis_map_country_codes(
1162
+ all_role_codes: dict[str, set[str]],
1163
+ focal_code: str,
1164
+ ) -> set[str]:
1165
+ """Collect all country codes that should be colored on an analysis map.
1166
+
1167
+ Countries mentioned in sending, receiving, spillover, or other structured
1168
+ analysis sections are all retained so the figure matches the narrative more
1169
+ closely. The focal country is always included.
1170
+ """
1171
+ mentioned_codes: set[str] = {focal_code}
1172
+ for role in ("focal", "adjacent", "sending", "receiving", "spillover", "other"):
1173
+ mentioned_codes.update(all_role_codes.get(role, set()))
1174
+ return mentioned_codes
1175
+
1176
+
1177
+ def _scan_text_for_countries(text: str, codes: set[str]) -> None:
1178
+ """Scan a text string for country names and add resolved codes to *codes*."""
1179
+ # Try the full text first
1180
+ code = resolve_country_code(text)
1181
+ if code:
1182
+ codes.add(code)
1183
+
1184
+ # Split on common delimiters including arrows
1185
+ for chunk in re.split(r"[,;/()\[\]]+|→|->|=>|↔|<->|<=>", text):
1186
+ chunk = chunk.strip()
1187
+ if not chunk or len(chunk) < 3:
1188
+ continue
1189
+ code = resolve_country_code(chunk)
1190
+ if code:
1191
+ codes.add(code)
1192
+
1193
+ # Also try individual multi-word segments that might be country names
1194
+ # e.g., "Argentina, USA, and other major..." → "Argentina", "USA"
1195
+ for chunk in re.split(r"\s+and\s+|\s+or\s+", text):
1196
+ chunk = chunk.strip().rstrip(".,;:")
1197
+ if chunk:
1198
+ code = resolve_country_code(chunk)
1199
+ if code:
1200
+ codes.add(code)
1201
+
1202
+
1203
+ def plot_analysis_map(
1204
+ parsed_analysis: ParsedAnalysis,
1205
+ *,
1206
+ focal_role: str = "sending",
1207
+ title: str | None = None,
1208
+ colors: CouplingColors | None = None,
1209
+ figsize: tuple[float, float] = (15, 8),
1210
+ custom_shapefile: str | Path | None = None,
1211
+ adm0_shapefile: str | Path | None = None,
1212
+ extra_mentioned_countries: set[str] | None = None,
1213
+ mentioned_countries_override: set[str] | None = None,
1214
+ focal_code_override: str | None = None,
1215
+ flows: list[dict[str, str]] | None = None,
1216
+ ) -> matplotlib.figure.Figure:
1217
+ """Generate a world map from a parsed LLM analysis result.
1218
+
1219
+ Extracts countries from the systems identified by the LLM, then colors
1220
+ the map based on their relationship to the focal country (determined
1221
+ by *focal_role*).
1222
+
1223
+ Parameters
1224
+ ----------
1225
+ parsed_analysis:
1226
+ A :class:`~metacouplingllm.llm.parser.ParsedAnalysis` object, typically
1227
+ obtained from ``AnalysisResult.parsed``.
1228
+ focal_role:
1229
+ Which system role to treat as the focal country for coloring.
1230
+ Defaults to ``"sending"``.
1231
+ title:
1232
+ Custom map title. Defaults to ``"Metacoupling Analysis Map"``.
1233
+ colors:
1234
+ Custom :class:`CouplingColors` instance.
1235
+ figsize:
1236
+ Figure size in inches.
1237
+ custom_shapefile:
1238
+ Path to a user-provided shapefile (``.shp``), GeoJSON, or
1239
+ GeoPackage to use instead of the default World Bank ADM0 data
1240
+ source. The file must contain an ``ISO_A3`` or ``iso_code``
1241
+ column. When provided, this takes precedence over
1242
+ *adm0_shapefile*.
1243
+ adm0_shapefile:
1244
+ Path to a World Bank ADM0 GeoPackage for country maps. If omitted,
1245
+ metacoupling tries to discover a local ``Admin 0_all_layers.gpkg``
1246
+ automatically, then auto-downloads the hosted
1247
+ ``Admin 0_all_layers`` mirror and official World Bank Admin 0 10m
1248
+ basemap if needed.
1249
+ extra_mentioned_countries:
1250
+ Optional validated country codes to color in addition to those
1251
+ extracted from the parsed analysis.
1252
+ flows:
1253
+ Optional pre-resolved flow list for arrow rendering. When omitted,
1254
+ raw ``parsed_analysis.flows`` are used.
1255
+
1256
+ Returns
1257
+ -------
1258
+ matplotlib.figure.Figure
1259
+
1260
+ Raises
1261
+ ------
1262
+ ImportError
1263
+ If geopandas or matplotlib are not installed.
1264
+ ValueError
1265
+ If no countries can be extracted from the analysis.
1266
+
1267
+ Examples
1268
+ --------
1269
+ >>> result = advisor.analyze("Avocado trade between Mexico, US, Canada")
1270
+ >>> fig = plot_analysis_map(result.parsed)
1271
+ >>> fig.savefig("avocado_map.png", dpi=150, bbox_inches="tight")
1272
+ """
1273
+ _check_dependencies()
1274
+
1275
+ if colors is None:
1276
+ colors = DEFAULT_COLORS
1277
+
1278
+ # ------------------------------------------------------------------
1279
+ # When structured overrides are provided (from second LLM call),
1280
+ # skip the regex-based country extraction entirely.
1281
+ # ------------------------------------------------------------------
1282
+ if focal_code_override and mentioned_countries_override is not None:
1283
+ focal_code = focal_code_override
1284
+ mentioned_codes = set(mentioned_countries_override)
1285
+ if title is None:
1286
+ title = (
1287
+ f"Metacoupling Analysis Map: "
1288
+ f"{get_country_name(focal_code) or focal_code}"
1289
+ )
1290
+ else:
1291
+ # Legacy path: regex extraction from analysis text
1292
+ all_role_codes = _extract_all_analysis_countries(parsed_analysis)
1293
+
1294
+ focal_codes = all_role_codes.get(focal_role, set())
1295
+ if not focal_codes and focal_role == "sending":
1296
+ focal_codes = all_role_codes.get("focal", set())
1297
+ focal_code: str | None = None
1298
+
1299
+ if focal_codes:
1300
+ focal_code = sorted(focal_codes)[0]
1301
+ else:
1302
+ single = _extract_countries_from_analysis(parsed_analysis)
1303
+ focal_code = single.get(focal_role)
1304
+ if focal_code is None and focal_role == "sending":
1305
+ focal_code = single.get("focal")
1306
+
1307
+ if focal_code is None:
1308
+ for flow in parsed_analysis.iter_flow_entries():
1309
+ direction = flow.get("direction", "")
1310
+ if not direction:
1311
+ continue
1312
+ parts = re.split(r"→|->|=>|↔|<->|<=>", direction)
1313
+ if parts:
1314
+ src = re.sub(r"\([^)]*\)", "", parts[0]).strip()
1315
+ code = resolve_country_code(src)
1316
+ if code:
1317
+ focal_code = code
1318
+ break
1319
+
1320
+ if focal_code is None:
1321
+ other_codes = all_role_codes.get("other", set())
1322
+ if other_codes:
1323
+ focal_code = sorted(other_codes)[0]
1324
+
1325
+ if focal_code is None:
1326
+ raise ValueError(
1327
+ f"Could not resolve a country from the '{focal_role}' "
1328
+ f"system. Try a different focal_role or use "
1329
+ f"plot_focal_country_map() with an explicit country name."
1330
+ )
1331
+
1332
+ if title is None:
1333
+ title = (
1334
+ f"Metacoupling Analysis Map: "
1335
+ f"{get_country_name(focal_code)}"
1336
+ )
1337
+
1338
+ mentioned_codes = _collect_analysis_map_country_codes(
1339
+ all_role_codes,
1340
+ focal_code,
1341
+ )
1342
+ if extra_mentioned_countries:
1343
+ mentioned_codes.update(extra_mentioned_countries)
1344
+
1345
+ # Load world shapefile
1346
+ world = _get_world_geodataframe(
1347
+ custom_shapefile=custom_shapefile,
1348
+ adm0_shapefile=adm0_shapefile,
1349
+ )
1350
+ shapefile_codes = set(world["iso_code"].dropna().unique())
1351
+
1352
+ # Classify ONLY mentioned countries; everything else is "na"
1353
+ classification: dict[str, str] = {}
1354
+ for code in shapefile_codes:
1355
+ if code == focal_code:
1356
+ classification[code] = "intracoupling"
1357
+ elif code in mentioned_codes:
1358
+ # Determine relationship with focal country from DB
1359
+ result = lookup_pericoupling(focal_code, code)
1360
+ if result.pair_type == PairCouplingType.PERICOUPLED:
1361
+ classification[code] = "pericoupling"
1362
+ else:
1363
+ classification[code] = "telecoupling"
1364
+ else:
1365
+ classification[code] = "na"
1366
+
1367
+ # Extract flows from the parsed analysis for arrow rendering
1368
+ if flows is None:
1369
+ parsed_flows = list(parsed_analysis.iter_flow_entries())
1370
+ flows = parsed_flows if parsed_flows else None
1371
+
1372
+ return _render_map(world, classification, colors, title, figsize, flows=flows)