示例#1
0
def test_init_clock():
    tester = f.Tester(SimpleALU, SimpleALU.CLK)
    tester.circuit.a = 1
    tester.circuit.b = 2
    tester.circuit.config_data = 0
    tester.circuit.config_en = 0
    tester.step(2)
    tester.circuit.c.expect(3)
    with tempfile.TemporaryDirectory() as tempdir:
        tester.compile_and_run("verilator",
                               flags=["--trace", "-Wno-fatal"],
                               directory=tempdir)
        vcd_file = os.path.join(tempdir, "logs", "SimpleALU.vcd")
        vcd = VCDVCD(vcd_file, signals=["TOP.CLK"])
        # One elem dict, we can grab the first element
        tvs = vcd["TOP.CLK"].tv
        assert tvs == [(0, '0'), (5, '1'), (10, '0')]

        if shutil.which("iverilog"):
            simulator = "iverilog"
        elif shutil.which("irun"):
            simulator = "ncsim"
        else:
            return
        tester.compile_and_run("system-verilog",
                               simulator=simulator,
                               directory=tempdir,
                               magma_opts={"sv": True},
                               dump_waveforms=True)
        vcd_file = os.path.join(tempdir, "waveforms.vcd")
        vcd = VCDVCD(vcd_file, signals=["SimpleALU_tb.dut.CLK"])
        tvs = vcd["SimpleALU_tb.dut.CLK"].tv
        assert tvs == [(0, '0'), (5, '1'), (10, '0')]
示例#2
0
def get_fifo_count_max(vcd_file, fifo_count_signal):
    "Return the maximum value of the given FIFO count signal in vcd trace."

    d = VCDVCD(vcd_file, signals=[fifo_count_signal],
               store_tvs=True).get_data()
    assert len(d) != 0, "FIFO count signal not found"
    events = list(d.values())[0]["tv"]
    max = 0
    for (time, val) in events:
        current = int(val, base=2)
        if current > max:
            max = current
    return max
示例#3
0
 def test_toplevel_signal(self):
     vcd = VCDVCD(vcd_string=self.SMALL_CLOCK_VCD)
     signal = vcd['clock']
     self.assertEqual(signal[0], '0')
     self.assertEqual(signal[1], '1')
     self.assertEqual(signal[2], '0')
     self.assertEqual(signal[3], '0')
示例#4
0
 def test_slice(self):
     vcd = VCDVCD('counter_tb.vcd')
     signal = vcd['counter_tb.out[1:0]']
     for t, signal_d in enumerate(signal[0:30]):
         if t < 2:
             self.assertEqual(signal_d, 'x')
         elif t < 6:
             self.assertEqual(signal_d, '0')
         else:
             self.assertEqual(int(signal_d,2), ((t - 4)//2)%4)
示例#5
0
def list_fifo_count_signals(vcd_file):
    "Return a list of FIFO count signal names from given vcd trace."

    sig_names = VCDVCD(vcd_file, print_dumps=False,
                       only_sigs=True).get_signals()
    fifo_cnt_names = []
    for cand_name in filter(lambda x: fifo_cname in x, sig_names):
        if fifo_mod_name in cand_name:
            fifo_cnt_names.append(cand_name)
    return fifo_cnt_names
示例#6
0
def list_stream_if(vcd_file):
    "Return a list of stream  interface names from given vcd trace."

    sig_names = VCDVCD(vcd_file, print_dumps=False,
                       only_sigs=True).get_signals()
    stream_if_names = []
    for cand_name in filter(lambda x: x.endswith(vname), sig_names):
        base_name = cand_name.replace(vname, "")
        if base_name + rname in sig_names:
            stream_if_names.append(base_name)
    return stream_if_names
示例#7
0
    def test_scopes(self):
        vcd = VCDVCD('counter_tb.vcd', store_scopes=True)
        scope_counter_tb = vcd[re.compile('counter_tb$')]

        self.assertTrue(isinstance(scope_counter_tb, vcdvcd.Scope))
        self.assertIsNotNone(scope_counter_tb['clock'])
        self.assertIsNotNone(scope_counter_tb['enable'])
        self.assertIsNotNone(scope_counter_tb['reset'])
        self.assertIsNotNone(scope_counter_tb['out[1:0]'])
        self.assertIsNotNone(scope_counter_tb['top'])

        self.assertTrue(isinstance(scope_counter_tb['clock'], vcdvcd.Signal))
        self.assertTrue(isinstance(scope_counter_tb['enable'], vcdvcd.Signal))
        self.assertTrue(isinstance(scope_counter_tb['reset'], vcdvcd.Signal))
        self.assertTrue(isinstance(scope_counter_tb['out[1:0]'],
                                   vcdvcd.Signal))
        self.assertTrue(isinstance(scope_counter_tb['top'], vcdvcd.Scope))

        signal = scope_counter_tb[re.compile('out.*')]
        self.assertTrue(scope_counter_tb['out[1:0]'] is signal)

        for t, signal_d in enumerate(signal[0:30]):
            if t < 2:
                self.assertEqual(signal_d, 'x')
            elif t < 6:
                self.assertEqual(signal_d, '0')
            else:
                self.assertEqual(int(signal_d, 2), ((t - 4) // 2) % 4)

        scope_top_module = scope_counter_tb[re.compile('top$')]
        self.assertTrue(isinstance(scope_top_module, vcdvcd.Scope))
        signal = scope_counter_tb[re.compile('top$')][re.compile('out.*')]
        self.assertTrue(signal is scope_top_module['out[1:0]'])

        self.assertIsNotNone(scope_top_module['clock'])
        self.assertIsNotNone(scope_top_module['enable'])
        self.assertIsNotNone(scope_top_module['reset'])
        self.assertIsNotNone(scope_top_module['out[1:0]'])

        self.assertTrue(isinstance(scope_top_module['clock'], vcdvcd.Signal))
        self.assertTrue(isinstance(scope_top_module['enable'], vcdvcd.Signal))
        self.assertTrue(isinstance(scope_top_module['reset'], vcdvcd.Signal))
        self.assertTrue(isinstance(scope_top_module['out[1:0]'],
                                   vcdvcd.Signal))

        for t, signal_d in enumerate(signal[0:30]):
            if t < 2:
                self.assertEqual(signal_d, 'x')
            elif t < 6:
                self.assertEqual(signal_d, '0')
            else:
                self.assertEqual(int(signal_d, 2), ((t - 4) // 2) % 4)
示例#8
0
    def test_REs(self):
        vcd = VCDVCD('counter_tb.vcd')
        signal = vcd[re.compile('counter_tb\.out.*')]
        for t, signal_d in enumerate(signal[0:30]):
            if t < 2:
                self.assertEqual(signal_d, 'x')
            elif t < 6:
                self.assertEqual(signal_d, '0')
            else:
                self.assertEqual(int(signal_d,2), ((t - 4)//2)%4)

        signals = vcd[re.compile('out.*')]
        self.assertEqual(len(signals),2)
示例#9
0
    def test_single_line_value_change(self):
        """
        Tests correct parsing when time stamp and value change are on the same
        line, separated by white space
        """
        vcd = VCDVCD(vcd_string=self.SINGLE_LINE_VALUE_CHANGE_VCD)
        D0 = vcd['X.D0']
        D1 = vcd['X.D1']
        self.assertEqual(D0[0], '0')
        self.assertEqual(D0[10], '1')

        self.assertEqual(D1[0], '1')
        self.assertEqual(D1[15], '0')
        self.assertEqual(D1[20], '1')
        self.assertEqual(D1[25], '0')
        self.assertEqual(D1[30], '1')
        self.assertEqual(D1[35], '0')
示例#10
0
 def test_data(self):
     vcd = VCDVCD('counter_tb.vcd')
     signal = vcd['counter_tb.out[1:0]']
     self.assertEqual(signal.tv[:6], [
         (0, 'x'),
         (2, '0'),
         (6, '1'),
         (8, '10'),
         (10, '11'),
         (12, '0'),
     ])
     self.assertEqual(signal[0], 'x')
     self.assertEqual(signal[1], 'x')
     self.assertEqual(signal[2], '0')
     self.assertEqual(signal[3], '0')
     self.assertEqual(signal[6], '1')
     self.assertEqual(signal[7], '1')
     self.assertEqual(signal[24], '10')
     self.assertEqual(signal[25], '10')
示例#11
0
def vcd2wavedrom():
    #vcd = parse_vcd(config['input'])
    vcd = VCDVCD(config['input'])
    config['filter'] = vcd.signals
    config['maxtime'] = vcd.endtime
    #    config['samplerate'] = int(args.samplerate)
    config['clocks'] = []
    config['signal'] = {}
    config['replace'] = {}
    timescale = int(vcd.timescale['magnitude'])
    config['timeunit'] = vcd.timescale['unit']
    vcd_dict = {}
    vcd_type = {}
    ### find sample time
    sampletime = config['maxtime']
    samplelist = []
    for i, j in vcd.data.items():
        if not (j.references[0] in config['exclude']):
            if (len(j.tv) > 2):
                sz = j.tv[1][0] - j.tv[0][0]
                if (sz > 0 and sz not in samplelist):
                    samplelist.append(sz)
            # get the last elment in the list
            tv = list(dict(j.tv).items())
            tvl = tv[-1]
            # if the last element is the same as the end ttime, remove it
            if (tvl[0] >= vcd.endtime):
                #                print(j.references[0], tv)
                tv.pop()


#                print(j.references[0], tv)

            vcd_dict[j.references[0]] = list(tv)
            vcd_type[j.references[0]] = int(j.size)

    # need to find sample list and use the gcd of the samplelist
    config['samplerate'] = gcd(samplelist)
    homogenize_waves(vcd_dict, timescale)
    dump_wavedrom(vcd_dict, vcd_type, timescale)
示例#12
0
import matplotlib.pyplot as plt
import sys
from vcdvcd import VCDVCD
from bitstring import BitArray

vcd = VCDVCD(sys.argv[1])
# times, amplitudes = zip(*vcd['top.sin'].tv)
# print(amplitudes)


def plot(name):
    x = vcd[name]
    times, amplitudes = zip(*x.tv)

    # print(amplitudes)
    size = int(x.size)

    amplitudes = list(
        map(lambda s: BitArray(bin=s.zfill(size)).uint, amplitudes))
    times = list(map(lambda t: t * vcd.timescale["magnitude"], times))

    plt.plot(times, amplitudes)


plot('top.sin')
# plot('top.cos')

plt.xlabel('timestamp')
plt.ylabel('amplitude')
plt.show()
示例#13
0
 def test_nonexistent_signal(self):
     vcd = VCDVCD(vcd_string=self.SMALL_CLOCK_VCD)
     with self.assertRaises(KeyError):
         vcd['non_existent_signal']
示例#14
0
def get_signal_names(vcd_path):
    """Load a vcd file and return the list of signal names including path
    """

    vcd = VCDVCD(vcd_path)
    return vcd.get_signals()
示例#15
0
def vcd_to_signals(vcd_path, signals='', module_path=''):
    """Load a vcd file times and values into Signals

    Args:
        vcd_path: Path to the .vcd file.
        signals: Name(s) of the signals to load. None or [] loads them all.
        module_path: Path of the signal(s) in the RTL hierarchy. A string to
                     apply to all the signals, or a dictionary {name: path,}
                     if a list of signals is provided.
                     In order to select signals by module (and differentiate
                     signals with equal names located in different modules),
                     provide the path to the signals that you want to extract.
                     Example:
                     Signals in the vcd file:
                       'dut.Top/uAdder/data[15:0]',
                       'dut.Top/uAdder/en',
                       'dut.Top/uAdder/dv',
                       'dut.Top/uMux/data[31:0]',
                       'dut.Top/uMux/en',
                       'dut.Top/uMux/dv',
                     Setting signals_base_path='uMux/' will return:
                       {'data': Signal(this will be 'dut.Top/uMux/data[31:0]'),
                        'en':   Signal(this will be 'dut.Top/uMux/en'),
                        'dv':   Signal(this will be 'dut.Top/uMux/dv')}
    """

    from hdlcomposer.signals import Signal

    vcd = VCDVCD(vcd_path)
    signals_in_vcd = vcd.get_signals()
    data = vcd.get_data()

    result_signals = {}

    if not signals:
        signals = signals_in_vcd
    elif not isinstance(signals, list):
        signals = [signals]
    if not isinstance(module_path, dict):
        module_path = {name: module_path for name in signals}

    for identifier in data:
        signal_names_in_id = data[identifier]['references']
        for vcd_signal_name in signal_names_in_id:
            for signal_name in module_path:
                size = int(data[identifier]['size'])
                matches, found_signal_name = find_signal_name(
                    vcd_signal_name, signal_name, module_path[signal_name],
                    (size > 1))
                if matches:
                    module_path.pop(signal_name)
                    result_signals[found_signal_name] = Signal(
                        signal_type=data[identifier]['var_type'],
                        signal_width=int(data[identifier]['size']),
                        signal_path=vcd_signal_name)
                    result_signals[found_signal_name].waveform = [
                        list(tv) for tv in data[identifier]['tv']
                    ]
                    break

    return result_signals
示例#16
0
    def testContains(self):
        vcd = VCDVCD('counter_tb.vcd', store_scopes=True)
        scope_counter_tb = vcd[re.compile('counter_tb$')]

        for element in ['clock','enable','reset','out[1:0]','top']:
            self.assertTrue(     element in scope_counter_tb)
示例#17
0
from vcdvcd import VCDVCD

# Do the parsing.
vcd = VCDVCD("negator_tb.vcd")

# List all human readable signal names.
print("signal_list: ", vcd.references_to_ids.keys())

# View all signal data.
# print(vcd.data)

# Get a signal by human readable name.
signal = vcd['negator_tb.clock']

# tv is a list of Time/Value delta pairs for this signal.
tv = signal.tv
print("clock: ", tv)
示例#18
0
def get_stream_if_stats(vcd_file, if_base_name):
    """Return statistics for given streaming interface in vcd trace in the
    following dict format:

    <stream_state>: (<num_samples>, <fraction_of_time>),

    where <stream_state> is the combination of (V)alid/(R)eady values,
    <num_samples> is the approximate number of rising clock edges spent in <state>
    , and <fraction_of_time> is the fraction of <num_samples> to total
    amount of time recorded by the trace.

    Example:
    {"{'V': 0, 'R': 0}": (5, 0.0006060606060606061),
     "{'V': 1, 'R': 0}": (0, 0.0),
     "{'V': 0, 'R': 1}": (7605, 0.9218181818181819),
     "{'V': 1, 'R': 1}": (640, 0.07757575757575758)}

    Here we can see the stream was transmitting values 7.7% of the time,
    and 9.2% of the time there was no incoming data (valid 0, ready 1)
    """
    if_valid = if_base_name + vname
    if_ready = if_base_name + rname
    v = VCDVCD(vcd_file, signals=[if_valid], store_tvs=True)
    endtime = v.get_endtime()
    v = v.get_data()
    assert len(v) != 0, "Streaming interface not found"
    v = list(v.values())[0]["tv"]
    v = list(map(lambda x: ("V", x[0], x[1]), v))
    v.append(("V", endtime, "0"))
    r = VCDVCD(vcd_file, signals=[if_ready], store_tvs=True).get_data()
    assert len(r) != 0, "Streaming interface not found"
    r = list(r.values())[0]["tv"]
    r = list(map(lambda x: ("R", x[0], x[1]), r))
    r.append(("R", endtime, "0"))
    events = sorted(v + r, key=lambda x: x[1])
    ret = {
        "{'V': 0, 'R': 0}": 0,
        "{'V': 1, 'R': 0}": 0,
        "{'V': 0, 'R': 1}": 0,
        "{'V': 1, 'R': 1}": 0,
    }
    status = {"V": 0, "R": 0}
    last_time = 0
    total_rising_clock_edges = 0
    for (sig, time, val) in events:
        # pyverilator generates 5 time units per sample
        time = time / 5
        # pyverilator generates 4 samples per clock period
        n_rising_clock_edges = int((time - last_time) / 4)
        # note that the calculation of n_rising_clock_edges is approximate
        # doing this exactly would require a cycle-by-cycle walkthrough of the
        # trace, which can take very long
        ret[str(status)] += n_rising_clock_edges
        total_rising_clock_edges += n_rising_clock_edges
        status[sig] = int(val)
        last_time = time

    for state in ret:
        v = ret[state]
        ret[state] = (v, v / total_rising_clock_edges)

    return ret
示例#19
0
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# SPDX-License-Identifier: Apache-2.0
from vcdvcd import VCDVCD
import numpy as np
import cv2
import sys

vcd1 = VCDVCD(sys.argv[1])
print(vcd1.signals)

# dino_vga_tb.dump[40:0]
data = vcd1[sys.argv[2]].tv
data = [x[1].zfill(41)[::-1] for x in data]
data = [x for x in data if x[40] == "1"]

data = [x for x in data if "z" not in x[30:33] and "x" not in x[30:33]]

# Parse to [(hs, vs, r, g, b), ...]
data = [(x[31], x[30], x[32], x[32], x[32]) for x in data]


def int4(x):
    if x == "0":
示例#20
0
from __future__ import print_function

import sys
from pprint import PrettyPrinter

import vcdvcd
from vcdvcd import VCDVCD

if (len(sys.argv) > 1):
    vcd_path = sys.argv[1]
else:
    vcd_path = 'counter_tb.vcd'
pp = PrettyPrinter()

print('# data')
vcd = VCDVCD(vcd_path)
pp.pprint(vcd.data)
print()

print('# references_to_ids()')
pp.pprint(vcd.references_to_ids)
print()

print('# timescale')
pp.pprint(vcd.timescale)
print()

print('# signals')
pp.pprint(vcd.signals)
print()
示例#21
0
                    "--source_lines",
                    help="Number of source code lines to print",
                    default=1,
                    type=int)
parser.add_argument("-a",
                    "--assembly",
                    help="Print out assembly instruction",
                    action="store_true")
parser.add_argument("-lf",
                    "--listing_file",
                    help="listing file to read assembly from",
                    default="../src/darksocv.lst")
args = parser.parse_args()

# Do the parsing.
vcd = VCDVCD(args.vcdfile)

# Get a signal by human readable name.
signal = vcd['darksimv.darksocv.core0.PC[31:0]']

tv = signal.tv

# A crude "PC"->"line" cache as addr2line calls can be expensive
cache = {}
a2l = addr2line(args.objectfile, args.addr2line)
source_printer = source_printer()
if args.assembly:
    lst_lookuper = lst_lookuper(args.listing_file)

for x in tv:
    time = x[0]
示例#22
0
ap.add_argument("-T",
                dest="time",
                default=0,
                type=int,
                metavar='<max-time>',
                help="Define a time at which to stop converting")
args = ap.parse_args()

# Get output stream
out = sys.stdout
if args.output != '-':
    out = open(args.output, "w")

# Construct VCD parser
print('Parsing input vcd.', file=sys.stderr)
vcd = VCDVCD(args.input)
data = vcd.get_data()
print('Done.', file=sys.stderr)


def format_value_dump(val, size, n_elems):
    """ Formats the value string to a hexadecimal representation, 0-padded to the next byte.

    Args:
        val (str): the string representing the value to format
        size (int): the bitwidth of val
        n_elems (int): the number of elements, required to pretty_print arrays. An array has the number of n_elems < size
    Returns:
        The formatted value. If the value is not numeric (e.g. an 'x'), val is returned as is.
    """
    digit = val.isdigit()
示例#23
0
from __future__ import print_function

import sys
from pprint import PrettyPrinter

from vcdvcd import VCDVCD

if (len(sys.argv) > 1):
    vcd_path = sys.argv[1]
else:
    vcd_path = 'counter_tb.vcd'
pp = PrettyPrinter()

print('# get_data()')
vcd = VCDVCD(vcd_path)
pp.pprint(vcd.get_data())
print()

print('# get_data(only_sigs=True)')
vcd = VCDVCD(vcd_path, only_sigs=True)
PrettyPrinter().pprint(vcd.get_data())
print()

print('# get_signals()')
vcd = VCDVCD(vcd_path, only_sigs=True)
pp.pprint(vcd.get_signals())
print()

print('# __init__(signals=)')
vcd_only_sigs = VCDVCD(vcd_path, only_sigs=True)