Example #1
0
    def testLatchOnEdge(self):
        """ Test DFF latches on clock rising edge """
        
        q, d, clk = [Signal(0) for i in range(3)]
        old_q, old_clk = [Signal(0) for i in range(2)]
        clock_gen = ClkDriver(clk)
        
        # change d longer than period so it will hold and change mid clock cycle
        @always(delay(36))
        def toggle():
            d.next = not d

        
        def testChange():
            for i in range(200):
                # check when no change in clock or falling edge
                if clk == old_clk or clk == 0:
                    self.assertEqual(bool(q), bool(old_q))
                # check for rising edge
                else:
                    self.assertEqual(bool(q), bool(d))
                old_q.next = q
                old_clk.next = clk
                yield delay(2)
        
        flip_flop = dff(q, d, clk)
        check = testChange()
        sim = Simulation(clock_gen, flip_flop, check, toggle)
        sim.run(200, quiet=1)
Example #2
0
    def test_jump(self):
            dlx_instance = dlx(program=os.path.join(ROOT, 'programs/test6.txt'), data_mem=self.data_mem, reg_mem=self.reg_mem, Clk=None)

            def test():
                yield delay(10)
                self.assertEqual(self.reg_mem[5].val, 0)
                yield delay(2)
                self.assertEqual(self.reg_mem[3].val, 8)
                yield delay(2)
                self.assertEqual(self.reg_mem[5].val, 4)
                yield delay(2)
                self.assertEqual(self.reg_mem[2].val, -4)
                yield delay(6)
                self.assertEqual(self.reg_mem[31].val, 7)
                yield delay(12)
                self.assertEqual(self.reg_mem[5].val, 8)
                yield delay(2)
                self.assertEqual(self.reg_mem[2].val, 0)
                yield delay(2)
                self.assertEqual(self.reg_mem[31].val, 24)
                yield delay(6)
                self.assertEqual(self.reg_mem[31].val, 52)
                yield delay(6)
                self.assertEqual(self.reg_mem[31].val, 7)

            check = test()
            sim = Simulation(dlx_instance, check)
            sim.run(60, quiet=True)
Example #3
0
    def test_lcounter(self):

        def bench():
            clk = Signal(False)
            lzero = Signal(True)
            lc = lcounter(clk, lzero)

            @instance
            def drive_stuff():
                clk.next = 0
                for j in range(2):
                    for i in range((1 << LCOUNT_BITS) - 1):
                        yield delay(1)
                        clk.next = 1
                        yield delay(1)
                        clk.next = 0
                        self.assertEqual(lzero, 0)
                    yield delay(1)
                    clk.next = 1
                    yield delay(1)
                    clk.next = 0
                    self.assertEqual(lzero, 1)

            return (lc, drive_stuff)

        tb = bench()
        sim = Simulation(tb)
        sim.run()
 def testReset(self):
     """ Test the reset function of a 4-bit counter """
     
     clk = Signal(0)
     rst = Signal(1)
     clock_gen = ClkDriver(clk, period=4)
     
     out = Signal(intbv(0)[4:])
     counter = Counter(out, clk, rst)
     
     def test():
         for i in range(200):
             # count up to 9 then reset
             if int(out) == 9:
                 rst.next = 0
                 yield delay(1)
                 self.assertEqual(int(out), 0)
             # turn off reset next time
             else:
                 rst.next = 1
             yield delay(1)
     
     check = test()
     sim = Simulation(counter, clock_gen, check)
     sim.run(400, quiet=1)
def run(x_vocab, y_skipgram, vocab_size):
    """Run train driver."""

    # simulate design
    #train = traceSignals(train)
    sim = Simulation(train(x_vocab, y_skipgram, vocab_size))
    sim.run()
 def testLoad(self):
     """ Test a Register load from 1 to 7 bits, always enabled """
     
     for i in range(1, 8):
         clk = Signal(0)
         clock_gen = ClkDriver(clk, period=4)
         
         #print "Testing", i, "bits"
         out = Signal(intbv(0)[i:])
         data = Signal(intbv(2**i - 1)[i:])
         en = Signal(1)
         reg = Register(out, data, clk, en)
         
         flag = Signal(0)
         
         # make sure it gets register value updated
         @always(clk.posedge)
         def test():
             # need to delay by one
             if flag == 1:
                 self.assertEqual(int(out), int(data))
             else:
                 flag.next = 1
         
         sim = Simulation(reg, clock_gen, test)
         sim.run(20, quiet=1)
def run_sim():
#    inst = traceSignals(env)
    inst = env()
    sim = Simulation(inst)

    sim.run(40000000)
    write_image()
Example #8
0
def main_simulate():
    resetn = Signal(bool(1))
    system_clock = Signal(bool(0))
    paddr = Signal(intbv(0, 0, 2**32))
    psel = Signal(bool(0))
    penable = Signal(bool(0))
    pwrite = Signal(bool(1))
    pwdata = Signal(intbv(0, 0, 2**32))
    pready = Signal(bool(0))
    prdata = Signal(intbv(0, 0, 2**32))
    pslverr = Signal(bool(0))
    apb3_bus_signals = [system_clock, resetn, paddr, psel, penable, pwrite,
                        pwdata, pready, prdata, pslverr]

    SYSTEM_CLOCK_FREQ = 10e6
    SYSTEM_CLOCK_PERIOD_IN_NS = int(1.0 / SYSTEM_CLOCK_FREQ * 1e9)

    def testbench():
        clock = drive_system_clock(system_clock, SYSTEM_CLOCK_PERIOD_IN_NS)
        reset = drive_reset(resetn)
        master = apb3_master_mock([(0x40050400, 0xffffffff),
                                   (0x40050400, 0xffff7fff)],
                                  *apb3_bus_signals)
        slave = fluidsp_controller(*(apb3_bus_signals))
        return clock, reset, slave, master

    traced_testbench = traceSignals(testbench)
    sim = Simulation(traced_testbench)
    sim.run(SYSTEM_CLOCK_PERIOD_IN_NS * 100)
Example #9
0
def run_ALU_cosim():
    # Initiate signals
    MAX_TIME = 1000000
    clock = Signal(0)
    reset = Signal(0)
    inA = Signal(intbv(0, 0, 2**32), delay=10)
    inB = Signal(intbv(0, 0, 2**32), delay=10)
    ALU_control = Signal(intbv(0, 0, 2**3), delay=10)
    pyData = Signal(intbv(0, 0, 2**32))
    pyZero = Signal(intbv(0, 0, 2**32))
    vData = Signal(intbv(0, 0, 2**32))
    vZero = Signal(intbv(0, 0, 2**32))

    # Build driver instances
    clock_driver = clock_generator(clock, period=20)
    control_driver = random_signal(clock, ALU_control, seed=1)
    A_rand = random_signal(clock, inA, seed=2)
    B_rand = random_signal(clock, inB, seed=3)
    reset_driver = pulse_generator(clock, reset)
    py_cosim = traceSignals(
        py_alu(clock, reset, inA, inB, ALU_control, pyData, pyZero))
    v_cosim = v_alu(clock, reset, ALU_control, inA, inB, vData, vZero)
    read_test = match_test_report(clock, (vData, vZero), (pyData, pyZero),
                                  a_name="v:",
                                  b_name="py:")

    sim = Simulation(instances())
    sim.run(MAX_TIME)
Example #10
0
    def run_test(self, test):
        clk = Signal(bool(0))
        out = Signal(bool(0))

        inst = clock_divider(clk, out, in_freq=50, out_freq=2)
        check = test(clk, out, 50, 2)
        sim = Simulation(inst, check)
        sim.run(quiet=1)
Example #11
0
    def run_test(self, test):
        din = Signal(intbv(0)[4:])
        hex_disp = Signal(intbv(0)[7:])

        inst = bcd_decoder(din, hex_disp)
        check = test(din, hex_disp)
        sim = Simulation(inst, check)
        sim.run(quiet=1)
Example #12
0
def sim():
    insts = []
    insts.append(traceSignals(gen, *args))
    insts.append(stimuli())
    sim = Simulation(insts)
    sim.run(duration)
    print
    sys.stdout.flush()
Example #13
0
def sim():
    insts = []
    insts.append(traceSignals(gen, *args))
    insts.append(stimuli())
    sim = Simulation(insts)
    sim.run(duration)
    print
    sys.stdout.flush()
Example #14
0
 def runTests(self, test):
     """Helper method to run the actual tests."""
     for w in range(1, MAX_WIDTH):
         B = Signal(intbv(0)[w:])
         G = Signal(intbv(0)[w:])
         dut = bin2gray(B, G)
         check = test(B, G)
         sim = Simulation(dut, check)
         sim.run(quiet=1)
    def test_not_mem_read(self):
        @instance
        def test():
            self.MemRead_ex.next = 0
            yield delay(1)
            self.assertEqual(int(self.Stall), 0)

        sim = Simulation(self.detector_, test)
        sim.run()
Example #16
0
 def runTests(self, test):
     """Helper method to run the actual tests."""
     for w in range(1, MAX_WIDTH):
         B = Signal(intbv(0)[w:])
         G = Signal(intbv(0)[w:])
         dut = bin2gray(B, G)
         check = test(B, G)
         sim = Simulation(dut, check)
         sim.run(quiet=1)
Example #17
0
    def test_not_mem_read(self):
        @instance
        def test():
            self.MemRead_ex.next = 0
            yield delay(1)
            self.assertEqual(int(self.Stall), 0)

        sim = Simulation(self.detector_, test)
        sim.run()
    def test_not_regwrite_wb(self):
        @instance
        def test():
            self.RegWrite_wb.next = 0
            yield delay(1)
            self.assertEqual(int(self.ForwardA), 0)
            self.assertEqual(int(self.ForwardB), 0)

        sim = Simulation(self.forwarding_, test)
        sim.run()
Example #19
0
    def sim(self):
        insts = []

        insts.append(traceSignals(self.gen, *self.args))
        insts += self.stimuli

        sim = Simulation(insts)
        sim.run(self.duration)
        print
        sys.stdout.flush()
Example #20
0
    def test_not_regwrite_wb(self):
        @instance
        def test():
            self.RegWrite_wb.next = 0
            yield delay(1)
            self.assertEqual(int(self.ForwardA), 0)
            self.assertEqual(int(self.ForwardB), 0)

        sim = Simulation(self.forwarding_, test)
        sim.run()
Example #21
0
def sim():
    from myhdl import Simulation, traceSignals
    import sys

    test_inst = traceSignals(create_test)

    sim = Simulation(test_inst)
    sim.run(20000)
    print
    sys.stdout.flush()
Example #22
0
def main_simulate():
    inst = test_signalgenerator(*get_signals())
    sim = Simulation(inst)
    # sim.run(SYSTEM_CLOCK_PERIOD_IN_NS * 1000)
    sim.run(0.01 * 1e9)  # run for 1ms
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(i_samples_times, i_samples, q_samples_times, q_samples)

    fig.savefig("output.png")
Example #23
0
    def sim(self):
        insts = []

        insts.append(traceSignals(self.gen, *self.args))
        insts += self.stimuli

        sim = Simulation(insts)
        sim.run(self.duration)
        print
        sys.stdout.flush()
Example #24
0
def main():
  #ddin = genSignal()
  #        sig data wll wul 
  ddin = genSig_discriminator() 
  
  disc = Discriminator()
  disc.convert()
  tbr = disc.tb(ddin)
  sim = Simulation(tbr)
  sim.run()
Example #25
0
def sim():
    from myhdl import Simulation, traceSignals
    import sys

    test_inst = traceSignals(create_test)

    sim = Simulation(test_inst)
    sim.run(20000)
    print
    sys.stdout.flush()
Example #26
0
def test_regfile():

    clk = Signal(bool(0))
    reset = ResetSignal(0, active=bool(1), async=True)

    size = 32

    read_addr1, read_addr2 = Signal(intbv(0)[5:]), Signal(intbv(0)[5:])
    write_addr = Signal(intbv(0)[5:])
    write_data = Signal(intbv(0, min=-2**32, max=2**32-1)) 
    read_data1, read_data2 = Signal(intbv(0, min=-2**32, max=2**32-1)), Signal(intbv(0, min=-2**32, max=2**32-1)) 

    write_ctrl = Signal(bool(0))

    reg_file = register_file(read_addr1, read_addr2, write_addr, write_data, read_data1, read_data2, write_ctrl, clk, reset, size)

    @always(delay(10))
    def tb_clk():
        clk.next = not clk

    @instance
    def tb_dut():

        for jj in range(100):
            wrlist = []

            yield clk.posedge
            # Write random data
            for ii in range(32):
                dwrite = randrange(-2**32,2**32-1)

                wrlist.append(dwrite)
                write_addr.next = ii
                write_data.next = dwrite
                write_ctrl.next = True
                yield clk.posedge


            write_ctrl.next = False

            yield clk.posedge
            # Verify written data        
            for ii in range(32):
                read_addr1.next = ii
                randread = randrange(32)
                read_addr2.next = randread
                yield clk.posedge
                
                assert read_data1 == wrlist[ii]
                assert read_data2 == wrlist[randread]

        raise StopSimulation

    sim = Simulation(tb_clk, tb_dut, reg_file)
    sim.run()
Example #27
0
    def simulate_quadrature(self, in_i, in_q, dspflow, **kwargs):
        """Actually run the simulation, with separate i and q inputs.

        :param in_i: The input i sequence.
        :param in_q: The input q sequence.
        :param dspflow: The MyHDL module representing the dsp flow.
        :param interp: How many samples to zero-stuff.
        :returns: The valid i and q sequences as a tuple.
        """
        interp = kwargs.get('interp', 1)
        loader = kwargs.get('loader', None)

        @instance
        def stimulus():
            self.t = 0

            if loader:
                yield loader()

            self.clearn.next = self.clearn.active
            yield self.delay(1)
            self.clearn.next = not self.clearn.active

            while self.t < len(in_i):
                yield self.produce(self.input.myhdl(in_i[self.t]),
                                   self.input.myhdl(in_q[self.t]), interp)
                self.t = self.t + 1
            self.input.valid.next = False
            yield self.delay(1)
            while self.output.valid:
                self.consume()
                yield self.delay(1)
            raise StopSimulation

        # Show the input
        #f_chain_in = figure_discrete_quadrature("chain in", 223, f, self.input, in_n, in_i, in_q)

        traced = traceSignals(dspflow)

        recordings = [
            s.record(self.clearn, self.clock) for s in self.recording
        ]

        s = Simulation(stimulus, recordings, traced)
        s.run()

        final_i, final_q = (np.array(self.results_i,
                                     dtype=self.output.numpy_dtype()),
                            np.array(self.results_q,
                                     dtype=self.output.numpy_dtype()))
        assert len(final_i) == len(final_q)
        final_n = np.arange(final_i.shape[0])

        #f_chain_out = figure_discrete_quadrature("chain out", 224, f, self.output, final_n, final_i, final_q)
        return final_i, final_q
Example #28
0
    def testUndefinedBit(self):
        """ Make sure NOT gate properly outputs None when given None """
        def test(out, a):
            yield delay(10)
            self.assertEqual(Signal(None), out)

        a, out = [Signal(None) for i in range(2)]
        gate = Not(out, a)
        check = test(out, a)
        sim = Simulation(gate, check)
        sim.run(quiet=1)
Example #29
0
def main():
    print "\n\n## stimulus ##\n"
    Simulation(stimulus()).run()
    print "\n\n## test ##\n"
    Simulation(test()).run()
    print "\n\n## testTimeout ##\n"
    Simulation(testTimeout()).run()
    print "\n\n## testNoJoin ##\n"
    Simulation(testNoJoin()).run()
    print "\n\n## testJoin ##\n"
    Simulation(testJoin()).run()
Example #30
0
def sim(visu = False):
  try:
    os.remove('_bench.vcd')
  except Exception as e:
    pass # just ignore, the file is probably not here.

  fsm = traceSignals(testbench())
  sim = Simulation(fsm)
  sim.run()
  if visu:
    call(['gtkwave', '_bench.vcd'])
Example #31
0
def sim(visu=False):
    try:
        os.remove('_bench.vcd')
    except Exception as e:
        pass  # just ignore, the file is probably not here.

    fsm = traceSignals(testbench())
    sim = Simulation(fsm)
    sim.run()
    if visu:
        call(['gtkwave', '_bench.vcd'])
Example #32
0
def test_memory():
    """
    Memory: Test load and R/W operations.
    """
    gen_test_file()
    trace = False
    if trace:
        sim = Simulation(traceSignals(_testbench))
    else:
        sim = Simulation(_testbench())
    sim.run()
Example #33
0
def test_core(hex_file, vcd):
    """
    Core: Behavioral test for the RISCV core.
    """
    if vcd:
        vcd = traceSignals(core_testbench, hex_file,)
        sim = Simulation(vcd)
    else:
        sim = Simulation(core_testbench(hex_file))

    sim.run()
Example #34
0
    def runTest(self,
                test,
                packet_width,
                dx_msb,
                dx_lsb,
                dy_msb,
                dy_lsb,
                buffer_depth,
                east,
                delay_ns=DELAY_NS):
        """Helper function to run a specific test with the standard signals"""
        # Regs
        clk, din_valid, read_en = [Signal(bool(0)) for i in range(3)]
        rst = Signal(bool(1))
        din_routing, din_token_controller = [
            Signal(intbv(0)[packet_width:0]) for i in range(2)
        ]
        empty_routing, empty_token_controller = [
            Signal(bool(1)) for _ in range(2)
        ]
        ren_in_north, ren_in_routing, ren_in_south = [
            Signal(bool(0)) for _ in range(3)
        ]
        # Wires
        ren_out_routing, ren_out_token_controller = [
            Signal(bool(0)) for _ in range(2)
        ]
        dout_routing = Signal(intbv(0)[packet_width - (dx_msb - dy_msb):0])
        dout_north, dout_south = \
            [Signal(intbv(0)[packet_width:0]) for _ in range(2)]
        routing_buffer_empty, north_buffer_empty, south_buffer_empty = [
            Signal(bool(1)) for i in range(3)
        ]

        ports = Ports(clk, rst, din_routing, din_token_controller,
                      empty_routing, ren_in_north, empty_token_controller,
                      ren_in_routing, ren_in_south, ren_out_routing,
                      ren_out_token_controller, dout_routing,
                      routing_buffer_empty, dout_north, north_buffer_empty,
                      dout_south, south_buffer_empty)

        params = Params(packet_width, dx_msb, dx_lsb, dy_msb, dy_lsb,
                        buffer_depth, east)

        dut = ForwardEastWest(ports, params)

        @always(delay(delay_ns))
        def clockGen():
            clk.next = not clk

        check = test(ports, params)

        sim = Simulation(dut, clockGen, check)
        sim.run()
def main():
    args = cliparse()
    if args.trace:
        mosi, miso, sck, ss = Signals(bool(0), 4)
        led = Signal(bool(0))
        clock=Clock(0, frequency=50e6)
        tb_fsm = traceSignals(tb,led, clock, mosi, miso, sck, ss, reset=None)
        sim = Simulation(tb_fsm)
        sim.run()  
    if args.build:
        build(args)    
Example #36
0
def test_cache():
    """
    Cache: Test loading from memory
    """
    gen_test_file()
    trace = False
    if trace:
        sim = Simulation(traceSignals(_testbench))
    else:
        sim = Simulation(_testbench())
    sim.run()
Example #37
0
    def simulate(self, stimulus, whitebox, **kwargs):
        """Acturally run the cosimulation with iverilog.
        
        :param stimulus: A callable that returns the cosim object.
        :param whitebox: A whitebox peripheral object.
        :param record_tx: Record the passed in number of valid samples.
        :param auto_stop: Raise ``StopSimulation`` when the correct number of samples have been recorded.
        :param sample_rate: Samples per second.
        """
        record_tx = kwargs.get('record_tx', None)
        auto_stop = kwargs.get('auto_stop', False)
        self.sample_rate = kwargs.get('sample_rate', 10e6)
        DAC2X_DURATION = int(1e9 / (self.sample_rate * 2))
        DAC_DURATION = int(1e9 / self.sample_rate)

        @instance
        def dac2x_clock():
            while True:
                self.dac2x_clock.next = not self.dac2x_clock
                yield delay(DAC2X_DURATION // 2)

        @instance
        def dac_clock():
            yield delay(DAC2X_DURATION // 4)
            while True:
                self.dac_clock.next = not self.dac_clock
                yield delay(DAC_DURATION // 2)

        @always(self.dac_clock.posedge, self.dac_clock.negedge,
                self.bus.presetn.negedge)
        def tx_recorder():
            if not self.bus.presetn:
                self.tx_q = []
                self.tx_i = []
                self.tx_n = []
            elif len(self.tx_i) == len(self.tx_q) and len(
                    self.tx_i) == record_tx:
                if auto_stop:
                    raise StopSimulation
            elif self.dac_en:
                if self.dac_clock:
                    self.tx_q.append(int(self.dac_data[:]))
                    self.tx_n.append(now())
                else:
                    self.tx_i.append(int(self.dac_data[:]))

        traced = traceSignals(whitebox)
        ss = [dac_clock, dac2x_clock, stimulus, traced]
        if 'record_tx' in kwargs:
            ss.append(tx_recorder)
        s = Simulation(ss)
        s.run()
Example #38
0
    def simulate(self, stimulus, whitebox, **kwargs):
        """Acturally run the cosimulation with iverilog.
        
        :param stimulus: A callable that returns the cosim object.
        :param whitebox: A whitebox peripheral object.
        :param record_tx: Record the passed in number of valid samples.
        :param auto_stop: Raise ``StopSimulation`` when the correct number of samples have been recorded.
        :param sample_rate: Samples per second.
        """
        record_tx = kwargs.get('record_tx', None)
        auto_stop = kwargs.get('auto_stop', False)
        self.sample_rate = kwargs.get('sample_rate', 10e6)
        DAC2X_DURATION = int(1e9 / (self.sample_rate * 2))
        DAC_DURATION = int(1e9 / self.sample_rate)

        @instance
        def dac2x_clock():
            while True:
                self.dac2x_clock.next = not self.dac2x_clock
                yield delay(DAC2X_DURATION // 2)

        @instance
        def dac_clock():
            yield delay(DAC2X_DURATION // 4)
            while True:
                self.dac_clock.next = not self.dac_clock
                yield delay(DAC_DURATION // 2)

        @always(self.dac_clock.posedge,
                self.dac_clock.negedge,
                self.bus.presetn.negedge)
        def tx_recorder():
            if not self.bus.presetn:
                self.tx_q = []
                self.tx_i = []
                self.tx_n = []
            elif len(self.tx_i) == len(self.tx_q) and len(self.tx_i) == record_tx:
                if auto_stop:
                    raise StopSimulation
            elif self.dac_en:
                if self.dac_clock:
                    self.tx_q.append(int(self.dac_data[:]))
                    self.tx_n.append(now())
                else:
                    self.tx_i.append(int(self.dac_data[:]))

        traced = traceSignals(whitebox)
        ss = [dac_clock, dac2x_clock, stimulus, traced]
        if 'record_tx' in kwargs:
            ss.append(tx_recorder)
        s = Simulation(ss)
        s.run()
Example #39
0
 def run(self, clks):
     """
     Run a test bench simulation.
     """
     myhdlvpi = os.path.join(config.verilogdir, 'myhdl.vpi')
     command = "vvp -m {myhdlvpi} {executable}".format(myhdlvpi=myhdlvpi, executable=self.executable)
     cosimdict = dict([(sn, getattr(self, sn)) for sn in self.signal_names])
     dut = Cosimulation(command, **cosimdict)
     drivers = [df() for df in self.drivers]
     sim = Simulation(dut, *drivers)
     sim.run(2*clks)
     dut.__del__()
     del dut
Example #40
0
 def simulate(self, clks=None):
     """
     Run a test bench simulation.
     """
     if clks is None:
         clks = 200
     self.dut = Cosimulation("vvp -m ./myhdl.vpi fftexec",
                             clk=self.clk, rst_n=self.rst_n,
                             din=self.in_data, din_nd=self.in_nd,
                             dout=self.out_data, dout_nd=self.out_nd,
                             overflow = self.overflow,
                             )
     sim = Simulation(self.dut, self.clk_driver(), self.control())
     sim.run(self.half_period*2*clks)
Example #41
0
 def run(self, clks):
     """
     Run a test bench simulation.
     """
     myhdlvpi = os.path.join(config.verilogdir, 'myhdl.vpi')
     command = "vvp -m {myhdlvpi} {executable}".format(
         myhdlvpi=myhdlvpi, executable=self.executable)
     cosimdict = dict([(sn, getattr(self, sn)) for sn in self.signal_names])
     dut = Cosimulation(command, **cosimdict)
     drivers = [df() for df in self.drivers]
     sim = Simulation(dut, *drivers)
     sim.run(2 * clks)
     dut.__del__()
     del dut
Example #42
0
    def testBench_add(self):

        def stimulus():

            a, b = self.op1_i.next, self.op2_i.next = [Signal(intbv(random.randint(0, 255))[32:]) for i in range(2)]

            self.control_i.next = intbv('0010')[4:] #add function
            expected = a + b
            yield delay(1)

            self.assertEqual(int(self.out_i), expected)

        sim = Simulation(self.alu_i, stimulus())
        sim.run()
Example #43
0
    def simulate_quadrature(self, in_i, in_q, dspflow, **kwargs):
        """Actually run the simulation, with separate i and q inputs.

        :param in_i: The input i sequence.
        :param in_q: The input q sequence.
        :param dspflow: The MyHDL module representing the dsp flow.
        :param interp: How many samples to zero-stuff.
        :returns: The valid i and q sequences as a tuple.
        """
        interp = kwargs.get('interp', 1)
        loader = kwargs.get('loader', None)
        @instance
        def stimulus():
            self.t = 0

            if loader:
                yield loader()

            self.clearn.next = self.clearn.active
            yield self.delay(1)
            self.clearn.next = not self.clearn.active

            while self.t < len(in_i):
                yield self.produce(self.input.myhdl(in_i[self.t]),
                        self.input.myhdl(in_q[self.t]), interp)
                self.t = self.t + 1
            self.input.valid.next = False
            yield self.delay(1)
            while self.output.valid:
                self.consume()
                yield self.delay(1)
            raise StopSimulation

        # Show the input
        #f_chain_in = figure_discrete_quadrature("chain in", 223, f, self.input, in_n, in_i, in_q)

        traced = traceSignals(dspflow)

        recordings = [s.record(self.clearn, self.clock) for s in self.recording]

        s = Simulation(stimulus, recordings, traced)
        s.run()

        final_i, final_q = (np.array(self.results_i, dtype=self.output.numpy_dtype()),
                np.array(self.results_q, dtype=self.output.numpy_dtype()))
        assert len(final_i) == len(final_q)
        final_n = np.arange(final_i.shape[0])

        #f_chain_out = figure_discrete_quadrature("chain out", 224, f, self.output, final_n, final_i, final_q)
        return final_i, final_q
Example #44
0
def sim():
    from myhdl import Simulation, traceSignals

    insts, test_gen, test_args = setup()

    test_inst = traceSignals(test_gen, *test_args)
    insts.append(test_inst)

    if 1:
        reader_inst = reader(test_args[0], test_args[1], 64, 123 * nsec)
        insts.append(reader_inst)

    sim = Simulation(*insts)
    sim.run(5 * usec)
Example #45
0
    def testBench_add(self):
        def stimulus():

            a, b = self.op1_i.next, self.op2_i.next = [
                Signal(intbv(random.randint(0, 255))[32:]) for i in range(2)
            ]

            self.control_i.next = intbv('0010')[4:]  #add function
            expected = a + b
            yield delay(1)

            self.assertEqual(int(self.out_i), expected)

        sim = Simulation(self.alu_i, stimulus())
        sim.run()
Example #46
0
    def test_merge_sort(self):
        ram = load_data_memory(os.path.join(ROOT, 'programs/hash/ram.txt'))
        dlx_instance = dlx(program=os.path.join(ROOT, 'programs/hash/rom.txt'), data_mem=ram, reg_mem=self.zreg_mem, Clk=None)

        def test():
            yield delay(1480*2)
            cared = ram[-80:]
            data = group(cared, 4)
            string = ' '.join(map(m2int, data))
            self.assertEqual(string, "262144 0 -645 -22 7 9 11 13 31 37 64 86 111 282 502 502 502 733 262144 0")
            print 'stack: %s' % string

        check = test()
        sim = Simulation(dlx_instance, check)
        sim.run(1480*2, quiet=True)
Example #47
0
    def testOneBit(self):
        """ Check that given a bit, we return the inverse """
        def test(out, a):
            yield delay(10)
            for i in range(2):
                a.next = i
                yield delay(10)
                #print a, b, out
                self.assertEqual(not a, out)

        a, out = [Signal(None) for i in range(2)]
        gate = Not(out, a)
        check = test(out, a)
        sim = Simulation(gate, check)
        sim.run(quiet=1)
Example #48
0
    def testUndefinedOneOfTwo(self):
        """ Make sure AND gate properly outputs None when given None """
        def test(out, a, b):
            yield delay(10)
            for i in range(2):
                a.next = i
                yield delay(10)
                #print a, b, out
                self.assertEqual(Signal(None), out)

        a, b, out = [Signal(None) for i in range(3)]
        gate = And(out, a, b)
        check = test(out, a, b)
        sim = Simulation(gate, check)
        sim.run(quiet=1)
Example #49
0
def issue_104_multiple_instance():
    sim1 = Simulation(test())
    sim1.run(1000)
    # sim1 is "puased"

    # try and create a second, third, forth simulation instance
    for ii in range(4):
        with raises_kind(SimulationError, _error.MultipleSim):
              another_sim = Simulation(test())
    # generating more sims should have failed
    sim1.run(1000)
    sim1.quit()
Example #50
0
    def test_state_machine(self):

        def bench():
            clk, keydown, threshold, state = make_sm_ios()
            sm = state_machine(clk, keydown, threshold, state)

            @instance
            def drive_stuff():
                keydown.next = False
                threshold.next = False
                clk.next = 0
                yield delay(1)
                clk.next = 1
                yield delay(1)
                self.assertEqual(RELEASE, state)

                yield delay(1)
                keydown.next = True
                yield delay(1)
                clk.next = 0
                yield delay(1)
                clk.next = 1
                yield delay(1)
                self.assertEqual(ATTACK, state)

                threshold.next = True
                yield delay(1)

                clk.next = 0
                yield delay(1)
                clk.next = 1
                yield delay(1)

                self.assertEqual(DECAY, state)
                keydown.next = False
                yield delay(1)

                clk.next = 0
                yield delay(1)
                clk.next = 1
                yield delay(1)
                self.assertEqual(RELEASE, state)

            return (sm, drive_stuff)

        tb = bench()
        sim = Simulation(tb)
        sim.run()
Example #51
0
 def testMux(self):
     def muxFunction(a, b, c, d):
         if c:
             return a
         else:
             return b
     Simulation(self.bench(muxFunction)).run(quiet=QUIET)
Example #52
0
    def test11(self):
        a, b, c, d = [Signal(0) for i in range(4)]

        def response():
            yield join(a, b.posedge, b.negedge, a)
            assert now() == 15
        Simulation(self.stimulus(a, b, c, d), response()).run(quiet=QUIET)
Example #53
0
    def test7(self):
        a, b, c, d = [Signal(0) for i in range(4)]

        def response():
            yield join(a, delay(30)), join(c, d)
            assert now() == 20
        Simulation(self.stimulus(a, b, c, d), response()).run(quiet=QUIET)
Example #54
0
    def test2(self):
        def g():
            yield delay(10)

        i = g()
        with raises_kind(SimulationError, _error.DuplicatedArg):
            Simulation(i, i)
Example #55
0
def main():
  ddin= genSignal()
  x = [i for i in range(len(ddin))]

  dv = Delay_Var()
  dv.convert()

  tbr = dv.tb(ddin, 4)
  sim = Simulation(tbr)
  sim.run()

  dv.ddout.append(0)
  p = biggles.FramedPlot()
  p.add( biggles.Curve(x, dv.ddout, color="red") )
  p.add( biggles.Curve(x, ddin, color="blue") )
  p.show()
    def test_condition2b(self):
        @instance
        def test():
            valueA, valueB = random.sample(range(32), 2)

            self.Rt_ex.next = valueA

            self.Rs_id.next = valueB
            self.Rt_id.next = valueB  #rt_ex != rt_id

            self.MemRead_ex.next = 1
            yield delay(1)
            self.assertEqual(int(self.Stall), 0)

        sim = Simulation(self.detector_, test)
        sim.run()
Example #57
0
 def test1(self):
     try:
         Simulation(None)
     except SimulationError as e:
         self.assertEqual(e.kind, _error.ArgType)
     except:
         self.fail()
Example #58
0
 def runner(self, test, gates):
     """Run the tests."""
     num_signals = 1 + int(log2(len(
         gates[0][1])))  # n inputs, plus 1 output
     for gate in gates:
         with self.subTest(gate=gate):
             m = import_module(gate[0])
             f = m.__dict__[
                 gate[0]]  # Module name must be the same as Gate name
             sigs = [Signal(0) for _ in range(num_signals)]
             check = test(gate[0], sigs, gate[1])
             sim = Simulation(f(*sigs), check)  # works
             #sim = Simulation(check)  # many failures
             #sim = Simulation(f(*sigs)) # all pass
             sim.run(quiet=1)
             print('OK: {}'.format(gate[0]))