-
Notifications
You must be signed in to change notification settings - Fork 0
/
semantic.py
292 lines (263 loc) · 11 KB
/
semantic.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
from owlready2 import get_ontology, default_world, sync_reasoner, Imp, Thing, onto_path
import dill
import itertools
class Ontology(object):
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls.ontology = get_ontology("ontology_merged.rdf").load()
cls._instance = super(Ontology, cls).__new__(
cls, *args, **kwargs)
return cls._instance
class Pipeline(object):
def __init__(self) -> None:
self.function_store = {}
self.pipelines = []
def _search(self, subpart, pertain=None):
store = {}
inputs = subpart.expects
for i in inputs:
for d in subpart.usesData:
try:
ps = d.pertain
if pertain is not None:
flag=True
for p in ps:
if p.name == pertain:
flag=False
break
if flag:
continue
#print(flag, d.pertain[0].name, pertain)
except:
None
#print("No pertain")
if i in d.returns:
if i not in store:
store[i] = []
if len(d.returns)>1:
store[i].append((eval(d.pythonDefinition[0]),None, d.returns.index(i), d.name))
else:
store[i].append((eval(d.pythonDefinition[0]),None, None, d.name))
for i in inputs:
if i not in store:
for d in subpart.usesExtractor:
if i in d.returns:
sub_store = self._search(d, pertain)
try:
ps = d.pertain
if pertain is not None:
flag=True
for p in ps:
if p.name == pertain:
flag=False
break
if flag:
continue
#print(flag, d.pertain[0].name, pertain)
except:
None
#print("No pertain")
if len(sub_store)>0:
if i not in store:
store[i] = []
#####
try:
[sub_store[o] for o in d.expects]
except:
continue
for combo in [list(x) for x in itertools.product(*[sub_store[o] for o in d.expects])]:
if len(d.returns)>1:
store[i].append((eval(d.pythonDefinition[0]), combo, d.returns.index(i),d.name))
else:
store[i].append((eval(d.pythonDefinition[0]), combo, None,d.name))
else:
continue
return store
def search_combo(self, combo, parts):
if isinstance(combo[1], list):
parts.append(combo[3])
if combo[2] is not None:
self.search_combo(combo[1][combo[2]], parts)
else:
self.search_combo(combo[1][0], parts)
else:
parts.append(combo[3])
return parts
def search(self, pertain=None):
default_world.as_rdflib_graph().serialize(destination="test.ttl")
sync_reasoner(infer_property_values = True)
models = default_world.sparql('SELECT ?s WHERE {?s a <http://example.com/ModelBuilder>}')
for m in models:
store = self._search(m[0], pertain)
inputs = m[0].expects
incomplete_pipeline = False
for i in inputs:
if i not in store:
incomplete_pipeline=True
break
if incomplete_pipeline:
continue
else:
duplicate_detect = set()
for combo in [list(x) for x in itertools.product(*[store[d] for d in m[0].expects])]:
alpha = tuple([tuple(self.search_combo(x, [])) for x in combo])
if alpha not in duplicate_detect:
self.pipelines.append((eval(m[0].pythonDefinition[0]), combo))
duplicate_detect.add(alpha)
def _execute(self, part):
executed_store = []
if part[1] is None:
if part[2] is None:
return dill.loads(part[0])()
else:
return dill.loads(part[0])()[part[2]]
else:
for s in part[1]:
if type(s) is list:
if s[1] is not None:
executed_store.append(dill.loads(s[0])()[s[1]])
else:
executed_store.append(dill.loads(s[0])())
else:
executed_store.append(self._execute(s))
self.function_store[dill.loads(part[0]).__name__] = dill.loads(part[0])(*executed_store)
if part[2] is None:
return dill.loads(part[0])(*executed_store)
else:
return dill.loads(part[0])(*executed_store)[part[2]]
def execute(self):
models = []
if len( self.pipelines)>0:
input()
for model in self.pipelines:
executed_store = []
for s in model[1]:
executed_store.append(self._execute(s))
model = dill.loads(model[0])(*executed_store)
print("############")
models.append(model)
return models#dill.loads(model[0])(*executed_store)
else:
print("Nothing to execute")
def _predict(self, part, dct):
data = {x.name:x for x in Thing.instances()}
fname = dill.loads(part[0]).__name__
if fname in data:
if len(data[fname].expects)>0:
inputs = [i.name for i in data[fname].expects]
res = []
for i in inputs:
if i in dct:
res.append(dct[i])
if len(res) == len(data[fname].expects):
if part[2] is None:
if len(res)==1:
return dill.loads(part[0])(res[0])
else:
return dill.loads(part[0])(*res)
else:
if len(res)==1:
return dill.loads(part[0])(res[0])[part[2]]
else:
return dill.loads(part[0])(*res)[part[2]]
### To be checked!
if len(data[fname].returns)>0:
outputs = [o.name for o in data[fname].returns]
res = []
for o in outputs:
if o in dct:
res.append(dct[o])
if len(res) == len(data[fname].returns):
if part[2] is None:
if len(res)==1:
return res[0]
else:
return res
else:
if len(res)==1:
return res[0]
else:
return res[part[2]]
executed_store = []
if part[1] is None:
if part[2] is None:
return dill.loads(part[0])()
else:
return dill.loads(part[0])()[part[2]]
else:
for s in part[1]:
if type(s) is list:
if s[1] is not None:
executed_store.append(dill.loads(s[0])()[s[1]])
else:
executed_store.append(dill.loads(s[0])())
else:
executed_store.append(self._predict(s, dct))
if part[2] is None:
return dill.loads(part[0])(*executed_store)
else:
return dill.loads(part[0])(*executed_store)[part[2]]
def transform(self, dct):
for model in self.pipelines:
predicted_store = []
for s in model[1]:
predicted_store.append(self._predict(s, dct))
return predicted_store
class Pertain():
def __init__(self, name):
self.name = name
def dataloader(*args, **kwargs):
def inner(func):
onto = Ontology().ontology
ns = onto.get_namespace("http://example.com/")
fdata = ns.DataLoader(func.__name__)
fdata.pythonDefinition = [str(dill.dumps(func))]
fno = onto.get_namespace("https://w3id.org/function/ontology#")
if 'output' in kwargs:
fparam = [fno.Parameter(o) for o in kwargs['output']]
fdata.returns = fparam
if 'pertain' in kwargs:
#fparam = [onto.search_one(label=i) for i in kwargs['pertain']]
fparam = [Pertain(x) for x in kwargs['pertain']]
fdata.pertain = fparam
return func
# returning inner function
return inner
def featuretransformer(*args, **kwargs):
def inner(func):
onto = Ontology().ontology
ns = onto.get_namespace("http://example.com/")
fdata = ns.FeatureTransformer(func.__name__)
fdata.pythonDefinition = [str(dill.dumps(func))]
fno = onto.get_namespace("https://w3id.org/function/ontology#")
if 'input' in kwargs:
fparam = [fno.Parameter(i) for i in kwargs['input']]
fdata.expects = fparam
if 'output' in kwargs:
fparam = [fno.Parameter(i) for i in kwargs['output']]
fdata.returns = fparam
if 'pertain' in kwargs:
fparam = [Pertain(x) for x in kwargs['pertain']]
#fparam = [onto.search_one(label=i) for i in kwargs['pertain']]
fdata.pertain = fparam
return func
# returning inner function
return inner
def modelbuilder(*args, **kwargs):
def inner(func):
onto = Ontology().ontology
ns = onto.get_namespace("http://example.com/")
fdata = ns.ModelBuilder(func.__name__)
fdata.pythonDefinition = [str(dill.dumps(func))]
fno = onto.get_namespace("https://w3id.org/function/ontology#")
if 'input' in kwargs:
fparam = [fno.Parameter(i) for i in kwargs['input']]
fdata.expects = fparam
if 'pertain' in kwargs:
#fparam = [onto.search_one(label=i) for i in kwargs['pertain']]
fparam = [Pertain(x) for x in kwargs['pertain']]
fdata.pertain = fparam
return func
# returning inner function
return inner