[go: up one dir, main page]

Menu

[r19]: / trunk / owl2x.py  Maximize  Restore  History

Download this file

280 lines (212 with data), 7.4 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
#
# Wrapper for the OWL2X java application.
#
# Anze Vavpetic <anze.vavpetic@ijs.si>, April 2011
#
import tempfile
import subprocess
import logging
import sys
import cPickle
import os
DEBUG = True
# Setup a logger
logger = logging.getLogger("owl2x [Python]")
#logger.setLevel(logging.DEBUG if DEBUG else logging.INFO)
ch = logging.StreamHandler()
formatter = logging.Formatter("%(name)s %(levelname)s: %(message)s")
ch.setFormatter(formatter)
logger.addHandler(ch)
# OWL2X jar relative to this script
# FIXME: use jpype for calling java classes instead
OWL2X_PATH = '%s/%s' % (os.path.dirname(os.path.abspath(__file__)), 'OWL2X/')
# Target predicate.
TARGET_PRED = 'target'
# Main type.
MAIN_TYPE = 'instance'
#Isa predicate.
ISA_PRED = 'isa'
class OWL2X(object):
@staticmethod
def get_segs_input(ontologies, mapping):
"""
Returns a tuple (g2ont, ont) suitable for segs.
"""
tmpDir = tempfile.mkdtemp()
ontologyFiles = []
for ont in ontologies:
if OWL2X.isURI(ont):
ontologyFiles.append(ont)
else:
tmp = tempfile.NamedTemporaryFile()
ontologyFiles.append(tmp)
tmp.write(ont)
tmp.flush()
tmp = tempfile.NamedTemporaryFile()
mappingStr = ''
for pair in mapping:
mappingStr += '%s ' % pair[0]
uris = pair[1]
for uri in uris:
mappingStr += '%s ' % uri
mappingStr += '\n'
tmp.write(mappingStr)
tmp.flush()
mappingFile = tmp.name
args = ['java', '-jar', '%s/owl2x.jar' % OWL2X_PATH, 'segs', 'short', tmpDir, mappingFile] + OWL2X.names(ontologyFiles)
logger.debug(args)
p = subprocess.Popen(args)
stdout_str, stderr_str = p.communicate()
logger.debug(stdout_str)
logger.debug(stderr_str)
for ontfile in ontologyFiles:
ontfile.close()
return ([eval(l) for l in open('%s/ont' % tmpDir)], [eval(l) for l in open('%s/g2ont' % tmpDir)])
@staticmethod
def get_aleph_input(ontologies, mapping, relations, posExamples, negExamples):
"""
Returns a tuple (pos, neg, b).
"""
tmpDir = tempfile.mkdtemp()
# Write ontologies to disk
ontologyFiles = []
for ont in ontologies:
if OWL2X.isURI(ont):
ontologyFiles.append(ont)
else:
tmp = tempfile.NamedTemporaryFile()
ontologyFiles.append(tmp)
tmp.write(ont)
tmp.flush()
tmp = tempfile.NamedTemporaryFile()
mappingStr = ''
for pair in mapping:
mappingStr += '%s ' % pair[0]
uris = pair[1]
for uri in uris:
mappingStr += '%s ' % uri
mappingStr += '\n'
tmp.write(mappingStr)
tmp.flush()
mappingFile = tmp.name
# Convert the ontologies.
args = ['java', '-jar', '%s/owl2x.jar' % OWL2X_PATH, 'prolog', 'short', tmpDir, mappingFile] + OWL2X.names(ontologyFiles)
logger.debug(args)
p = subprocess.Popen(args)
stdout_str, stderr_str = p.communicate()
logger.debug(stdout_str)
logger.debug(stderr_str)
for ontfile in ontologyFiles:
if 'close' in dir(ontfile):
ontfile.close()
# Convert examples.
pos, neg = "", ""
# Assume posExamples and negExamples are lists of example IDs
for ex in posExamples:
pos += '%s(i%d).\n' % (TARGET_PRED, int(ex[0]))
for ex in negExamples:
neg += '%s(i%d).\n' % (TARGET_PRED, int(ex[0]))
# Now add the custom relations.
sys.path.append(tmpDir)
import b
# Assumes relations has the form: [[r_name1, [(a, b), ...]], [r_name2, [...]], ...]
for relation in relations:
r_name = relation[0]
b.modes.append(":- modeb(1, %s(+%s, -%s))." % (r_name, MAIN_TYPE, MAIN_TYPE))
b.table.append(":- table %s/2." % r_name)
b.determinations.append(":- determination(%s/1, %s/2)." % (TARGET_PRED, r_name))
for pair in relation[1]:
b.definitions.append("%s(i%s, i%s)." % (r_name, pair[0], pair[1]))
bk = ""
bk += bappend(b.table)
bk += bappend(b.modes)
bk += bappend(b.determinations)
bk += bappend(b.isa)
bk += '%s(X,Y) :- %s(X,Z), %s(Z,Y).\n' % (ISA_PRED, ISA_PRED, ISA_PRED)
bk += open('prune.pl').read() + "\n\n"
bk += bappend(b.definitions)
bk += bappend(b.instances)
# Append original example rank / label
for ex in posExamples:
bk += "orig_label(i%d, '%s').\n" % (ex[0], str(ex[1]))
for ex in negExamples:
bk += "orig_label(i%d, '%s').\n" % (ex[0], str(ex[1]))
return (pos, neg, bk)
@staticmethod
def isURI(text):
# For example: http://www.berkeleybop.org/ontologies/owl/GO.owl
return text.strip().startswith("http://")
@staticmethod
def names(fileList):
new = []
for f in fileList:
if 'name' in dir(f):
new.append(f.name)
else:
new.append(f)
return new
def bappend(table):
s = ""
for e in table:
s += e + '\n'
return s
#
#
# TESTS
#
#
def test1():
ont1 = open('geography.owl').read()
ont2 = open('occupation.owl').read()
ont3 = open('banking_services.owl').read()
m = open('bank_map.txt')
mapping = []
for l in m:
mapping.append(eval(l))
posExaples = range(0, 15)
negExamples = range(15, 30)
relations = [["married", [(1,4), (16,2), (19, 3)]]]
pos, neg, b = OWL2X.get_aleph_input([ont1, ont2, ont3], mapping, relations, posExaples, negExamples)
#print pos
#print neg
#print b
lala = open('lala.f', 'w')
lala.write(pos)
lala.close()
lala = open('lala.n', 'w')
lala.write(neg)
lala.close()
lala = open('lala.b', 'w')
lala.write(b)
lala.close()
import aleph
runner = aleph.Aleph()
rules = runner.induce('induce', 'testic', pos, neg, b)
print rules
def test2():
ont1 = open('gene_ontology.owl').read()
m = open('hsa_map.txt')
mapping = []
for l in m:
mapping.append(eval(l))
posExaples = range(0, 15)
negExamples = range(15, 30)
#relations = [["married", [(1,4), (16,2), (19, 3)]]]
pos, neg, b = OWL2X.get_aleph_input([ont1], mapping, [], posExaples, negExamples)
lala = open('brbr.f', 'w')
lala.write(pos)
lala.close()
lala = open('brbr.n', 'w')
lala.write(neg)
lala.close()
lala = open('brbr.b', 'w')
lala.write(b)
lala.close()
#import aleph
#runner = aleph.Aleph()
#rules = runner.induce('induce_cover', 'testic2', pos, neg, b)
#print rules
# Test.
if __name__ == '__main__':
#test1()
test2()