-
Notifications
You must be signed in to change notification settings - Fork 2
/
toinpho.py
73 lines (61 loc) · 2.07 KB
/
toinpho.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
from inpho.model import *
import re
def from_dlv(filename, load_obj=False):
"""
Function to build a taxonomy from the specified DLV output file.
"""
# build regex for instance and link search
regex_class = re.compile("class\(i(\d+)\)")
regex_isa = re.compile("isa\(i(\d+),i(\d+)\)")
regex_ins = re.compile("ins\(i(\d+),i(\d+)\)")
regex_links = re.compile("link\(i(\d+),i(\d+)\)")
# process DLV output file
with open(filename) as f:
dlv = f.read()
classes = frozenset(regex_class.findall(dlv))
subclasses = frozenset(regex_isa.findall(dlv))
subclasses = dict(subclasses)
instances = frozenset(regex_ins.findall(dlv))
instances = dict(instances)
nodes = dict()
links = frozenset(regex_links.findall(dlv))
links = dict(links)
# clear former ontotree table
for node in Session.query(Node).all():
print "removing", node.label
Session.delete(node)
for idea in Session.query(Idea).all():
print "removing instances and links from", idea.label
idea.instances = []
idea.links = []
Session.commit()
# add new classes
for cls in classes:
idea = Session.query(Entity).get(cls)
node = Node()
node.label = idea.label
node.concept_id = cls
node.parent_id = None
nodes[cls] = node
print "adding", node.label
Session.add(node)
Session.commit()
# add subclass relations
for child, parent in subclasses.iteritems():
nodes[child].parent_id = nodes[parent].ID
Session.commit()
# add instances
for child, parent in instances.iteritems():
idea1 = Session.query(Idea).get(parent)
idea2 = Session.query(Idea).get(child)
idea1.instances.append(idea2)
Session.commit()
# add links
for i1, i2 in links.iteritems():
idea1 = Session.query(Idea).get(i1)
idea2 = Session.query(Idea).get(i2)
idea1.links.append(idea2)
Session.commit()
if __name__ == '__main__':
import sys
from_dlv(sys.argv[-1])