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,868 @@
1
+ """
2
+ Response parser for coupling-first metacoupling analyses.
3
+
4
+ The parser expects top-level sections organised by coupling type:
5
+
6
+ - Coupling Classification
7
+ - Intracoupling Analysis
8
+ - Pericoupling Analysis
9
+ - Telecoupling Analysis
10
+ - Cross-coupling Interactions
11
+ - Research Gaps and Suggestions
12
+
13
+ Each active coupling section is parsed into a structured
14
+ ``CouplingSection`` with internal subsections for systems, flows,
15
+ agents, causes, and effects.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import re
21
+ from dataclasses import dataclass, field
22
+ from typing import Iterator
23
+
24
+
25
+ @dataclass
26
+ class CouplingSection:
27
+ """Structured content for one coupling type."""
28
+
29
+ systems: list[dict[str, str]] = field(default_factory=list)
30
+ flows: list[dict[str, str]] = field(default_factory=list)
31
+ agents: list[dict[str, str]] = field(default_factory=list)
32
+ causes: dict[str, list[str]] = field(default_factory=dict)
33
+ effects: dict[str, list[str]] = field(default_factory=dict)
34
+
35
+ @property
36
+ def is_empty(self) -> bool:
37
+ """Return ``True`` when the section has no parsed content."""
38
+ return not (
39
+ self.systems
40
+ or self.flows
41
+ or self.agents
42
+ or self.causes
43
+ or self.effects
44
+ )
45
+
46
+
47
+ def _normalize_system_role(role: str) -> str:
48
+ """Normalize system-role names across coupling sections."""
49
+ normalized = re.sub(r"\s*\([^)]*\)", "", role.strip().lower()).strip()
50
+ normalized = re.sub(r"\s+", " ", normalized)
51
+ aliases = {
52
+ "focal": "focal",
53
+ "focal system": "focal",
54
+ "adjacent": "adjacent",
55
+ "adjacent system": "adjacent",
56
+ "sending": "sending",
57
+ "sending system": "sending",
58
+ "receiving": "receiving",
59
+ "receiving system": "receiving",
60
+ "spillover": "spillover",
61
+ "spillover system": "spillover",
62
+ }
63
+ return aliases.get(normalized, normalized)
64
+
65
+
66
+ def _normalize_system_scope(scope: str | None) -> str:
67
+ """Normalize optional system-scope qualifiers such as adjacent/distant."""
68
+ if not scope:
69
+ return ""
70
+ normalized = scope.strip().lower().strip("() ")
71
+ normalized = re.sub(r"\s+", " ", normalized)
72
+ aliases = {
73
+ "adjacent": "adjacent",
74
+ "distant": "distant",
75
+ }
76
+ return aliases.get(normalized, normalized)
77
+
78
+
79
+ @dataclass
80
+ class ParsedAnalysis:
81
+ """Structured representation of a coupling-first analysis response."""
82
+
83
+ coupling_classification: str = ""
84
+ intracoupling: CouplingSection | None = None
85
+ pericoupling: CouplingSection | None = None
86
+ telecoupling: CouplingSection | None = None
87
+ cross_coupling_interactions: list[str] = field(default_factory=list)
88
+ research_gaps: list[str] = field(default_factory=list)
89
+ raw_text: str = ""
90
+ pericoupling_info: dict[str, str] | None = None
91
+ map_data: dict[str, object] | None = None
92
+
93
+ @property
94
+ def is_parsed(self) -> bool:
95
+ """Return ``True`` if at least some structured data was extracted."""
96
+ return bool(
97
+ self.coupling_classification
98
+ or self.cross_coupling_interactions
99
+ or self.research_gaps
100
+ or any(section and not section.is_empty for _, section in self.iter_coupling_sections())
101
+ )
102
+
103
+ def get_coupling_section(self, name: str) -> CouplingSection | None:
104
+ """Return the named coupling section if present."""
105
+ normalized = name.strip().lower()
106
+ if normalized == "intracoupling":
107
+ return self.intracoupling
108
+ if normalized == "pericoupling":
109
+ return self.pericoupling
110
+ if normalized == "telecoupling":
111
+ return self.telecoupling
112
+ return None
113
+
114
+ def iter_coupling_sections(
115
+ self,
116
+ ) -> Iterator[tuple[str, CouplingSection]]:
117
+ """Yield active coupling sections in canonical order."""
118
+ for name, section in (
119
+ ("intracoupling", self.intracoupling),
120
+ ("pericoupling", self.pericoupling),
121
+ ("telecoupling", self.telecoupling),
122
+ ):
123
+ if section is not None:
124
+ yield name, section
125
+
126
+ def active_coupling_types(self) -> list[str]:
127
+ """Return the active coupling-type names in canonical order."""
128
+ return [name for name, section in self.iter_coupling_sections() if not section.is_empty]
129
+
130
+ def iter_system_entries(
131
+ self,
132
+ *,
133
+ role: str | None = None,
134
+ coupling_type: str | None = None,
135
+ ) -> Iterator[dict[str, str]]:
136
+ """Yield parsed system entries across active coupling sections."""
137
+ normalized_role = _normalize_system_role(role) if role else None
138
+ for section_name, section in self.iter_coupling_sections():
139
+ if coupling_type and section_name != coupling_type.lower():
140
+ continue
141
+ for entry in section.systems:
142
+ entry_role = _normalize_system_role(entry.get("role", ""))
143
+ if normalized_role and entry_role != normalized_role:
144
+ continue
145
+ yield entry
146
+
147
+ def get_system_entries(
148
+ self,
149
+ role: str,
150
+ *,
151
+ coupling_type: str | None = None,
152
+ ) -> list[dict[str, str]]:
153
+ """Return all system entries for a role."""
154
+ return list(
155
+ self.iter_system_entries(role=role, coupling_type=coupling_type)
156
+ )
157
+
158
+ def get_first_system_entry(
159
+ self,
160
+ role: str,
161
+ *,
162
+ coupling_type: str | None = None,
163
+ ) -> dict[str, str] | None:
164
+ """Return the first system entry for a role, if any."""
165
+ return next(
166
+ iter(self.get_system_entries(role, coupling_type=coupling_type)),
167
+ None,
168
+ )
169
+
170
+ def get_system_detail(
171
+ self,
172
+ role: str,
173
+ sub_field: str | None = None,
174
+ *,
175
+ coupling_type: str | None = None,
176
+ ) -> str:
177
+ """Return a system detail from the first matching system entry."""
178
+ entry = self.get_first_system_entry(role, coupling_type=coupling_type)
179
+ if entry is None:
180
+ return ""
181
+ if sub_field:
182
+ return entry.get(sub_field, "")
183
+ parts: list[str] = []
184
+ if entry.get("name"):
185
+ parts.append(entry["name"])
186
+ if entry.get("human_subsystem"):
187
+ parts.append(f"Human subsystem: {entry['human_subsystem']}")
188
+ if entry.get("natural_subsystem"):
189
+ parts.append(f"Natural subsystem: {entry['natural_subsystem']}")
190
+ if entry.get("geographic_scope"):
191
+ parts.append(f"Geographic scope: {entry['geographic_scope']}")
192
+ if entry.get("description"):
193
+ parts.append(entry["description"])
194
+ return "; ".join(parts)
195
+
196
+ def iter_flow_entries(
197
+ self,
198
+ *,
199
+ coupling_type: str | None = None,
200
+ ) -> Iterator[dict[str, str]]:
201
+ """Yield parsed flow entries across active coupling sections."""
202
+ for section_name, section in self.iter_coupling_sections():
203
+ if coupling_type and section_name != coupling_type.lower():
204
+ continue
205
+ yield from section.flows
206
+
207
+ def iter_agent_entries(
208
+ self,
209
+ *,
210
+ coupling_type: str | None = None,
211
+ ) -> Iterator[dict[str, str]]:
212
+ """Yield parsed agent entries across active coupling sections."""
213
+ for section_name, section in self.iter_coupling_sections():
214
+ if coupling_type and section_name != coupling_type.lower():
215
+ continue
216
+ yield from section.agents
217
+
218
+ def iter_category_items(
219
+ self,
220
+ kind: str,
221
+ *,
222
+ coupling_type: str | None = None,
223
+ ) -> Iterator[tuple[str, str, str]]:
224
+ """Yield ``(coupling_type, category, item)`` triples."""
225
+ attr = kind.lower()
226
+ if attr not in {"causes", "effects"}:
227
+ return
228
+ for section_name, section in self.iter_coupling_sections():
229
+ if coupling_type and section_name != coupling_type.lower():
230
+ continue
231
+ grouped = getattr(section, attr)
232
+ for category, items in grouped.items():
233
+ for item in items:
234
+ yield section_name, category, item
235
+
236
+ def iter_text_fragments(self) -> Iterator[str]:
237
+ """Yield all substantive text fragments in the parsed analysis."""
238
+ if self.coupling_classification:
239
+ yield self.coupling_classification
240
+ for _, section in self.iter_coupling_sections():
241
+ for entry in section.systems:
242
+ for value in entry.values():
243
+ if isinstance(value, str) and value:
244
+ yield value
245
+ for flow in section.flows:
246
+ for value in flow.values():
247
+ if isinstance(value, str) and value:
248
+ yield value
249
+ for agent in section.agents:
250
+ for value in agent.values():
251
+ if isinstance(value, str) and value:
252
+ yield value
253
+ for grouped in (section.causes, section.effects):
254
+ for items in grouped.values():
255
+ for item in items:
256
+ if item:
257
+ yield item
258
+ for item in self.cross_coupling_interactions:
259
+ if item:
260
+ yield item
261
+ for gap in self.research_gaps:
262
+ if gap:
263
+ yield gap
264
+
265
+
266
+ def _extract_sections(
267
+ text: str,
268
+ patterns: dict[str, re.Pattern[str]],
269
+ ) -> dict[str, str]:
270
+ """Split *text* into named sections using the supplied patterns."""
271
+ found: list[tuple[int, str]] = []
272
+ for name, pattern in patterns.items():
273
+ match = pattern.search(text)
274
+ if match:
275
+ found.append((match.start(), name))
276
+
277
+ if not found:
278
+ return {}
279
+
280
+ found.sort(key=lambda item: item[0])
281
+ sections: dict[str, str] = {}
282
+ for idx, (start, name) in enumerate(found):
283
+ header_end = text.index("\n", start) + 1 if "\n" in text[start:] else len(text)
284
+ body_end = found[idx + 1][0] if idx + 1 < len(found) else len(text)
285
+ sections[name] = text[header_end:body_end].strip()
286
+ return sections
287
+
288
+
289
+ _TOP_SECTION_PATTERNS: dict[str, re.Pattern[str]] = {
290
+ "coupling_classification": re.compile(
291
+ r"^#+\s*\d*\.?\s*coupling\s+classification",
292
+ re.IGNORECASE | re.MULTILINE,
293
+ ),
294
+ "intracoupling": re.compile(
295
+ r"^#+\s*\d*\.?\s*intracoupling\s+analysis",
296
+ re.IGNORECASE | re.MULTILINE,
297
+ ),
298
+ "pericoupling": re.compile(
299
+ r"^#+\s*\d*\.?\s*pericoupling\s+analysis",
300
+ re.IGNORECASE | re.MULTILINE,
301
+ ),
302
+ "telecoupling": re.compile(
303
+ r"^#+\s*\d*\.?\s*telecoupling\s+analysis",
304
+ re.IGNORECASE | re.MULTILINE,
305
+ ),
306
+ "cross_coupling_interactions": re.compile(
307
+ r"^#+\s*\d*\.?\s*cross[-\s]+coupling\s+interactions?",
308
+ re.IGNORECASE | re.MULTILINE,
309
+ ),
310
+ "research_gaps": re.compile(
311
+ r"^#+\s*\d*\.?\s*(research\s+gaps?(?:\s*&\s*suggestions|\s+and\s+suggestions)?)",
312
+ re.IGNORECASE | re.MULTILINE,
313
+ ),
314
+ }
315
+
316
+ _COUPLING_SUBSECTION_PATTERNS: dict[str, re.Pattern[str]] = {
317
+ "systems": re.compile(
318
+ r"^#{1,6}\s*\d+(?:\.\d+)?\.?\s*systems?\s+identification",
319
+ re.IGNORECASE | re.MULTILINE,
320
+ ),
321
+ "flows": re.compile(
322
+ r"^#{1,6}\s*\d+(?:\.\d+)?\.?\s*flows?\s+analysis",
323
+ re.IGNORECASE | re.MULTILINE,
324
+ ),
325
+ "agents": re.compile(
326
+ r"^#{1,6}\s*\d+(?:\.\d+)?\.?\s*agents?",
327
+ re.IGNORECASE | re.MULTILINE,
328
+ ),
329
+ "causes": re.compile(
330
+ r"^#{1,6}\s*\d+(?:\.\d+)?\.?\s*causes?",
331
+ re.IGNORECASE | re.MULTILINE,
332
+ ),
333
+ "effects": re.compile(
334
+ r"^#{1,6}\s*\d+(?:\.\d+)?\.?\s*effects?",
335
+ re.IGNORECASE | re.MULTILINE,
336
+ ),
337
+ }
338
+
339
+
340
+ _BULLET_RE = re.compile(r"^\s*[-*•]\s+", re.MULTILINE)
341
+
342
+ _CAUSE_EFFECT_CATEGORY_ALIASES: dict[str, str] = {
343
+ "economic": "economic",
344
+ "economics": "economic",
345
+ "socioeconomic": "economic",
346
+ "socio-economic": "economic",
347
+ "financial": "economic",
348
+ "market": "economic",
349
+ "political": "political / institutional",
350
+ "institutional": "political / institutional",
351
+ "political / institutional": "political / institutional",
352
+ "political/institutional": "political / institutional",
353
+ "governance": "political / institutional",
354
+ "ecological": "ecological / biological",
355
+ "biological": "ecological / biological",
356
+ "ecological / biological": "ecological / biological",
357
+ "ecological/biological": "ecological / biological",
358
+ "environmental": "ecological / biological",
359
+ "biodiversity": "ecological / biological",
360
+ "technological": "technological / infrastructural",
361
+ "infrastructural": "technological / infrastructural",
362
+ "technological / infrastructural": "technological / infrastructural",
363
+ "technological/infrastructural": "technological / infrastructural",
364
+ "infrastructure": "technological / infrastructural",
365
+ "cultural": "cultural / social / demographic",
366
+ "social": "cultural / social / demographic",
367
+ "demographic": "cultural / social / demographic",
368
+ "cultural / social / demographic": "cultural / social / demographic",
369
+ "cultural/social/demographic": "cultural / social / demographic",
370
+ "cultural / demographic / social": "cultural / social / demographic",
371
+ "hydrological": "hydrological",
372
+ "water": "hydrological",
373
+ "climatic": "climatic / atmospheric",
374
+ "atmospheric": "climatic / atmospheric",
375
+ "climatic / atmospheric": "climatic / atmospheric",
376
+ "climatic/atmospheric": "climatic / atmospheric",
377
+ "climate": "climatic / atmospheric",
378
+ "biogeochemical": "climatic / atmospheric",
379
+ "geological": "geological / geomorphological",
380
+ "geomorphological": "geological / geomorphological",
381
+ "geological / geomorphological": "geological / geomorphological",
382
+ "geological/geomorphological": "geological / geomorphological",
383
+ }
384
+
385
+
386
+ def _normalize_cause_effect_category(category: str) -> str:
387
+ """Normalize cause/effect headings to the fixed category vocabulary."""
388
+ normalized = category.strip().lower()
389
+ normalized = re.sub(r"\s+", " ", normalized)
390
+ return _CAUSE_EFFECT_CATEGORY_ALIASES.get(normalized, normalized)
391
+
392
+
393
+ def _extract_bullets(text: str) -> list[str]:
394
+ """Extract bullet items from text."""
395
+ items: list[str] = []
396
+ for line in text.splitlines():
397
+ line = line.strip()
398
+ if _BULLET_RE.match(line):
399
+ clean = _BULLET_RE.sub("", line).strip()
400
+ if clean:
401
+ items.append(clean)
402
+ return items
403
+
404
+
405
+ def _extract_categorized_bullets(text: str) -> dict[str, list[str]]:
406
+ """Extract bullets grouped under bold headings."""
407
+ result: dict[str, list[str]] = {}
408
+ current_category = "general"
409
+ for line in text.splitlines():
410
+ stripped = line.strip()
411
+ heading_match = re.match(
412
+ r"\*{2}([^*]+)\*{2}\s*(?::|[-—–].*)?\s*$",
413
+ stripped,
414
+ )
415
+ if heading_match:
416
+ current_category = _normalize_cause_effect_category(
417
+ heading_match.group(1)
418
+ )
419
+ continue
420
+ if _BULLET_RE.match(stripped):
421
+ clean = _BULLET_RE.sub("", stripped).strip()
422
+ if clean:
423
+ result.setdefault(current_category, []).append(clean)
424
+ return result
425
+
426
+
427
+ _SYSTEM_ROLE_ALIASES: dict[str, str] = {
428
+ "focal": "focal",
429
+ "focal system": "focal",
430
+ "adjacent": "adjacent",
431
+ "adjacent system": "adjacent",
432
+ "sending": "sending",
433
+ "sending system": "sending",
434
+ "receiving": "receiving",
435
+ "receiving system": "receiving",
436
+ "spillover": "spillover",
437
+ "spillover system": "spillover",
438
+ }
439
+
440
+ _SYSTEM_SUBFIELD_ALIASES: dict[str, str] = {
441
+ "human subsystem": "human_subsystem",
442
+ "human subsystems": "human_subsystem",
443
+ "human component": "human_subsystem",
444
+ "human components": "human_subsystem",
445
+ "natural subsystem": "natural_subsystem",
446
+ "natural subsystems": "natural_subsystem",
447
+ "natural component": "natural_subsystem",
448
+ "natural components": "natural_subsystem",
449
+ "geographic scope": "geographic_scope",
450
+ "geography": "geographic_scope",
451
+ "location": "geographic_scope",
452
+ }
453
+
454
+
455
+ def _parse_systems(text: str) -> list[dict[str, str]]:
456
+ """Parse a systems-identification block into system-entry dicts."""
457
+ system_heading_re = re.compile(
458
+ r"(?:#{1,6}\s*)?\*{0,2}\s*"
459
+ r"(Focal|Adjacent|Sending|Receiving|Spillover)\s*(?:System)?"
460
+ r"(?:\s*\(([^)]+)\))?"
461
+ r"\s*\*{0,2}\s*:\s*(.*)$",
462
+ re.IGNORECASE,
463
+ )
464
+
465
+ systems: list[dict[str, str]] = []
466
+ current: dict[str, str] | None = None
467
+
468
+ def _flush() -> None:
469
+ nonlocal current
470
+ if current:
471
+ systems.append(dict(current))
472
+ current = None
473
+
474
+ found_heading = False
475
+
476
+ for line in text.splitlines():
477
+ stripped = line.strip()
478
+ if not stripped:
479
+ continue
480
+
481
+ heading_match = system_heading_re.match(stripped)
482
+ if heading_match:
483
+ _flush()
484
+ found_heading = True
485
+ role = _normalize_system_role(heading_match.group(1))
486
+ current = {"role": role}
487
+ scope = _normalize_system_scope(heading_match.group(2))
488
+ if scope:
489
+ current["system_scope"] = scope
490
+ name = heading_match.group(3).strip().rstrip("*").strip()
491
+ if name:
492
+ current["name"] = name
493
+ continue
494
+
495
+ if current is not None:
496
+ clean = _BULLET_RE.sub("", stripped).strip()
497
+ if not clean:
498
+ continue
499
+ subfield_match = re.match(r"\*{0,2}([^:*]+)\*{0,2}\s*:\s*(.*)", clean)
500
+ if subfield_match:
501
+ label = subfield_match.group(1).strip().lower()
502
+ value = subfield_match.group(2).strip()
503
+ normalized = _SYSTEM_SUBFIELD_ALIASES.get(label)
504
+ if normalized:
505
+ current[normalized] = value
506
+ else:
507
+ current[label.replace(" ", "_")] = value
508
+ else:
509
+ existing = current.get("description", "")
510
+ current["description"] = (
511
+ f"{existing} {clean}".strip() if existing else clean
512
+ )
513
+
514
+ _flush()
515
+ if found_heading and systems:
516
+ return systems
517
+
518
+ # Fallback: flat bullets such as "- Focal: Michigan"
519
+ for item in _extract_bullets(text):
520
+ match = re.match(r"\*{0,2}([^:*]+)\*{0,2}\s*:\s*(.*)", item)
521
+ if not match:
522
+ continue
523
+ role = _normalize_system_role(match.group(1))
524
+ if role in {"focal", "adjacent", "sending", "receiving", "spillover"}:
525
+ entry = {"role": role, "name": match.group(2).strip()}
526
+ scope_match = re.search(r"\(([^)]+)\)", match.group(1))
527
+ scope = _normalize_system_scope(scope_match.group(1) if scope_match else None)
528
+ if scope:
529
+ entry["system_scope"] = scope
530
+ systems.append(entry)
531
+ return systems
532
+
533
+
534
+ _AGENT_LEVEL_ALIASES: dict[str, str] = {
535
+ "individuals / households": "individuals / households",
536
+ "individuals/households": "individuals / households",
537
+ "individual": "individuals / households",
538
+ "individuals": "individuals / households",
539
+ "person": "individuals / households",
540
+ "people": "individuals / households",
541
+ "household": "individuals / households",
542
+ "households": "individuals / households",
543
+ "family": "individuals / households",
544
+ "families": "individuals / households",
545
+ "resident": "individuals / households",
546
+ "residents": "individuals / households",
547
+ "farmer": "individuals / households",
548
+ "farmers": "individuals / households",
549
+ "consumer": "individuals / households",
550
+ "consumers": "individuals / households",
551
+ "tourist": "individuals / households",
552
+ "tourists": "individuals / households",
553
+ "firms / traders / corporations": "firms / traders / corporations",
554
+ "firms/traders/corporations": "firms / traders / corporations",
555
+ "firm": "firms / traders / corporations",
556
+ "firms": "firms / traders / corporations",
557
+ "trader": "firms / traders / corporations",
558
+ "traders": "firms / traders / corporations",
559
+ "company": "firms / traders / corporations",
560
+ "companies": "firms / traders / corporations",
561
+ "corporation": "firms / traders / corporations",
562
+ "corporations": "firms / traders / corporations",
563
+ "business": "firms / traders / corporations",
564
+ "businesses": "firms / traders / corporations",
565
+ "exporter": "firms / traders / corporations",
566
+ "exporters": "firms / traders / corporations",
567
+ "importer": "firms / traders / corporations",
568
+ "importers": "firms / traders / corporations",
569
+ "governments / policymakers": "governments / policymakers",
570
+ "governments/policymakers": "governments / policymakers",
571
+ "government": "governments / policymakers",
572
+ "governments": "governments / policymakers",
573
+ "policymaker": "governments / policymakers",
574
+ "policymakers": "governments / policymakers",
575
+ "policy maker": "governments / policymakers",
576
+ "policy makers": "governments / policymakers",
577
+ "regulator": "governments / policymakers",
578
+ "regulators": "governments / policymakers",
579
+ "agency": "governments / policymakers",
580
+ "agencies": "governments / policymakers",
581
+ "organization": "organizations / NGOs",
582
+ "organizations": "organizations / NGOs",
583
+ "organisations": "organizations / NGOs",
584
+ "organisation": "organizations / NGOs",
585
+ "organizations / ngos": "organizations / NGOs",
586
+ "organizations/ngos": "organizations / NGOs",
587
+ "ngo": "organizations / NGOs",
588
+ "ngos": "organizations / NGOs",
589
+ "nonprofit": "organizations / NGOs",
590
+ "non-profit": "organizations / NGOs",
591
+ "university": "organizations / NGOs",
592
+ "universities": "organizations / NGOs",
593
+ "research institution": "organizations / NGOs",
594
+ "research institutions": "organizations / NGOs",
595
+ "non-human agents": "non-human agents",
596
+ "nonhuman agents": "non-human agents",
597
+ "non-human": "non-human agents",
598
+ "nonhuman": "non-human agents",
599
+ "animal": "non-human agents",
600
+ "animals": "non-human agents",
601
+ "species": "non-human agents",
602
+ "organism": "non-human agents",
603
+ "organisms": "non-human agents",
604
+ "pathogen": "non-human agents",
605
+ "pathogens": "non-human agents",
606
+ "pest": "non-human agents",
607
+ "pests": "non-human agents",
608
+ "invasive species": "non-human agents",
609
+ "livestock": "non-human agents",
610
+ "crop": "non-human agents",
611
+ "crops": "non-human agents",
612
+ }
613
+
614
+
615
+ def _detect_agent_level(text: str) -> str:
616
+ """Detect an agent level in a text string."""
617
+ bracket_match = re.search(r"\[([^\]]+)\]", text)
618
+ if bracket_match:
619
+ label = re.sub(r"\s+", " ", bracket_match.group(1).strip().lower())
620
+ if label in _AGENT_LEVEL_ALIASES:
621
+ return _AGENT_LEVEL_ALIASES[label]
622
+ lowered = text.lower()
623
+ for label, normalized in _AGENT_LEVEL_ALIASES.items():
624
+ if label in lowered:
625
+ return normalized
626
+ return ""
627
+
628
+
629
+ def _parse_agents(text: str) -> list[dict[str, str]]:
630
+ """Parse agent bullets into structured dicts."""
631
+ agents: list[dict[str, str]] = []
632
+ for item in _extract_bullets(text):
633
+ agent: dict[str, str] = {}
634
+ bracket_match = re.match(r"\[([^\]]+)\]\s*(.*)", item)
635
+ if bracket_match:
636
+ label = re.sub(r"\s+", " ", bracket_match.group(1).strip().lower())
637
+ level = _AGENT_LEVEL_ALIASES.get(label, "")
638
+ rest = bracket_match.group(2).strip()
639
+ if level:
640
+ agent["level"] = level
641
+ colon_match = re.match(r"([^:]+):\s*(.*)", rest)
642
+ if colon_match:
643
+ agent["name"] = colon_match.group(1).strip()
644
+ agent["description"] = colon_match.group(2).strip()
645
+ else:
646
+ agent["name"] = rest
647
+ agents.append(agent)
648
+ continue
649
+
650
+ colon_match = re.match(r"([^:]+):\s*(.*)", item)
651
+ if colon_match:
652
+ agent["name"] = colon_match.group(1).strip()
653
+ agent["description"] = colon_match.group(2).strip()
654
+ else:
655
+ agent["name"] = item
656
+
657
+ detected_level = _detect_agent_level(item)
658
+ if detected_level:
659
+ agent["level"] = detected_level
660
+ agents.append(agent)
661
+ return agents
662
+
663
+
664
+ _FLOW_CATEGORIES = {
665
+ "capital", "energy", "information", "matter", "organisms", "people",
666
+ }
667
+
668
+ _FLOW_CATEGORY_ALIASES: dict[str, str] = {
669
+ "material": "matter",
670
+ "materials": "matter",
671
+ "goods": "matter",
672
+ "commodity": "matter",
673
+ "commodities": "matter",
674
+ "financial": "capital",
675
+ "finance": "capital",
676
+ "monetary": "capital",
677
+ "money": "capital",
678
+ "economic": "capital",
679
+ "knowledge": "information",
680
+ "data": "information",
681
+ "technology": "information",
682
+ "human": "people",
683
+ "labor": "people",
684
+ "labour": "people",
685
+ "migration": "people",
686
+ "organism": "organisms",
687
+ "biological": "organisms",
688
+ "species": "organisms",
689
+ "wildlife": "organisms",
690
+ "power": "energy",
691
+ "electricity": "energy",
692
+ }
693
+
694
+
695
+ def _detect_flow_category(text: str) -> str:
696
+ """Detect a canonical flow category in a string."""
697
+ lowered = text.lower()
698
+ for category in _FLOW_CATEGORIES:
699
+ if category in lowered:
700
+ return category
701
+ for alias, canonical in _FLOW_CATEGORY_ALIASES.items():
702
+ if alias in lowered:
703
+ return canonical
704
+ return ""
705
+
706
+
707
+ def _detect_direction(text: str) -> str:
708
+ """Detect a direction string containing an arrow."""
709
+ arrow_match = re.search(
710
+ r"([A-Za-z][\w\s/,()'-]*?)\s*(?:→|->|=>)\s*([A-Za-z][\w\s/,()'-]*)",
711
+ text,
712
+ )
713
+ if arrow_match:
714
+ return f"{arrow_match.group(1).strip()} → {arrow_match.group(2).strip()}"
715
+ bidirectional_match = re.search(
716
+ r"([A-Za-z][\w\s/,()'-]*?)\s*(?:↔|<->|<=>)\s*([A-Za-z][\w\s/,()'-]*)",
717
+ text,
718
+ )
719
+ if bidirectional_match:
720
+ return (
721
+ f"Bidirectional ({bidirectional_match.group(1).strip()} ↔ "
722
+ f"{bidirectional_match.group(2).strip()})"
723
+ )
724
+ if "bidirectional" in text.lower():
725
+ return "Bidirectional"
726
+ return ""
727
+
728
+
729
+ def _parse_multiline_flows(text: str) -> list[dict[str, str]]:
730
+ """Parse multi-line flow blocks under bold category headings."""
731
+ flow_heading_re = re.compile(
732
+ r"(?:\d+\.?\s*)?\*{2}\s*(?:\d+\.?\s*)?([\w\s/]+?flows?)\s*\*{2}\s*:?\s*$",
733
+ re.IGNORECASE | re.MULTILINE,
734
+ )
735
+ headings = list(flow_heading_re.finditer(text))
736
+ if not headings:
737
+ return []
738
+
739
+ flows: list[dict[str, str]] = []
740
+ for idx, match in enumerate(headings):
741
+ block_start = match.end()
742
+ block_end = headings[idx + 1].start() if idx + 1 < len(headings) else len(text)
743
+ block = text[block_start:block_end].strip()
744
+ category = _detect_flow_category(match.group(1))
745
+ direction = ""
746
+ description_parts: list[str] = []
747
+ for line in block.splitlines():
748
+ stripped = line.strip()
749
+ if not stripped:
750
+ continue
751
+ clean = _BULLET_RE.sub("", stripped).strip()
752
+ if not clean:
753
+ continue
754
+ direction_match = re.match(r"\*{0,2}direction\*{0,2}\s*:\s*(.*)", clean, re.IGNORECASE)
755
+ if direction_match:
756
+ direction = direction_match.group(1).strip()
757
+ continue
758
+ description_match = re.match(r"\*{0,2}description\*{0,2}\s*:\s*(.*)", clean, re.IGNORECASE)
759
+ if description_match:
760
+ description_parts.append(description_match.group(1).strip())
761
+ continue
762
+ if not direction:
763
+ detected_direction = _detect_direction(clean)
764
+ if detected_direction:
765
+ direction = detected_direction
766
+ continue
767
+ description_parts.append(clean)
768
+
769
+ flow: dict[str, str] = {}
770
+ if category:
771
+ flow["category"] = category
772
+ if direction:
773
+ flow["direction"] = direction
774
+ if description_parts:
775
+ flow["description"] = " ".join(description_parts)
776
+ if flow:
777
+ flows.append(flow)
778
+ return flows
779
+
780
+
781
+ def _parse_flows(text: str) -> list[dict[str, str]]:
782
+ """Parse a flow-analysis block into flow-entry dicts."""
783
+ multiline = _parse_multiline_flows(text)
784
+ if multiline:
785
+ return multiline
786
+
787
+ flows: list[dict[str, str]] = []
788
+ for item in _extract_bullets(text):
789
+ flow: dict[str, str] = {}
790
+ bracket_match = re.match(r"\[([^\]]+)\]\s*([^:]+):\s*(.*)", item)
791
+ if bracket_match:
792
+ flow["category"] = _detect_flow_category(bracket_match.group(1)) or bracket_match.group(1).strip().lower()
793
+ flow["direction"] = bracket_match.group(2).strip()
794
+ flow["description"] = bracket_match.group(3).strip()
795
+ flows.append(flow)
796
+ continue
797
+
798
+ category_match = re.search(r"\*{0,2}category\*{0,2}\s*:\s*([^|*]+)", item, re.IGNORECASE)
799
+ direction_match = re.search(r"\*{0,2}direction\*{0,2}\s*:\s*([^|*]+)", item, re.IGNORECASE)
800
+ description_match = re.search(r"\*{0,2}description\*{0,2}\s*:\s*(.*)", item, re.IGNORECASE)
801
+ if category_match:
802
+ flow["category"] = _detect_flow_category(category_match.group(1)) or category_match.group(1).strip().lower()
803
+ if direction_match:
804
+ flow["direction"] = direction_match.group(1).strip()
805
+ if description_match:
806
+ flow["description"] = description_match.group(1).strip()
807
+ if flow:
808
+ flows.append(flow)
809
+ continue
810
+
811
+ detected_direction = _detect_direction(item)
812
+ detected_category = _detect_flow_category(item)
813
+ if detected_category:
814
+ flow["category"] = detected_category
815
+ if detected_direction:
816
+ flow["direction"] = detected_direction
817
+ if item:
818
+ flow.setdefault("description", item)
819
+ if flow:
820
+ flows.append(flow)
821
+ return flows
822
+
823
+
824
+ def _parse_coupling_section(text: str) -> CouplingSection | None:
825
+ """Parse one coupling-type top-level section."""
826
+ subsections = _extract_sections(text, _COUPLING_SUBSECTION_PATTERNS)
827
+ if not subsections:
828
+ return None
829
+
830
+ section = CouplingSection()
831
+ if "systems" in subsections:
832
+ section.systems = _parse_systems(subsections["systems"])
833
+ if "flows" in subsections:
834
+ section.flows = _parse_flows(subsections["flows"])
835
+ if "agents" in subsections:
836
+ section.agents = _parse_agents(subsections["agents"])
837
+ if "causes" in subsections:
838
+ section.causes = _extract_categorized_bullets(subsections["causes"])
839
+ if "effects" in subsections:
840
+ section.effects = _extract_categorized_bullets(subsections["effects"])
841
+ return None if section.is_empty else section
842
+
843
+
844
+ def parse_analysis(response_text: str) -> ParsedAnalysis:
845
+ """Parse a coupling-first LLM response into ``ParsedAnalysis``."""
846
+ result = ParsedAnalysis(raw_text=response_text)
847
+ sections = _extract_sections(response_text, _TOP_SECTION_PATTERNS)
848
+ if not sections:
849
+ return result
850
+
851
+ result.coupling_classification = sections.get("coupling_classification", "")
852
+ if "intracoupling" in sections:
853
+ result.intracoupling = _parse_coupling_section(sections["intracoupling"])
854
+ if "pericoupling" in sections:
855
+ result.pericoupling = _parse_coupling_section(sections["pericoupling"])
856
+ if "telecoupling" in sections:
857
+ result.telecoupling = _parse_coupling_section(sections["telecoupling"])
858
+ if "cross_coupling_interactions" in sections:
859
+ interactions = _extract_bullets(sections["cross_coupling_interactions"])
860
+ result.cross_coupling_interactions = interactions or [
861
+ line.strip()
862
+ for line in sections["cross_coupling_interactions"].splitlines()
863
+ if line.strip()
864
+ ]
865
+ if "research_gaps" in sections:
866
+ result.research_gaps = _extract_bullets(sections["research_gaps"])
867
+
868
+ return result