forked from opennars/OpenNARS-for-Applications
-
Notifications
You must be signed in to change notification settings - Fork 0
/
evaluation.py
executable file
·187 lines (178 loc) · 8.71 KB
/
evaluation.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
"""
* The MIT License
*
* Copyright 2020 The OpenNARS authors.
*
* 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.
* """
from subprocess import PIPE, run
import subprocess
import glob
#NAR C tests & metrics, only print fully output on failure, always print the metrics:
def ctests(Example, Args, DoneAfterMetric):
result = run(Args.split(" "), stdout=PIPE, stderr=PIPE, universal_newlines=True)
if result.returncode != 0:
print(result.stdout, result.stderr)
exit(result.returncode)
for line in reversed(result.stdout.split("\n")):
if "ratio=" in line:
if DoneAfterMetric:
print(Example + " metrics: " + line)
return
else:
print(line)
print("\n" + Example + " successful!")
ctests("System tests", "./NAR", False)
#Q&A metrics for the Narsese and English files:
TimeCntGlobal = 0
TimeSumGlobal = 0
ConfidenceCntGlobal = 0
ConfidenceSumGlobal = 0.0
QuestionsTotalGlobal = 0.0
QuestionsAnsweredGlobal = 0.0
def Test(Example, outputString):
global Timing, ConfidenceCntGlobal, ConfidenceSumGlobal, TimeSumGlobal, TimeCntGlobal, QuestionsTotalGlobal, QuestionsAnsweredGlobal
TimeCnt = 0.0
TimeSum = 0.0
ConfidenceCnt = 0.0
ConfidenceSum = 0.0
QuestionsTotal = 0.0
QuestionsAnswered = 0.0
expect_condition = "Comment: expected: "
expect_condition_answer = expect_condition + "Answer: "
expect_condition_execution = expect_condition + "^"
lines = outputString.split('\n')
AnswerRatioTest = True
for i in range(len(lines)):
line = lines[i].strip()
if line.startswith(expect_condition):
QuestionsTotal += 1.0
QuestionsTotalGlobal += 1.0
isAnswerCondition = line.startswith(expect_condition_answer)
isExecutionCondition = line.startswith(expect_condition_execution)
if isAnswerCondition:
ConfidenceExpected = 0
ExpectedOutput = line.split(expect_condition_answer)[1].strip() + " "
if "Truth:" in ExpectedOutput:
AnswerRatioTest = False
if not AnswerRatioTest:
ExpectedOutput = ExpectedOutput.split("Truth:")[0]
TruthValue = line.split("Truth:")[1]
ConfidenceExpected = float(TruthValue.split("confidence=")[1])
FoundOutput = False
ConfidenceObtainedMax = 0
CreationTimeOfMax = 0
for j in reversed(range(i)): #go in reverse, don't jump over previous expects
line_before = lines[j].strip()
if line_before.startswith("Answer:") and ExpectedOutput in line_before:
ConfidenceObtained = float(line_before.split("confidence=")[1])
CreationTime = int(line_before.split("creationTime=")[1].split(" ")[0])
if ConfidenceObtained > ConfidenceObtainedMax:
ConfidenceObtainedMax = ConfidenceObtained
CreationTimeOfMax = CreationTime
FoundOutput = True
QuestionsAnswered += 1.0
QuestionsAnsweredGlobal += 1.0
if line_before.startswith(expect_condition):
break
if not AnswerRatioTest:
if not FoundOutput or ConfidenceObtainedMax < ConfidenceExpected:
print("Failure for " + line + " in " + Example)
exit(0)
TimeSum += float(CreationTime)
TimeCnt += 1.0
ConfidenceSum += ConfidenceObtainedMax
ConfidenceCnt += 1.0
if isExecutionCondition:
AnswerRatioTest = False
Message = line.split(expect_condition)[1]
HadAnswer = False
for j in reversed(range(i)):
line_before = lines[j].strip()
if line_before.startswith("^"):
if Message != line_before:
print("Failure for " + line + " in "+ Example)
exit(0)
else:
HadAnswer = True
QuestionsAnswered += 1.0
QuestionsAnsweredGlobal += 1.0
break
if not HadAnswer:
print("Failure for " + line + " in "+ Example)
exit(0)
if AnswerRatioTest:
if QuestionsTotal > 0:
print("\nQ&A stress test results for test " + Example)
print("Total questions = " + str(QuestionsTotal))
print("Correctly answered ones = " + str(QuestionsAnswered))
print("Answer ratio = " + str(QuestionsAnswered / QuestionsTotal))
else:
print("\nPassed " + Example)
else:
if TimeCnt > 0 and ConfidenceCnt > 0:
print("\nQ&A metrics for test " + Example)
print("Average answer time = " + str(TimeSum/TimeCnt))
print("Average answer confidence = " + str(ConfidenceSum/ConfidenceCnt))
print("Combined loss = " + str((1.0 - ConfidenceSum/ConfidenceCnt) * (TimeSum/TimeCnt)))
else:
print("\nPassed " + Example)
TimeSumGlobal += TimeSum
TimeCntGlobal += TimeCnt
ConfidenceSumGlobal += ConfidenceSum
ConfidenceCntGlobal += ConfidenceCnt
#Evaluate tests & performance on all Narsese examples:
print("\nNow running Q&A experiments:")
for filename in sorted(glob.glob("./examples/nal/*.nal")):
Test(filename, subprocess.getoutput("./NAR shell < " + filename))
print("\nNarsese integration tests successful!")
QuestionsTotalGlobalTemp = QuestionsTotalGlobal
#Evaluate tests & performance English examples:
for filename in sorted(glob.glob('./examples/english/*.english')):
Test(filename, subprocess.getoutput("python3 english_to_narsese.py EventOutput quiet < " + filename + " | ./NAR shell"))
if QuestionsTotalGlobal == QuestionsTotalGlobalTemp:
print("\nEnglish integration tests skipped, install python3 and nltk to include them in the evaluation!")
else:
print("\nEnglish integration tests successful!")
#Print global metrics:
if TimeCntGlobal > 0:
print("\nQ&A metrics global")
print("Average answer time = " + str(TimeSumGlobal/TimeCntGlobal))
print("Average answer confidence = " + str(ConfidenceSumGlobal/ConfidenceCntGlobal))
print("Combined loss = " + str((1.0 - ConfidenceSumGlobal/ConfidenceCntGlobal) * (TimeSumGlobal/TimeCntGlobal)))
#Print Q&A answer rate:
print("\nQ&A answer rate global")
print("Total questions = " + str(QuestionsTotalGlobal))
print("Correctly answered ones = " + str(QuestionsAnsweredGlobal))
print("Answer ratio = " + str(QuestionsAnsweredGlobal / QuestionsTotalGlobal))
print("\nSheep counting task:")
print(subprocess.getoutput("cd ./misc/Python/ && python3 count_sheep.py").split("\n")[-1])
print(subprocess.getoutput("cd ./misc/Python/ && python3 discriminativefunction.py silent seed=42"))
print(subprocess.getoutput("cd ./misc/Python/ && python3 conditioning.py silent seed=42"))
print(subprocess.getoutput("cd ./misc/Python/ && python3 sortingtask.py silent seed=42"))
print(subprocess.getoutput("cd ./misc/Python/ && python3 identitymatching.py silent seed=42"))
#Print procedure learning metrics:
print("\nNow running procedure learning examples for 10K iterations each:")
ctests("Pong", "./NAR pong 10000", True)
ctests("Pong2", "./NAR pong2 10000", True)
ctests("Alien", "./NAR alien 20000", True)
ctests("Cartpole", "./NAR cartpole 10000", True)
ctests("Robot", "./NAR robot 1200", True)
ctests("Bandrobot", "./NAR bandrobot 10000", True)
print("\nProcedure learning metrics done")