forked from dice-group/Ontolearn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinders.py
352 lines (297 loc) · 14.2 KB
/
binders.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
# -----------------------------------------------------------------------------
# MIT License
#
# Copyright (c) 2024 Ontolearn Team
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# -----------------------------------------------------------------------------
"""Pyhon binders of other concept learners."""
import subprocess
from datetime import datetime
from typing import List, Dict
from .utils import create_experiment_folder
import re
import time
from ontolearn.learning_problem import PosNegLPStandard
class PredictedConcept:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def __iter__(self):
yield self.Prediction
class DLLearnerBinder:
"""
dl-learner python binder.
"""
def __init__(self, binary_path=None, model=None, kb_path=None, storage_path=".", max_runtime=3):
try:
assert binary_path
assert model
assert kb_path
except AssertionError:
print(f'binary_path:{binary_path}, model:{model} kb_path{kb_path} can not be None')
raise
self.binary_path = binary_path
self.kb_path = kb_path
self.name = model
self.max_runtime = max_runtime
if storage_path is not None:
self.storage_path = storage_path
else:
self.storage_path, _ = create_experiment_folder()
self.best_predictions = None
self.config_name_identifier = None
def write_dl_learner_config(self, pos: List[str], neg: List[str]) -> str:
"""Writes config file for dl-learner.
Args:
pos: A list of URIs of individuals indicating positive examples in concept learning problem.
neg: A list of URIs of individuals indicating negatives examples in concept learning problem.
Returns:
str: Path of generated config file.
"""
assert len(pos) > 0 and isinstance(pos[0], str)
assert len(neg) > 0 and isinstance(neg[0], str)
Text = list()
pos_string = "{ "
neg_string = "{ "
for i in pos:
pos_string += "\"" + str(
i) + "\","
for j in neg:
neg_string += "\"" + str(
j) + "\","
pos_string = pos_string[:-1]
pos_string += "}"
neg_string = neg_string[:-1]
neg_string += "}"
Text.append("rendering = \"dlsyntax\"")
Text.append("// knowledge source definition")
Text.append("cli.type = \"org.dllearner.cli.CLI\"")
Text.append("ks.type = \"OWL File\"")
Text.append("\n")
Text.append("// knowledge source definition")
Text.append(
"ks.fileName = \"" + self.kb_path + '\"')
Text.append("\n")
Text.append("reasoner.type = \"closed world reasoner\"")
Text.append("reasoner.sources = { ks }")
Text.append("\n")
Text.append("lp.type = \"PosNegLPStandard\"")
Text.append("accuracyMethod.type = \"fmeasure\"")
Text.append("\n")
Text.append("lp.positiveExamples =" + pos_string)
Text.append("\n")
Text.append("lp.negativeExamples =" + neg_string)
Text.append("\n")
Text.append("alg.writeSearchTree = \"true\"")
Text.append("op.type = \"rho\"")
Text.append("op.useNumericDatatypes = \"false\"")
Text.append("op.useCardinalityRestrictions = \"false\"")
if self.name == 'celoe':
Text.append("alg.type = \"celoe\"")
Text.append("alg.stopOnFirstDefinition = \"true\"")
elif self.name == 'ocel':
Text.append("alg.type = \"ocel\"")
Text.append("alg.showBenchmarkInformation = \"true\"")
elif self.name == 'eltl':
Text.append("alg.type = \"eltl\"")
Text.append("alg.maxNrOfResults = \"1\"")
Text.append("alg.stopOnFirstDefinition = \"true\"")
else:
raise ValueError('Wrong algorithm chosen.')
Text.append("alg.maxExecutionTimeInSeconds = " + str(self.max_runtime))
Text.append("\n")
pathToConfig = self.storage_path + '/' + self.name + '_' + datetime.now().strftime("%Y%m%d_%H%M%S_%f") + '.conf'
with open(pathToConfig, "wb") as wb:
for i in Text:
wb.write(i.encode("utf-8"))
wb.write("\n".encode("utf-8"))
return pathToConfig
def fit(self, lp: PosNegLPStandard, max_runtime: int = None):
"""Fit dl-learner model on a given positive and negative examples.
Args:
lp:PosNegLPStandard
lp.pos A list of URIs of individuals indicating positive examples in concept learning problem.
lp.neg A list of URIs of individuals indicating negatives examples in concept learning problem.
max_runtime: Limit to stop the algorithm after n seconds.
Returns:
self.
"""
if max_runtime:
self.max_runtime = max_runtime
pathToConfig = self.write_dl_learner_config(pos=[i.str for i in lp.pos],
neg=[i.str for i in lp.neg])
total_runtime = time.time()
res = subprocess.run([self.binary_path, pathToConfig], capture_output=True, universal_newlines=True)
total_runtime = round(time.time() - total_runtime, 3)
self.best_predictions = self.parse_dl_learner_output(res.stdout.splitlines(), pathToConfig)
self.best_predictions['Runtime'] = total_runtime
return self
def best_hypotheses(self, n: int = None) -> PredictedConcept:
# @ TODO:
# Convert string to OWL class object
# {'Prediction': 'Child', 'Accuracy': 1.0, 'F-measure': 1.0, 'NumClassTested': 3, 'Runtime': 3.502}
return PredictedConcept(**self.best_hypothesis())
def best_hypothesis(self):
""" Return predictions if exists.
Returns:
The prediction or the string 'No prediction found.'
"""
if self.best_predictions:
return self.best_predictions
else:
print('No prediction found.')
def parse_dl_learner_output(self, output_of_dl_learner: List[str], file_path: str) -> Dict:
"""Parse the output received from executing dl-learner.
Args:
output_of_dl_learner: The output of dl-learner to parse.
file_path: The file path to store the output.
Returns:
A dictionary of {'Prediction': ..., 'Accuracy': ..., 'F-measure': ...}.
"""
solutions = None
best_concept_str = None
acc = -1.0
f_measure = -1.0
search_info = None
num_expression_tested = -1
# DL-learner does not provide a unified output :(
# ELTL => No info pertaining to the number of concept tested, number of retrieval etc.
# CELOE => Algorithm terminated successfully (time: 245ms, 188 descriptions tested, 69 nodes in the search
# tree).
# OCEL => Algorithm stopped (4505 descriptions tested).
time.time()
txt_path = file_path + '.txt' # self.storage_path + '/output_' + self.name + '_' + str(time.time()) + '.txt'
# (1) Store output of dl learner and extract solutions.
with open(txt_path, 'w') as w:
for th, sentence in enumerate(output_of_dl_learner):
w.write(sentence + '\n')
if 'solutions' in sentence and '1:' in output_of_dl_learner[th + 1]:
solutions = output_of_dl_learner[th:]
if 'Algorithm' in sentence:
search_info = sentence
# check whether solutions found
if solutions: # if solution found, check the correctness of relevant part of dl-learner output.
try:
assert isinstance(solutions, list)
assert 'solutions' in solutions[0]
assert len(solutions) > 0
assert '1: ' in solutions[1][:5]
except AssertionError:
print(type(solutions))
print('####')
print(solutions[0])
print('####')
print(len(solutions))
else:
# no solution found.
print('#################')
print('#######{}##########'.format(self.name))
print('#################')
for i in output_of_dl_learner[-3:-1]:
print(i)
if 'descriptions' in i:
search_info = i
print('#################')
print('#######{}##########'.format(self.name))
print('#################')
_ = re.findall(r'\d+ descriptions tested', search_info)
assert len(_) == 1
# Get the numbers
num_expression_tested = int(re.findall(r'\d+', _[0])[0])
return {'Model': self.name, 'Prediction': best_concept_str, 'Accuracy': float(acc) * .01,
'F-measure': float(f_measure) * .01, 'NumClassTested': int(num_expression_tested)}
# top_predictions must have the following form
"""solutions ......:
1: Parent(pred.acc.: 100.00 %, F - measure: 100.00 %)
2: ⊤ (pred.acc.: 50.00 %, F-measure: 66.67 %)
3: Person(pred.acc.: 50.00 %, F - measure: 66.67 %)
"""
best_solution = solutions[1]
if self.name == 'ocel':
""" parse differently"""
token = '(accuracy '
start_index = len('1: ')
end_index = best_solution.index(token)
best_concept_str = best_solution[start_index:end_index - 1] # -1 due to white space between *) (*.
quality_info = best_solution[end_index:]
# best_concept_str => *Sister ⊔ (Female ⊓ (¬Granddaughter))*
# quality_info => *(accuracy 100%, length 16, depth 2)*
# Create a list to hold the numbers
predicted_accuracy_info = re.findall(r'accuracy \d*%', quality_info)
assert len(predicted_accuracy_info) == 1
assert predicted_accuracy_info[0][-1] == '%' # percentage sign
acc = re.findall(r'\d+\.?\d+', predicted_accuracy_info[0])[0]
_ = re.findall(r'\d+ descriptions tested', search_info)
assert len(_) == 1
# Get the numbers
num_expression_tested = int(re.findall(r'\d+', _[0])[0])
elif self.name in ['celoe', 'eltl']:
# e.g. => 1: Sister ⊔ (∃ married.Brother) (pred. acc.: 90.24%, F-measure: 91.11%)
# Heuristic => Quality info start with *(pred. acc.: *
token = '(pred. acc.: '
start_index = len('1: ')
end_index = best_solution.index(token)
best_concept_str = best_solution[start_index:end_index - 1] # -1 due to white space between *) (*.
quality_info = best_solution[end_index:]
# best_concept_str => *Sister ⊔ (Female ⊓ (¬Granddaughter))*
# quality_info => *(pred. acc.: 79.27%, F-measure: 82.83%)*
# Create a list to hold the numbers
predicted_accuracy_info = re.findall(r'pred. acc.: \d+.\d+%', quality_info)
f_measure_info = re.findall(r'F-measure: \d+.\d+%', quality_info)
assert len(predicted_accuracy_info) == 1
assert len(f_measure_info) == 1
assert predicted_accuracy_info[0][-1] == '%' # percentage sign
assert f_measure_info[0][-1] == '%' # percentage sign
acc = re.findall(r'\d+\.?\d+', predicted_accuracy_info[0])[0]
f_measure = re.findall(r'\d+\.?\d+', f_measure_info[0])[0]
if search_info is not None:
# search_info is expected to be " Algorithm terminated successfully (time: 252ms, 188 descriptions
# tested, 69 nodes in the search tree)."
_ = re.findall(r'\d+ descriptions tested', search_info)
if len(_) == 0:
assert self.name == 'eltl'
else:
assert len(_) == 1
# Get the numbers
num_expression_tested = int(re.findall(r'\d+', _[0])[0])
else:
raise ValueError
# 100% into range between 1.0 and 0.0
return {'Prediction': best_concept_str, 'Accuracy': float(acc) * .01, 'F-measure': float(f_measure) * .01,
'NumClassTested': int(num_expression_tested)}
@staticmethod
def train(dataset: List = None) -> None:
""" Dummy method, currently it does nothing."""
def fit_from_iterable(self, dataset: List = None, max_runtime=None) -> List[Dict]:
"""Fit dl-learner model on a list of given positive and negative examples.
Args:
dataset: A list of tuple (s,p,n) where
s => string representation of target concept,
p => positive examples, i.e. s(p)=1 and
n => negative examples, i.e. s(n)=0.
max_runtime: Limit to stop the algorithm after n seconds.
Returns:
self.
"""
raise NotImplementedError
assert len(dataset) > 0
if max_runtime:
assert isinstance(max_runtime, int)
self.max_runtime = max_runtime
return [self.fit(pos=p, neg=n, max_runtime=self.max_runtime).best_hypothesis() for (s, p, n) in dataset]