-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathvcd2json.py
323 lines (285 loc) · 10.8 KB
/
vcd2json.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
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
"""Create WaveJSON text string from VCD file."""
import sys
class _SignalDef:
def __init__(self, name, sid, length):
self._name = name
self._sid = sid
self._length = length
self._fmt = ''
class WaveExtractor:
def __init__(self, vcd_file, json_file, path_list):
"""
Extract signal values from VCD file and output in JSON format.
Specify VCD filename, JSON filename, and signal path list.
If <json_file> is an empty string, standard output is used.
Use slashes to separate signal path hierarchies.
The first signal of the list is regarded as clock.
Other signals are sampled on the negative edge of the clock.
"""
self._vcd_file = vcd_file
self._json_file = json_file
self._path_list = [path.strip('/') for path in path_list]
self._wave_chunk = 20
self._start_time = 0
self._end_time = 0
self._setup()
@property
def wave_chunk(self):
"""Number of wave samples per time group."""
return self._wave_chunk
@wave_chunk.setter
def wave_chunk(self, value):
self._wave_chunk = value
@property
def start_time(self):
"""Sampling start time."""
return self._start_time
@start_time.setter
def start_time(self, value):
self._start_time = value
@property
def end_time(self):
"""Sampling end time."""
return self._end_time
@end_time.setter
def end_time(self, value):
self._end_time = value
def _setup(self):
def create_path_dict(fin):
hier_list = []
path_list = []
path_dict = {}
while True:
line = fin.readline()
if not line:
raise EOFError('Can\'t find word "$enddefinitions".')
words = line.split()
if not words:
continue
if words[0] == '$enddefinitions':
return path_list, path_dict
if words[0] == '$scope':
hier_list.append(words[2])
elif words[0] == '$var':
path = '/'.join(hier_list + [words[4]])
path_list.append(path)
path_dict[path] = _SignalDef(name=words[4],
sid=words[3],
length=int(words[2]))
elif words[0] == '$upscope':
del hier_list[-1]
def update_path_dict(path_list, path_dict):
new_path_dict = {}
for path in path_list:
signal_def = path_dict.get(path, None)
if not signal_def:
raise ValueError('Can\'t find path "{0}".'.format(path))
new_path_dict[path] = signal_def
return new_path_dict
fin = open(self._vcd_file, 'rt')
path_list, path_dict = create_path_dict(fin)
if self._path_list:
path_dict = update_path_dict(self._path_list, path_dict)
else:
self._path_list = path_list
self._path_dict = path_dict
self._fin = fin
def print_props(self):
"""
Display the properties. If an empty path list is given to
the constructor, display the list created from the VCD file.
"""
print("vcd_file = '" + self._vcd_file + "'")
print("json_file = '" + self._json_file + "'")
print("path_list = [", end='')
for i, path in enumerate(self._path_list):
if i != 0:
print(" ", end='')
print("'" + path + "'", end='')
if i != len(self._path_list)-1:
print(",")
else:
print("]")
print("wave_chunk = " + str(self._wave_chunk))
print("start_time = " + str(self._start_time))
print("end_time = " + str(self._end_time))
return 0
def wave_format(self, signal_path, fmt):
"""
Set the display format of the multi-bit signal. <fmt> is
one of the following characters. The default is 'x'.
'b' - Binary.
'd' - Signed decimal.
'u' - Unsigned decimal.
'x' - Hexa-decimal, lowercase is used.
'X' - Hexa-decimal, uppercase is used.
"""
if fmt not in ('b', 'd', 'u', 'x', 'X'):
raise ValueError('"{0}": Invalid format character.'.format(fmt))
self._path_dict[signal_path]._fmt = fmt
return 0
def execute(self):
"""Perform signal sampling and JSON generation."""
fin = self._fin
path_list = self._path_list
path_dict = self._path_dict
wave_chunk = self._wave_chunk
start_time = self._start_time
end_time = self._end_time
sampler = _SignalSampler(wave_chunk, start_time, end_time)
jsongen = _JsonGenerator(path_list, path_dict, wave_chunk)
clock_id = path_dict[path_list[0]]._sid
id_list = [path_dict[path]._sid for path in path_list]
value_dict = {sid: 'x' for sid in id_list}
sample_dict = {sid: [] for sid in id_list}
if self._json_file == '':
fout = sys.stdout
else:
self.print_props()
print()
print('Create WaveJSON file "{0}".'.format(self._json_file))
fout = open(self._json_file, 'wt')
fout.write(jsongen.create_header())
while True:
origin = sampler.run(fin, clock_id, value_dict, sample_dict)
if len(sample_dict[clock_id]) == 0:
break
fout.write(jsongen.create_body(origin, sample_dict))
fout.write(jsongen.create_footer())
fin.close()
fout.close()
return 0
class _SignalSampler():
def __init__(self, wave_chunk, start_time, end_time):
self._wave_chunk = wave_chunk
self._start_time = start_time
self._end_time = end_time
self._now = 0
def run(self, fin, clock_id, value_dict, sample_dict):
origin = self._now
clock_prev = value_dict[clock_id]
for sid in sample_dict:
del sample_dict[sid][:]
data_count = 0
while True:
if self._end_time != 0 and self._end_time < int(self._now):
return origin
line = fin.readline()
if not line:
return origin
words = line.split()
if not words:
continue
char = words[0][0]
if char == '$':
continue
if char == 'r':
continue
if char in ('0', '1', 'x', 'z'):
sid = words[0][1:]
if sid in value_dict:
value_dict[sid] = char
continue
if char == 'b':
sid = words[1]
if sid in value_dict:
value_dict[sid] = words[0][1:]
continue
if char == '#':
next_now = words[0][1:]
clock = value_dict[clock_id]
if clock_prev == '0' and clock == '1':
if data_count == 0:
origin = self._now
elif self._start_time <= int(origin) and \
clock_prev == '1' and clock == '0':
for sid in sample_dict:
sample_dict[sid].append(value_dict[sid])
data_count += 1
if data_count == self._wave_chunk:
self._now = next_now
return origin
self._now = next_now
clock_prev = clock
continue
raise ValueError('"{0}": Unexpected character.'.format(char))
class _JsonGenerator():
def __init__(self, path_list, path_dict, wave_chunk):
self._path_list = path_list
self._path_dict = path_dict
self._wave_chunk = wave_chunk
self._clock_name = path_dict[path_list[0]]._name
self._name_width = max([len(path_dict[path]._name)
for path in path_list])
def create_header(self):
name = '"{0}"'.format(self._clock_name).ljust(self._name_width + 2)
wave = '"{0}"'.format('p' + '.' * (self._wave_chunk - 1))
json = '{ "head": {"tock":1},\n'
json += ' "signal": [\n'
json += ' { "name": '+name+', "wave": '+wave+' }'
return json
def create_body(self, origin, sample_dict):
def create_wave(samples):
prev = None
wave = ''
for value in samples:
if value == prev:
wave += '.'
else:
wave += value
prev = value
return '"'+wave+'"'
def create_wave_data(samples, length, fmt):
prev = None
wave = ''
data = ''
for value in samples:
if value == prev:
wave += '.'
elif all([c == '0' or c == '1' for c in value]):
wave += '='
data += ' ' + data_format(value, length, fmt)
elif all([c == 'z' for c in value]):
wave += 'z'
else:
wave += 'x'
prev = value
return '"'+wave+'"', '"'+data[1:]+'"'
def data_format(value, length, fmt):
value = int(value, 2)
if fmt == 'b':
fmt = '0' + str(length) + 'b'
elif fmt == 'd':
if value >= 2**(length-1):
value -= 2**length
elif fmt == 'u':
fmt = 'd'
elif fmt == 'X':
fmt = '0' + str((length+3)//4) + 'X'
else:
fmt = '0' + str((length+3)//4) + 'x'
return format(value, fmt)
json = ',\n'
json += ' {},\n'
json += ' ["{0}"'.format(origin)
for path in self._path_list[1:]:
name = self._path_dict[path]._name
sid = self._path_dict[path]._sid
length = self._path_dict[path]._length
if length == 1:
name = '"{0}"'.format(name).ljust(self._name_width + 2)
wave = create_wave(sample_dict[sid])
json += ',\n { "name": '+name+', "wave": '+wave+' }'
else:
fmt = self._path_dict[path]._fmt
name = '"{0}"'.format(name).ljust(self._name_width + 2)
wave, data = create_wave_data(sample_dict[sid], length, fmt)
json += ',\n { "name": '+name+', "wave": '+wave+\
', "data": '+data+' }'
json += '\n ]'
return json
def create_footer(self):
json = '\n'
json += ' ]\n'
json += '}\n'
return json