-
Notifications
You must be signed in to change notification settings - Fork 5
/
SparqlQuery.py
1748 lines (1494 loc) · 68.8 KB
/
SparqlQuery.py
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 re
import textwrap
from askomics.libaskomics.Params import Params
from askomics.libaskomics.PrefixManager import PrefixManager
from askomics.libaskomics.SparqlQueryLauncher import SparqlQueryLauncher
from askomics.libaskomics.Utils import Utils
from collections import defaultdict
class SparqlQuery(Params):
"""Format a sparql query
Attributes
----------
private_graphs : list
all user private graph
public_graphs : list
all public graph
"""
def __init__(self, app, session, json_query=None, get_graphs=False):
"""init
Parameters
----------
app : Flask
Flask app
session :
AskOmics session
"""
Params.__init__(self, app, session)
self.json = json_query
self.sparql = None
self.graphs = []
self.endpoints = []
self.remote_graphs = defaultdict(list)
self.selects = []
self.federated = False
# local endpoint (for federated query engine)
self.local_endpoint_f = self.settings.get('triplestore', 'endpoint')
try:
self.local_endpoint_f = self.settings.get('federation', 'local_endpoint')
except Exception:
pass
# No need to call this twice if we need it later (sparql queries)
if get_graphs:
self.set_graphs_and_endpoints()
def set_graphs(self, graphs):
"""Set graphs
Parameters
----------
graphs : list
graphs
"""
self.graphs = graphs
def set_endpoints(self, endpoints):
"""Set endpoints
Parameters
----------
endpoints : list
Endpoints
"""
self.endpoints = endpoints
def set_remote_graph(self, remote_graphs):
"""Set endpoints
Parameters
----------
endpoints : list
Endpoints
"""
self.remote_graphs = remote_graphs
def is_federated(self):
"""Return True if there is more than 1 endpoint
Returns
-------
bool
True or False
"""
if len(self.endpoints) > 1:
return True
return False
def replace_froms(self):
"""True if not federated and endpoint is local
Returns
-------
bool
True or False
"""
if not self.is_federated():
if self.endpoints == [self.local_endpoint_f]:
return True
return False
def get_federated_froms(self):
"""Get @from string fir the federated query engine
Returns
-------
string
The from string
"""
from_string = "@from <{}>".format(self.local_endpoint_f)
for graph in self.graphs:
from_string += " <{}>".format(graph)
return from_string
def get_froms(self):
"""Get FROM string
Returns
-------
string
FROM string
"""
from_string = ''
for graph in self.graphs:
from_string += '\nFROM <{}>'.format(graph)
return from_string
def get_federated_line(self):
"""Get federtated line
Returns
-------
string
@federate <endpoint1> <endpoint1> ...
"""
federated_string = '@federate '
for endpoint in self.endpoints:
federated_string += '<{}> '.format(endpoint)
return federated_string
def format_graph_name(self, graph):
"""Format graph name by removing base graph and timestamp
Parameters
----------
graph : string
The graph name
Returns
-------
string
Formated graph name
"""
regexp = r"{}:.*:".format(
self.settings.get("triplestore", "default_graph"),
)
return "_".join(re.sub(regexp, "", graph).split("_")[:-1])
def format_endpoint_name(self, endpoint):
"""Replace local url by "local triplestore"
Parameters
----------
endpoint : string
The endpoint name
Returns
-------
string
Formated endpoint name
"""
if endpoint in (self.settings.get("triplestore", "endpoint"), self.local_endpoint_f):
return "local triplestore"
return endpoint
def get_graphs_and_endpoints(self, selected_graphs=[], selected_endpoints=[], all_selected=False):
"""get graphs and endpoints (uri and names)
Returns
-------
list
List of dict uri name
"""
graphs = {}
endpoints = {}
for graph in self.graphs:
graphs[graph] = {
"uri": graph,
"name": self.format_graph_name(graph),
"selected": True if all_selected else True if graph in selected_graphs else False
}
for endpoint in self.endpoints:
endpoints[endpoint] = {
"uri": endpoint,
"name": self.format_endpoint_name(endpoint),
"selected": True if all_selected else True if endpoint in selected_endpoints else False
}
return (graphs, endpoints)
def get_default_query(self):
"""Get the default query
Returns
-------
str
the default query
"""
query = textwrap.dedent(
'''
SELECT DISTINCT ?s ?p ?o
WHERE {
?s ?p ?o
}
'''
)
return query
def prefix_query(self, query):
"""Add prefix and dedent a sparql query string
Parameters
----------
query : string
The sparql query
Returns
-------
string
Formatted query
"""
prefix_manager = PrefixManager(self.app, self.session)
query = textwrap.dedent(query)
return '{}{}'.format(
prefix_manager.get_prefix(),
query
)
def toggle_public(self, graph, public):
"""Change public status of data into the triplestore
Parameters
----------
graph : string
Graph to update public status
public : string
true or false (string)
"""
query = '''
WITH GRAPH <{graph}>
DELETE {{
<{graph}> askomics:public ?public .
}}
INSERT {{
<{graph}> askomics:public <{public}> .
}}
WHERE {{
<{graph}> askomics:public ?public .
}}
'''.format(graph=graph, public=public)
query_launcher = SparqlQueryLauncher(self.app, self.session)
query_launcher.execute_query(self.prefix_query(query), is_update=True)
def get_default_query_with_prefix(self):
"""Get default query with the prefixes
Returns
-------
str
default query with prefixes
"""
prefix_manager = PrefixManager(self.app, self.session)
return '{}{}'.format(
prefix_manager.get_prefix(),
self.get_default_query()
)
def format_query(self, query, limit=30, replace_froms=True, federated=False, ignore_single_tenant=True):
"""Format the Sparql query
- remove all FROM
- add FROM <graph> (public graph and user graph)
- set a limit if not (or if its to big)
Parameters
----------
query : string
sparql query to format
limit : int, optional
Description
Returns
-------
string
formatted sparql query
"""
froms = ''
if federated:
federated_line = "" if self.settings.getboolean("askomics", "single_tenant", fallback=False) else "{}\n{}".format(self.get_federated_line(), self.get_federated_froms())
federated_graphs_string = self.get_federated_remote_from_graphs()
else:
if replace_froms and (not self.settings.getboolean("askomics", "single_tenant", fallback=False)):
froms = self.get_froms()
query_lines = query.split('\n')
new_query = ''
for line in query_lines:
# Remove all FROM and LIMIT and @federated
if not line.upper().lstrip().startswith('FROM') and not line.upper().lstrip().startswith('LIMIT') and not line.upper().lstrip().startswith('@FEDERATE'):
if line.upper().lstrip().startswith('SELECT') and federated:
new_query += "\n{}\n".format(federated_line)
new_query += "\n{}\n".format(federated_graphs_string)
new_query += '\n{}'.format(line)
# Add new FROM
if line.upper().lstrip().startswith('SELECT'):
self.selects = [i for i in line.split() if i.startswith('?')]
new_query += froms
# Compute the limit
if line.upper().lstrip().startswith('LIMIT') and limit:
given_lim = int(re.findall(r'\d+', line)[0])
if given_lim < limit and given_lim != 0:
limit = given_lim
continue
# Add limit
if limit:
new_query += '\nLIMIT {}'.format(limit)
return new_query
def get_checked_asked_graphs(self, asked_graphs):
"""Check if asked graphs are present in public and private graphs
Parameters
----------
asked_graphs : list
list of graphs asked by the user
Returns
-------
list
list of graphs asked by the user, in the public and private graphs
"""
return Utils.intersect(asked_graphs, self.private_graphs + self.public_graphs)
def get_froms_from_graphs(self, graphs):
"""Get FROM's form a list of graphs
Parameters
----------
graphs : list
List of graphs
Returns
-------
str
from string
"""
from_string = ''
for graph in graphs:
from_string += '\nFROM <{}>'.format(graph)
return from_string
def get_federated_froms_from_graphs(self, graphs):
"""Get @from string fir the federated query engine
Returns
-------
string
The from string
"""
from_string = "@from <{}>".format(self.local_endpoint_f)
for graph in graphs:
from_string += " <{}>".format(graph)
return from_string
def get_federated_remote_from_graphs(self):
"""Get @from string fir the federated query engine
Returns
-------
string
The from string
"""
from_string = ""
for endpoint in self.endpoints:
remote_graphs = self.remote_graphs.get(endpoint, [])
if len(remote_graphs) == 1:
from_string += "\n@graph <{}> <{}>".format(endpoint, remote_graphs[0])
return from_string
def get_endpoints_string(self):
"""get endpoint strngs for the federated query engine
Returns
-------
string
the endpoint string
"""
endpoints_string = '@federate '
for endpoint in self.endpoints:
endpoints_string += "<{}> ".format(endpoint)
return endpoints_string
def set_graphs_and_endpoints(self, entities=None, graphs=None, endpoints=None, ontologies={}):
"""Get all public and private graphs containing the given entities
Parameters
----------
entities : list, optional
list of entity uri
"""
filter_entity_string = ''
if entities:
substr = ",".join(["<{}>".format(entity) for entity in entities])
filter_entity_string = 'FILTER (?entity_uri IN( ' + substr + ' ))'
filter_public_string = 'FILTER (?public = <true>)'
if 'user' in self.session:
filter_public_string = 'FILTER (?public = <true> || ?creator = <{}>)'.format(self.session["user"]["username"])
query = '''
SELECT DISTINCT ?graph ?endpoint ?entity_uri ?remote_graph
WHERE {{
?graph_abstraction askomics:public ?public .
?graph_abstraction dc:creator ?creator .
?graph askomics:public ?public .
?graph dc:creator ?creator .
GRAPH ?graph_abstraction {{
?graph_abstraction prov:atLocation ?endpoint .
OPTIONAL {{?graph_abstraction dcat:Dataset ?remote_graph .}}
?entity_uri a ?askomics_type .
}}
GRAPH ?graph {{
{{ [] a ?entity_uri . }}
UNION
{{ ?entity_uri a ?askomics_type . }}
}}
VALUES ?askomics_type {{askomics:entity askomics:ontology}}
{}
{}
}}
'''.format(filter_public_string, filter_entity_string)
query_launcher = SparqlQueryLauncher(self.app, self.session)
header, results = query_launcher.process_query(self.prefix_query(query))
self.graphs = []
self.endpoints = []
self.remote_graphs = defaultdict(list)
for res in results:
if not graphs or res["graph"] in graphs:
# Override with onto graph if matching uri
if ontologies.get(res['entity_uri']):
graph = ontologies[res['entity_uri']]['graph']
else:
graph = res["graph"]
self.graphs.append(graph)
# If local triplestore url is not accessible by federated query engine
if res["endpoint"] == self.settings.get('triplestore', 'endpoint') and self.local_endpoint_f is not None:
endpoint = self.local_endpoint_f
else:
endpoint = res["endpoint"]
if not endpoints or endpoint in endpoints:
self.endpoints.append(endpoint)
if res.get("remote_graph"):
self.remote_graphs[endpoint].append(res.get("remote_graph"))
self.endpoints = Utils.unique(self.endpoints)
self.federated = len(self.endpoints) > 1
def get_uri_parameters(self, uri, endpoints):
"""Get parameters for a specific data URI
Parameters
----------
uri : string
URI to search
Returns
-------
dict
The corresponding parameters
"""
raw_query = '''
SELECT DISTINCT ?predicate ?object ?faldo_value ?faldo_relation
WHERE {{
?URI ?predicate ?object .
?URI a ?entitytype .
FILTER(! STRSTARTS(STR(?predicate), STR(askomics:)))
OPTIONAL {{
?faldo_uri rdfs:domain ?entitytype .
?faldo_uri rdfs:label ?attribute_label .
OPTIONAL {{
?object faldo:begin/faldo:position ?faldo_value .
?faldo_uri rdf:type askomics:faldoStart
}}
OPTIONAL {{
?object faldo:end/faldo:position ?faldo_value .
?faldo_uri rdf:type askomics:faldoEnd
}}
OPTIONAL {{
?object faldo:begin/faldo:reference/rdfs:label ?faldo_value .
?faldo_uri rdf:type askomics:faldoReference
}}
OPTIONAL {{
?object faldo:begin/rdf:type ?Gene1_strandCategory .
?Gene1_strand_faldoStrand a ?Gene1_strandCategory .
?Gene1_strand_faldoStrand rdfs:label ?faldo_value .
?faldo_uri rdf:type askomics:faldoStrand .
}}
OPTIONAL {{
?faldo_uri askomics:uri ?node_uri
}}
VALUES ?predicate {{faldo:location}}
}}
VALUES ?URI {{{}}}
BIND(IF(isBlank(?faldo_uri), ?node_uri ,?faldo_uri) as ?faldo_relation)
}}
'''.format(uri)
federated = self.is_federated()
replace_froms = self.replace_froms()
raw_query = self.prefix_query(raw_query)
sparql = self.format_query(raw_query, replace_froms=replace_froms, federated=federated)
query_launcher = SparqlQueryLauncher(self.app, self.session, get_result_query=True, federated=federated, endpoints=endpoints)
_, data = query_launcher.process_query(sparql)
formated_data = []
for row in data:
predicate = row['predicate']
object = row['object']
if row.get('faldo_relation'):
predicate = row.get("faldo_relation")
if row.get('faldo_value'):
object = row.get('faldo_value')
formated_data.append({
'predicate': predicate,
'object': object,
})
return formated_data
def autocomplete_local_ontology(self, uri, query, max_terms, label):
"""Get results for a specific query
Parameters
----------
uri : string
ontology uri
query : string
query to search
Returns
-------
dict
The corresponding parameters
"""
subquery = ""
if query:
subquery = 'FILTER(contains(lcase(?label), "{}"))'.format(query.lower())
raw_query = '''
SELECT DISTINCT ?label
WHERE {{
?uri rdf:type owl:Class .
?uri {} ?label .
{}
}}
'''.format(label, subquery)
raw_query = self.prefix_query(raw_query)
is_federated = self.is_federated()
sparql = self.format_query(raw_query, limit=max_terms, replace_froms=True, federated=is_federated)
query_launcher = SparqlQueryLauncher(self.app, self.session, get_result_query=True, federated=is_federated)
_, data = query_launcher.process_query(sparql)
formated_data = []
for row in data:
formated_data.append(row['label'])
return formated_data
def format_sparql_variable(self, name):
"""Format a name into a sparql variable by remove spacial char and add a ?
Parameters
----------
name : string
name to convert
Returns
-------
string
The corresponding sparql variable
"""
return "?{}".format(re.sub(r'[^a-zA-Z0-9]+', '_', name))
def is_bnode(self, uri, entities):
"""Check if a node uri is a blank node
Parameters
----------
uri : string
node uri
entities : list
all the entities
Returns
-------
Bool
True if uri correspond to a blank node
"""
for entity in entities:
if entity["uri"] == uri and entity["type"] == "bnode":
return True
return False
def get_block_ids(self, node_id):
"""Get blockid and sblockid of a node with its id
Parameters
----------
node_id : int
Node id
Returns
-------
int, int
blockid and sblockid
"""
for node in self.json["nodes"]:
if node["id"] == node_id:
return node["specialNodeId"], node["specialNodeGroupId"], node["specialPreviousIds"], node.get("depth")
return None, None, (None, None), None
def triple_block_to_string(self, triple_block):
"""Convert a triple block to a SPARQL string
Parameters
----------
triple_block : dict
A triple block
Returns
-------
str
Corresponding SPARQL
"""
if triple_block["type"] in ("UNION", "MINUS"):
block_string = "{\n"
i = 0
current_spacing = " "
for sblock in triple_block["sblocks"]:
sblock_string = "{"
triples_string = '\n{}'.format(current_spacing * 2).join([self.triple_dict_to_string(triple_dict) for triple_dict in sblock["triples"]])
triples_string += '\n{}'.format(current_spacing * 2)
triples_string += '\n{}'.format(current_spacing * 2).join([filtr for filtr in sblock["filters"]])
triples_string += '\n{}'.format(current_spacing * 2)
triples_string += '\n{}'.format(current_spacing * 2).join([value for value in sblock["values"]])
sblock_string += "\n{}{}\n{}}}".format(current_spacing * 2, triples_string, current_spacing * 2)
block_string += "{}{} ".format(current_spacing * 2, triple_block["type"]) if (triple_block["type"] == "MINUS" or i > 0) else current_spacing * 2
block_string += sblock_string + "\n"
i += 1
block_string += current_spacing + "}\n"
return block_string
def triple_dict_to_string(self, triple_dict):
"""Convert a triple dict into a triple string
Parameters
----------
triple_dict : dict
The triple dict
Returns
-------
string
The triple string
"""
triple = "{} {} {} .".format(triple_dict["subject"], triple_dict["predicate"], triple_dict["object"])
if triple_dict["optional"]:
if triple_dict.get("nested_start"):
triple = "OPTIONAL {{{}".format(triple)
else:
triple = "OPTIONAL {{{}}}".format(triple)
# Close the }} if end of the nest
if triple_dict.get("nested_end"):
triple = " " + triple + "}"
elif triple_dict.get("nested"):
triple = " " + triple
return triple
def get_uri_filter_value(self, value):
"""Get full uri from a filter value (curie or uri)
:xxx --> :xxx
uniprot:xxx --> <http://purl.uniprot.org/core/xxx>
http://example.org/xxx --> <http://example.org/xxx>
xxx --> xxx is not a valid URI or CURIE
bla:xxx --> bla: is not a known prefix
Parameters
----------
value : string
Input filter
Returns
-------
string
corresponding uri
Raises
------
ValueError
Invalid URI or CURIE return a value error
"""
if Utils().is_url(value):
return "<{}>".format(value)
elif ":" in value:
prefix, val = value.split(":")
if prefix:
prefix_manager = PrefixManager(self.app, self.session)
namespace = prefix_manager.get_namespace(prefix)
if namespace:
return "<{}{}>".format(namespace, val)
else:
raise ValueError("{}: is not a known prefix".format(prefix))
else:
return value
raise ValueError("{} is not a valid URI or CURIE".format(value))
def get_block_type(self, blockid):
"""Summary
Parameters
----------
blockid : TYPE
Description
Returns
-------
TYPE
Description
"""
types_dict = {
"unionNode": "UNION",
"minusNode": "MINUS"
}
# Union sub-block
if '_' in str(blockid):
return "DEFAULT"
for node in self.json["nodes"]:
if node["type"] in ("unionNode", "minusNode"):
if node["specialNodeId"] == blockid:
return types_dict[node["type"]]
return None
def store_triple(self, triple, blockid, sblockid, pblock_ids, depth):
"""Store a triple inthe right list
Parameters
----------
triple : dict
triple dict
typ : str
relatin or attribute
block_info : None, optional
block info if triple is part of a block
"""
if blockid:
if depth:
self.update_block_dict(depth, "triples", triple)
else:
self.store_block(triple, blockid, sblockid, pblock_ids)
else:
self.triples.append(triple)
def store_filter(self, filtr, blockid, sblockid, pblock_ids, depth):
"""Store a FILTER in the right list
Parameters
----------
triple : dict
triple dict
typ : str
relatin or attribute
block_info : None, optional
block info if triple is part of a block
"""
if blockid:
if depth:
self.update_block_dict(depth, "filters", filtr)
else:
self.store_filter_block(filtr, blockid, sblockid)
else:
self.filters.append(filtr)
def store_value(self, value, blockid, sblockid, pblock_ids, depth):
"""Store a VALUES inthe right list
Parameters
----------
triple : dict
triple dict
typ : str
relatin or attribute
block_info : None, optional
block info if triple is part of a block
"""
if blockid:
if depth:
self.update_block_dict(depth, "values", value)
else:
self.store_values_block(value, blockid, sblockid)
else:
self.values.append(value)
def store_values_block(self, value, blockid, sblockid):
"""Add a VALUES in a block. If block exist, add the triples, else, create a new block.
Same for the sub block
Parameters
----------
triple : dict
The triple dict to add
blockid : int
Block id
sblockid : int
Sub block id
"""
for block in self.triples_blocks:
if block["id"] == blockid:
for sblock in block["sblocks"]:
if sblock["id"] == sblockid:
sblock["values"].append(value)
return
block["sblocks"].append({
"id": sblockid,
"triples": [],
"filters": [],
"values": [value, ]
})
return
self.triples_blocks.append({
"id": blockid,
"type": self.get_block_type(blockid),
"sblocks": [{
"id": sblockid,
"triples": [],
"filters": [],
"values": [value, ]
}, ]
})
def store_filter_block(self, filtr, blockid, sblockid):
"""Add a FILTER in a block. If block exist, add the triples, else, create a new block.
Same for the sub block
Parameters
----------
triple : dict
The triple dict to add
blockid : int
Block id
sblockid : int
Sub block id
"""
for block in self.triples_blocks:
if block["id"] == blockid:
for sblock in block["sblocks"]:
if sblock["id"] == sblockid:
sblock["filters"].append(filtr)
return
block["sblocks"].append({
"id": sblockid,
"triples": [],
"filters": [filtr, ],
"values": []
})
return
self.triples_blocks.append({
"id": blockid,
"type": self.get_block_type(blockid),
"sblocks": [{
"id": sblockid,
"triples": [],
"filters": [filtr, ],
"values": []
}, ]
})
def store_block(self, triple, blockid, sblockid, pblock_ids):
"""Add a triple in a block. If block exist, add the triples, else, create a new block.
Same for the sub block
Parameters
----------
triple : dict
The triple dict to add
blockid : int
Block id
sblockid : int
Sub block id
"""
for block in self.triples_blocks:
if block["id"] == blockid:
for sblock in block["sblocks"]:
if sblock["id"] == sblockid:
sblock["triples"].append(triple)
return
block["sblocks"].append({
"id": sblockid,
"triples": [triple, ],
"filters": [],
"values": []
})
return
self.triples_blocks.append({
"id": blockid,
"type": self.get_block_type(blockid),
"sblocks": [{
"id": sblockid,
"triples": [triple, ],
"filters": [],
"values": []
}, ]
})
def update_sub_block(self, block_dict, depths, type, value, current_depth):
depth = depths[current_depth]
if depth not in block_dict:
block_dict[depth] = {
"type": self.get_block_type(depth),
"triples": [],
"filters": [],
"values": [],
"sub_blocks": {}
}
# End of branch
if current_depth == len(depths) - 1:
block_dict[depth][type].append(value)
else:
self.update_sub_block(block_dict[depth]["sub_blocks"], depths, type, value, current_depth + 1)