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,713 @@
1
+ """
2
+ Curated case-study examples from the telecoupling/metacoupling literature.
3
+
4
+ Each example demonstrates how the framework components map to a real-world
5
+ study, providing concrete illustrations the LLM can reference when advising
6
+ researchers.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass, field
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class FrameworkExample:
16
+ """A curated example of the telecoupling/metacoupling framework applied."""
17
+
18
+ title: str
19
+ source: str
20
+ domain: str
21
+ coupling_type: str # "telecoupling" | "metacoupling"
22
+ description: str
23
+ systems: dict[str, str | dict[str, str]] # role -> description or nested dict
24
+ flows: list[dict[str, str]] # each: {category, direction, description}
25
+ agents: list[dict[str, str]] # each: {level, name, description}
26
+ causes: list[dict[str, str]] # each: {category, description}
27
+ effects: list[dict[str, str]] # each: {system, type, description}
28
+ keywords: list[str] = field(default_factory=list)
29
+
30
+
31
+ # ---------------------------------------------------------------------------
32
+ # Example 1: Soybean Trade (Liu et al., 2013)
33
+ # ---------------------------------------------------------------------------
34
+
35
+ SOYBEAN_TRADE = FrameworkExample(
36
+ title="International Soybean Trade: Brazil to China",
37
+ source="Liu et al. (2013) – Framing Sustainability in a Telecoupled World",
38
+ domain="agriculture, trade, land use",
39
+ coupling_type="telecoupling",
40
+ description=(
41
+ "Large-scale soybean trade between Brazil (sending) and China "
42
+ "(receiving), with spillover effects on other soy-producing and "
43
+ "consuming nations. This telecoupling drives land-use change in "
44
+ "Brazil and food supply dynamics in China."
45
+ ),
46
+ systems={
47
+ "sending": {
48
+ "name": "Brazil",
49
+ "human_subsystem": (
50
+ "Soybean farmers, agribusiness companies, government "
51
+ "land-use policy makers, export agencies."
52
+ ),
53
+ "natural_subsystem": (
54
+ "Tropical forests, Cerrado grasslands, biodiversity, "
55
+ "soil and water resources in the Amazon and Cerrado biomes."
56
+ ),
57
+ "geographic_scope": "Amazon and Cerrado biomes, Brazil.",
58
+ },
59
+ "receiving": {
60
+ "name": "China",
61
+ "human_subsystem": (
62
+ "Food processing industry, livestock sector, consumers, "
63
+ "trade policy makers."
64
+ ),
65
+ "natural_subsystem": (
66
+ "Agricultural land spared from soybean cultivation, "
67
+ "local ecosystems."
68
+ ),
69
+ "geographic_scope": "Soybean-importing and consuming regions of China.",
70
+ },
71
+ "spillover": {
72
+ "name": "Other soy-producing and importing nations",
73
+ "human_subsystem": (
74
+ "Soybean farmers in Argentina and USA affected by market "
75
+ "competition; consumers in other importing nations facing "
76
+ "price changes."
77
+ ),
78
+ "natural_subsystem": (
79
+ "Agricultural and forest ecosystems in competing regions "
80
+ "experiencing land-use pressure; ecosystems in countries "
81
+ "neighboring Brazil affected by cross-border deforestation."
82
+ ),
83
+ "geographic_scope": "Argentina, USA, and other major soy-producing regions.",
84
+ },
85
+ },
86
+ flows=[
87
+ {
88
+ "category": "matter",
89
+ "direction": "Brazil → China",
90
+ "description": "Soybeans and soybean products exported from Brazil to China",
91
+ },
92
+ {
93
+ "category": "capital",
94
+ "direction": "China → Brazil",
95
+ "description": "Payment for soybeans; Chinese investment in Brazilian agriculture",
96
+ },
97
+ {
98
+ "category": "information",
99
+ "direction": "bidirectional",
100
+ "description": "Market information, price signals, trade regulations",
101
+ },
102
+ ],
103
+ agents=[
104
+ {"level": "individuals / households", "name": "Brazilian soybean farmers", "description": "Smallholder and commercial farmers in sending system"},
105
+ {"level": "firms / traders / corporations", "name": "Brazilian agribusiness companies", "description": "Large-scale soy producers and exporters in sending system"},
106
+ {"level": "firms / traders / corporations", "name": "Chinese food processing and livestock companies", "description": "Import and process soybeans in receiving system"},
107
+ {"level": "governments / policymakers", "name": "Brazilian and Chinese government trade agencies", "description": "Regulate and facilitate bilateral trade"},
108
+ {"level": "firms / traders / corporations", "name": "International commodity traders and brokers", "description": "Intermediaries facilitating global soybean trade"},
109
+ {"level": "individuals / households", "name": "Consumers in China", "description": "Drive demand for soybean products in receiving system"},
110
+ ],
111
+ causes=[
112
+ {"category": "economic", "description": "Growing demand for soybeans in China for animal feed and cooking oil"},
113
+ {"category": "economic", "description": "Competitive pricing of Brazilian soybeans on the global market"},
114
+ {"category": "economic", "description": "Rapid economic growth and rising meat consumption in China"},
115
+ {"category": "ecological / biological", "description": "Availability of arable land in Brazil for soybean expansion in Cerrado and Amazon biomes"},
116
+ {"category": "political / institutional", "description": "International trade liberalization policies facilitating bilateral commodity trade"},
117
+ ],
118
+ effects=[
119
+ {"system": "sending", "type": "ecological / biological", "description": "Deforestation and habitat loss in the Amazon and Cerrado (sending system)"},
120
+ {"system": "sending", "type": "climatic / atmospheric", "description": "Carbon emissions from land-use change and soil degradation (sending system)"},
121
+ {"system": "sending", "type": "ecological / biological", "description": "Loss of biodiversity due to conversion of native habitats to monoculture (sending system)"},
122
+ {"system": "sending", "type": "hydrological", "description": "Water pollution from agrochemical runoff and altered watershed hydrology (sending system)"},
123
+ {"system": "sending", "type": "economic", "description": "Economic growth in agricultural sector; land conflicts (sending system)"},
124
+ {"system": "receiving", "type": "economic", "description": "Affordable animal feed supporting livestock industry growth (receiving system)"},
125
+ {"system": "receiving", "type": "ecological / biological", "description": "Reduced pressure on domestic land for soybean cultivation (receiving system)"},
126
+ {"system": "spillover", "type": "economic", "description": "Price competition affecting soybean farmers in Argentina, USA (spillover system)"},
127
+ {"system": "spillover", "type": "ecological / biological", "description": "Potential shifts in deforestation to other regions (spillover system)"},
128
+ {"system": "spillover", "type": "political / institutional", "description": "Trade policy adjustments in competing nations responding to market shifts (spillover system)"},
129
+ ],
130
+ keywords=["soybean", "trade", "agriculture", "deforestation", "land use",
131
+ "commodity", "food", "Brazil", "China"],
132
+ )
133
+
134
+
135
+ # ---------------------------------------------------------------------------
136
+ # Example 2: Red Imported Fire Ant Invasion (Liu et al., 2013)
137
+ # ---------------------------------------------------------------------------
138
+
139
+ RIFA_INVASION = FrameworkExample(
140
+ title="Red Imported Fire Ant (RIFA) Invasion: USA to China",
141
+ source="Liu et al. (2013) – Framing Sustainability in a Telecoupled World",
142
+ domain="species invasion, trade, biosecurity",
143
+ coupling_type="telecoupling",
144
+ description=(
145
+ "Invasion of red imported fire ants from the United States to China "
146
+ "via international trade and shipping. The sending system (USA) "
147
+ "harbors established RIFA populations that are inadvertently "
148
+ "transported to the receiving system (China) through cargo."
149
+ ),
150
+ systems={
151
+ "sending": {
152
+ "name": "United States",
153
+ "human_subsystem": (
154
+ "Port operators, exporters, biosecurity agencies in "
155
+ "the southeastern US."
156
+ ),
157
+ "natural_subsystem": (
158
+ "Ecosystems where RIFA is established, including "
159
+ "disturbed habitats and agricultural lands."
160
+ ),
161
+ "geographic_scope": "Southeastern United States port regions.",
162
+ },
163
+ "receiving": {
164
+ "name": "China",
165
+ "human_subsystem": (
166
+ "Importers, quarantine agencies, affected communities "
167
+ "near ports receiving international cargo."
168
+ ),
169
+ "natural_subsystem": (
170
+ "Native ecosystems vulnerable to RIFA invasion, "
171
+ "agricultural lands, and urban green spaces."
172
+ ),
173
+ "geographic_scope": "Chinese port cities and surrounding regions.",
174
+ },
175
+ "spillover": {
176
+ "name": "Other countries along shipping routes",
177
+ "human_subsystem": (
178
+ "Port operators and biosecurity agencies in countries "
179
+ "along shared shipping routes, communities affected by "
180
+ "secondary RIFA spread."
181
+ ),
182
+ "natural_subsystem": (
183
+ "Native ecosystems in transit and neighboring countries "
184
+ "potentially exposed to RIFA through similar trade pathways."
185
+ ),
186
+ "geographic_scope": (
187
+ "Southeast Asian nations, Pacific island countries, "
188
+ "and other trading partners along shared shipping routes."
189
+ ),
190
+ },
191
+ },
192
+ flows=[
193
+ {
194
+ "category": "organisms",
195
+ "direction": "USA → China",
196
+ "description": "Unintentional transport of RIFA colonies in shipping containers and cargo",
197
+ },
198
+ {
199
+ "category": "matter",
200
+ "direction": "USA → China",
201
+ "description": "Trade goods (legitimate cargo) that serve as vectors for ant transport",
202
+ },
203
+ {
204
+ "category": "information",
205
+ "direction": "bidirectional",
206
+ "description": "Biosecurity protocols, invasion alerts, scientific knowledge on RIFA management",
207
+ },
208
+ ],
209
+ agents=[
210
+ {"level": "firms / traders / corporations", "name": "Shipping companies and port operators", "description": "Intermediaries inadvertently transporting RIFA in cargo"},
211
+ {"level": "firms / traders / corporations", "name": "Exporters and importers of goods", "description": "Commercial entities in sending and receiving systems"},
212
+ {"level": "governments / policymakers", "name": "National biosecurity and quarantine agencies", "description": "Government agencies managing invasive species risk in both systems"},
213
+ {"level": "organizations / NGOs", "name": "Scientists studying invasive species", "description": "Researchers providing management knowledge in both systems"},
214
+ {"level": "non-human agents", "name": "Red imported fire ants", "description": "Invasive organisms whose survival and spread actively shape receiving-system impacts"},
215
+ ],
216
+ causes=[
217
+ {"category": "ecological / biological", "description": "RIFA colonies established in disturbed habitats near ports, facilitating inadvertent loading onto cargo containers"},
218
+ {"category": "political / institutional", "description": "Inadequate biosecurity inspection protocols for shipped goods at ports"},
219
+ {"category": "economic", "description": "Growth of international trade volume between the US and China"},
220
+ {"category": "economic", "description": "Globalization of supply chains increasing shipping frequency and vector pathways"},
221
+ ],
222
+ effects=[
223
+ {"system": "receiving", "type": "ecological / biological", "description": "Displacement of native ant species and reduction in arthropod biodiversity (receiving system)"},
224
+ {"system": "receiving", "type": "ecological / biological", "description": "Ecological damage to native ecosystems and disruption of food webs (receiving system)"},
225
+ {"system": "receiving", "type": "economic", "description": "Agricultural damage, public health risks (stings), control costs (receiving system)"},
226
+ {"system": "sending", "type": "political / institutional", "description": "Potential trade restrictions or increased inspection requirements (sending system)"},
227
+ {"system": "sending", "type": "economic", "description": "Increased biosecurity costs for exporters (sending system)"},
228
+ {"system": "spillover", "type": "ecological / biological", "description": "Risk of secondary spread to neighboring countries from China (spillover system)"},
229
+ ],
230
+ keywords=["invasive", "species", "fire ant", "RIFA", "biosecurity", "trade",
231
+ "shipping", "pest", "biological invasion"],
232
+ )
233
+
234
+
235
+ # ---------------------------------------------------------------------------
236
+ # Example 3: Beijing Urban Water Supply (Deines et al., 2016)
237
+ # ---------------------------------------------------------------------------
238
+
239
+ BEIJING_WATER = FrameworkExample(
240
+ title="Beijing Urban Water Supply Telecouplings",
241
+ source="Deines et al. (2016) – Telecoupling in Urban Water Systems",
242
+ domain="water resources, urban, infrastructure",
243
+ coupling_type="telecoupling",
244
+ description=(
245
+ "Beijing's water supply involves three distinct telecouplings: "
246
+ "(1) the South-to-North Water Transfer Project (SNWTP) physically "
247
+ "moving water from the Yangtze to Beijing; (2) virtual water imports "
248
+ "through agricultural and industrial goods; and (3) payments for "
249
+ "ecosystem services (PES) to upstream communities for water quality "
250
+ "protection."
251
+ ),
252
+ systems={
253
+ "sending": {
254
+ "name": "Source water regions",
255
+ "human_subsystem": (
256
+ "Farmers, local governments, dam operators in the "
257
+ "Yangtze River basin and upstream watersheds."
258
+ ),
259
+ "natural_subsystem": (
260
+ "River ecosystems, watersheds, agricultural landscapes "
261
+ "in the Yangtze basin and upstream areas."
262
+ ),
263
+ "geographic_scope": (
264
+ "Yangtze River basin (SNWTP source), agricultural regions "
265
+ "providing virtual water, upstream watersheds."
266
+ ),
267
+ },
268
+ "receiving": {
269
+ "name": "Beijing",
270
+ "human_subsystem": (
271
+ "Urban residents, municipal government, water utilities, "
272
+ "industries in Beijing metropolitan area."
273
+ ),
274
+ "natural_subsystem": (
275
+ "Local water resources, urban ecosystems, and aquifers "
276
+ "under the Beijing metropolitan area."
277
+ ),
278
+ "geographic_scope": "Beijing metropolitan area.",
279
+ },
280
+ "spillover": {
281
+ "name": "Communities along the SNWTP route and downstream areas",
282
+ "human_subsystem": (
283
+ "Displaced communities along SNWTP construction route, "
284
+ "farmers and residents in regions competing for the same "
285
+ "water resources."
286
+ ),
287
+ "natural_subsystem": (
288
+ "River ecosystems downstream of source diversions with "
289
+ "reduced flows, wetlands and aquatic habitats along the "
290
+ "SNWTP corridor."
291
+ ),
292
+ "geographic_scope": (
293
+ "Communities along the SNWTP route, downstream areas of "
294
+ "source rivers, regions competing for shared water resources."
295
+ ),
296
+ },
297
+ },
298
+ flows=[
299
+ {
300
+ "category": "matter",
301
+ "direction": "Yangtze basin → Beijing",
302
+ "description": "Physical water transferred via the South-to-North Water Transfer Project",
303
+ },
304
+ {
305
+ "category": "matter",
306
+ "direction": "Agricultural regions → Beijing",
307
+ "description": "Virtual water embedded in imported agricultural and industrial goods",
308
+ },
309
+ {
310
+ "category": "capital",
311
+ "direction": "Beijing → upstream communities",
312
+ "description": "Payments for ecosystem services to protect water quality upstream",
313
+ },
314
+ {
315
+ "category": "capital",
316
+ "direction": "Beijing → source regions",
317
+ "description": "Government investment in SNWTP infrastructure",
318
+ },
319
+ {
320
+ "category": "information",
321
+ "direction": "bidirectional",
322
+ "description": "Water quality monitoring data, management policies, scientific assessments",
323
+ },
324
+ ],
325
+ agents=[
326
+ {"level": "governments / policymakers", "name": "Beijing municipal government and water utilities", "description": "Managing water demand in receiving system"},
327
+ {"level": "governments / policymakers", "name": "Central government agencies managing SNWTP", "description": "Intermediary planning and operating water transfer infrastructure"},
328
+ {"level": "individuals / households", "name": "Upstream farming communities participating in PES", "description": "Households in sending system receiving payments for ecosystem services"},
329
+ {"level": "individuals / households", "name": "Agricultural producers in virtual water source regions", "description": "Farmers in sending system producing water-intensive goods"},
330
+ {"level": "individuals / households", "name": "Displaced communities along SNWTP route", "description": "Households in spillover system affected by infrastructure construction"},
331
+ ],
332
+ causes=[
333
+ {"category": "hydrological", "description": "Chronic water scarcity in Beijing relative to demand due to limited local water resources"},
334
+ {"category": "political / institutional", "description": "Government decision to construct SNWTP infrastructure as a national priority project"},
335
+ {"category": "cultural / social / demographic", "description": "Rapid urbanization and population growth in Beijing increasing water demand"},
336
+ {"category": "hydrological", "description": "Uneven spatial distribution of water resources across China (south water-rich, north water-poor)"},
337
+ {"category": "economic", "description": "Increasing per-capita water consumption driven by economic growth and rising living standards"},
338
+ ],
339
+ effects=[
340
+ {"system": "receiving", "type": "hydrological", "description": "Improved water supply security for Beijing residents and industries (receiving system)"},
341
+ {"system": "receiving", "type": "economic", "description": "Economic benefits from reliable water supply for urban industries (receiving system)"},
342
+ {"system": "sending", "type": "hydrological", "description": "Reduced river flows and altered hydrology in source basins (sending system)"},
343
+ {"system": "sending", "type": "ecological / biological", "description": "Altered riparian and aquatic ecosystems downstream of diversions (sending system)"},
344
+ {"system": "sending", "type": "economic", "description": "Income from PES payments; restrictions on land use for water protection (sending system)"},
345
+ {"system": "spillover", "type": "cultural / social / demographic", "description": "Displacement of communities for SNWTP construction; compensation disputes (spillover system)"},
346
+ {"system": "spillover", "type": "hydrological", "description": "Reduced water availability for downstream users of source rivers (spillover system)"},
347
+ {"system": "spillover", "type": "political / institutional", "description": "Inter-provincial water allocation conflicts and governance challenges (spillover system)"},
348
+ ],
349
+ keywords=["water", "urban", "transfer", "infrastructure", "SNWTP", "virtual water",
350
+ "PES", "ecosystem services", "scarcity", "Beijing"],
351
+ )
352
+
353
+
354
+ # ---------------------------------------------------------------------------
355
+ # Example 4: Panda Conservation and SDGs (Zhao et al., 2021)
356
+ # ---------------------------------------------------------------------------
357
+
358
+ PANDA_SDGS = FrameworkExample(
359
+ title="Panda Conservation Metacoupling and SDGs",
360
+ source="Zhao et al. (2021) – Metacoupling of SDGs across Panda Reserves",
361
+ domain="conservation, biodiversity, sustainable development goals",
362
+ coupling_type="metacoupling",
363
+ description=(
364
+ "Metacoupling analysis across 67 giant panda nature reserves in China, "
365
+ "examining how tourism flows and panda loan programs create "
366
+ "socioeconomic-environmental interactions that generate synergies and "
367
+ "tradeoffs among the UN Sustainable Development Goals (SDGs). "
368
+ "This demonstrates metacoupling encompassing intracoupling (within "
369
+ "reserves), pericoupling (between adjacent reserves), and telecoupling "
370
+ "(between distant reserves and international partners)."
371
+ ),
372
+ systems={
373
+ "sending": {
374
+ "name": "Panda nature reserves (e.g., Wolong)",
375
+ "human_subsystem": (
376
+ "Reserve management authorities, local communities, "
377
+ "tourism operators."
378
+ ),
379
+ "natural_subsystem": (
380
+ "Giant panda habitat, bamboo forests, montane "
381
+ "biodiversity."
382
+ ),
383
+ "geographic_scope": "67 giant panda nature reserves across China.",
384
+ },
385
+ "receiving": {
386
+ "name": "Zoos worldwide and tourist source cities",
387
+ "human_subsystem": (
388
+ "Zoo management, urban populations, conservation donors, "
389
+ "tourists."
390
+ ),
391
+ "natural_subsystem": (
392
+ "Urban environments, captive breeding facilities."
393
+ ),
394
+ "geographic_scope": (
395
+ "International and domestic zoos; tourist source cities "
396
+ "sending visitors to reserves."
397
+ ),
398
+ },
399
+ "spillover": {
400
+ "name": "Adjacent communities and conservation community",
401
+ "human_subsystem": (
402
+ "Communities adjacent to reserves affected by tourism "
403
+ "overflow, regions experiencing changes in conservation "
404
+ "funding allocation, global conservation community "
405
+ "influenced by panda diplomacy."
406
+ ),
407
+ "natural_subsystem": (
408
+ "Non-protected ecosystems adjacent to reserves facing "
409
+ "tourism development pressures, habitats in areas where "
410
+ "conservation funding was redirected."
411
+ ),
412
+ "geographic_scope": (
413
+ "Areas surrounding panda reserves, regions with "
414
+ "competing conservation priorities."
415
+ ),
416
+ },
417
+ },
418
+ flows=[
419
+ {
420
+ "category": "organisms",
421
+ "direction": "Reserves → zoos worldwide",
422
+ "description": "Giant pandas loaned to international and domestic zoos",
423
+ },
424
+ {
425
+ "category": "people",
426
+ "direction": "Urban areas → reserves",
427
+ "description": "Tourist flows from cities to panda nature reserves",
428
+ },
429
+ {
430
+ "category": "capital",
431
+ "direction": "Zoos/tourists → reserves",
432
+ "description": "Panda loan fees and tourism revenue supporting conservation",
433
+ },
434
+ {
435
+ "category": "information",
436
+ "direction": "bidirectional",
437
+ "description": "Conservation knowledge exchange, scientific research collaboration",
438
+ },
439
+ ],
440
+ agents=[
441
+ {"level": "governments / policymakers", "name": "Reserve management authorities", "description": "Manage panda reserves in sending system"},
442
+ {"level": "organizations / NGOs", "name": "International and domestic zoos", "description": "Receive loaned pandas in receiving system"},
443
+ {"level": "individuals / households", "name": "Local communities near reserves", "description": "Households in sending/spillover systems affected by tourism"},
444
+ {"level": "individuals / households", "name": "Tourists", "description": "Visitors to panda reserves in receiving/intermediary role"},
445
+ {"level": "firms / traders / corporations", "name": "Tourism operators", "description": "Commercial tourism services facilitating visitor flows"},
446
+ {"level": "governments / policymakers", "name": "Chinese government conservation agencies", "description": "Intermediary agencies designing panda loan and conservation policies"},
447
+ {"level": "organizations / NGOs", "name": "International conservation organizations", "description": "Intermediary NGOs supporting global conservation efforts"},
448
+ ],
449
+ causes=[
450
+ {"category": "political / institutional", "description": "Panda loan agreements between Chinese government and foreign zoos as diplomatic instruments"},
451
+ {"category": "cultural / social / demographic", "description": "Growing domestic and international ecotourism demand driven by cultural fascination with pandas"},
452
+ {"category": "cultural / social / demographic", "description": "Global interest in giant panda conservation as a flagship and culturally iconic species"},
453
+ {"category": "political / institutional", "description": "Chinese policy to use panda diplomacy for international relations"},
454
+ {"category": "economic", "description": "Need for sustainable funding mechanisms for nature reserve management"},
455
+ ],
456
+ effects=[
457
+ {"system": "sending", "type": "economic", "description": "Tourism revenue and panda loan fees supporting local livelihoods (SDG 1, 8) (sending system)"},
458
+ {"system": "sending", "type": "ecological / biological", "description": "Habitat protection through conservation programs (SDG 15); but tourism pressure on ecosystems (sending system)"},
459
+ {"system": "sending", "type": "ecological / biological", "description": "Panda population recovery from breeding and habitat protection programs (sending system)"},
460
+ {"system": "receiving", "type": "cultural / social / demographic", "description": "Educational and recreational value of panda exhibits; zoo revenue (SDG 4) (receiving system)"},
461
+ {"system": "receiving", "type": "ecological / biological", "description": "Contribution to captive breeding and genetic diversity programs (SDG 15) (receiving system)"},
462
+ {"system": "spillover", "type": "economic", "description": "Unequal distribution of tourism benefits among nearby communities (SDG 10) (spillover system)"},
463
+ {"system": "spillover", "type": "ecological / biological", "description": "Tourism development pressures on adjacent non-protected areas (spillover system)"},
464
+ {"system": "spillover", "type": "political / institutional", "description": "Reallocation of conservation funding priorities influenced by panda diplomacy (spillover system)"},
465
+ ],
466
+ keywords=["panda", "conservation", "SDG", "sustainable development", "tourism",
467
+ "ecotourism", "biodiversity", "nature reserve", "loan", "wildlife"],
468
+ )
469
+
470
+
471
+ # ---------------------------------------------------------------------------
472
+ # Example 5: Wolong Nature Reserve Metacoupling (Liu, 2017)
473
+ # ---------------------------------------------------------------------------
474
+
475
+ WOLONG_METACOUPLING = FrameworkExample(
476
+ title="Wolong Nature Reserve: Full Metacoupling Analysis",
477
+ source="Liu (2017) – Integration across a metacoupled world",
478
+ domain="conservation, wildlife, tourism, migration, ecosystem services",
479
+ coupling_type="metacoupling",
480
+ description=(
481
+ "Comprehensive metacoupling analysis of Wolong Nature Reserve in China, "
482
+ "demonstrating how intracoupling (local human-nature interactions such as "
483
+ "fuelwood collection and agriculture), pericoupling (immigration through "
484
+ "marriage from adjacent counties, panda movement across reserve boundaries), "
485
+ "and telecoupling (panda loans to distant zoos, international tourism) "
486
+ "interact in complex ways. This is the foundational worked example of "
487
+ "the metacoupling framework showing all three coupling types."
488
+ ),
489
+ systems={
490
+ "sending": {
491
+ "name": "Wolong Nature Reserve",
492
+ "human_subsystem": (
493
+ "Reserve management, local residents (~5,000 people in "
494
+ "~1,200 households), breeding center staff."
495
+ ),
496
+ "natural_subsystem": (
497
+ "Giant panda habitat, bamboo forests, montane ecosystems, "
498
+ "~150 wild pandas and 200+ captive pandas."
499
+ ),
500
+ "geographic_scope": "Wolong Nature Reserve, Sichuan Province, China.",
501
+ },
502
+ "receiving": {
503
+ "name": "Zoos and tourist source cities",
504
+ "human_subsystem": (
505
+ "Zoo managers, tourists, families in adjacent counties "
506
+ "(Xiaojin, Li, Wenchuan for pericoupling)."
507
+ ),
508
+ "natural_subsystem": (
509
+ "Urban environments, captive breeding facilities at "
510
+ "receiving zoos."
511
+ ),
512
+ "geographic_scope": (
513
+ "Beijing Zoo, National Zoo (Washington DC), other "
514
+ "domestic and international zoos; adjacent counties."
515
+ ),
516
+ },
517
+ "spillover": {
518
+ "name": "Neighboring regions and wider conservation community",
519
+ "human_subsystem": (
520
+ "Communities in areas from which people travel to see "
521
+ "pandas at receiving-system zoos; residents in neighboring "
522
+ "regions affected by tourism infrastructure development."
523
+ ),
524
+ "natural_subsystem": (
525
+ "Panda habitat corridors crossing reserve boundaries into "
526
+ "adjacent areas; ecosystems in neighboring regions affected "
527
+ "by development for tourism infrastructure."
528
+ ),
529
+ "geographic_scope": (
530
+ "Regions neighboring Wolong reserve, areas along panda "
531
+ "habitat corridors, broader regions affected by conservation "
532
+ "funding reallocation."
533
+ ),
534
+ },
535
+ },
536
+ flows=[
537
+ {
538
+ "category": "organisms",
539
+ "direction": "Wolong -> zoos worldwide",
540
+ "description": "Captive pandas loaned to domestic and international zoos (telecoupling); total loans grew from <20 in 1998 to 85 in 2010",
541
+ },
542
+ {
543
+ "category": "people",
544
+ "direction": "Tourist cities -> Wolong",
545
+ "description": "Tourist flows from domestic and international cities to Wolong (telecoupling)",
546
+ },
547
+ {
548
+ "category": "people",
549
+ "direction": "Adjacent counties -> Wolong",
550
+ "description": "Immigration through marriage from neighboring Xiaojin, Li, Wenchuan counties (pericoupling)",
551
+ },
552
+ {
553
+ "category": "organisms",
554
+ "direction": "Across reserve boundaries",
555
+ "description": "Wild panda movement across Wolong reserve boundaries to adjacent areas (pericoupling)",
556
+ },
557
+ {
558
+ "category": "capital",
559
+ "direction": "Zoos/tourists -> Wolong",
560
+ "description": "Panda loan fees (up to $1M per panda per year) and tourism revenue (telecoupling)",
561
+ },
562
+ {
563
+ "category": "matter",
564
+ "direction": "Within Wolong",
565
+ "description": "Fuelwood collection, agriculture, and resource use by local households (intracoupling)",
566
+ },
567
+ ],
568
+ agents=[
569
+ {"level": "governments / policymakers", "name": "Wolong Nature Reserve Administration", "description": "Reserve management in sending system"},
570
+ {"level": "governments / policymakers", "name": "China's State Forestry Administration", "description": "Designs panda loan policies as intermediary"},
571
+ {"level": "non-human agents", "name": "Giant pandas", "description": "Flagship organisms whose movement, reproduction, and conservation status shape tourism and panda-loan couplings"},
572
+ {"level": "individuals / households", "name": "Local residents in Wolong (~1,200 households)", "description": "Households in sending system / intracoupling"},
573
+ {"level": "organizations / NGOs", "name": "International and domestic zoos", "description": "Receive loaned pandas in receiving system"},
574
+ {"level": "individuals / households", "name": "Tourists from China and worldwide", "description": "Visitors in receiving system"},
575
+ {"level": "individuals / households", "name": "Families in adjacent counties", "description": "Involved in cross-boundary marriage (pericoupling)"},
576
+ ],
577
+ causes=[
578
+ {"category": "cultural / social / demographic", "description": "Strong global interest in giant pandas as an iconic and culturally significant species"},
579
+ {"category": "political / institutional", "description": "Panda loan agreements between Chinese government and foreign zoos as diplomatic instruments"},
580
+ {"category": "cultural / social / demographic", "description": "Marriage customs enabling cross-boundary immigration from adjacent counties (pericoupling)"},
581
+ {"category": "economic", "description": "Need for sustainable funding for nature reserve management"},
582
+ {"category": "political / institutional", "description": "China's panda diplomacy strategy for international relations"},
583
+ {"category": "cultural / social / demographic", "description": "Local population dynamics (aging, young people leaving) creating labor needs filled by marriage immigration"},
584
+ ],
585
+ effects=[
586
+ {"system": "sending", "type": "economic", "description": "Tourism revenue and panda loan fees supporting conservation and local livelihoods (sending system)"},
587
+ {"system": "sending", "type": "ecological / biological", "description": "Reduced local disturbance from fuelwood programs; but tourism pressure on habitat (sending system)"},
588
+ {"system": "sending", "type": "cultural / social / demographic", "description": "Population growth from cross-boundary marriage immigration (pericoupling) (sending system)"},
589
+ {"system": "receiving", "type": "cultural / social / demographic", "description": "Educational value and visitor revenue at zoos with loaned pandas (receiving system)"},
590
+ {"system": "receiving", "type": "climatic / atmospheric", "description": "CO2 emissions from transporting pandas between systems (receiving system)"},
591
+ {"system": "spillover", "type": "economic", "description": "Increased visitation to zoos in spillover areas to see pandas (spillover system)"},
592
+ {"system": "spillover", "type": "ecological / biological", "description": "Panda habitat connectivity affected by development in adjacent areas (spillover system)"},
593
+ {"system": "spillover", "type": "ecological / biological", "description": "Reduced genetic diversity risk from panda movement across reserve boundaries (spillover system)"},
594
+ ],
595
+ keywords=["panda", "Wolong", "conservation", "nature reserve", "tourism",
596
+ "panda loan", "marriage", "migration", "wildlife", "ecosystem",
597
+ "intracoupling", "pericoupling", "fuelwood"],
598
+ )
599
+
600
+
601
+ # ---------------------------------------------------------------------------
602
+ # All Examples
603
+ # ---------------------------------------------------------------------------
604
+
605
+ ALL_EXAMPLES: list[FrameworkExample] = [
606
+ SOYBEAN_TRADE,
607
+ RIFA_INVASION,
608
+ BEIJING_WATER,
609
+ PANDA_SDGS,
610
+ WOLONG_METACOUPLING,
611
+ ]
612
+
613
+
614
+ def get_relevant_examples(
615
+ research_context: str,
616
+ max_examples: int = 2,
617
+ ) -> list[FrameworkExample]:
618
+ """Select the most relevant examples based on keyword overlap.
619
+
620
+ Parameters
621
+ ----------
622
+ research_context:
623
+ The user's research description to match against.
624
+ max_examples:
625
+ Maximum number of examples to return.
626
+
627
+ Returns
628
+ -------
629
+ A list of the most relevant ``FrameworkExample`` instances, ordered by
630
+ relevance (highest first).
631
+ """
632
+ if not research_context.strip():
633
+ # Return the first examples as defaults when no context given.
634
+ return ALL_EXAMPLES[:max_examples]
635
+
636
+ context_lower = research_context.lower()
637
+ context_words = set(context_lower.split())
638
+
639
+ scored: list[tuple[float, FrameworkExample]] = []
640
+ for example in ALL_EXAMPLES:
641
+ score = 0.0
642
+ # Keyword matching (each keyword found in context scores a point)
643
+ for kw in example.keywords:
644
+ kw_lower = kw.lower()
645
+ if kw_lower in context_lower:
646
+ score += 2.0 # substring match (stronger)
647
+ elif kw_lower in context_words:
648
+ score += 1.0 # exact word match
649
+ # Domain match
650
+ for domain_word in example.domain.split(", "):
651
+ if domain_word.lower() in context_lower:
652
+ score += 1.5
653
+ scored.append((score, example))
654
+
655
+ # Sort by score descending
656
+ scored.sort(key=lambda x: x[0], reverse=True)
657
+
658
+ return [example for _, example in scored[:max_examples]]
659
+
660
+
661
+ def format_example(example: FrameworkExample) -> str:
662
+ """Format a single example as readable text for prompt injection."""
663
+ lines: list[str] = []
664
+ lines.append(f"### {example.title}")
665
+ lines.append(f"Source: {example.source}")
666
+ lines.append(f"Type: {example.coupling_type.title()}")
667
+ lines.append(f"\n{example.description}\n")
668
+
669
+ lines.append("**Systems:**")
670
+ for role, value in example.systems.items():
671
+ if isinstance(value, dict):
672
+ name = value.get("name", "")
673
+ lines.append(f" **{role.title()} System**: {name}")
674
+ if value.get("human_subsystem"):
675
+ lines.append(f" - **Human subsystem**: {value['human_subsystem']}")
676
+ if value.get("natural_subsystem"):
677
+ lines.append(f" - **Natural subsystem**: {value['natural_subsystem']}")
678
+ if value.get("geographic_scope"):
679
+ lines.append(f" - **Geographic scope**: {value['geographic_scope']}")
680
+ else:
681
+ lines.append(f" - {role.title()}: {value}")
682
+
683
+ lines.append("\n**Flows:**")
684
+ for flow in example.flows:
685
+ lines.append(
686
+ f" - [{flow['category'].title()}] {flow['direction']}: "
687
+ f"{flow['description']}"
688
+ )
689
+
690
+ lines.append("\n**Agents:**")
691
+ for agent in example.agents:
692
+ level = agent.get("level", "").title()
693
+ name = agent.get("name", "")
694
+ desc = agent.get("description", "")
695
+ lines.append(f" - [{level}] {name}: {desc}")
696
+
697
+ lines.append("\n**Causes:**")
698
+ for cause in example.causes:
699
+ cat = cause.get("category", cause.get("type", "")).title()
700
+ lines.append(f" - [{cat}] {cause['description']}")
701
+
702
+ lines.append("\n**Effects:**")
703
+ # Group effects by category (type), not by system
704
+ effects_by_type: dict[str, list[str]] = {}
705
+ for effect in example.effects:
706
+ cat = effect.get("type", "general").title()
707
+ effects_by_type.setdefault(cat, []).append(effect["description"])
708
+ for cat, items in effects_by_type.items():
709
+ lines.append(f" **{cat}**")
710
+ for item in items:
711
+ lines.append(f" - {item}")
712
+
713
+ return "\n".join(lines)