forked from HKUST-KnowComp/EFOK-CQA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert_beta_dataset.py
294 lines (244 loc) · 10.1 KB
/
convert_beta_dataset.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
import os
import os.path as osp
import json
import pickle
from typing import Dict
from tqdm import tqdm
from src.language import foq
from src.language.grammar import parse_lstr_to_lformula
from src.structure.knowledge_graph_index import KGIndex
from src.structure.knowledge_graph import KnowledgeGraph
beta_types_key_list = [
('e', ('r',)),
('e', ('r', 'r')),
('e', ('r', 'r', 'r')),
(('e', ('r',)), ('e', ('r',))),
(('e', ('r',)), ('e', ('r',)), ('e', ('r',))),
((('e', ('r',)), ('e', ('r',))), ('r',)),
(('e', ('r', 'r')), ('e', ('r',))),
(('e', ('r',)), ('e', ('r', 'n'))),
(('e', ('r',)), ('e', ('r',)), ('e', ('r', 'n'))),
((('e', ('r',)), ('e', ('r', 'n'))), ('r',)),
(('e', ('r', 'r')), ('e', ('r', 'n'))),
(('e', ('r', 'r', 'n')), ('e', ('r',))),
(('e', ('r',)), ('e', ('r',)), ('u',)),
((('e', ('r',)), ('e', ('r',)), ('u',)), ('r',)),
((('e', ('r', 'n')), ('e', ('r', 'n'))), ('n',)),
((('e', ('r', 'n')), ('e', ('r', 'n'))), ('n', 'r'))]
labeled_beta_types_list = [
('s1', ('r1',)),
('s1', ('r1', 'r2')),
('s1', ('r1', 'r2', 'r3')),
(('s1', ('r1',)), ('s2', ('r2',))),
(('s1', ('r1',)), ('s2', ('r2',)), ('s3', ('r3',))),
((('s1', ('r1',)), ('s2', ('r2',))), ('r3',)),
(('s1', ('r1', 'r2')), ('s2', ('r3',))),
(('s1', ('r1',)), ('s2', ('r2', 'n'))),
(('s1', ('r1',)), ('s2', ('r2',)), ('s3', ('r3', 'n'))),
((('s1', ('r1',)), ('s2', ('r2', 'n'))), ('r3',)),
(('s1', ('r1', 'r2')), ('s2', ('r3', 'n'))),
(('s1', ('r1', 'r2', 'n')), ('s2', ('r3',))),
(('s1', ('r1',)), ('s2', ('r2',)), ('u',)),
((('s1', ('r1',)), ('s2', ('r2',)), ('u',)), ('r3',)),
((('s1', ('r1', 'n')), ('s2', ('r2', 'n'))), ('n',)),
((('s1', ('r1', 'n')), ('s2', ('r2', 'n'))), ('n', 'r3'))
]
beta_lstr_list = [
"r1(s1,f)", # 1p
"r1(s1,e1)&r2(e1,f)", # 2p
"r1(s1,e1)&r2(e1,e2)&r3(e2,f)", # 3p
"r1(s1,f)&r2(s2,f)", # 2i
"r1(s1,f)&r2(s2,f)&r3(s3,f)", # 3i
"r1(s1,e1)&r2(s2,e1)&r3(e1,f)", ## ip
"r1(s1,e1)&r2(e1,f)&r3(s2,f)", # pi
"r1(s1,f)&!r2(s2,f)", #2in
"r1(s1,f)&r2(s2,f)&!r3(s3,f)", # 3in
"r1(s1,e1)&!r2(s2,e1)&r3(e1,f)", # inp
"r1(s1,e1)&r2(e1,f)&!r3(s2,f)", # pin
"r1(s1,e1)&!r2(e1,f)&r3(s2,f)", # pni
"r1(s1,f)|r2(s2,f)", # 2u
"(r1(s1,e1)|r2(s2,e1))&r3(e1,f)", # up
"!(!r1(s1,f)&!r2(s2,f))", # 2u-dnf
"!(!r1(s1,e1)|r2(s2,e1))&r3(e1,f)",# up-dnf
]
beta_names = [
'1p', '2p', '3p', '2i', '3i', 'ip', 'pi', '2in', '3in', 'inp', 'pin', 'pni', '2u', 'up', '2u-dnf', 'up-dnf'
]
beta_lstr2name = {}
for s, n in zip(beta_lstr_list, beta_names):
beta_lstr2name[
parse_lstr_to_lformula(s).lstr()
] = n
universal_case = "r1(f_author, u_paper) -> r2(u_paper, s_nips)"
ucaes = "(!r1(f_author, u_paper))|r2(u_paper, s_nips)"
def beta_type_to_ldict():
pass
def align_entities_relations(labeled_beta_type, beta_sample) -> Dict:
d = {}
def _align(labeled_beta_type, beta_sample):
for sub_type, sub_sample in zip(labeled_beta_type, beta_sample):
if not isinstance(sub_type, str):
_align(sub_type, sub_sample)
else:
if sub_type[0] in 'sr':
d[sub_type] = sub_sample
_align(labeled_beta_type, beta_sample)
return d
def convert_beta_folder(beta_folder, output_folder):
"""
Convert the folder of beta dataset into the output data
the structure of the beta folder
indices
- ent2id.pkl
- id2ent.pkl
- id2rel.pkl
- rel2id.pkl
knowledge graphs and queries
{test/valid/train}.txt
train_queries
train-queries.pkl
train-answers.pkl
evaluation queries
{test/valid}-queries.pkl
{test/valid}-easy-answers.pkl
{test/valid}-hard-answers.pkl
the structure of output folder
kgindex.json: aggregrates the indices files into one
used by the KGIndex.load()
{train/test/valid}.tsv: triple information in the tsv
used by KnowledgeGraph.create()
{train/test/valid}_qaa.json: dictionary
key: lstr of each type
value: List of triples (mapping dict, easy_answer, hard_answer)
for train, the hard answer is empty list
"""
# build knowledge graph indices
print("converting KGIndex")
os.makedirs(output_folder, exist_ok=True)
kgidx = KGIndex()
with open(osp.join(beta_folder, 'ent2id.pkl'), 'rb') as f:
entity_to_id = pickle.load(f)
eids = []
for name, eid in entity_to_id.items():
kgidx.register_entity(name, eid)
eids.append(eid)
assert max(eids) - min(eids) + 1 == len(kgidx.map_entity_name_to_id)
with open(osp.join(beta_folder, 'rel2id.pkl'), 'rb') as f:
relation_to_id = pickle.load(f)
rids = []
for name, rid in relation_to_id.items():
kgidx.register_relation(name, rid)
rids.append(rid)
assert max(rids) - min(rids) + 1 == len(kgidx.map_relation_name_to_id)
print("dump converted KGIndex")
kgidx.dump(osp.join(output_folder, 'kgindex.json'))
kgidx = KGIndex.load(osp.join(output_folder, 'kgindex.json'))
# train knowledge graphs
print("converting train KnowledgeGraph")
train_kg = KnowledgeGraph.create(
triple_files=osp.join(beta_folder, 'train.txt'),
kgindex=kgidx)
print("dump converted train KnowledgeGraph")
train_kg.dump(osp.join(output_folder, 'train_kg.tsv'))
print("converting valid KnowledgeGraph")
valid_kg = KnowledgeGraph.create(
triple_files=[osp.join(beta_folder, 'train.txt'),
osp.join(beta_folder, 'valid.txt')],
kgindex=kgidx)
print("dump converted valid KnowledgeGraph")
valid_kg.dump(osp.join(output_folder, 'valid_kg.tsv'))
print("converting test KnowledgeGraph")
test_kg = KnowledgeGraph.create(
triple_files=[osp.join(beta_folder, 'train.txt'),
osp.join(beta_folder, 'valid.txt'),
osp.join(beta_folder, 'test.txt')],
kgindex=kgidx)
print("dump converted test KnowledgeGraph")
test_kg.dump(osp.join(output_folder, 'test_kg.tsv'))
# knowledge graph queries
# train queries
with open(osp.join(beta_folder, "train-queries.pkl"), 'rb') as f:
train_queries = pickle.load(f)
with open(osp.join(beta_folder, "train-answers.pkl"), 'rb') as f:
train_answers = pickle.load(f)
lstr_xy_dict = {}
for key, labeled_type, lstr in zip(
beta_types_key_list, labeled_beta_types_list, beta_lstr_list):
samples = list(train_queries[key])
if len(samples) == 0:
print(key, lstr, "not found in the dataset")
continue
lformula = parse_lstr_to_lformula(lstr)
folf = fof.ConjunctiveFormula(lformula)
print(folf.formula.lstr())
lstr_xy_dict[lstr] = []
for sample in tqdm(samples, desc='train query answer processing'):
d = align_entities_relations(labeled_type, sample)
answer = {'f': list(train_answers[sample])}
folf.append_relation_and_symbols(d)
lstr_xy_dict[lstr].append(
(d, answer, [])
)
with open(osp.join(output_folder, 'train-qaa.json'), 'wt') as f:
print([k for k in lstr_xy_dict])
json.dump(lstr_xy_dict, f)
# valid queries
with open(osp.join(beta_folder, "valid-queries.pkl"), 'rb') as f:
valid_queries = pickle.load(f)
with open(osp.join(beta_folder, "valid-easy-answers.pkl"), 'rb') as f:
valid_easy_answers = pickle.load(f)
with open(osp.join(beta_folder, "valid-hard-answers.pkl"), 'rb') as f:
valid_hard_answers = pickle.load(f)
lstr_xy_dict = {}
for key, labeled_type, lstr in zip(
beta_types_key_list, labeled_beta_types_list, beta_lstr_list):
samples = list(valid_queries[key])
lformula = parse_lstr_to_lformula(lstr)
folf = fof.ConjunctiveFormula(lformula)
print(folf.formula.lstr())
lstr_xy_dict[lstr] = []
for sample in tqdm(samples, desc="valid query answer processing"):
d = align_entities_relations(labeled_type, sample)
easy_answer = {'f': list(valid_easy_answers[sample])}
hard_answer = {'f': list(valid_hard_answers[sample])}
folf.append_relation_and_symbols(d)
lstr_xy_dict[lstr].append(
(d, easy_answer, hard_answer)
)
with open(osp.join(output_folder, 'valid-qaa.json'), 'wt') as f:
json.dump(lstr_xy_dict, f)
# test queries
with open(osp.join(beta_folder, "test-queries.pkl"), 'rb') as f:
test_queries = pickle.load(f)
with open(osp.join(beta_folder, "test-easy-answers.pkl"), 'rb') as f:
test_easy_answers = pickle.load(f)
with open(osp.join(beta_folder, "test-hard-answers.pkl"), 'rb') as f:
test_hard_answers = pickle.load(f)
lstr_xy_dict = {}
for key, labeled_type, lstr in zip(
beta_types_key_list, labeled_beta_types_list, beta_lstr_list):
samples = list(test_queries[key])
lformula = parse_lstr_to_lformula(lstr)
folf = fof.ConjunctiveFormula(lformula)
print(folf.formula.lstr())
lstr_xy_dict[lstr] = []
for sample in tqdm(samples, desc='test query answer processing'):
d = align_entities_relations(labeled_type, sample)
# possible answers into the key-value form
easy_answer = {'f': list(test_easy_answers[sample])}
hard_answer = {'f': list(test_hard_answers[sample])}
folf.append_relation_and_symbols(d)
lstr_xy_dict[lstr].append(
(d, easy_answer, hard_answer)
)
with open(osp.join(output_folder, 'test-qaa.json'), 'wt') as f:
json.dump(lstr_xy_dict, f)
if __name__ == "__main__":
beta_folder = "/data/zwanggc/FirstOrderQueryEstimation/data/{}"
output_folder = "./data/{}"
for dataset in [
"FB15k-237-q2b",
"FB15k-q2b", "NELL-q2b"]:
print(dataset)
convert_beta_folder(beta_folder.format(dataset),
output_folder.format(dataset))