-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata_utils.py
More file actions
2768 lines (2509 loc) · 118 KB
/
data_utils.py
File metadata and controls
2768 lines (2509 loc) · 118 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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import re
import pandas as pd
import matplotlib.pyplot as plt
from typing import List, Tuple, Optional, Dict, Any
from datetime import datetime
import logging
import base64
from io import BytesIO
import requests.exceptions
from simple_plotter import simple_plot_query
from utils_query import (
match_variable_from_yaml,
extract_examples_from_data,
get_available_workspaces,
extract_variable_and_region_from_query,
resolve_natural_language_variable_universal,
resolve_natural_language_variable_with_score,
resolve_natural_language_variable_candidates,
resolve_natural_language_variable_ranked,
extract_region_from_query,
format_region_label,
)
from utils.yaml_loader import load_all_yaml_files
from difflib import get_close_matches
import pickle
import os
# Create cached versions of YAML loading
def get_cached_yaml_definitions():
# Try file cache
cache_file = "cache/yaml_dicts.pkl"
if os.path.exists(cache_file):
with open(cache_file, 'rb') as f:
return pickle.load(f)
# Load YAML files (expensive operation)
variable_dict = load_all_yaml_files('definitions/variable')
region_dict = load_all_yaml_files('definitions/region')
result = (variable_dict, region_dict)
# Save to cache
os.makedirs("cache", exist_ok=True)
with open(cache_file, 'wb') as f:
pickle.dump(result, f)
return result
# Load variable and region definitions from YAML files (replace lines 18-20)
variable_dict, region_dict = get_cached_yaml_definitions()
logger = logging.getLogger(__name__)
def _normalize_free_text(text: str) -> str:
return re.sub(r"\s+", " ", str(text or "").strip().lower())
def _token_set(text: str) -> set[str]:
return {tok for tok in re.findall(r"[a-z0-9]+", _normalize_free_text(text)) if tok}
def _looks_like_plot_request(text: str) -> bool:
tokens = _token_set(text)
return bool(tokens & {"plot", "graph", "chart", "visualize", "visualise"})
def _looks_like_comparison_request(text: str) -> bool:
q = _normalize_free_text(text)
tokens = _token_set(text)
return bool(
{"compare", "comparison", "versus", "vs"} & tokens
or re.search(r"\bcompare\b", q)
or re.search(r"\bvs\b", q)
or re.search(r"\bversus\b", q)
)
def _looks_like_data_request(text: str) -> bool:
tokens = _token_set(text)
if _looks_like_plot_request(text):
return True
data_terms = {
"data", "value", "values", "timeseries", "time", "series", "trend",
"show", "display", "give", "provide", "retrieve", "fetch",
"emission", "emissions", "capacity", "energy", "generation",
"electricity", "demand", "supply", "variable", "variables",
"gdp", "growth", "share", "shares", "price", "prices",
"trajectory", "renewable", "renewables",
}
if tokens & data_terms:
return True
q = _normalize_free_text(text)
return bool(re.search(r"\btime\s+series\b", q) or re.search(r"\bunder\s+different\s+scenarios\b", q))
def _looks_like_discovery_request(text: str) -> bool:
q = _normalize_free_text(text)
tokens = _token_set(text)
explicit_category_list = any(
_looks_like_category_list_request(text, category)
for category in ("models", "variables", "regions", "scenarios", "workspaces")
)
if explicit_category_list:
return False
availability_terms = {"available", "included", "exist", "exists", "have", "contains", "included"}
categories = {"model", "models", "variable", "variables", "region", "regions", "scenario", "scenarios", "workspace", "workspaces"}
if tokens & availability_terms and tokens & categories:
return True
if tokens & {"list", "overview", "discover", "browse", "explore"} and tokens & categories:
return True
if re.search(r"\bwhat\s+can\s+i\s+ask\b", q):
return True
if re.search(r"\bwhat\s+kinds?\s+of\s+data\b", q):
return True
if re.search(r"\bhelp\s+me\s+find\s+data\b", q):
return True
return False
def _looks_like_model_info_request(text: str) -> bool:
q = _normalize_free_text(text)
tokens = _token_set(text)
if tokens & {
"info", "information", "details", "describe", "about", "explain",
"assumption", "assumptions", "methodology", "structure", "works",
}:
return True
return bool(
re.search(r"\btell\s+me\s+about\b", q)
or re.search(r"\bhow\s+does\b", q)
or re.search(r"\bwhat\s+are\s+the\s+assumptions\b", q)
)
def _looks_like_category_list_request(text: str, category: str) -> bool:
q = _normalize_free_text(text)
tokens = _token_set(text)
singular = category.rstrip("s")
valid_names = {singular, category}
if category == "variables":
valid_names.update({"indicator", "indicators", "metric", "metrics"})
if category == "regions":
valid_names.update({"country", "countries", "location", "locations", "area", "areas"})
if category == "scenarios":
valid_names.update({"pathway", "pathways"})
if category == "models":
valid_names.update({"iam", "iams"})
category_pattern = "|".join(sorted((re.escape(name) for name in valid_names), key=len, reverse=True))
explicit_list_terms = {"list", "which", "available", "included", "show", "display", "enumerate"}
if tokens & valid_names and tokens & explicit_list_terms:
if tokens & {"price", "trajectory", "trend", "plot", "graph", "chart", "compare", "growth", "share", "emissions", "capacity", "gdp"}:
return False
return True
return bool(
re.search(rf"\bwhat\s+(?:{category_pattern})\s+(?:are\s+)?(?:available|included)\b", q)
or re.search(
rf"\b(?:what|which)\s+(?:{category_pattern})\s+can\s+you\s+"
r"(?:plot|graph|chart|visuali[sz]e|show|display)\b",
q,
)
or re.search(rf"\bwhich\s+(?:{category_pattern})\b", q)
)
def _history_has_region_or_workspace(
history: list | None,
region_dict: dict,
ts_data: list
) -> bool:
if not history:
return False
region_candidates = sorted({str(r.get('region', '')).strip() for r in ts_data if r and r.get('region')})
workspaces = get_available_workspaces(ts_data)
for turn in history:
user_msg = ""
if isinstance(turn, (list, tuple)) and turn:
user_msg = str(turn[0] or "")
elif isinstance(turn, dict):
if turn.get("role") == "user":
user_msg = str(turn.get("content", "") or "")
if not user_msg:
continue
msg_lower = user_msg.lower()
if workspaces and any(ws.lower() in msg_lower for ws in workspaces if ws):
return True
if extract_region_from_query(user_msg, region_dict, region_candidates):
return True
return False
def _rank_variable_candidates(
question: str,
variable_dict: dict,
available_vars: set,
ranked_vars: list | None = None,
significant_words: list | None = None,
limit: int = 3,
) -> list[str]:
"""
Return a short list of the best variable candidates to confirm with the user.
The list prefers exact semantic matches, then available-variable substring matches,
then fuzzy fallbacks from the YAML resolver.
"""
query_lower = question.lower()
if not available_vars:
return []
candidates: list[str] = []
stop_words = {
"the", "a", "an", "and", "or", "but", "in", "on", "at", "to", "for", "of", "with", "by",
"show", "plot", "graph", "chart", "visualize", "display", "give", "me", "please", "data",
"value", "values", "time", "series", "timeseries", "trend", "region", "regions", "workspace",
"workspaces", "model", "models", "scenario", "scenarios", "what", "which", "want", "need",
"use", "it", "this", "that", "here", "there", "load", "please"
}
if ranked_vars:
candidates.extend([name for name, _, _, _ in ranked_vars if name in available_vars])
query_terms = set()
if significant_words:
query_terms.update(w for w in significant_words if len(w) > 2 and w not in stop_words)
query_terms.update(
w for w in re.findall(r"\b\w+\b", query_lower)
if len(w) > 2 and w not in stop_words
)
if query_terms:
term_matches = [
var for var in available_vars
if any(term in var.lower() for term in query_terms)
]
candidates.extend(term_matches)
if "co2" in query_lower or "carbon dioxide" in query_lower:
candidates.extend([v for v in available_vars if "co2" in v.lower() or "emission" in v.lower()])
if any(term in query_lower for term in ["emission", "emissions"]):
candidates.extend([v for v in available_vars if "emission" in v.lower() or "co2" in v.lower()])
if "solar" in query_lower or "pv" in query_lower or "photovoltaic" in query_lower:
candidates.extend([v for v in available_vars if "solar" in v.lower() or "pv" in v.lower()])
if "wind" in query_lower:
candidates.extend([v for v in available_vars if "wind" in v.lower()])
if "oil" in query_lower:
candidates.extend([v for v in available_vars if "oil" in v.lower()])
if any(term in query_lower for term in ["capacity", "generation", "demand", "investment"]):
candidates.extend([
v for v in available_vars
if any(term in v.lower() for term in ["capacity", "generation", "demand", "investment"])
])
if not candidates:
candidates = resolve_natural_language_variable_candidates(question, variable_dict, top_k=limit)
candidates = [c for c in candidates if c in available_vars]
if not candidates:
candidates = find_similar_available_variables(
question,
available_vars,
intent=_infer_variable_intent(question, significant_words),
significant_words=significant_words,
)
deduped: list[str] = []
for candidate in candidates:
if candidate and candidate not in deduped:
deduped.append(candidate)
if len(deduped) >= limit:
break
return deduped
def _record_has_year_data(record: dict) -> bool:
record = record or {}
if any(str(k).isdigit() for k in record.keys()):
return True
years = record.get("years")
return isinstance(years, dict) and any(str(k).isdigit() for k in years.keys())
def _infer_variable_intent(question: str, significant_words: list | None = None) -> str:
ql = (question or "").lower()
words = set(w.lower() for w in (significant_words or []) if w)
joined = " ".join(sorted(words))
def _has_any(tokens: list[str]) -> bool:
return any(t in ql or t in joined for t in tokens)
if _has_any(["methane", "ch4"]):
return "methane"
if _has_any(["gdp", "economic", "economy", "growth"]):
return "gdp"
if _has_any(["price", "prices", "cost", "costs", "trajectory"]):
return "price"
if _has_any(["share", "shares", "fraction"]):
return "share"
if _has_any(["renewable", "renewables", "clean energy"]):
return "renewables"
if _has_any(["oil"]):
return "oil"
if _has_any(["gas"]):
return "gas"
if _has_any(["hydrogen"]):
return "hydrogen"
if _has_any(["nuclear"]):
return "nuclear"
if _has_any(["hydro", "hydropower"]):
return "hydro"
if _has_any(["solar", "pv", "photovoltaic"]):
return "solar"
if _has_any(["wind"]):
return "wind"
if _has_any(["transport", "transportation"]):
return "transport"
if _has_any(["industry", "industrial"]):
return "industry"
if _has_any(["building", "buildings", "residential", "commercial"]):
return "buildings"
if _has_any(["co2", "emission", "emissions", "carbon"]):
return "emissions_co2"
if _has_any(["capacity"]):
return "capacity"
if _has_any(["electricity", "power", "generation"]):
return "electricity"
if _has_any(["demand"]):
return "demand"
if _has_any(["supply"]):
return "supply"
if _has_any(["investment", "investments", "invest"]):
return "investment"
return "general"
def _tokenize_text(text: str) -> set[str]:
return {t for t in re.findall(r"[a-z0-9]+", (text or "").lower()) if len(t) >= 2}
def _query_terms(question: str, significant_words: list | None = None) -> set[str]:
stop_words = {
"the", "a", "an", "and", "or", "but", "in", "on", "at", "to", "for", "of", "with", "by",
"show", "plot", "graph", "chart", "visualize", "display", "give", "me", "please", "data",
"value", "values", "time", "series", "timeseries", "trend", "region", "regions", "workspace",
"workspaces", "model", "models", "scenario", "scenarios", "what", "which", "want", "need",
"use", "it", "this", "that", "here", "there", "load", "under", "list", "available",
"tell", "about", "compare", "vs", "versus", "can", "you", "from"
}
terms = _tokenize_text(question)
if significant_words:
terms.update(str(w).lower() for w in significant_words if w)
return {t for t in terms if t not in stop_words}
def _query_profile(question: str, significant_words: list | None = None) -> dict[str, set[str] | bool]:
ql = (question or "").lower()
terms = _query_terms(question, significant_words)
def _has(*tokens: str) -> bool:
return any(token in ql or token in terms for token in tokens)
sector_terms = {
"transport": _has("transport", "transportation", "mobility", "vehicle", "vehicles"),
"industry": _has("industry", "industrial", "manufacturing", "steel", "cement"),
"buildings": _has("building", "buildings", "residential", "commercial", "heating", "cooling"),
"power": _has("electricity", "power", "generation", "grid"),
"afolu": _has("afolu", "land", "agriculture", "forestry", "lulucf"),
}
energy_terms = {
"renewables": _has("renewable", "renewables", "clean"),
"solar": _has("solar", "pv", "photovoltaic"),
"wind": _has("wind", "onshore", "offshore"),
"oil": _has("oil", "petroleum", "liquids"),
"gas": _has("gas", "methane", "naturalgas", "natural", "lng"),
"hydrogen": _has("hydrogen", "h2"),
"nuclear": _has("nuclear"),
"hydro": _has("hydro", "hydropower"),
"coal": _has("coal"),
"bioenergy": _has("biomass", "bioenergy", "biofuel", "biofuels"),
}
metric_terms = {
"emissions": _has("emission", "emissions", "co2", "carbon", "ghg", "greenhouse", "ch4", "methane", "n2o"),
"capacity": _has("capacity", "installed"),
"generation": _has("generation", "produce", "produced", "production", "electricity"),
"demand": _has("demand", "consumption", "use", "used"),
"supply": _has("supply", "supplyside", "production"),
"investment": _has("investment", "invest", "investments", "spending", "capital"),
"price": _has("price", "cost", "costs"),
"share": _has("share", "shares", "fraction"),
"gdp": _has("gdp", "growth", "economy", "economic"),
}
broad = {
"broad_metric": sum(metric_terms.values()) <= 1,
"broad_sector": sum(sector_terms.values()) == 0,
"broad_energy": sum(energy_terms.values()) <= 1,
}
return {
"terms": terms,
"sector_terms": {k for k, v in sector_terms.items() if v},
"energy_terms": {k for k, v in energy_terms.items() if v},
"metric_terms": {k for k, v in metric_terms.items() if v},
"broad_metric": broad["broad_metric"],
"broad_sector": broad["broad_sector"],
"broad_energy": broad["broad_energy"],
}
def _has_meaningful_query_signal(
question: str,
significant_words: list | None = None,
region: str | None = None,
scenario: str | None = None,
model: str | None = None,
) -> bool:
"""
Decide whether the user's free-text query contains enough semantic signal
to offer ranked variable choices instead of asking a generic follow-up.
"""
profile = _query_profile(question, significant_words)
terms = set(profile["terms"])
for value in [region, scenario, model]:
if value:
terms -= _tokenize_text(str(value))
weak_terms = {
"data", "show", "give", "plot", "graph", "chart", "value", "values",
"time", "series", "timeseries", "query", "information", "info"
}
terms = {term for term in terms if term not in weak_terms}
if profile["metric_terms"] or profile["sector_terms"] or profile["energy_terms"]:
return True
return len(terms) >= 2
def _variable_relevance_score(
variable: str,
question: str,
intent: str,
significant_words: list | None = None,
prefer_with_years: bool = False,
) -> float:
var = str(variable or "")
var_lower = var.lower()
var_terms = _tokenize_text(var_lower.replace("|", " "))
profile = _query_profile(question, significant_words)
query_terms = profile["terms"]
score = 0.0
overlap = query_terms & var_terms
score += len(overlap) * 5.0
if intent != "general":
strict_family = _filter_vars_by_intent([var], intent, strict=True)
soft_family = _filter_vars_by_intent([var], intent, strict=False)
if strict_family:
score += 20.0
elif soft_family:
score += 10.0
else:
score -= 12.0
sector_terms = profile["sector_terms"]
energy_terms = profile["energy_terms"]
metric_terms = profile["metric_terms"]
sector_map = {
"transport": ["transport", "transportation", "mobility", "vehicle"],
"industry": ["industry", "industrial", "steel", "cement"],
"buildings": ["building", "buildings", "residential", "commercial", "heating", "cooling"],
"power": ["electricity", "power", "generation", "grid"],
"afolu": ["afolu", "land", "agriculture", "forestry", "lulucf"],
}
energy_map = {
"renewables": ["renewable", "renewables", "solar", "wind", "hydro", "biomass", "bioenergy", "geothermal"],
"solar": ["solar", "pv", "photovoltaic"],
"wind": ["wind", "onshore", "offshore"],
"oil": ["oil", "petroleum", "liquids"],
"gas": ["gas", "methane", "lng"],
"hydrogen": ["hydrogen"],
"nuclear": ["nuclear"],
"hydro": ["hydro", "hydropower"],
"coal": ["coal"],
"bioenergy": ["biomass", "bioenergy", "biofuel"],
}
metric_map = {
"emissions": ["emission", "emissions", "co2", "carbon", "ch4", "methane", "ghg"],
"capacity": ["capacity", "installed"],
"generation": ["generation", "electricity", "power", "secondary energy"],
"demand": ["demand", "consumption", "final energy", "useful energy"],
"supply": ["supply", "primary energy", "secondary energy", "production"],
"investment": ["investment", "capital", "spending"],
"price": ["price", "cost"],
"share": ["share", "fraction"],
"gdp": ["gdp", "gross domestic product"],
}
for name, tokens in sector_map.items():
has_in_query = name in sector_terms
has_in_var = any(token in var_lower for token in tokens)
if has_in_query and has_in_var:
score += 8.0
elif has_in_query and not has_in_var:
score -= 4.0
elif not has_in_query and has_in_var and sector_terms:
score -= 3.0
for name, tokens in energy_map.items():
has_in_query = name in energy_terms
has_in_var = any(token in var_lower for token in tokens)
if has_in_query and has_in_var:
score += 8.0
elif has_in_query and not has_in_var:
score -= 4.0
elif not has_in_query and has_in_var and energy_terms:
score -= 2.0
for name, tokens in metric_map.items():
has_in_query = name in metric_terms
has_in_var = any(token in var_lower for token in tokens)
if has_in_query and has_in_var:
score += 9.0
elif has_in_query and not has_in_var:
score -= 5.0
elif not has_in_query and has_in_var and metric_terms:
score -= 2.0
if "emissions" in metric_terms and "co2" in query_terms:
if "emissions|co2" in var_lower or var_lower.startswith("gross emissions|co2"):
score += 10.0
elif "co2" in var_lower:
score += 4.0
else:
score -= 8.0
if "methane" in query_terms or "ch4" in query_terms:
if "methane" in var_lower or "ch4" in var_lower:
score += 12.0
else:
score -= 8.0
if "generation" in metric_terms and "investment" in var_lower and "investment" not in metric_terms:
score -= 10.0
if "capacity" in metric_terms and "generation" in var_lower and "capacity" not in var_lower:
score -= 5.0
if "demand" in metric_terms and "supply" in var_lower and "demand" not in var_lower:
score -= 4.0
if "investment" not in metric_terms and "investment" in var_lower:
score -= 12.0
if "price" not in metric_terms and "price" in var_lower:
score -= 10.0
if "share" in metric_terms and "investment" in var_lower and "investment" not in metric_terms:
score -= 14.0
if "renewables" in energy_terms and "investment" in var_lower and "investment" not in metric_terms:
score -= 10.0
if "renewables" in energy_terms and any(token in var_lower for token in ["primary energy", "secondary energy", "electricity"]):
score += 8.0
# Broad electricity requests should not drift into investment/price families.
if "electricity" in profile["metric_terms"] or "power" in profile["sector_terms"]:
if not (metric_terms & {"investment", "price", "capacity", "generation", "demand", "supply"}):
if any(token in var_lower for token in ["investment", "price", "cost"]):
score -= 18.0
if intent == "electricity" and "investment" not in metric_terms and "investment" in var_lower:
score -= 14.0
# If the query names a specific fuel or technology, heavily penalize variables that miss it.
named_energy_terms = set(profile["energy_terms"])
if named_energy_terms:
missing_named = [
term for term in named_energy_terms
if term in {"solar", "wind", "oil", "gas", "hydrogen", "nuclear", "hydro", "coal", "bioenergy"}
and not any(token in var_lower for token in energy_map[term])
]
score -= 12.0 * len(missing_named)
conflicting_fuels = {
"oil": {"gas", "coal", "hydrogen", "bioenergy"},
"gas": {"oil", "coal", "hydrogen", "bioenergy"},
"coal": {"oil", "gas", "hydrogen", "bioenergy"},
"hydrogen": {"oil", "gas", "coal", "bioenergy"},
}
for primary, conflicts in conflicting_fuels.items():
if primary in named_energy_terms and not any(token in var_lower for token in energy_map[primary]):
if any(conflict in var_lower for conflict in conflicts):
score -= 10.0
if "buildings" in profile["sector_terms"]:
if any(token in var_lower for token in ["final energy", "lighting", "appliances", "space heating", "space cooling"]):
score += 8.0
if "hydrogen" in var_lower:
score -= 6.0
if "transport" in profile["sector_terms"] and "emissions" in profile["metric_terms"]:
if "emission" in var_lower or "co2" in var_lower:
score += 10.0
elif "demand|" in var_lower:
score -= 4.0
if "solar" in question.lower():
if "capacity" in question.lower() and "capacity|electricity|solar" in var_lower:
score += 15.0
if "capacity additions|electricity|solar" in var_lower and not any(
token in question.lower() for token in ["addition", "additions", "new capacity", "build rate", "annual build"]
):
score -= 18.0
if any(token in question.lower() for token in ["energy", "electricity", "power", "generation"]):
if "secondary energy|electricity|solar" in var_lower or "generation|electricity|solar" in var_lower:
score += 14.0
elif "capacity|electricity|solar" in var_lower:
score += 8.0
if "investment" in var_lower:
score -= 10.0
if "oil" in question.lower():
if any(token in question.lower() for token in ["demand", "consumption", "energy", "use"]):
if any(token in var_lower for token in ["final energy", "primary energy", "secondary energy", "demand"]):
score += 14.0
if "electricity|oil" in var_lower and "electricity" not in question.lower():
score -= 6.0
if "investment" in var_lower:
score -= 8.0
if "electricity" in question.lower() and not (
set(profile["energy_terms"]) & {"solar", "wind", "oil", "gas", "hydrogen", "nuclear", "hydro", "coal", "bioenergy"}
):
if any(token in var_lower for token in ["|solar", "|wind", "|hydro", "|nuclear", "|oil", "|gas", "|coal", "|hydrogen", "|bioenergy"]):
score -= 10.0
if profile["broad_metric"] and profile["broad_sector"]:
score -= max(0, var.count("|") - 2) * 1.5
elif profile["broad_sector"]:
score -= max(0, var.count("|") - 3) * 1.0
top_family = var.split("|", 1)[0].lower()
friendly_families = {
"emissions": 6.0,
"gross emissions": 5.0,
"final energy": 5.0,
"primary energy": 4.0,
"secondary energy": 5.0,
"capacity": 5.0,
"investment": 3.0,
"price": 2.0,
"trade": 1.0,
}
if top_family in friendly_families:
score += friendly_families[top_family]
if not any(term in query_terms for term in {"export", "import", "trade", "forcing"}):
if any(token in var_lower for token in ["export", "import", "forcing"]):
score -= 10.0
if "trade" not in query_terms and top_family == "trade":
score -= 6.0
if prefer_with_years:
score += 1.0
return score
def _variable_matches_query_signal(
variable: str,
question: str,
intent: str,
significant_words: list | None = None,
) -> bool:
if _is_capacity_additions_mismatch(question, variable):
return False
score = _variable_relevance_score(variable, question, intent, significant_words)
if intent == "general":
return score >= 8
return score >= 12
def _is_capacity_additions_mismatch(question: str, variable: str | None) -> bool:
ql = str(question or "").lower()
vl = str(variable or "").lower()
if "capacity additions" not in vl:
return False
if "capacity" not in ql:
return False
return not any(
token in ql
for token in ["addition", "additions", "new capacity", "build rate", "annual build"]
)
def _clean_label_text(text: str) -> str:
cleaned = str(text or "")
replacements = {
"commerciall": "commercial",
"residential and commercial": "buildings",
"transportation": "transport",
}
for src, dst in replacements.items():
cleaned = re.sub(rf"\b{re.escape(src)}\b", dst, cleaned, flags=re.IGNORECASE)
cleaned = cleaned.replace("|", " ")
cleaned = re.sub(r"\s+", " ", cleaned).strip()
return cleaned
def _describe_variable_option(variable: str) -> str:
v = str(variable or "")
lower = v.lower()
parts = []
if "emissions|co2" in lower or lower.startswith("gross emissions|co2"):
parts.append("CO2 emissions")
elif "emissions|ch4" in lower or "methane" in lower:
parts.append("methane emissions")
elif "emissions" in lower:
parts.append("emissions")
elif "final energy" in lower:
parts.append("final energy use")
elif "primary energy" in lower:
parts.append("primary energy")
elif "secondary energy|electricity" in lower:
parts.append("electricity output")
elif "secondary energy" in lower:
parts.append("secondary energy")
elif "capacity|electricity" in lower:
parts.append("power capacity")
elif "capacity" in lower:
parts.append("capacity")
elif "investment" in lower:
parts.append("investment")
elif "price" in lower:
parts.append("price")
elif "demand" in lower:
parts.append("demand")
if "transport" in lower or "transportation" in lower:
parts.append("transport")
elif "industry" in lower or "industrial" in lower:
parts.append("industry")
elif any(token in lower for token in ["building", "residential", "commercial"]):
parts.append("buildings")
elif "afolu" in lower or "land" in lower:
parts.append("land use")
if "solar" in lower:
parts.append("solar")
elif "wind" in lower:
parts.append("wind")
elif "oil" in lower:
parts.append("oil")
elif "gas" in lower:
parts.append("gas")
elif "hydrogen" in lower:
parts.append("hydrogen")
elif "electricity" in lower and "output" not in " ".join(parts):
parts.append("electricity")
if not parts:
return ""
seen = []
for part in parts:
if part and part not in seen:
seen.append(_clean_label_text(part))
return ", ".join(seen[:3])
def _describe_choice_option(kind: str, option: str) -> str:
if kind == "variable":
return _describe_variable_option(option)
if kind == "region":
opt = str(option or "")
pretty = format_region_label(opt)
if pretty != opt:
return pretty
return ""
if kind == "scenario":
opt = str(option or "")
lower = opt.lower()
labels = []
if "baseline" in lower or lower.endswith("_bau") or lower == "bau":
labels.append("baseline")
if "curpol" in lower or "current policy" in lower:
labels.append("current policy")
if "ndc" in lower:
labels.append("NDC")
if "nze" in lower or "net-zero" in lower or "net zero" in lower:
labels.append("net zero")
if "1.5" in lower:
labels.append("1.5C pathway")
if "ssp" in lower:
m = re.search(r"(ssp\d)", lower)
labels.append(m.group(1).upper() if m else "SSP")
deduped = []
for label in labels:
if label and label not in deduped:
deduped.append(label)
return ", ".join(deduped[:2])
return ""
def _preferred_family_matches(question: str, available_vars: set[str]) -> list[str]:
"""
Hand-tuned family preferences for common plain-language phrases.
This keeps high-signal queries like "solar energy" and "oil demand"
in the right variable family instead of drifting to weaker matches.
"""
ql = (question or "").lower()
candidates: list[str] = []
if "solar" in ql:
if "capacity" in ql:
candidates.extend(
v for v in available_vars
if "solar" in v.lower() and "capacity|electricity" in v.lower()
)
if any(token in ql for token in ["energy", "electricity", "power", "generation"]):
candidates.extend(
v for v in available_vars
if "solar" in v.lower()
and (
"secondary energy|electricity" in v.lower()
or "generation|electricity" in v.lower()
or "capacity|electricity" in v.lower()
)
and "investment" not in v.lower()
)
if "oil" in ql and any(token in ql for token in ["demand", "consumption", "energy", "use"]):
candidates.extend(
v for v in available_vars
if "oil" in v.lower()
and any(
token in v.lower()
for token in ["final energy", "primary energy", "secondary energy", "demand"]
)
and "investment" not in v.lower()
)
deduped: list[str] = []
for candidate in candidates:
if candidate and candidate not in deduped:
deduped.append(candidate)
return deduped
def _broad_electricity_candidates(available_vars: set[str]) -> list[str]:
"""
Return broad electricity-family variables for generic electricity questions.
Prefer high-level output, use, capacity, and emissions variables over
technology- or sector-specific branches.
"""
preferred_order = [
"Secondary Energy|Electricity",
"Final Energy|Electricity",
"Capacity|Electricity",
"Emissions|CO2|Energy|Supply|Electricity",
"Emissions|CO2|Electricity",
]
candidates: list[str] = []
for name in preferred_order:
if name in available_vars and name not in candidates:
candidates.append(name)
if candidates:
return candidates
blocked_tokens = {
"transport", "transportation", "passenger", "freight",
"residential", "commercial", "industry", "other sector",
"solar", "wind", "hydro", "nuclear", "oil", "gas", "coal",
"biomass", "bioenergy", "geothermal", "hydrogen",
"investment", "price", "cost", "capital", "sequestration", "additions",
}
fallback = []
for variable in sorted(available_vars):
lower = variable.lower()
if "electricity" not in lower:
continue
if any(token in lower for token in blocked_tokens):
continue
fallback.append(variable)
return fallback[:3]
def _rank_scored_candidates(
candidates: list[str],
question: str,
intent: str,
significant_words: list | None = None,
popularity: dict[str, int] | None = None,
limit: int = 3,
) -> list[str]:
seen: list[str] = []
for candidate in candidates:
if candidate and candidate not in seen:
seen.append(candidate)
ranked = sorted(
seen,
key=lambda var: (
-(
_variable_relevance_score(var, question, intent, significant_words)
+ min((popularity or {}).get(var, 0), 8) * 0.75
),
var.count("|"),
len(var),
var,
),
)
return ranked[:limit]
def _filter_vars_by_intent(variables: set[str] | list[str], intent: str, strict: bool = False) -> list[str]:
items = [v for v in variables if v]
if not items:
return []
def _prioritize(matches: list[str]) -> list[str]:
if strict:
return matches
remainder = [v for v in items if v not in matches]
return matches + remainder
if intent == "emissions_co2":
co2 = [v for v in items if ("co2" in v.lower() and "emission" in v.lower()) or v.lower().startswith("gross emissions|co2")]
emissions = [v for v in items if "emission" in v.lower()]
preferred = co2 if co2 else emissions
if not preferred:
return []
return _prioritize(preferred)
if intent == "methane":
meth = [v for v in items if "ch4" in v.lower() or "methane" in v.lower()]
if not meth:
return []
return _prioritize(meth)
if intent == "solar":
solar = [v for v in items if "solar" in v.lower() or "pv" in v.lower()]
if not solar:
return []
preferred = [
v for v in solar
if any(k in v.lower() for k in ["generation", "electricity", "secondary energy", "capacity"])
and "investment" not in v.lower()
]
if preferred:
return _prioritize(preferred)
return _prioritize(solar)
if intent == "wind":
wind = [v for v in items if "wind" in v.lower()]
return _prioritize(wind)
if intent == "capacity":
cap = [v for v in items if "capacity" in v.lower()]
return _prioritize(cap)
if intent == "electricity":
elec = [v for v in items if "electricity" in v.lower() or "power" in v.lower() or "generation" in v.lower()]
return _prioritize(elec)
if intent == "demand":
demand = [v for v in items if "demand" in v.lower()]
return _prioritize(demand)
if intent == "supply":
supply = [v for v in items if "supply" in v.lower()]
return _prioritize(supply)
if intent == "investment":
inv = [v for v in items if "investment" in v.lower()]
return _prioritize(inv)
if intent == "price":
price = [v for v in items if "price" in v.lower() or "cost" in v.lower()]
return _prioritize(price)
if intent == "gdp":
gdp = [v for v in items if "gdp" in v.lower() or "gross domestic product" in v.lower()]
return _prioritize(gdp)
if intent == "share":
share = [v for v in items if "share" in v.lower() or "fraction" in v.lower()]
non_investment = [v for v in share if "investment" not in v.lower()]
if non_investment:
return _prioritize(non_investment)
return _prioritize(share)
if intent == "renewables":
renewables = [
v for v in items
if any(k in v.lower() for k in ["renewable", "renewables", "solar", "wind", "hydro", "bio", "geothermal"])
]
if any("share" in v.lower() or "fraction" in v.lower() for v in renewables):
renewable_shares = [
v for v in renewables
if ("share" in v.lower() or "fraction" in v.lower()) and "investment" not in v.lower()
]
if renewable_shares:
return _prioritize(renewable_shares)
return _prioritize(renewables)
if intent == "transport":
transport = [v for v in items if "transport" in v.lower()]
emissions_transport = [
v for v in transport
if "emission" in v.lower() or "co2" in v.lower() or "carbon" in v.lower()
]
if emissions_transport:
return _prioritize(emissions_transport)
return _prioritize(transport)