-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsparql_statistics.py
More file actions
1383 lines (1217 loc) · 49.8 KB
/
sparql_statistics.py
File metadata and controls
1383 lines (1217 loc) · 49.8 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 argparse
import json
import sys
from collections import Counter
from tqdm import tqdm
from universal_ml_utils.io import dump_jsonl
from utils import load_sparql_parser, parse_sparql
# Wikidata IRI base prefixes, sorted by length (longest first) for correct matching
WIKIDATA_IRI_PREFIXES = [
("http://www.wikidata.org/prop/statement/value-normalized/", "psn:"),
("http://www.wikidata.org/prop/qualifier/value-normalized/", "pqn:"),
("http://www.wikidata.org/prop/reference/value-normalized/", "prn:"),
("http://www.wikidata.org/prop/direct-normalized/", "wdtn:"),
("http://www.wikidata.org/prop/statement/value/", "psv:"),
("http://www.wikidata.org/prop/qualifier/value/", "pqv:"),
("http://www.wikidata.org/prop/reference/value/", "prv:"),
("http://www.wikidata.org/prop/statement/", "ps:"),
("http://www.wikidata.org/prop/qualifier/", "pq:"),
("http://www.wikidata.org/prop/reference/", "pr:"),
("http://www.wikidata.org/entity/statement/", "wds:"),
("http://www.wikidata.org/prop/novalue/", "wdno:"),
("http://www.wikidata.org/prop/direct/", "wdt:"),
("http://www.wikidata.org/wiki/Special:EntityData/", "wdata:"),
("http://www.wikidata.org/reference/", "wdref:"),
("http://www.wikidata.org/entity/", "wd:"),
("http://www.wikidata.org/value/", "wdv:"),
("http://www.wikidata.org/prop/", "p:"),
("http://wikiba.se/ontology#", "wikibase:"),
]
# Default prefix map (standard Wikidata prefixes, as predefined by WDQS)
DEFAULT_PREFIX_MAP = {prefix: base for base, prefix in WIKIDATA_IRI_PREFIXES}
WIKIDATA_BASE = "http://www.wikidata.org/"
def get_wikidata_prefix(iri: str) -> str | None:
"""
Get the canonical Wikidata prefix for an IRI, or None if not a Wikidata IRI.
Returns "other:" for Wikidata IRIs that don't match any known prefix.
"""
for base, prefix in WIKIDATA_IRI_PREFIXES:
if iri.startswith(base):
return prefix
# Check if it's still a Wikidata IRI (but with unknown prefix)
if iri.startswith(WIKIDATA_BASE):
return "other:"
return None
def extract_prefix_declarations(tree: dict | list) -> dict[str, str]:
"""
Extract PREFIX declarations from the parse tree.
Returns a dict mapping prefix (e.g., "wd:") to base IRI (e.g., "http://www.wikidata.org/entity/").
Includes default Wikidata prefixes, which can be overridden by explicit declarations.
"""
# Start with default Wikidata prefixes
prefix_map: dict[str, str] = DEFAULT_PREFIX_MAP.copy()
def visit(node: dict | list) -> None:
if isinstance(node, dict):
# Look for PrefixDecl which contains PNAME_NS and IRIREF
if node.get("name") == "PrefixDecl":
pname_ns = None
iri_ref = None
for child in node.get("children", []):
if isinstance(child, dict):
if child.get("name") == "PNAME_NS":
pname_ns = child.get("value") # e.g., "wd:"
elif child.get("name") == "IRIREF":
iri_ref = child.get("value") # e.g., "<http://...>"
if pname_ns and iri_ref:
# Strip angle brackets from IRI
base_iri = iri_ref[1:-1]
prefix_map[pname_ns] = base_iri
for child in node.get("children", []):
visit(child)
elif isinstance(node, list):
for item in node:
visit(item)
visit(tree)
return prefix_map
def collect_iris(
tree: dict | list,
iris_by_prefix: dict[str, set[str]],
query_prefix_map: dict[str, str],
) -> None:
"""
Recursively collect Wikidata IRIs from the parse tree, grouped by canonical prefix.
Uses query_prefix_map to resolve prefixed names (PNAME_LN) to full IRIs,
then classifies them by Wikidata prefix.
"""
if isinstance(tree, dict):
name = tree.get("name")
value = tree.get("value")
if name == "IRIREF" and value:
# Full IRI like <http://...>, strip brackets
iri = value[1:-1]
prefix = get_wikidata_prefix(iri)
if prefix:
iris_by_prefix[prefix].add(iri)
elif name == "PNAME_LN" and value:
# Prefixed name like wd:Q42 or custom:Q42
# Find the prefix part (everything up to and including the colon)
colon_idx = value.find(":")
if colon_idx != -1:
query_prefix = value[: colon_idx + 1] # e.g., "wd:" or "custom:"
local_name = value[colon_idx + 1 :] # e.g., "Q42"
# Look up the base IRI from the query's PREFIX declarations
base_iri = query_prefix_map.get(query_prefix)
if base_iri:
# Expand to full IRI
full_iri = base_iri + local_name
# Classify by canonical Wikidata prefix
canonical_prefix = get_wikidata_prefix(full_iri)
if canonical_prefix:
iris_by_prefix[canonical_prefix].add(full_iri)
for child in tree.get("children", []):
collect_iris(child, iris_by_prefix, query_prefix_map)
elif isinstance(tree, list):
for item in tree:
collect_iris(item, iris_by_prefix, query_prefix_map)
STRING_LITERAL_NODES = {
"STRING_LITERAL1",
"STRING_LITERAL2",
"STRING_LITERAL_LONG1",
"STRING_LITERAL_LONG2",
}
NUMERIC_LITERAL_NODES = {
"INTEGER",
"DECIMAL",
"DOUBLE",
"INTEGER_POSITIVE",
"INTEGER_NEGATIVE",
"DECIMAL_POSITIVE",
"DECIMAL_NEGATIVE",
"DOUBLE_POSITIVE",
"DOUBLE_NEGATIVE",
}
def collect_literals(tree: dict | list, literals: set[str]) -> None:
"""Recursively collect unique literals (both string and numeric) from the parse tree.
Normalizes literal values by stripping quotes from string literals so that:
- 400, "400", '400', and "400"^^xsd:integer all become 400
- "hello", 'hello', and "hello"@en all become hello
"""
if isinstance(tree, dict):
name = tree.get("name")
value = tree.get("value")
if name in STRING_LITERAL_NODES and value:
# Strip quotes from string literals (single, double, or triple)
# Handle """ ''' " ' in that order
normalized_value = value
for quote in ['"""', "'''", '"', "'"]:
if normalized_value.startswith(quote) and normalized_value.endswith(
quote
):
normalized_value = normalized_value[len(quote) : -len(quote)]
break
literals.add(normalized_value)
elif name in NUMERIC_LITERAL_NODES and value:
literals.add(value)
for child in tree.get("children", []):
collect_literals(child, literals)
elif isinstance(tree, list):
for item in tree:
collect_literals(item, literals)
def _extract_string_from_subtree(tree: dict | list) -> str | None:
"""Find and return the first STRING_LITERAL value in a subtree, or None."""
if isinstance(tree, dict):
if tree.get("name") in STRING_LITERAL_NODES:
return tree.get("value")
for child in tree.get("children", []):
result = _extract_string_from_subtree(child)
if result is not None:
return result
elif isinstance(tree, list):
for item in tree:
result = _extract_string_from_subtree(item)
if result is not None:
return result
return None
def _has_lang_builtin(tree: dict | list) -> bool:
"""Check if a subtree contains a LANG BuiltInCall."""
if isinstance(tree, dict):
if tree.get("name") == "BuiltInCall":
children = tree.get("children", [])
if (
children
and isinstance(children[0], dict)
and children[0].get("name") == "LANG"
):
return True
for child in tree.get("children", []):
if _has_lang_builtin(child):
return True
elif isinstance(tree, list):
for item in tree:
if _has_lang_builtin(item):
return True
return False
def _strip_literal_quotes(value: str) -> str:
"""Strip surrounding quotes from a string literal value."""
if (value.startswith('"') and value.endswith('"')) or (
value.startswith("'") and value.endswith("'")
):
return value[1:-1]
return value
def collect_languages(tree: dict | list, languages: set[str]) -> None:
"""
Recursively collect language identifiers from:
1. LANGTAG nodes on language-tagged literals (e.g., @en)
2. LANGMATCHES(LANG(?x), "en*") calls - second argument
3. LANG(?x) = "en" comparisons in RelationalExpression
"""
if isinstance(tree, dict):
name = tree.get("name")
value = tree.get("value")
# 1. LANGTAG: @en -> en
if name == "LANGTAG" and value:
lang = value.lstrip("@").lower()
if lang:
languages.add(lang)
# 2. BuiltInCall with LANGMATCHES: extract second Expression child
if name == "BuiltInCall":
children = tree.get("children", [])
if (
children
and isinstance(children[0], dict)
and children[0].get("name") == "LANGMATCHES"
):
expressions = [
c
for c in children
if isinstance(c, dict) and c.get("name") == "Expression"
]
if len(expressions) >= 2:
lang_str = _extract_string_from_subtree(expressions[1])
if lang_str:
lang = _strip_literal_quotes(lang_str).rstrip("*").lower()
if lang:
languages.add(lang)
# 3. RelationalExpression with ComparisonOp(=) and LANG on one side
if name == "RelationalExpression":
children = tree.get("children", [])
has_eq = any(
isinstance(c, dict)
and c.get("name") == "ComparisonOp"
and any(
isinstance(gc, dict) and gc.get("value") == "="
for gc in c.get("children", [])
)
for c in children
)
if has_eq:
num_exprs = [
c
for c in children
if isinstance(c, dict) and c.get("name") == "NumericExpression"
]
if len(num_exprs) == 2:
if _has_lang_builtin(num_exprs[0]):
lang_str = _extract_string_from_subtree(num_exprs[1])
elif _has_lang_builtin(num_exprs[1]):
lang_str = _extract_string_from_subtree(num_exprs[0])
else:
lang_str = None
if lang_str:
lang = _strip_literal_quotes(lang_str).lower()
if lang:
languages.add(lang)
for child in tree.get("children", []):
collect_languages(child, languages)
elif isinstance(tree, list):
for item in tree:
collect_languages(item, languages)
def normalize_tree(
tree: dict | list,
normalize_properties: bool = False,
var_map: dict[str, str] | None = None,
entity_map: dict[str, str] | None = None,
property_map: dict[str, str] | None = None,
literal_map: dict[str, str] | None = None,
) -> dict | list:
"""
Normalize a SPARQL parse tree by replacing:
- Variables with ?var0, ?var1, ... (preserving binding structure)
- Entity IRIs (wd:Qxxx) with wd:E0, wd:E1, ...
- Literals (both string and numeric) with "lit0", "lit1", ... (same value gets same placeholder)
- Optionally property IRIs with wdt:P0, p:P0, etc.
- Language tags and datatypes are removed entirely
The same original value always maps to the same placeholder within a query,
preserving the structure (e.g., if ?x appears twice, both become ?var0).
Returns a new normalized tree (does not modify original).
"""
if var_map is None:
var_map = {}
if entity_map is None:
entity_map = {}
if property_map is None:
property_map = {}
if literal_map is None:
literal_map = {}
# Property prefixes (for normalization)
property_prefixes = {
"wdt:",
"p:",
"ps:",
"pq:",
"pr:",
"psv:",
"pqv:",
"prv:",
"psn:",
"pqn:",
"prn:",
"wdtn:",
"wdno:",
}
# Entity prefixes
entity_prefixes = {"wd:", "s:", "ref:", "v:"}
if isinstance(tree, dict):
name = tree.get("name")
value = tree.get("value")
new_node: dict = {"name": name}
# Skip PREFIX declarations entirely - they don't affect structural equivalence
if name == "PrefixDecl":
return new_node
if name == "VAR1" or name == "VAR2":
# Variable like ?x or $x - same variable always gets same placeholder
if value not in var_map:
var_map[value] = f"?var{len(var_map)}"
new_node["value"] = var_map[value]
elif name == "PNAME_LN" and value:
# Prefixed name like wd:Q42 or wdt:P31
colon_idx = value.find(":")
if colon_idx != -1:
prefix = value[: colon_idx + 1]
local = value[colon_idx + 1 :]
if prefix in entity_prefixes:
# Entity IRI - same entity always gets same placeholder
if value not in entity_map:
entity_map[value] = f"{prefix}E{len(entity_map)}"
new_node["value"] = entity_map[value]
elif prefix in property_prefixes:
if normalize_properties:
# Property IRI - same property always gets same placeholder
if value not in property_map:
property_map[value] = f"{prefix}P{len(property_map)}"
new_node["value"] = property_map[value]
else:
# Keep property IRIs as-is
new_node["value"] = value
else:
# Other prefixed names - keep as-is
new_node["value"] = value
else:
new_node["value"] = value
elif name == "IRIREF" and value:
# Full IRI like <http://...>
iri = value[1:-1] # Strip angle brackets
wd_prefix = get_wikidata_prefix(iri)
if wd_prefix:
# Convert to prefixed form for normalization
for base, prefix in WIKIDATA_IRI_PREFIXES:
if iri.startswith(base):
local = iri[len(base) :]
prefixed = f"{prefix}{local}"
if prefix in entity_prefixes:
# Same entity always gets same placeholder
if prefixed not in entity_map:
entity_map[prefixed] = f"{prefix}E{len(entity_map)}"
new_node["value"] = f"<{entity_map[prefixed]}>"
elif prefix in property_prefixes:
if normalize_properties:
# Same property always gets same placeholder
if prefixed not in property_map:
property_map[prefixed] = (
f"{prefix}P{len(property_map)}"
)
new_node["value"] = f"<{property_map[prefixed]}>"
else:
new_node["value"] = value
else:
new_node["value"] = value
break
else:
new_node["value"] = value
else:
# Non-Wikidata IRI - keep as-is
new_node["value"] = value
elif name in (
"STRING_LITERAL1",
"STRING_LITERAL2",
"STRING_LITERAL_LONG1",
"STRING_LITERAL_LONG2",
):
# String literal - same value always gets same placeholder
if value not in literal_map:
literal_map[value] = f'"lit{len(literal_map)}"'
new_node["value"] = literal_map[value]
elif name in (
"INTEGER",
"DECIMAL",
"DOUBLE",
"INTEGER_POSITIVE",
"INTEGER_NEGATIVE",
"DECIMAL_POSITIVE",
"DECIMAL_NEGATIVE",
"DOUBLE_POSITIVE",
"DOUBLE_NEGATIVE",
):
# Numeric literal - same value always gets same placeholder
if value not in literal_map:
literal_map[value] = f'"lit{len(literal_map)}"'
new_node["value"] = literal_map[value]
elif value is not None:
new_node["value"] = value
if "children" in tree:
# Filter out LANGTAG and datatype nodes (IRIREF following ^^)
filtered_children = []
skip_next = False
for i, child in enumerate(tree["children"]):
if skip_next:
skip_next = False
continue
# Skip LANGTAG nodes entirely
if isinstance(child, dict) and child.get("name") == "LANGTAG":
continue
# Skip ^^ operator and following IRIREF (datatype annotation)
if isinstance(child, dict) and child.get("value") == "^^":
# Skip this and the next child (the datatype IRI)
if i + 1 < len(tree["children"]):
skip_next = True
continue
filtered_children.append(child)
new_node["children"] = [
normalize_tree(
child,
normalize_properties,
var_map,
entity_map,
property_map,
literal_map,
)
for child in filtered_children
]
return new_node
elif isinstance(tree, list):
return [
normalize_tree(
item,
normalize_properties,
var_map,
entity_map,
property_map,
literal_map,
)
for item in tree
]
else:
return tree
def tree_to_sparql(tree: dict | list) -> str:
"""
Convert a parse tree to SPARQL by extracting all terminal values.
This provides a human-readable representation of the (normalized) query.
Skips PREFIX declarations as they don't affect structural equivalence.
"""
terminals = []
def collect_terminals(node: dict | list) -> None:
if isinstance(node, dict):
name = node.get("name")
value = node.get("value")
children = node.get("children", [])
# Skip PREFIX declarations entirely
if name == "PrefixDecl":
return
if value and not children:
# Terminal node - add its value
terminals.append(value)
# Recurse into children
for child in children:
collect_terminals(child)
elif isinstance(node, list):
for item in node:
collect_terminals(item)
collect_terminals(tree)
return " ".join(terminals)
def collect_present_nodes(tree: dict | list, present: set[str]) -> None:
"""Recursively collect node names present in the parse tree."""
if isinstance(tree, dict):
if "name" in tree:
present.add(tree["name"])
if "children" in tree:
for child in tree["children"]:
collect_present_nodes(child, present)
elif isinstance(tree, list):
for item in tree:
collect_present_nodes(item, present)
def count_node_occurrences(tree: dict | list, node_name: str) -> int:
"""Recursively count occurrences of a specific node name in the parse tree."""
count = 0
if isinstance(tree, dict):
if tree.get("name") == node_name:
count += 1
if "children" in tree:
for child in tree["children"]:
count += count_node_occurrences(child, node_name)
elif isinstance(tree, list):
for item in tree:
count += count_node_occurrences(item, node_name)
return count
# ── WDQL comparison helpers ────────────────────────────────────────────────────
def _find_node(tree: dict | list, name: str) -> dict | None:
"""Find first node with given name in parse tree (DFS)."""
if isinstance(tree, dict):
if tree.get("name") == name:
return tree
for child in tree.get("children", []):
result = _find_node(child, name)
if result is not None:
return result
elif isinstance(tree, list):
for item in tree:
result = _find_node(item, name)
if result is not None:
return result
return None
def _find_all_nodes(
tree: dict | list,
name: str,
skip_names: set[str] | None = None,
) -> list[dict]:
"""Find all nodes with given name; don't descend into nodes whose name is in skip_names."""
results: list[dict] = []
_skip = skip_names or set()
def walk(node: dict | list) -> None:
if isinstance(node, dict):
node_name = node.get("name")
if node_name in _skip:
return
if node_name == name:
results.append(node)
for child in node.get("children", []):
walk(child)
elif isinstance(node, list):
for item in node:
walk(item)
walk(tree)
return results
def _copy_node(node: dict) -> dict:
"""Copy name and value of a tree node (without children)."""
new: dict = {}
if "name" in node:
new["name"] = node["name"]
if "value" in node:
new["value"] = node["value"]
return new
def _is_wikibase_label_service(service_node: dict) -> bool:
"""Return True if a ServiceGraphPattern is the wikibase:label service."""
children = service_node.get("children", [])
# Grammar: SERVICE [SilentOptional] VarOrIri GroupGraphPattern
# With skip_empty=True, SilentOptional may be absent, so find VarOrIri by name.
var_or_iri = next(
(c for c in children if isinstance(c, dict) and c.get("name") == "VarOrIri"),
None,
)
if var_or_iri is None:
return False
iri = _find_node(var_or_iri, "IRIREF")
if iri is not None and iri.get("value") == "<http://wikiba.se/ontology#label>":
return True
pname = _find_node(var_or_iri, "PNAME_LN")
if pname is not None and pname.get("value") == "wikibase:label":
return True
return False
def remove_label_service(tree: dict | list) -> tuple[dict | list, bool]:
"""Return (new_tree, stripped) where SERVICE wikibase:label clauses are removed
and stripped=True if at least one was found.
Mirrors grasp.tasks.wikidata_query_logs.remove_service().
"""
stripped = False
def _remove(node: dict | list) -> dict | list:
nonlocal stripped
if isinstance(node, dict):
if (
node.get("name") == "ServiceGraphPattern"
and _is_wikibase_label_service(node)
):
stripped = True
return {"name": "ServiceGraphPattern"} # empty leaf
new_node = _copy_node(node)
if "children" in node:
new_node["children"] = [_remove(c) for c in node["children"]]
return new_node
elif isinstance(node, list):
return [_remove(item) for item in node]
return node
result = _remove(tree)
return result, stripped
def _triple_has_only_rdfs_label(triple_node: dict) -> bool:
"""Return True if a TriplesSameSubjectPath has only rdfs:label as its predicate."""
prop_list = _find_node(triple_node, "PropertyListPathNotEmpty")
if prop_list is None:
return False
# VerbPathObjectListOptional with children means there are additional predicates (after ';')
for child in prop_list.get("children", []):
if (
isinstance(child, dict)
and child.get("name") == "VerbPathObjectListOptional"
and child.get("children")
):
return False
for node in _find_all_nodes(prop_list, "IRIREF"):
if node.get("value") == "<http://www.w3.org/2000/01/rdf-schema#label>":
return True
for node in _find_all_nodes(prop_list, "PNAME_LN"):
if node.get("value") == "rdfs:label":
return True
return False
def remove_rdfs_label_triples(tree: dict | list) -> dict | list:
"""Return a new tree with TriplesSameSubjectPath nodes that use only
rdfs:label as their predicate removed."""
if isinstance(tree, dict):
if tree.get("name") == "TriplesSameSubjectPath" and _triple_has_only_rdfs_label(
tree
):
return {"name": "TriplesSameSubjectPath"} # empty leaf
new_node = _copy_node(tree)
if "children" in tree:
new_node["children"] = [
remove_rdfs_label_triples(c) for c in tree["children"]
]
return new_node
elif isinstance(tree, list):
return [remove_rdfs_label_triples(item) for item in tree]
return tree
def _filter_has_only_lang(filter_node: dict) -> bool:
"""Return True if a Filter node's BuiltInCalls are exclusively LANG or LANGMATCHES."""
builtin_calls = _find_all_nodes(filter_node, "BuiltInCall")
if not builtin_calls:
return False
lang_names = {"LANG", "LANGMATCHES"}
for call in builtin_calls:
children = call.get("children", [])
if not children or not isinstance(children[0], dict):
return False
if children[0].get("name") not in lang_names:
return False
return True
def remove_lang_filters(tree: dict | list) -> dict | list:
"""Return a new tree with Filter nodes whose constraints are exclusively
LANG/LANGMATCHES removed. Mirrors the clean-side replacement of
SERVICE wikibase:label with FILTER(LANGMATCHES(LANG(?x), ...))."""
if isinstance(tree, dict):
if tree.get("name") == "Filter" and _filter_has_only_lang(tree):
return {"name": "Filter"} # empty leaf
new_node = _copy_node(tree)
if "children" in tree:
new_node["children"] = [remove_lang_filters(c) for c in tree["children"]]
return new_node
elif isinstance(tree, list):
return [remove_lang_filters(item) for item in tree]
return tree
def _get_where_body(tree: dict | list) -> dict | None:
"""Return the top-level GroupGraphPattern (the WHERE body), or None."""
where = _find_node(tree, "WhereClause")
if where is None:
return None
return _find_node(where, "GroupGraphPattern")
def _normalize_for_comparison(
tree: dict | list,
normalize_literals: bool = False,
prefix_map: dict[str, str] | None = None,
) -> dict | list:
"""Normalize a tree for cross-query comparison:
- Variables → generic placeholder ?_
- PNAME_LN → expanded full IRI using prefix_map when provided
- Optionally collapse all literals to a generic placeholder
"""
if isinstance(tree, dict):
name = tree.get("name")
value = tree.get("value")
if name in ("VAR1", "VAR2"):
return {"name": name, "value": "?_"}
if normalize_literals and name in (
STRING_LITERAL_NODES | NUMERIC_LITERAL_NODES
):
return {"name": name, "value": '"_"'}
if name == "PNAME_LN" and value and prefix_map:
colon = value.find(":")
if colon != -1:
base = prefix_map.get(value[: colon + 1])
if base:
return {"name": "IRIREF", "value": f"<{base}{value[colon + 1 :]}>"}
new_node = _copy_node(tree)
if "children" in tree:
new_node["children"] = [
_normalize_for_comparison(c, normalize_literals, prefix_map)
for c in tree["children"]
]
return new_node
elif isinstance(tree, list):
return [
_normalize_for_comparison(item, normalize_literals, prefix_map)
for item in tree
]
return tree
def _extract_triples(
body: dict | list,
normalize_literals: bool = False,
prefix_map: dict[str, str] | None = None,
) -> set[str]:
"""Extract normalized triple-pattern strings from a WHERE body."""
normalized = _normalize_for_comparison(body, normalize_literals, prefix_map)
triples: set[str] = set()
for node in _find_all_nodes(normalized, "TriplesSameSubjectPath"):
s = tree_to_sparql(node).strip()
if s:
triples.add(s)
return triples
def _extract_iris(
body: dict | list,
prefix_map: dict[str, str] | None = None,
) -> set[str]:
"""Extract all full IRIs from a parse tree as <...> strings.
PNAME_LN nodes are expanded to full IRIs when prefix_map is provided.
"""
iris: set[str] = set()
def walk(node: dict | list) -> None:
if isinstance(node, dict):
name = node.get("name")
value = node.get("value")
if name == "IRIREF" and value:
iris.add(value)
elif name == "PNAME_LN" and value and prefix_map:
colon = value.find(":")
if colon != -1:
base = prefix_map.get(value[: colon + 1])
if base:
iris.add(f"<{base}{value[colon + 1 :]}>")
for child in node.get("children", []):
walk(child)
elif isinstance(node, list):
for item in node:
walk(item)
walk(body)
return iris
def _jaccard(a: set, b: set) -> float:
"""Jaccard similarity: |a ∩ b| / |a ∪ b|. Returns 1.0 if both sets are empty."""
if not a and not b:
return 1.0
return len(a & b) / len(a | b)
def _print_jaccard_dist(scores: list[float], label: str, n_total: int) -> None:
"""Print mean, median, and key percentages for a list of Jaccard scores."""
n = len(scores)
if n == 0:
return
mean_j = sum(scores) / n
median_j = sorted(scores)[n // 2]
perfect = sum(1 for s in scores if s == 1.0)
zero = sum(1 for s in scores if s == 0.0)
print(f" {label}:")
print(f" Mean: {mean_j:.3f} Median: {median_j:.3f}")
print(
f" Perfect match (1.0): {perfect:,} ({perfect / n_total * 100:.1f}%)"
f" | No overlap (0.0): {zero:,} ({zero / n_total * 100:.1f}%)"
)
# Constructs we're interested in tracking (terminals from sparql.l and rules from sparql.y)
KEYWORD_CONSTRUCTS = [
# Query types (terminals)
("SELECT", "SELECT query"),
("CONSTRUCT", "CONSTRUCT query"),
("DESCRIBE", "DESCRIBE query"),
("ASK", "ASK query"),
# Graph pattern keywords (terminals)
("UNION", "UNION"),
("MINUS", "MINUS"),
("OPTIONAL", "OPTIONAL"),
("FILTER", "FILTER"),
("SERVICE", "SERVICE"),
("BIND", "BIND"),
("VALUES", "VALUES"),
("EXISTS", "EXISTS"),
# Solution modifier keywords (terminals)
("GROUP", "GROUP BY"),
("HAVING", "HAVING"),
("ORDER", "ORDER BY"),
("LIMIT", "LIMIT"),
("OFFSET", "OFFSET"),
("DISTINCT", "DISTINCT"),
# Aggregate keywords (terminals)
("COUNT", "COUNT"),
("SUM", "SUM"),
("MIN", "MIN"),
("MAX", "MAX"),
("AVG", "AVG"),
("SAMPLE", "SAMPLE"),
("GROUP_CONCAT", "GROUP_CONCAT"),
# Property paths (literal tokens)
("|", "Path alternative (|)"),
("/", "Path sequence (/)"),
("PathMod", "Path modifier (?, *, +)"),
# Subquery (rule)
("SubSelect", "Subquery"),
]
FUNCTION_CONSTRUCTS = {
# String functions
"STR",
"LANG",
"LANGMATCHES",
"DATATYPE",
"CONCAT",
"STRLEN",
"UCASE",
"LCASE",
"ENCODE_FOR_URI",
"CONTAINS",
"STRSTARTS",
"STRENDS",
"STRBEFORE",
"STRAFTER",
"SUBSTR",
"REPLACE",
"STRLANG",
"STRDT",
# Numeric functions
"ABS",
"CEIL",
"FLOOR",
"ROUND",
"RAND",
# Date/Time functions
"YEAR",
"MONTH",
"DAY",
"HOURS",
"MINUTES",
"SECONDS",
"TIMEZONE",
"TZ",
"NOW",
# Hash functions
"MD5",
"SHA1",
"SHA256",
"SHA384",
"SHA512",
# Node functions
"IRI",
"URI",
"BNODE",
"UUID",
"STRUUID",
# Type checking functions
"BOUND",
"SAMETERM",
"ISIRI",
"ISURI",
"ISBLANK",
"ISLITERAL",
"ISNUMERIC",
# Conditional functions
"COALESCE",
"IF",
# Pattern matching
"REGEX",
# Variable binding (treated as function for this metric)
"BIND",
}
# All tracked constructs for construct Jaccard comparison
SPARQL_CONSTRUCTS = {node for node, _ in KEYWORD_CONSTRUCTS} | FUNCTION_CONSTRUCTS
# Basic features: triple patterns, FILTER, ORDER BY, LIMIT, OFFSET, DISTINCT, query type
BASIC_CONSTRUCTS = {
"FILTER",
"ORDER",
"LIMIT",
"OFFSET",
"DISTINCT",
"SELECT",
"ASK",
"CONSTRUCT",
"DESCRIBE",
}
def is_advanced_query(tree: dict | list) -> bool:
"""
Check if a query is classified as advanced.
A query is advanced if it uses any tracked construct beyond basic features.
Basic features are: triple patterns, FILTER, ORDER BY, LIMIT, OFFSET, DISTINCT, and query types.
"""
present: set[str] = set()
collect_present_nodes(tree, present)
tracked_constructs = {node for node, _ in KEYWORD_CONSTRUCTS}
advanced_in_query = (present & tracked_constructs) - BASIC_CONSTRUCTS
return len(advanced_in_query) > 0
def main() -> None: