-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnar_wrapper.py
More file actions
executable file
·123 lines (103 loc) · 4.52 KB
/
nar_wrapper.py
File metadata and controls
executable file
·123 lines (103 loc) · 4.52 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
"""
Wrapper around ONA's NAR file that allows it to be reset, and tested that it does not have a memory leak etc.
"""
import os
import sys
import subprocess
path_to_ona_nar = os.environ.get("PATH_TO_ONA_NAR")
if path_to_ona_nar is not None and os.path.exists(path_to_ona_nar):
NAR = subprocess.Popen([path_to_ona_nar, "shell"], stdin=subprocess.PIPE,
stdout=subprocess.PIPE, universal_newlines=True)
else:
deafult_path_to_ona_nar = "./../../projects/OpenNARS-for-Applications/NAR"
print("WARN: OS ENV Variable ", path_to_ona_nar, " null or does not exists. Trying a defult path:",deafult_path_to_ona_nar)
path_to_ona_nar = deafult_path_to_ona_nar
NAR = subprocess.Popen([path_to_ona_nar, "shell"], stdin=subprocess.PIPE,
stdout=subprocess.PIPE, universal_newlines=True)
def parseTruth(T):
return {"frequency": T.split("frequency=")[1].split(" confidence")[0], "confidence": T.split(" confidence=")[1].split(" dt=")[0].split(" occurrenceTime=")[0]}
def parseTask(s):
M = {"occurrenceTime" : "eternal"}
if " :|:" in s:
M["occurrenceTime"] = "now"
s = s.replace(" :|:","")
if "occurrenceTime" in s:
M["occurrenceTime"] = s.split("occurrenceTime=")[1].split(" ")[0]
sentence = s.split(" occurrenceTime=")[0] if " occurrenceTime=" in s else s.split(" Priority=")[0]
M["punctuation"] = sentence[-4] if ":|:" in sentence else sentence[-1]
M["term"] = sentence.split(" creationTime")[0].split(" occurrenceTime")[0].split(" Truth")[0][:-1]
if "Truth" in s:
M["truth"] = parseTruth(s.split("Truth: ")[1])
return M
def parseReason(sraw):
if "implication: " not in sraw:
return None
Implication = parseTask(sraw.split("implication: ")[-1].split("precondition: ")[0]) #last reason only (others couldn't be associated currently)
Precondition = parseTask(sraw.split("precondition: ")[-1].split("\n")[0])
Implication["occurrenceTime"] = "eternal"
Precondition["punctuation"] = Implication["punctuation"] = "."
Reason = {}
Reason["desire"] = sraw.split("decision expectation=")[-1].split(" ")[0]
Reason["hypothesis"] = Implication
Reason["precondition"] = Precondition
return Reason
def parseExecution(e):
if "args " not in e:
return {"operator" : e.split(" ")[0], "arguments" : []}
return {"operator" : e.split(" ")[0], "arguments" : e.split("args ")[1].split("{SELF} * ")[1][:-1]}
def GetRawOutput():
NAR.stdin.write("0\n")
NAR.stdin.flush()
ret = ""
before = []
requestOutputArgs = False
while "done with 0 additional inference steps." != ret.strip():
if ret != "":
before.append(ret.strip())
if ret.strip() == "//Operation result product expected:":
requestOutputArgs = True
break
ret = NAR.stdout.readline()
return before[:-1], requestOutputArgs
def GetOutput():
lines, requestOutputArgs = GetRawOutput()
executions = [parseExecution(l) for l in lines if l.startswith('^')]
inputs = [parseTask(l.split("Input: ")[1]) for l in lines if l.startswith('Input:')]
derivations = [parseTask(l.split("Derived: " if l.startswith('Derived:') else "Revised:")[1]) for l in lines if l.startswith('Derived:') or l.startswith('Revised:')]
answers = [parseTask(l.split("Answer: ")[1]) for l in lines if l.startswith('Answer:')]
reason = parseReason("\n".join(lines))
return {"input": inputs, "derivations": derivations, "answers": answers, "executions": executions, "reason": reason, "raw": "\n".join(lines), "requestOutputArgs" : requestOutputArgs}
def GetStats():
Stats = {}
lines, _ = GetRawOutput()
for l in lines:
if ":" in l:
leftside = l.split(":")[0].replace(" ", "_").strip()
rightside = float(l.split(":")[1].strip())
Stats[leftside] = rightside
return Stats
def AddInput(narsese, Print=True):
NAR.stdin.write(narsese + '\n')
NAR.stdin.flush()
ReturnStats = narsese == "*stats"
if ReturnStats:
return GetStats()
ret = GetOutput()
if Print:
print(ret["raw"])
sys.stdout.flush()
return ret
def Exit():
NAR.sendline("quit")
def Reset():
global NAR
NAR.kill()
NAR = subprocess.Popen([path_to_ona_nar, "shell"], stdin=subprocess.PIPE,
stdout=subprocess.PIPE, universal_newlines=True)
AddInput("*reset")
AddInput("*volume=100")
if __name__ == '__main__':
# test that Reset works. Not totally convinced it does
for i in range(100):
print(i)
Reset()