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 @@
1
+ """Output formatting for analysis results."""
@@ -0,0 +1,276 @@
1
+ """
2
+ Human-readable formatting of coupling-first analysis results.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from metacouplingllm.llm.parser import CouplingSection, ParsedAnalysis
8
+
9
+
10
+ _SEPARATOR = "=" * 72
11
+ _SUB_SEPARATOR = "-" * 40
12
+
13
+
14
+ class AnalysisFormatter:
15
+ """Formats :class:`ParsedAnalysis` objects into readable text."""
16
+
17
+ @staticmethod
18
+ def _format_system_label(entry: dict[str, str]) -> str:
19
+ """Return a display label for a parsed system role."""
20
+ role = entry.get("role", "system").strip().lower()
21
+ if role in {"focal", "adjacent", "sending", "receiving", "spillover"}:
22
+ label = f"{role.title()} System"
23
+ else:
24
+ label = role.replace("_", " ").title()
25
+
26
+ scope = entry.get("system_scope", "").strip().lower()
27
+ if scope:
28
+ label = f"{label} ({scope})"
29
+ return label
30
+
31
+ @staticmethod
32
+ def _format_systems(section: CouplingSection) -> list[str]:
33
+ lines: list[str] = []
34
+ for entry in section.systems:
35
+ lines.append(f" [{AnalysisFormatter._format_system_label(entry)}]")
36
+ if entry.get("name"):
37
+ lines.append(f" {entry['name']}")
38
+ if entry.get("human_subsystem"):
39
+ lines.append(f" Human subsystem: {entry['human_subsystem']}")
40
+ if entry.get("natural_subsystem"):
41
+ lines.append(f" Natural subsystem: {entry['natural_subsystem']}")
42
+ if entry.get("geographic_scope"):
43
+ lines.append(f" Geographic scope: {entry['geographic_scope']}")
44
+ if entry.get("description"):
45
+ lines.append(f" {entry['description']}")
46
+ known = {
47
+ "role",
48
+ "name",
49
+ "human_subsystem",
50
+ "natural_subsystem",
51
+ "geographic_scope",
52
+ "description",
53
+ "system_scope",
54
+ }
55
+ for key, value in entry.items():
56
+ if key not in known and value:
57
+ lines.append(f" {key.replace('_', ' ').title()}: {value}")
58
+ return lines
59
+
60
+ @staticmethod
61
+ def _format_flows(section: CouplingSection) -> list[str]:
62
+ lines: list[str] = []
63
+ for idx, flow in enumerate(section.flows, 1):
64
+ category = flow.get("category", "unspecified").title()
65
+ direction = flow.get("direction", "Unspecified")
66
+ description = flow.get("description", "")
67
+ lines.append(f" {idx}. [{category}] {direction}")
68
+ if description:
69
+ lines.append(f" {description}")
70
+ return lines
71
+
72
+ @staticmethod
73
+ def _format_agents(section: CouplingSection) -> list[str]:
74
+ lines: list[str] = []
75
+ for agent in section.agents:
76
+ level = agent.get("level", "").title()
77
+ name = agent.get("name", "")
78
+ description = agent.get("description", "")
79
+ prefix = f"[{level}] " if level else ""
80
+ suffix = f" - {description}" if description else ""
81
+ lines.append(f" - {prefix}{name}{suffix}")
82
+ return lines
83
+
84
+ @staticmethod
85
+ def _format_grouped_items(
86
+ grouped: dict[str, list[str]],
87
+ ) -> list[str]:
88
+ lines: list[str] = []
89
+ for category, items in grouped.items():
90
+ lines.append(f" {category.title()}:")
91
+ for item in items:
92
+ lines.append(f" - {item}")
93
+ return lines
94
+
95
+ @staticmethod
96
+ def _append_coupling_section(
97
+ parts: list[str],
98
+ number: int,
99
+ title: str,
100
+ section: CouplingSection | None,
101
+ ) -> None:
102
+ if section is None or section.is_empty:
103
+ return
104
+ parts.append(f"{number}. {title}")
105
+ parts.append(_SUB_SEPARATOR)
106
+
107
+ if section.systems:
108
+ parts.append(f" {number}.1 Systems Identification")
109
+ parts.extend(AnalysisFormatter._format_systems(section))
110
+ parts.append("")
111
+ if section.flows:
112
+ parts.append(f" {number}.2 Flows Analysis")
113
+ parts.extend(AnalysisFormatter._format_flows(section))
114
+ parts.append("")
115
+ if section.agents:
116
+ parts.append(f" {number}.3 Agents")
117
+ parts.extend(AnalysisFormatter._format_agents(section))
118
+ parts.append("")
119
+ if section.causes:
120
+ parts.append(f" {number}.4 Causes")
121
+ parts.extend(AnalysisFormatter._format_grouped_items(section.causes))
122
+ parts.append("")
123
+ if section.effects:
124
+ parts.append(f" {number}.5 Effects")
125
+ parts.extend(AnalysisFormatter._format_grouped_items(section.effects))
126
+ parts.append("")
127
+
128
+ @staticmethod
129
+ def format_full(analysis: ParsedAnalysis) -> str:
130
+ """Produce a complete human-readable report."""
131
+ if not analysis.is_parsed:
132
+ return analysis.raw_text
133
+
134
+ parts: list[str] = [
135
+ _SEPARATOR,
136
+ "METACOUPLING FRAMEWORK ANALYSIS",
137
+ _SEPARATOR,
138
+ "",
139
+ ]
140
+
141
+ if analysis.coupling_classification:
142
+ parts.append("1. Coupling Classification")
143
+ parts.append(_SUB_SEPARATOR)
144
+ parts.append(analysis.coupling_classification)
145
+ parts.append("")
146
+
147
+ AnalysisFormatter._append_coupling_section(
148
+ parts,
149
+ 2,
150
+ "Intracoupling Analysis",
151
+ analysis.intracoupling,
152
+ )
153
+ AnalysisFormatter._append_coupling_section(
154
+ parts,
155
+ 3,
156
+ "Pericoupling Analysis",
157
+ analysis.pericoupling,
158
+ )
159
+ AnalysisFormatter._append_coupling_section(
160
+ parts,
161
+ 4,
162
+ "Telecoupling Analysis",
163
+ analysis.telecoupling,
164
+ )
165
+
166
+ if analysis.cross_coupling_interactions:
167
+ parts.append("5. Cross-coupling Interactions")
168
+ parts.append(_SUB_SEPARATOR)
169
+ for item in analysis.cross_coupling_interactions:
170
+ parts.append(f" - {item}")
171
+ parts.append("")
172
+
173
+ if analysis.research_gaps:
174
+ parts.append("6. Research Gaps and Suggestions")
175
+ parts.append(_SUB_SEPARATOR)
176
+ for gap in analysis.research_gaps:
177
+ parts.append(f" - {gap}")
178
+ parts.append("")
179
+
180
+ if analysis.pericoupling_info:
181
+ info = analysis.pericoupling_info
182
+ if info.get("level") == "adm1":
183
+ parts.append("PERICOUPLING DATABASE VALIDATION (SUBNATIONAL)")
184
+ else:
185
+ parts.append("PERICOUPLING DATABASE VALIDATION")
186
+ parts.append(_SUB_SEPARATOR)
187
+ for key, value in info.items():
188
+ if key == "level":
189
+ continue
190
+ if key == "pair_results":
191
+ for pair_result in str(value).split("; "):
192
+ parts.append(f" {pair_result}")
193
+ continue
194
+ label = key.replace("_", " ").title()
195
+ parts.append(f" {label}: {value}")
196
+ parts.append("")
197
+
198
+ parts.append(_SEPARATOR)
199
+ return "\n".join(parts)
200
+
201
+ @staticmethod
202
+ def format_summary(analysis: ParsedAnalysis) -> str:
203
+ """Produce a brief overview highlighting key findings."""
204
+ if not analysis.is_parsed:
205
+ raw = analysis.raw_text.strip()
206
+ return raw[:500] + "..." if len(raw) > 500 else raw
207
+
208
+ lines: list[str] = ["ANALYSIS SUMMARY", _SUB_SEPARATOR]
209
+ if analysis.coupling_classification:
210
+ first_line = analysis.coupling_classification.split("\n")[0].strip()
211
+ lines.append(f"Classification: {first_line}")
212
+
213
+ active = analysis.active_coupling_types()
214
+ if active:
215
+ lines.append(
216
+ "Active coupling types: " + ", ".join(name.title() for name in active)
217
+ )
218
+
219
+ flow_count = sum(1 for _ in analysis.iter_flow_entries())
220
+ if flow_count:
221
+ lines.append(f"Number of flows: {flow_count}")
222
+
223
+ gap_count = len(analysis.research_gaps)
224
+ if gap_count:
225
+ lines.append(f"Research gaps: {gap_count} items")
226
+
227
+ return "\n".join(lines)
228
+
229
+ @staticmethod
230
+ def format_component(analysis: ParsedAnalysis, component: str) -> str:
231
+ """Render a single component section."""
232
+ component_lower = component.lower().strip()
233
+ if component_lower in ("classification", "coupling_classification", "coupling"):
234
+ return analysis.coupling_classification or "(No classification data)"
235
+ if component_lower in ("intracoupling", "pericoupling", "telecoupling"):
236
+ section = analysis.get_coupling_section(component_lower)
237
+ if section is None or section.is_empty:
238
+ return f"(No {component_lower} data)"
239
+ pseudo = ParsedAnalysis(raw_text="")
240
+ setattr(pseudo, component_lower, section)
241
+ return AnalysisFormatter.format_full(pseudo)
242
+ if component_lower in ("cross_coupling", "cross-coupling", "interactions"):
243
+ if not analysis.cross_coupling_interactions:
244
+ return "(No cross-coupling interaction data)"
245
+ return "\n".join(f"- {item}" for item in analysis.cross_coupling_interactions)
246
+ if component_lower in ("research gaps", "gaps", "suggestions", "research_gaps"):
247
+ if not analysis.research_gaps:
248
+ return "(No research gap data)"
249
+ return "\n".join(f"- {item}" for item in analysis.research_gaps)
250
+ return f"(Unknown component: {component})"
251
+
252
+ @staticmethod
253
+ def format_comparison(analyses: list[ParsedAnalysis]) -> str:
254
+ """Produce a side-by-side comparison of multiple analyses."""
255
+ if not analyses:
256
+ return "(No analyses to compare)"
257
+ if len(analyses) == 1:
258
+ return AnalysisFormatter.format_full(analyses[0])
259
+
260
+ lines: list[str] = [_SEPARATOR, "COMPARATIVE ANALYSIS", _SEPARATOR, ""]
261
+ for idx, analysis in enumerate(analyses, 1):
262
+ lines.append(f"--- Analysis {idx} ---")
263
+ if analysis.coupling_classification:
264
+ first = analysis.coupling_classification.split("\n")[0].strip()
265
+ lines.append(f" Classification: {first}")
266
+ active = analysis.active_coupling_types()
267
+ if active:
268
+ lines.append(
269
+ " Active coupling types: "
270
+ + ", ".join(name.title() for name in active)
271
+ )
272
+ flow_count = sum(1 for _ in analysis.iter_flow_entries())
273
+ lines.append(f" Flows: {flow_count}")
274
+ lines.append(f" Research gaps: {len(analysis.research_gaps)}")
275
+ lines.append("")
276
+ return "\n".join(lines)
@@ -0,0 +1 @@
1
+ """Prompt templates and assembly for LLM-based framework analysis."""