-
Notifications
You must be signed in to change notification settings - Fork 2
/
testOrgs.py
215 lines (157 loc) · 6.18 KB
/
testOrgs.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
import sys, os, subprocess, glob
simulationTemplate="""// auto-generated by evolverilog
`include "%s" // include the module to call
module organismSimulator;
reg %s; // number of Inputs Args
wire %s; // number of Outputs Args
parameter settleDelay = 10000;
%s uut (%s,%s); // module to call, number of Output, Input Args
integer i;
initial
begin
$display (%s); // io structure
// should run number of inputs ^ 2 times
for (i = 0; i < %d; i = i + 1) begin
{%s} = i; // number of Input Args
#settleDelay
$display ("%s",%s,%s); // total args, outputs, inputs
end
end
endmodule"""
def writeSimulation(verilogTestOutputFile,organismModuleFile,
numInputs,numOutputs,organismModuleName=None):
if organismModuleName is None:
organismModuleName = organismModuleFile.split('.')[0]
totalArgs = numInputs+numOutputs
inputs = ','.join('Input%d'%i for i in xrange(numInputs))
outputs = ','.join('Output%d'%i for i in xrange(numOutputs))
display = ','.join('%d' for i in xrange(totalArgs))
ioStructure = '"'+','.join('out' if i < numOutputs else 'in' for i in xrange(totalArgs) )+'"'
templateArgs = (organismModuleFile,inputs,outputs,organismModuleName,
outputs,inputs,ioStructure,numInputs**2,inputs,display,outputs,
inputs)
simulationCode = simulationTemplate%templateArgs
f = open(verilogTestOutputFile,'w')
f.write(simulationCode)
f.close()
def getSimulationResultFromFile(filepath):
fin = open(filepath,'r')
txt = fin.read()
fin.close()
return getSimulationResultFromText(txt)
def getSimulationResultFromText(txt):
lines = txt.split('\n')
# reads first line (contains formatting information)
ioStructure = lines[0].split(',')
numberOfInputs = ioStructure.count("in")
numberOfOutputs = ioStructure.count("out")
s = SimulationResult(numberOfInputs,numberOfOutputs)
# will go through lines 1:END (Note: last element is EOF)
for line in lines[1:-1]:
simResults = line.strip(' ').split(',') # csv format
s.addTrial(
SimulationTrial(
tuple(int(a) for a in simResults[0:numberOfOutputs]),
tuple(int(b) for b in simResults[numberOfOutputs:])
)
)
return s
class SimulationMap:
def __init__(self,simulationResult):
self._map = dict(
( tuple( t.getInputs() ),tuple( t.getOutputs() ) )
for t in simulationResult.getTrials()
)
self._numberOfInputs = simulationResult.getNumberOfInputs()
self._numberOfOutputs = simulationResult.getNumberOfOutputs()
def getResult(self,inputTuple):
return self._map[tuple(inputTuple)]
def getNumberOfInputs(self):
return self._numberOfInputs
def getNumberOfOutputs(self):
return self._numberOfOutputs
def __str__(self):
trials = []
for simInput, simOutput in self._map.iteritems():
trials.append(
'\tInput: %s. Output: %s.'%(str(simInput),str(simOutput))
)
return 'Simulation Map:\n%s'%('\n'.join(trials))
class SimulationResult:
def __init__(self,numInputs,numOutputs):
self._trials = []
self._numberOfInputs = numInputs
self._numberOfOutputs = numOutputs
def addTrial(self,simTrial):
self._trials.append(simTrial)
def getTrials(self):
return self._trials
def getNumberOfInputs(self):
return self._numberOfInputs
def getNumberOfOutputs(self):
return self._numberOfOutputs
def __str__(self):
return '\n'.join(["Trial %d: %s"%(i,str(trial)) for i,trial in enumerate(self.getTrials())])
class SimulationTrial:
def __init__(self,outputs,inputs):
self._inputs = inputs
self._outputs = outputs
def getInputs(self):
return self._inputs
def getOutputs(self):
return self._outputs
def __str__(self):
return "Inputs: %s. Outputs: %s"%(str(self.getInputs()),str(self.getOutputs()))
def testOrganism(filepath, subdir, numInputs, numOutputs,
organismModuleName, clearFiles=True, testFileName = 'organismTest',
writeSim=True):
# write the verilog test file
if writeSim:
writeSimulation(
os.path.join(subdir,'%s.v'%testFileName),
filepath,
numInputs,
numOutputs,
organismModuleName
)
# print 'Testing organism: %s'%filepath
# compile the test file
subprocess.call([
'iverilog', '-o',
os.path.join(subdir,'%s.o'%testFileName),
os.path.join(subdir,'%s.v'%testFileName)]
)
# get the test file results
process = subprocess.Popen([
'vvp',
os.path.join(subdir,'%s.o'%testFileName)],
stdout=subprocess.PIPE
)
# pull output from pipe
output = process.communicate() #(stdout, stderr)
# convert into a SimulationResult from pipe output
simResult = getSimulationResultFromText('\n'.join(output[0].split('\r\n')))
# print simResult
if clearFiles:
try:
os.remove(os.path.join(subdir,'%s.o'%testFileName))
os.remove(os.path.join(subdir,'%s.v'%testFileName))
except:
print "Error clearing files!"
print "Files are to be cleared, but the files probably don't exist."
return simResult
def testOrganisms(subdir,numInputs,numOutputs,organismModuleName,
testFileName = 'organismTest'):
"""
Run the evolverilog test suite in a subdirectory.
"""
allResults = {}
# for all files with a verilog extension, test the organism
for file in glob.glob(os.path.join(subdir, '*.v')):
allResults[file] = testOrganism(file,subdir,numInputs,
numOutputs,organismModuleName)
# print allResults.keys()
os.remove(os.path.join(subdir,'%s.o'%testFileName))
os.remove(os.path.join(subdir,'%s.v'%testFileName))
if __name__ == "__main__":
testOrganisms(sys.argv[1],2,1,'andTest')