-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterpret_example_multilevel.py
More file actions
266 lines (159 loc) · 5.88 KB
/
interpret_example_multilevel.py
File metadata and controls
266 lines (159 loc) · 5.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
"""
Interpreter specialized for multilevel (mixed-effects) model outputs.
Multilevel models contain additional components such as random effects
and variance structures.
This module focuses on explaining those elements correctly.
"""
import re
from typing import Dict, List
from retrieval.search import semantic_search
from retrieval.logging_config import setup_logging
logger = setup_logging("interpret.linear")
# Same purpose as in linear interpreter.
# Kept separate for clarity and independence.
def clean_markdown(text: str) -> str:
"""
Remove markdown artifacts and bullet symbols for clean reporting.
"""
cleaned_lines = []
for line in text.splitlines():
stripped = line.strip()
if not stripped:
continue
if stripped.startswith("#"):
continue
if stripped.startswith("##"):
continue
if stripped.startswith("###"):
continue
if stripped.startswith("---"):
continue
if stripped.startswith("- "):
stripped = stripped[2:]
cleaned_lines.append(stripped)
return "\n".join(cleaned_lines)
# Removes duplicate KB hits.
# Multilevel queries often retrieve overlapping explanations.
def unique_and_trim(results: List[str]) -> List[str]:
seen = set()
unique = []
for r in results:
key = r[:120]
if key not in seen:
seen.add(key)
unique.append(r)
return unique
"""
Detect multilevel-specific statistical concepts in model output.
This includes:
- fixed effects
- random effects
- variance components
- model selection metrics
"""
def extract_multilevel_signals(text: str) -> Dict[str, List[str]]:
signals = {}
if "lme(" in text or "Random effects" in text:
signals["model_type"] = [
"interpretation of nlme lme model with nested random effects"
]
if "Fixed effects" in text:
signals["fixed"] = [
"interpretation of fixed effects in multilevel model"
]
if "Random effects" in text:
signals["variance"] = [
"interpretation of random effects variance components"
]
# Detect AIC / BIC / logLik
if "AIC" in text or "BIC" in text or "loglik" in text or "logLik" in text or "loglik" in text:
signals["metrics"] = [
"model selection criteria in multilevel models AIC BIC logLik REML ML"
]
return signals
"""
Main interpretation pipeline for multilevel models.
This works similarly to the linear interpreter but targets
hierarchical model concepts.
"""
def interpret_multilevel_output(text: str):
if not isinstance(text, str) or not text.strip():
raise ValueError("Invalid model output")
print("=== MULTILEVEL MODEL INTERPRETATION ===\n")
logger.info("Interpreting model output (%d chars)", len(text))
signals = extract_multilevel_signals(text)
logger.info("Detected signals: %s", list(signals.keys()))
if "model_type" in signals:
print("## Model Type\n")
for q in signals["model_type"]:
logger.debug("Searching KB for signal: %s", q)
try:
results = semantic_search(q, k=3)
except Exception as e:
logger.error("Search failed for signal '%s': %s", q, e)
continue
results = unique_and_trim(results)
results = results[:1]
for r in results:
formatted = clean_markdown(r)
for p in formatted.split("\n"):
if p.strip():
print(" ", p)
print()
if "fixed" in signals:
print("## Fixed Effects\n")
for q in signals["fixed"]:
logger.debug("Searching KB for signal: %s", q)
try:
results = semantic_search(q, k=3)
except Exception as e:
logger.error("Search failed for signal '%s': %s", q, e)
continue
results = unique_and_trim(results)
results = results[:1]
for r in results:
formatted = clean_markdown(r)
for p in formatted.split("\n"):
if p.strip():
print(" ", p)
print()
if "variance" in signals:
print("## Variance Components\n")
for q in signals["variance"]:
logger.debug("Searching KB for signal: %s", q)
try:
results = semantic_search(q, k=3)
except Exception as e:
logger.error("Search failed for signal '%s': %s", q, e)
continue
results = unique_and_trim(results)
results = results[:1]
for r in results:
formatted = clean_markdown(r)
for p in formatted.split("\n"):
if p.strip():
print(" ", p)
print()
if "metrics" in signals:
print("## Model Metrics\n")
for q in signals["metrics"]:
logger.debug("Searching KB for signal: %s", q)
try:
results = semantic_search(q, k=3)
except Exception as e:
logger.error("Search failed for signal '%s': %s", q, e)
continue
results = unique_and_trim(results)
results = results[:1]
for r in results:
formatted = clean_markdown(r)
for p in formatted.split("\n"):
if p.strip():
print(" ", p)
print()
print("=== END OF REPORT ===")
# Entry point for manual testing with example multilevel output.
if __name__ == "__main__":
with open("examples/hlm_output_multilevel_R.txt") as f:
text = f.read()
interpret_multilevel_output(text)