-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPyMTI.py
More file actions
226 lines (190 loc) · 7.51 KB
/
PyMTI.py
File metadata and controls
226 lines (190 loc) · 7.51 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
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
#!/usr/bin/python
# PyMTI - A Python utility for using Modelsim in jupyter and browser w/vcd and matplotlib
# A python package for generating logic signals from a given Boolean vectors file.
# Copyright (C) 2025 M. B. Ghaznavi-Ghoushchi
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see <http://www.gnu.org/licenses/>.
import numpy as np
import os
import re
from matplotlib import pyplot as plt
import vcdvcd
import hdlparse.verilog_parser as vlog
DEBUG = False
def plot_signal(ax, vcd, name, endtime=None):
xscale = float(vcd.timescale["timescale"])*1e9
if not endtime:
endtime = vcd[name].endtime
signal = vcd[name]
signal.tv = vcdvcd.condition_signal_tv(signal.tv)
x, y = list(zip(*signal.tv))
x, y = vcdvcd.expand_signal(x, y, endtime)
ax.plot(np.array(x)*xscale, y)
def plot_signal_in(signal, ax, xscale=1):
signal.tv = vcdvcd.condition_signal_tv(signal.tv)
x, y = list(zip(*signal.tv))
ax.plot(np.array(x)*xscale, y)
def plot(trace_file, save_name, save_title, signals, analog_in_signal, nbits=12):
vcd = vcdvcd.VCDVCD(trace_file)
fig, axes = plt.subplots(len(signals)+1, 1, sharex=True)
xscale = float(vcd.timescale["timescale"])*1e9 # ns
ylabel_format = dict(rotation=0, fontsize=14, snap=True, labelpad=80)
for ax, signal in zip(axes[1:], signals):
name, label = signal
ax.set_ylabel(label, **ylabel_format)
plot_signal(ax, vcd, name)
name, label = analog_in_signal
axes[0].set_ylabel(label, **ylabel_format)
plot_signal_in(vcd[name], axes[0])
for ax, signal in zip(axes, [analog_in_signal, *signals]):
lines = ax.get_lines()
for line in lines:
line.set_linestyle('-')
line.set_color('k')
line.set_marker('')
fig.set_tight_layout(True)
fig.set_figwidth(10)
fig.set_figheight(6)
label_x = -0.15
signal_max = (1<<nbits)
margin = signal_max*.05
axes[0].set_ylim((-margin, signal_max+margin))
axes[-1].set_ylim((-margin, signal_max+margin))
axes[-1].set_xlabel("Time (ns)")
axes[-1].get_xaxis().set_visible(True)
axes[0].set_title(save_title)
axes[-1].set_xlim((0, 3))
fig.align_labels()
plt.savefig(save_name, bbox_inches="tight")
plt.show()
def parse_verilog_files(files):
extractor = vlog.VerilogExtractor()
modules = {}
for file in files:
mods = extractor.extract_objects(file)
for mod in mods:
modules[mod.name] = {
'ports': [(p.name, p.mode, p.data_type) for p in mod.ports],
'generics': [(g.name, g.mode, g.data_type) for g in mod.generics],
'instances': set() # To be filled later
}
return modules
def find_module_instances(files, modules):
instance_pattern = re.compile(r'\b([A-Za-z_][A-Za-z0-9_]+)\s+([A-Za-z_][A-Za-z0-9_]+)\s*\(', re.MULTILINE)
for file in files:
with open(file, 'r') as f:
code = f.read()
code_nocomments = re.sub(r'//.*', '', code)
code_nocomments = re.sub(r'/\*.*?\*/', '', code_nocomments, flags=re.DOTALL)
instances = instance_pattern.findall(code_nocomments)
for inst_mod, inst_name in instances:
if inst_mod in modules:
for mod in modules:
if f"module {mod}" in code:
modules[mod]['instances'].add(inst_mod)
return modules
def find_top_modules(modules):
instantiated = set()
for mod, info in modules.items():
instantiated.update(info['instances'])
top_modules = [m for m in modules if m not in instantiated]
if not top_modules:
testbench_candidates = [m for m in modules if m.endswith(('_test', '_tb', 'testbench'))]
if testbench_candidates:
top_modules = testbench_candidates
else:
top_modules = []
return top_modules
def generate_do_file(modules, files, top_module, do_filename='run_sim.do', sim_time=1000):
lines = []
do_file_content1 = """
##################################
# A simple modelsim do file #
##################################
# 1) Create a library for working in
vlib work
# 2) Compile the half adder
#vcom -93 -explicit -work work HalfAdder.vhd
"""
lines.append(do_file_content1)
lines.append("# 2) Compile the half adder")
for f in files:
lines.append(f"vlog {f}")
lines.append("# 3) Load it for simulation")
lines.append(f"vsim {top_module}")
do_file_content2 = """
# 4) Open some selected windows for viewing
view structure
view signals
view wave
"""
lines.append(do_file_content2)
do_file_content3 = """
# 5) Show some of the signals in the wave window
add wave -noupdate -divider -height 32 Inputs
"""
lines.append(do_file_content3)
for mod, info in modules.items():
if (DEBUG):
print(f"mode: {mod} info: {info}")
if info['generics']:
next
for name, mode, dtype in info['ports']:
if (mode.lower() == 'input'):
lines.append(f"add wave -noupdate {name}")
do_file_content4 = """
add wave -noupdate -divider -height 32 Outputs
"""
lines.append(do_file_content4)
for mod, info in modules.items():
if (DEBUG):
print(f"mode: {mod} info: {info}")
if info['generics']:
next
for name, mode, dtype in info['ports']:
if (mode.lower() == "output"):
lines.append(f"add wave -noupdate {name}")
do_file_content5 = """
add wave -noupdate -divider -height 32 Inouts
"""
lines.append(do_file_content5)
for mod, info in modules.items():
if (DEBUG):
print(f"mode: {mod} info: {info}")
if info['generics']:
next
for name, mode, dtype in info['ports']:
if (mode.lower() == "inout"):
lines.append(f"add wave -noupdate {name}")
lines.append(f"# 7) Run the simulation for {sim_time} ns")
lines.append(f"run {sim_time}")
lines.append("quit -f")
with open(do_filename, 'w') as f:
f.write('\n'.join(lines))
print(f"[INFO] Generated ModelSim DO file '{do_filename}' for top module '{top_module}'")
def print_summary(modules):
print("\n=== Design Summary ===")
for mod, info in modules.items():
print(f"Module: {mod}")
if info['generics']:
print(" Parameters:")
for name, mode, dtype in info['generics']:
print(f" {mode} {name} : {dtype}")
print(" Ports:")
for name, mode, dtype in info['ports']:
print(f" {mode} {name} : {dtype}")
if info['instances']:
print(f" Instantiates: {', '.join(info['instances'])}")
else:
print(" Instantiates: None")
print()