def test_construct_cint(): clock = Clock(0, frequency=50e6) y = CInt(0, min=-8, max=8) # Elaboration definitions, the results are evaluated # in simulation not the explicit code below - the # following *constructs* the HDL (generators) that are # simulated and converted. with clock_domain(clock) as ctx: # Create a new CInt: `x`, create generators for # the addition operations. x = CInt(2) + CInt(4) # Assign to the CInt: `y`, create a generator for # the assignment. y.next = x + 1 inst = ctx.blocks() # Get a reference ot the output of the construct context yy = y.sig tbclk = clock.process() @hdl.instance def tbstim(): print("[{:8d}] 1a: ".format(hdl.now()), x, y, yy) yield hdl.delay(10) yield clock.posedge yield clock.posedge print("[{:8d}] 2a: ".format(hdl.now()), x, y, yy) assert yy == 7 raise hdl.StopSimulation # Run a simulation of the above myhdl.generators hdl.Simulation([tbclk, tbstim, inst]).run()
def test_initial_state(): ''' É importante deixarmos claro qual o objetivo do teste. Isso nos ajuda a recordar ou descobrir o que motivou as escolhas do desenvolvedor no passado. Esse primeiro teste valida que no início o display mostrará o valor zero. ''' # Nessa declaração inicial temos os parâmetros do circuito sob teste circuit_param = design.Parameters(nleds=8) def stimulus(signals): ''' Dado que o processo de inicialização é interno não precisamos de estímulo ao circuito digital nesse ponto.abs ''' yield mhd.delay(1) def verification(signals): assert signals.leds == 0, 'The display must show Zero' yield mhd.delay(1) simulator = mhd.Simulation(bench(stimulus, verification, circuit_param)) simulator.run(10)
def block(self): def run_and_stop(): yield from func(self) raise myhdl.StopSimulation insts = [x(self, func) for x in blocks] + [run_and_stop()] sim = myhdl.Simulation(insts) sim.run(quiet=1)
def simFixPoint(self): """ Simulate filter in fix-point description """ # Setup the Testbench and run dlg = QFD(self) # instantiate file dialog object plt_types = "png (*.png);;svg (*.svg)" plt_file, plt_type = dlg.getSaveFileName_(caption="Save plots as", directory=dirs.save_dir, filter=plt_types) plt_file = str(plt_file) if plt_file != "": plt_file = os.path.normpath(plt_file) plt_type = str(plt_type) logger.info('Using plot filename "%s"', plt_file) plt_dir_name = os.path.dirname( plt_file) # extract the directory path if not os.path.isdir( plt_dir_name): # create directory if it doesn't exist os.mkdir(plt_dir_name) dirs.save_dir = plt_dir_name # make this directory the new default / base dir # plt_file_name = os.path.splitext(os.path.basename(plt_file))[0] # filename without suffix plt_file_name = os.path.basename(plt_file) logger.info('Creating plot file "{0}"'.format( os.path.join(plt_dir_name, plt_file_name))) self.setupHDL(file_name=plt_file_name, dir_name=plt_dir_name) logger.info("Fixpoint simulation setup") tb = self.flt.simulate_freqz(num_loops=3, Nfft=1024) clk = myhdl.Signal(False) ts = myhdl.Signal(False) x = myhdl.Signal( myhdl.intbv(0, min=-2**(self.W[0] - 1), max=2**(self.W[0] - 1))) y = myhdl.Signal( myhdl.intbv(0, min=-2**(self.W[0] - 1), max=2**(self.W[0] - 1))) try: sim = myhdl.Simulation(tb) logger.info("Fixpoint simulation started") sim.run() logger.info("Fixpoint plotting started") self.flt.plot_response() logger.info("Fixpoint plotting finished") except myhdl.SimulationError as e: logger.warning("Simulation failed:\n{0}".format(e))
def configure_simulation(self, max_time=None, add_generators=[]): """ Configure MyHDL simulation. Arguments: * max_time: optional max time to simulate. None means simulation without time limit. * add_generators: external MyHDL generators to add to the simulation """ # myhdl simulation: extract all generators and prepare # arguments for obj in self.noc_ref.all_list(): prevcount = len(add_generators) add_generators.extend(obj.tbm.get_generators()) #self.debug("configure_simulation: adding %d generators from object %s" % (len(add_generators)-prevcount, repr(obj))) if isinstance(obj, ipcore): add_generators.extend(obj.channel_ref.tbm.get_generators()) #self.debug("configure_simulation: plus ipcore channel: adding %d generators from object %s" % (len(add_generators)-prevcount, repr(obj.channel_ref))) # -------------------------------- # debug info # TODO: try to get info about generators, particularly obtain origin # info about @always and @always_comb generators #self.debug("configure_simulation: list of generators: (count = %d)" % len(add_generators)) #for genl in add_generators: #if not isinstance(genl, list): #gen2 = [genl] #else: #gen2 = genl #self.debug("configure_simulation: generator list '%s'" % repr(genl)) #for gen in gen2: #self.debug("configure_simulation: generator '%s'" % repr(gen)) #try: #self.debug("configure_simulation: inspect info name '%s'" % gen.gen.__name__) #self.debug("configure_simulation: inspect info locals '%s'" % repr(gen.gen.gi_frame.f_locals.keys())) #for k, v in gen.gen.gi_frame.f_locals.iteritems(): #self.debug("configure_simulation: inspect info locals[%s] '%s'" % (k, repr(v))) #if gen.gen.__name__ == "genfunc": #self.debug("configure_simulation: inspect info deep name '%s'" % gen.func.__name__) #except: #pass # -------------------------------- self.sim_object = myhdl.Simulation(*add_generators) self.sim_duration = max_time self.debug( "configure_simulation: will run until simulation time '%d'" % max_time)
def run(self): # can now either generate or simulate/convert/generateTcl if self.args.QsysGenerate and not self.args.ignoreQsys: if self.args.verbose: print('Generating {} for Qsys' .format(self.args.targetHDL)) # force std_logic_vectors instead of unsigned in Interface as Qsys wants this myhdl.toVHDL.std_logic_ports = True self.convert(self, 'vhdl') # override self.args.targetHDL as this is 'always'verilog? # rename the entity and architecture identifiers to match the name given by Qsys generate.updateEntity("{}" .format(self.modulename), self.args.QsysGenerate[1]) # delete existing target target = "{}{}.vhd" .format(self.args.QsysGenerate[0], self.args.QsysGenerate[1]) if os.path.exists(target): os.remove(target) os.rename("{}.vhd".format(self.modulename), target) else: if self.args.verbose: print('Simulate, Convert, Generate _hw.tcl') if self.testbench: # remove 'old' .vcd file filename = self.testbench[1].__name__ + ".vcd" if os.access(filename, os.F_OK): os.unlink(filename) # Run Simulation testbench = myhdl.traceSignals(self.testbench[1], self) sim = myhdl.Simulation(testbench) sim.run(self.testbench[0]) if self.convert: if self.args.targetHDL is not None: self.convert(self, self.args.targetHDL) else: # do both languages self.convert(self, 'vhdl') self.convert(self, 'verilog') if self.gentcl: generate.writeHwTcl(self.generics, self.connectionpointlist, self.modulename, version=self.gentcl[0], author=self.gentcl[1], group=self.gentcl[2])
def test_simulate(self): import myhdl duration = 1 def _sim(): bus = Apb3Bus(duration=duration) bus_presetn = bus.presetn bus_pclk = bus.pclk bus_paddr = bus.paddr bus_psel = bus.psel bus_penable = bus.penable bus_pwrite = bus.pwrite bus_pwdata = bus.pwdata bus_pready = bus.pready bus_prdata = bus.prdata bus_pslverr = bus.pslverr status_led = Signal(bool(False)) slave = apb3_simple_slave(bus, status_led) @myhdl.instance def __sim(): yield bus.reset() assert not status_led yield bus.transmit(0x40, 0x0001) assert status_led yield bus.receive(0x40) assert bus.rdata == 0x0001 assert not status_led yield bus.receive(0x40) assert bus.rdata == 0x0002 assert status_led raise StopSimulation return __sim, slave s = myhdl.Simulation(myhdl.traceSignals(_sim)) s.run()
clock.next = not clock @myhdl.instance def check_equality(): yield clock.posedge reset.next = False yield clock.posedge # Simply check the initial value and the first couple of transitions for i in range(10): ref_state = reference.state[::-1] for s, ref in zip(state, ref_state): assert s == ref yield clock.posedge reference.update_state() raise myhdl.StopSimulation() # Use all instances for simulation return myhdl.instances() s = myhdl.Simulation(test_rule30()) s.run(None) print "Everything seems good!"
def simulation_thread(self): params = copy.copy(self.params) clock = myhdl.Signal(bool()) reset = myhdl.ResetSignal(bool(True), True, True) phase_step = myhdl.Signal(myhdl.intbv(0)[self.params.phase_acc_bits:]) BITS = self.params.out_bits cos_out = myhdl.Signal(myhdl.intbv(0, -2**(BITS - 1), 2**(BITS - 1))) sin_out = myhdl.Signal(myhdl.intbv(0, -2**(BITS - 1), 2**(BITS - 1))) # Constants samples = self.params.fft_samples dut = nco.NCOCordic(clock, reset, phase_step, cos_out, sin_out, PHASE_PRECISION=self.params.phase_bits, LUT_DEPTH=self.params.lut_depth, DITHER=self.params.phase_dither, CORDIC_STAGES=self.params.cordic_stages) output = [] @myhdl.always(myhdl.delay(1)) def clockgen(): clock.next = not clock @myhdl.instance def simulate(): # A couple of cycles to reset the circuit reset.next = True phase_step.next = 0 yield clock.negedge yield clock.negedge reset.next = False phase_step.next = self.params.phase_step # Flush the pipeline once for i in range(0, self.params.pipeline_length): yield clock.negedge # Now the first correct sample is at the output for sample in range(0, samples): time = sample / self.params.frequency theoretical_phase = (sample / self.params.frequency * self.params.actual_tone % 1.0) * 2 * np.pi # Save the result output.append((time, theoretical_phase, int(cos_out.val), int(sin_out.val))) self.emit('simulation_progress', sample / float(samples)) if self._thread_abort: raise myhdl.StopSimulation("Simulation Aborted") yield clock.negedge raise myhdl.StopSimulation myhdl.Simulation(dut, clockgen, simulate).run(None) simulation_result = np.array(output, dtype=np.float64) self.emit('simulation_done', simulation_result, params)
def test_mdct(args=None): """ A simple test to exercise the MDCT block """ clock = Signal(bool(0)) reset = ResetSignal(1, active=1, async=True) datai = DataBus(w=8) datao = DataBus(w=12) fini = Signal(bool(0)) tbdut = prep_cosim(clock, reset, datai, datao, args=args) @always(delay(10)) def tbclk(): clock.next = not clock def bench_mdct(): numin_s = Signal(0) numout_s = Signal(0) def pulse_reset(): reset.next = reset.active yield delay(13) reset.next = reset.active yield delay(113) reset.next = not reset.active yield delay(13) yield clock.posedge @instance def tbmon(): numin, numout = 0, 0 while True: yield clock.posedge if datao.dv: numout += 1 if datai.dv: numin += 1 if numin == (80 * 80 * 4) - 1: print("input finished") if numout == (80 * 80 * 4) - 1: print("output finished") fini.next = True numin_s.next = numin numout_s.next = numout @instance def tbstim(): yield pulse_reset() # @todo: use or remove # stream data in at max rate, 80x80x4 (4 components) # for row in range(80): # for col in range(80): # for cmp in range(4): # datai.data.next = randint(0, 255) # datai.dv.next = True # yield clock.posedge # @todo: use or remove # stream data in at a slow rate (does all the output come out) # for ii in range(100): # for jj in range(64): # for cmp in range(4): # datai.data.next = randint(0, 255) # datai.dv.next = True # yield clock.posedge # datai.dv.next = False # yield delay(2000) # only do 64 sample blocks for ii in range(200): # 400 for nn in range(2): for jj in range(64): # 64 datai.data.next = randint(0, 255) datai.dv.next = True yield clock.posedge # wait one clock datai.dv.next = False yield clock.posedge # wait a long time datai.dv.next = False yield delay(2000) # all done datai.dv.next = False yield clock.posedge # wait for all the outputs for ii in range(1000): yield delay(100) yield clock.posedge if fini: break yield delay(100) print(" %d in, %d out" % ( numin_s, numout_s, )) raise StopSimulation return tbclk, tbmon, tbstim gt = bench_mdct() myhdl.Simulation(( gt, tbdut, )).run()
import myhdl def hello_world(): interval = myhdl.delay(10) @myhdl.always(interval) def say_hello(): print(f'{myhdl.now()}: Hello!') return say_hello instance = hello_world() sim = myhdl.Simulation(instance) sim.run(50)
left = main(CLK, RST_X, left_rx, left_tx, 0) right = main(CLK, RST_X, right_rx, right_tx, 1) @myhdl.always_comb def assign(): right_rx.next = left_tx left_rx.next = right_tx @myhdl.always(myhdl.delay(CLK_PERIOD / 2)) def clkgen(): CLK.next = not CLK @myhdl.instance def stimulus(): RST_X.next = 0 yield myhdl.delay(RST_TIME) RST_X.next = 1 while (1): yield CLK.posedge return left, right, assign, clkgen, stimulus test_uart = myhdl.traceSignals(tb_uart) # enable to generate vcd file sim = myhdl.Simulation(test_uart) sim.run() #**** Generate Verilog HDL #******************************************************************************* #myhdl.toVerilog(uartTx, CLK, RST_X, WE, DIN, TXD, READY)
DIN.next = cycle @myhdl.always(CLK.posedge) def cyclegen(): if not RST_X: cycle.next = 0 else: cycle.next = cycle + 1 @myhdl.instance def stimulus(): RST_X.next = 0 yield myhdl.delay(RST_TIME) RST_X.next = 1 while (cycle < HALT_CYCLE): yield CLK.posedge print "cycle(DIN): %10d DOUT: %10d ENQ: %d DEQ: %d EMPTY %d FULL %d" % ( cycle, DOUT, ENQ, DEQ, EMPTY, FULL) raise myhdl.StopSimulation return inst, clkgen, assign, cyclegen, stimulus test_fifo = myhdl.traceSignals(tb_fifo) # enable to generate vcd file sim = myhdl.Simulation(test_fifo) sim.run() #**** Generate Verilog HDL #******************************************************************************* myhdl.toVerilog(fifo, CLK, RST_X, ENQ, DEQ, DIN, DOUT, EMPTY, FULL)
#**** Testbench #******************************************************************************* def tb_counter(): inst = counter(CLK, RST_X, VALUE) @myhdl.always(myhdl.delay(CLK_PERIOD / 2)) def clkgen(): CLK.next = not CLK @myhdl.instance def stimulus(): RST_X.next = 0 yield myhdl.delay(RST_TIME) RST_X.next = 1 while (1): yield CLK.posedge if (VALUE > HALT_VALUE): raise myhdl.StopSimulation print "VALUE is %d" % VALUE return inst, clkgen, stimulus tb_cnt = myhdl.traceSignals(tb_counter) # enable to generate vcd file sim = myhdl.Simulation(tb_cnt) sim.run() #**** Generate Verilog HDL #******************************************************************************* myhdl.toVerilog(counter, CLK, RST_X, VALUE)