def run_ng_sim(ng): g = DataFlowGraph() d = Dumper(layout) g.add_connection(ng, d) c = CompositeActor(g) run_simulation(c, ncycles=20)
def run_io(self): run_simulation(self) del self.i[-1], self.o[0] if self.i[0] != (0, 0, 0): assert self.o[0] != (0, 0, 0) if self.i[-1] != self.i[-2]: assert self.o[-1] != self.o[-2], self.o[-2:]
def main(): buf = BytesIO() cli.main(buf) tb = Pdq2Sim(buf.getvalue()) run_simulation(tb, vcd_name="pdq2.vcd", ncycles=700) out = np.array(tb.outputs, np.uint16).view(np.int16) plt.plot(out) plt.show()
def run_gateware(self): import sys sys.path.append(pdq2_gateware) from gateware.pdq2 import Pdq2Sim from migen.sim.generic import run_simulation buf = self.test_cmd_program() tb = Pdq2Sim(buf) tb.ctrl_pads.trigger.reset = 1 run_simulation(tb, ncycles=len(buf) + 250) delays = 7, 10, 30 y = list(zip(*tb.outputs[len(buf) + 130:])) y = list(zip(*(yi[di:] for yi, di in zip(y, delays)))) self.assertGreaterEqual(len(y), 80) self.assertEqual(len(y[0]), 3) return y
def _main(): import logging logging.basicConfig(level=logging.DEBUG) # from migen.fhdl import verilog # print(verilog.convert(Dac())) t = np.arange(7) * 18 t = t.astype(np.int32) v = (1 << 14)*(1 - np.cos(t/t[-1]*2*np.pi))/2 v = v.astype(np.int16) k = 3 p = pdq2.Pdq2(dev="dummy") c = p.channels[0] s = c.new_segment() s.dac(t, v, order=k, first=dict(trigger=True)) s.dds(2*t, (v/c.cordic_gain).astype(np.int16), 0*t + (1 << 14), (t/t[-1]*(1 << 13)).astype(np.int16), first=dict(trigger=False)) mem = c.serialize() tb = TB(list(np.fromstring(mem, "<u2"))) run_simulation(tb, ncycles=400, vcd_name="dac.vcd") plt.plot(t, v, "xk") sp = interpolate.splrep(t, v, k=k, s=0) tt = np.arange(t[-1]) vv = interpolate.splev(tt, sp) plt.plot(tt, vv, "+g") vv1 = [] widths = np.array([0, 1, 2, 2]) dv = pdq2.Segment.interpolate(t, v, k, t[:-1], widths) dv = dv/2**(16*widths) for i, (ti, dvi) in enumerate(zip(t, dv)): dt = 0 while ti + dt < t[i + 1]: dt += 1 vv1.append(dvi[0]) for ki in range(k): dvi[ki] += dvi[ki + 1] plt.step(tt + 1, vv1, "-g") out = np.array(tb.outputs, np.uint16).view(np.int16) plt.step(np.arange(len(out)) - 22, out, "-r") plt.show()
def _main(): #from migen.fhdl import verilog #print(verilog.convert(Dac())) t = np.arange(0, 5) * .12e-6 v = 9*(1-np.cos(t/t[-1]*2*np.pi))/2 p = pdq2.Pdq2() p.freq = 100e6 k = 3 mem = p.map_frames([b"".join([ p.frame(t, v, order=k, end=False), p.frame(2*t, v, 0*t+np.pi/2, 20e6*t/t[-1], trigger=False) ])]) tb = TB(list(np.fromstring(mem, "<u2"))) run_simulation(tb, ncycles=250, vcd_name="dac.vcd") plt.plot(t, v, "xk") sp = interpolate.splrep(t, v, k=k) tt = np.arange(t[0], t[-1], 1/p.freq) vv = interpolate.splev(tt, sp) plt.plot(tt, vv, "+g") vv1 = [] dv = p.interpolate(t*p.freq, v, order=k) j = 0 for i, tti in enumerate(tt): if tti >= t[j]: v = [dvi[j] for dvi in dv] k = np.searchsorted(tt, t[j + 1]) j += 1 vv1.append(v[0]) for k in range(len(v) - 1): v[k] += v[k+1] plt.step(tt + 1/p.freq, vv1, "-g") out = np.array(tb.outputs, np.uint16).view(np.int16)*20./(1<<16) tim = np.arange(out.shape[0])/p.freq plt.step(tim - 22/p.freq, out, "-r") plt.show()
def main(): tb = Pdq2Sim(open(sys.argv[1], "rb").read()) run_simulation(tb, vcd_name="pdq2.vcd", ncycles=1000) out = np.array(tb.outputs, np.uint16).view(np.int16) plt.plot(out) plt.show()
class EscapeTB(Module): def __init__(self, data): self.source = SimSource(data) unescaper = Unescaper(data_layout) self.asink = SimSink("a") self.bsink = SimSink("b") g = DataFlowGraph() g.add_connection(self.source, unescaper) g.add_connection(unescaper, self.asink, "source_a") g.add_connection(unescaper, self.bsink, "source_b") self.submodules.comp = CompositeActor(g) def do_simulation(self, selfp): if self.source.token_exchanger.done: raise StopSimulation if __name__ == "__main__": data = [ 1, 2, 0xa5, 3, 4, 0xa5, 0xa5, 5, 6, 0xa5, 0xa5, 0xa5, 7, 8, 0xa5, 0xa5, 0xa5, 0xa5, 9, 10 ] aexpect = [1, 2, 4, 0xa5, 5, 6, 0xa5, 8, 0xa5, 0xa5, 9, 10] bexpect = [3, 7] tb = EscapeTB(data) run_simulation(tb, vcd_name="escape.vcd") assert tb.asink.recv == aexpect, (tb.asink.recv, aexpect) assert tb.bsink.recv == bexpect, (tb.bsink.recv, bexpect)
addrs=reads_addrs) record = etherbone.EtherboneRecord() record.writes = None record.reads = reads record.bca = 0 record.rca = 0 record.rff = 0 record.cyc = 0 record.wca = 0 record.wff = 0 record.byte_enable = 0xf record.wcount = 0 record.rcount = len(reads_addrs) packet = etherbone.EtherbonePacket() packet.records = [record] self.etherbone_model.send(packet) yield from self.etherbone_model.receive() loopback_writes_datas = [] loopback_writes_datas = self.etherbone_model.rx_packet.records.pop( ).writes.get_datas() # check results s, l, e = check(writes_datas, loopback_writes_datas) print("shift " + str(s) + " / length " + str(l) + " / errors " + str(e)) if __name__ == "__main__": run_simulation(TB(), ncycles=4096, vcd_name="my.vcd", keep_files=True)
selfp.scrambler.ce = 1 selfp.scrambler.reset = 1 yield selfp.scrambler.reset = 0 # log results yield sim_values = [] for i in range(self.length): sim_values.append(selfp.scrambler.value) yield # stop selfp.scrambler.ce = 0 for i in range(32): yield # get C code reference c_values = self.get_c_values(self.length) # check results s, l, e = check(c_values, sim_values) print("shift " + str(s) + " / length " + str(l) + " / errors " + str(e)) if __name__ == "__main__": from migen.sim.generic import run_simulation length = 8192 run_simulation(TB(length), ncycles=length + 100, vcd_name="my.vcd")
def my_generator(): for x in range(20): t = TWrite(x, x) yield t print(str(t) + " delay=" + str(t.latency)) for x in range(20): t = TRead(x) yield t print(str(t) + " delay=" + str(t.latency)) for x in range(20): t = TRead(x + l2_size // 4) yield t print(str(t) + " delay=" + str(t.latency)) class TB(Module): def __init__(self): self.submodules.ctler = LASMIcon(sdram_phy, sdram_geom, sdram_timing) self.submodules.xbar = lasmibus.Crossbar([self.ctler.lasmic], self.ctler.nrowbits) self.submodules.logger = DFILogger(self.ctler.dfi) self.submodules.bridge = wishbone2lasmi.WB2LASMI( l2_size // 4, self.xbar.get_master()) self.submodules.initiator = wishbone.Initiator(my_generator()) self.submodules.conn = wishbone.InterconnectPointToPoint( self.initiator.bus, self.bridge.wishbone) if __name__ == "__main__": run_simulation(TB(), vcd_name="my.vcd")
vsync = bool(c & 2) hsync = bool(c & 1) value = _bit(b, 0) ^ _bit(b, 9) for i in range(1, 8): value |= (_bit(b, i) ^ _bit(b, i-1) ^ (~_bit(b, 8) & 1)) << i return de, hsync, vsync, value if __name__ == "__main__": from migen.sim.generic import run_simulation from random import Random rng = Random(788) test_list = [rng.randrange(256) for i in range(500)] tb = _EncoderTB(test_list) run_simulation(tb) check = [_decode_tmds(out)[3] for out in tb.outs] assert(check == test_list) nb0 = 0 nb1 = 0 for out in tb.outs: for i in range(10): if _bit(out, i): nb1 += 1 else: nb0 += 1 print("0/1: {}/{} ({:.2f})".format(nb0, nb1, nb0/nb1))
def run_io(self): run_simulation(self) del self.o[0] if self.i[0] != (0, 0, 0): assert self.o[0] != (0, 0, 0)
from random import Random from migen.fhdl.std import * from migen.genlib.cdc import GrayCounter from migen.sim.generic import run_simulation class TB(Module): def __init__(self, width=3): self.width = width self.submodules.gc = GrayCounter(self.width) self.prng = Random(7345) def do_simulation(self, selfp): print("{0:0{1}b} CE={2} bin={3}".format(selfp.gc.q, self.width, selfp.gc.ce, selfp.gc.q_binary)) selfp.gc.ce = self.prng.getrandbits(1) if __name__ == "__main__": run_simulation(TB(), ncycles=35)
yield TWrite(64, 0) yield # Test GPIO yield TWrite(65, 0xff) yield class _TestPads: def __init__(self): self.a = Signal(6) self.d = Signal(8) self.sel = Signal(5) self.p = Signal(2) self.fud_n = Signal() self.wr_n = Signal() self.rd_n = Signal() self.rst_n = Signal() class _TB(Module): def __init__(self): pads = _TestPads() self.submodules.dut = AD9858(pads, drive_fud=True) self.submodules.initiator = wishbone.Initiator(_test_gen()) self.submodules.interconnect = wishbone.InterconnectPointToPoint( self.initiator.bus, self.dut.bus) if __name__ == "__main__": run_simulation(_TB(), vcd_name="ad9858.vcd")
from migen.fhdl.std import * from migen.sim.generic import run_simulation # Our simple counter, which increments at every cycle # and prints its current value in simulation. class Counter(Module): def __init__(self): self.count = Signal(4) # At each cycle, increase the value of the count signal. # We do it with convertible/synthesizable FHDL code. self.sync += self.count.eq(self.count + 1) # This function will be called at every cycle. def do_simulation(self, selfp): # Simply read the count signal and print it. # The output is: # Count: 0 # Count: 1 # Count: 2 # ... print("Count: " + str(selfp.count)) if __name__ == "__main__": dut = Counter() # Since we do not use StopSimulation, limit the simulation # to some number of cycles. run_simulation(dut, ncycles=20)
def run_with(self, cb, ncycles=-1): self.tb.callback = cb run_simulation(self.tb, ncycles=ncycles)
elts = ["@" + str(selfp.simulator.cycle_counter)] if self.state == 0: if selfp.req: elts.append("Refresher requested access") self.state = 1 elif self.state == 1: if self.prng.randrange(0, 5) == 0: elts.append("Granted access to refresher") selfp.ack = 1 self.state = 2 elif self.state == 2: if not selfp.req: elts.append("Refresher released access") selfp.ack = 0 self.state = 0 if len(elts) > 1: print("\t".join(elts)) class TB(Module): def __init__(self): self.submodules.dut = Refresher(13, 2, tRP=3, tREFI=100, tRFC=5) self.submodules.logger = CommandLogger(self.dut.cmd) self.submodules.granter = Granter(self.dut.req, self.dut.ack) if __name__ == "__main__": run_simulation(TB(), ncycles=400)
# Test FUD yield TWrite(64, 0) yield # Test GPIO yield TWrite(65, 0xff) yield class _TestPads: def __init__(self): self.a = Signal(6) self.d = Signal(8) self.sel = Signal(5) self.fud_n = Signal() self.wr_n = Signal() self.rd_n = Signal() self.rst_n = Signal() class _TB(Module): def __init__(self): pads = _TestPads() self.submodules.dut = AD9xxx(pads, drive_fud=True) self.submodules.initiator = wishbone.Initiator(_test_gen()) self.submodules.interconnect = wishbone.InterconnectPointToPoint( self.initiator.bus, self.dut.bus) if __name__ == "__main__": run_simulation(_TB(), vcd_name="ad9xxx.vcd")
def do_simulation(self, selfp): f = 2**(self.fir.wsize - 1) v = 0.1 * cos(2 * pi * self.frequency * selfp.simulator.cycle_counter) selfp.fir.i = int(f * v) self.inputs.append(v) self.outputs.append(selfp.fir.o / f) if __name__ == "__main__": # Compute filter coefficients with SciPy. coef = signal.remez(30, [0, 0.1, 0.2, 0.4, 0.45, 0.5], [0, 1, 0]) # Simulate for different frequencies and concatenate # the results. in_signals = [] out_signals = [] for frequency in [0.05, 0.1, 0.25]: tb = TB(coef, frequency) run_simulation(tb, ncycles=200) in_signals += tb.inputs out_signals += tb.outputs # Plot data from the input and output waveforms. plt.plot(in_signals) plt.plot(out_signals) plt.show() # Print the Verilog source for the filter. fir = FIR(coef) print(verilog.convert(fir, ios={fir.i, fir.o}))
def main(): run_simulation(TB(), ncycles=8000, vcd_name="my.vcd", keep_files=True)
def test_wb_writer(): print("*** Testing Wishbone writer") run_simulation(TBWishboneWriter())
def test_wb_reader(): print("*** Testing Wishbone reader") run_simulation(TBWishboneReader())
def run_ng_sim(ng): run_simulation(TestBench(ng), ncycles=50)
class TB(Module): def __init__(self): self.submodules.ctler = LASMIcon(sdram_phy, sdram_geom, sdram_timing) self.submodules.xbar = lasmibus.Crossbar([self.ctler.lasmic], self.ctler.nrowbits) self.submodules.logger = DFILogger(self.ctler.dfi) self.submodules.writer = dma_lasmi.Writer(self.xbar.get_master()) self.comb += self.writer.address_data.stb.eq(1) pl = self.writer.address_data.payload pl.a.reset = 255 pl.d.reset = pl.a.reset * 2 self.sync += If(self.writer.address_data.ack, pl.a.eq(pl.a + 1), pl.d.eq(pl.d + 2)) self.open_row = None def do_simulation(self, selfp): dfip = selfp.ctler.dfi for p in dfip.phases: if p.ras_n and not p.cas_n and not p.we_n: # write d = dfip.phases[0].wrdata | (dfip.phases[1].wrdata << 64) print(d) if d != p.address // 2 + p.bank * 512 + self.open_row * 2048: print("**** ERROR ****") elif not p.ras_n and p.cas_n and p.we_n: # activate self.open_row = p.address if __name__ == "__main__": run_simulation(TB(), ncycles=3500, vcd_name="my.vcd")
for i in range(10): v = i + 5 print("==> " + str(v)) yield Token("source", {"maximum": v}) class SimSource(SimActor): def __init__(self): self.source = Source([("maximum", 32)]) SimActor.__init__(self, source_gen()) def sink_gen(): while True: t = Token("sink") yield t print(t.value["value"]) class SimSink(SimActor): def __init__(self): self.sink = Sink([("value", 32)]) SimActor.__init__(self, sink_gen()) if __name__ == "__main__": source = SimSource() loop = misc.IntSequence(32) sink = SimSink() g = DataFlowGraph() g.add_connection(source, loop) g.add_connection(loop, sink) comp = CompositeActor(g) run_simulation(comp, ncycles=500)
self.submodules.tap = wishbone.Tap(self.slave.bus) self.submodules.intercon = wishbone.InterconnectPointToPoint( self.master.bus, self.slave.bus) self.cycle = 0 def gen_reads(self): for a in range(10): t = TRead(a) yield t print("read {} in {} cycles(s)".format(t.data, t.latency)) def do_simulation(self, selfp): if selfp.pads.cs_n: self.cycle = 0 else: self.cycle += 1 if not selfp.slave.dq.oe: selfp.slave.dq.i = self.cycle & 0xf do_simulation.passive = True if __name__ == "__main__": from migen.sim.generic import run_simulation from migen.fhdl import verilog pads = Record([("cs_n", 1), ("clk", 1), ("dq", 4)]) s = SpiFlash(pads) print(verilog.convert(s, ios={pads.clk, pads.cs_n, pads.dq, s.bus.adr, s.bus.dat_r, s.bus.cyc, s.bus.ack, s.bus.stb})) run_simulation(SpiFlashTB(), vcd_name="spiflash.vcd")
def gen_simulation(self, selfp): while not self.reader.done: yield yield from riffa.channel_write(selfp.simulator, self.tbmem.cmd_tx, [0xF1005]) while not self.tbmem.flushack: yield addr = self.data_to_send[0] num_errors = 0 for i in range(self.data_to_send[1]): if self.tbmem.read_mem(addr) != self.results[i]: num_errors += 1 if num_errors <= 10: print(hex(addr) + ": " + str(self.tbmem.read_mem(addr)) + " (should be " + str(self.results[i]) + ")") addr += 4 if num_errors > 10: print("And " + str(num_errors-10) + " more.") i = self.data_to_send[1] - 2 addr = self.data_to_send[0] + (i << 2) print(hex(addr) + ": " + str(self.tbmem.read_mem(addr))) print(self.results[i]) i = self.data_to_send[1] - 1 addr = self.data_to_send[0] + (i << 2) print(hex(addr) + ": " + str(self.tbmem.read_mem(addr))) print(self.results[i]) yield 10 # gen_simulation.passive = True if __name__ == "__main__": tb = TB() run_simulation(tb, vcd_name="tb.vcd", keep_files=True, ncycles=100000)
self.channel = channel def gen_simulation(self, selfp): yield from riffa.channel_write(selfp.simulator, self.channel, [i+1337 for i in range(17)]) yield yield yield class Reader(Module): def __init__(self, channel): self.channel = channel def gen_simulation(self, selfp): while True: words = yield from riffa.channel_read(selfp.simulator, self.channel) print(words) gen_simulation.passive = True class RiffaTB(Module): def __init__(self): channel = riffa.Interface(data_width=128) dummy = Signal() self.comb += dummy.eq(channel.raw_bits()) self.submodules.writer = Writer(channel) self.submodules.reader = Reader(channel) if __name__ == "__main__": tb = RiffaTB() run_simulation(tb, vcd_name="tb.vcd")
class TB(Module): def __init__(self): self.submodules.ctler = LASMIcon(sdram_phy, sdram_geom, sdram_timing) self.submodules.xbar = lasmibus.Crossbar([self.ctler.lasmic], self.ctler.nrowbits) self.submodules.logger = DFILogger(self.ctler.dfi) self.submodules.writer = dma_lasmi.Writer(self.xbar.get_master()) self.comb += self.writer.address_data.stb.eq(1) pl = self.writer.address_data.payload pl.a.reset = 255 pl.d.reset = pl.a.reset*2 self.sync += If(self.writer.address_data.ack, pl.a.eq(pl.a + 1), pl.d.eq(pl.d + 2) ) self.open_row = None def do_simulation(self, selfp): dfip = selfp.ctler.dfi for p in dfip.phases: if p.ras_n and not p.cas_n and not p.we_n: # write d = dfip.phases[0].wrdata | (dfip.phases[1].wrdata << 64) print(d) if d != p.address//2 + p.bank*512 + self.open_row*2048: print("**** ERROR ****") elif not p.ras_n and p.cas_n and p.we_n: # activate self.open_row = p.address if __name__ == "__main__": run_simulation(TB(), ncycles=3500, vcd_name="my.vcd")
class TB(Module): def __init__(self): self.w = 4 self.submodules.dut = Divider(self.w) def gen_simulation(self, selfp): selfp.dut.dividend_i = 6 selfp.dut.divisor_i = 4 selfp.dut.valid_i = 1 yield selfp.dut.dividend_i = 9 selfp.dut.divisor_i = 3 yield selfp.dut.dividend_i = 0 selfp.dut.divisor_i = 0 selfp.dut.valid_i = 0 yield self.w if selfp.dut.valid_o: print("Quotient: " + str(selfp.dut.quotient_o)) print("Remainder: " + str(selfp.dut.remainder_o)) yield if selfp.dut.valid_o: print("Quotient: " + str(selfp.dut.quotient_o)) print("Remainder: " + str(selfp.dut.remainder_o)) yield if __name__ == "__main__": tb = TB() run_simulation(tb, vcd_name="tb.vcd", ncycles=200)
] err_cnt = self._error_count.status self.sync += [ If(self._reset.re, err_cnt.eq(0) ).Elif(self._dma.data.stb, If(self._dma.data.d != lfsr.o, err_cnt.eq(err_cnt + 1)) ) ] def get_csrs(self): return [self._magic, self._reset, self._error_count] + self._dma.get_csrs() class _LFSRTB(Module): def __init__(self, *args, **kwargs): self.submodules.dut = LFSR(*args, **kwargs) self.comb += self.dut.ce.eq(1) def do_simulation(self, selfp): print("{0:032x}".format(selfp.dut.o)) if __name__ == "__main__": from migen.fhdl import verilog from migen.sim.generic import run_simulation lfsr = LFSR(3, 4, [3, 2]) print(verilog.convert(lfsr, ios={lfsr.ce, lfsr.reset, lfsr.o})) run_simulation(_LFSRTB(128), ncycles=20)
t = TWrite(4*bank+x, 0x1000*bank + 0x100*x) yield t print("{0}: Wrote in {1} cycle(s)".format(n, t.latency)) for x in range(4): t = TRead(4*bank+x) yield t print("{0}: Read {1:x} in {2} cycle(s)".format(n, t.data, t.latency)) assert(t.data == 0x1000*bank + 0x100*x) class MyModel(lasmibus.TargetModel): def read(self, bank, address): r = 0x1000*bank + 0x100*address #print("read from bank {0} address {1} -> {2:x}".format(bank, address, r)) return r def write(self, bank, address, data, we): print("write to bank {0} address {1:x} data {2:x}".format(bank, address, data)) assert(data == 0x1000*bank + 0x100*address) class TB(Module): def __init__(self): self.submodules.controller = lasmibus.Target(MyModel(), aw=4, dw=32, nbanks=4, req_queue_size=4, read_latency=4, write_latency=1) self.submodules.xbar = lasmibus.Crossbar([self.controller.bus], 2) self.initiators = [lasmibus.Initiator(my_generator(n), self.xbar.get_master()) for n in range(4)] self.submodules += self.initiators if __name__ == "__main__": run_simulation(TB())
if ret != expected_ret: ## TODO print("Wrong return value! Expected " + str(expected_ret) + ", received " + str(ret)) yield from self.tbmem.send_flush_command(selfp) # check memory modifications num_errors = 0 for i in range(size): # address "i"th word in range addr = baseaddr + (i << log2_int(self.wordsize // 8)) # compare to expected # print(hex(addr) + ": " + str(self.tbmem.read_mem(addr))) if self.tbmem.read_mem(addr) != expected_results[i]: num_errors += 1 # print a few errors but not too many if num_errors <= 10: print( hex(addr) + ": " + str(self.tbmem.read_mem(addr)) + " (expected " + str(expected_results[i]) + ")") if num_errors > 10: print(str(num_errors) + " errors total.") if num_errors == 0: print("Test passed.") if __name__ == "__main__": tb = TB() run_simulation(tb, vcd_name="tb.vcd", keep_files=True, ncycles=100000)
def do_simulation(self, selfp): f = 2 ** (self.fir.wsize - 1) v = 0.1 * cos(2 * pi * self.frequency * selfp.simulator.cycle_counter) selfp.fir.i = int(f * v) self.inputs.append(v) self.outputs.append(selfp.fir.o / f) if __name__ == "__main__": # Compute filter coefficients with SciPy. coef = signal.remez(30, [0, 0.1, 0.2, 0.4, 0.45, 0.5], [0, 1, 0]) # Simulate for different frequencies and concatenate # the results. in_signals = [] out_signals = [] for frequency in [0.05, 0.1, 0.25]: tb = TB(coef, frequency) run_simulation(tb, ncycles=200) in_signals += tb.inputs out_signals += tb.outputs # Plot data from the input and output waveforms. plt.plot(in_signals) plt.plot(out_signals) plt.show() # Print the Verilog source for the filter. fir = FIR(coef) print(verilog.convert(fir, ios={fir.i, fir.o}))
def run_with(self, cb, ncycles=None): self.tb.callback = cb run_simulation(self.tb, ncycles=ncycles)
for x in range(10): t = TRead(128*n + 48*n*x) yield t print("{0:3}: reads done".format(n)) def my_generator_w(n): for x in range(10): t = TWrite(128*n + 48*n*x, x) yield t print("{0:3}: writes done".format(n)) def my_generator(n): if n % 2: return my_generator_w(n // 2) else: return my_generator_r(n // 2) class TB(Module): def __init__(self): self.submodules.dut = LASMIcon(sdram_phy, sdram_geom, sdram_timing) self.submodules.xbar = lasmibus.Crossbar([self.dut.lasmic], self.dut.nrowbits) self.submodules.logger = DFILogger(self.dut.dfi) masters = [self.xbar.get_master() for i in range(6)] self.initiators = [Initiator(my_generator(n), master) for n, master in enumerate(masters)] self.submodules += self.initiators if __name__ == "__main__": run_simulation(TB(), vcd_name="my.vcd")
self.ycbcr444to422.sink.payload.cb.eq(self.streamer.source.data[8:16]), self.ycbcr444to422.sink.payload.cr.eq(self.streamer.source.data[0:8]), Record.connect(self.ycbcr444to422.source, self.ycbcr422to444.sink), Record.connect(self.ycbcr422to444.source, self.logger.sink, leave_out=["y", "cb", "cr"]), self.logger.sink.data[16:24].eq(self.ycbcr422to444.source.y), self.logger.sink.data[8:16].eq(self.ycbcr422to444.source.cb), self.logger.sink.data[0:8].eq(self.ycbcr422to444.source.cr) ] def gen_simulation(self, selfp): for i in range(16): yield # chain ycbcr444to422 and ycbcr422to444 raw_image = RAWImage(None, "lena.png", 64) raw_image.rgb2ycbcr() raw_image.pack_ycbcr() packet = Packet(raw_image.data) self.streamer.send(packet) yield from self.logger.receive() raw_image.set_data(self.logger.packet) raw_image.unpack_ycbcr() raw_image.ycbcr2rgb() raw_image.save("lena_resampling.png") if __name__ == "__main__": run_simulation(TB(), ncycles=8192, vcd_name="my.vcd", keep_files=True)
from migen.fhdl.std import * from migen.sim.generic import run_simulation from replacementpolicies import * from random import shuffle class TB(Module): def __init__(self): self.npages = 4 self.submodules.dut = TrueLRU(npages=self.npages) def gen_simulation(self, selfp): selfp.dut.lru = 135 # 2 0 1 3 yield selfp.dut.hit = 1 test_adrs = list(range(16)) shuffle(test_adrs) for i in test_adrs: selfp.dut.pg_adr = i % self.npages print("Hit " + str(i % self.npages)) yield 3 print("LRU: " + str(selfp.dut.pg_to_replace)) if __name__ == "__main__": tb = TB() run_simulation(tb, vcd_name="tb.vcd", ncycles=5000)
def __init__(self): source = SimSource() sink = SimSink() # A tortuous way of passing integer tokens. packer = structuring.Pack(base_layout, pack_factor) to_raw = structuring.Cast(packed_layout, rawbits_layout) from_raw = structuring.Cast(rawbits_layout, packed_layout) unpacker = structuring.Unpack(pack_factor, base_layout) self.g = DataFlowGraph() self.g.add_connection(source, packer) self.g.add_connection(packer, to_raw) self.g.add_connection(to_raw, from_raw) self.g.add_connection(from_raw, unpacker) self.g.add_connection(unpacker, sink) self.submodules.comp = CompositeActor(self.g) self.submodules.reporter = perftools.DFGReporter(self.g) if __name__ == "__main__": tb = TB() run_simulation(tb, ncycles=1000) g = nx.MultiDiGraph() for u, v, edge in tb.g.edges_iter(): g.add_edge(u, v, **edge) g_layout = nx.spectral_layout(g) nx.draw(g, g_layout) nx.draw_networkx_edge_labels(g, g_layout, tb.reporter.get_edge_labels()) plt.show()
hpd_rr = Signal() self.sync += [ hpd_rr.eq(hpd_r), hpd_r.eq(self.hpd) ] self.sync += [ If((~hpd_r & hpd_rr), count.eq(1), self.counter.eq(0)), If((hpd_r & ~hpd_rr), count.eq(0)), If(count, self.counter.eq(self.counter + 1)), If(((math.ceil(0.5e-3*clk_freq) <= self.counter) & (self.counter <= math.ceil(1e-3*clk_freq)) & (hpd_r & ~hpd_rr)), self.hpd_irq_o.eq(1) ), If( (self.counter >= math.ceil(2e-3*clk_freq)), self.hpd_ev_o.eq(1), count.eq(0), self.counter.eq(0)), If( self.hpd_irq_o, self.hpd_irq_o.eq(0)), If( self.hpd_ev_o, self.hpd_ev_o.eq(0))] def do_simulation(self, selfp): if selfp.simulator.cycle_counter < 10: selfp.hpd = 1 elif 10 < selfp.simulator.cycle_counter < 12+math.ceil(2e-3*self.clk_freq): selfp.hpd = 0 else: selfp.hpd = 1 if selfp.hpd_irq_o or selfp.hpd_ev_o : print("SimCounter: {}, HPD: {}, counter: {} irq: {}, ev: {}".format( selfp.simulator.cycle_counter, selfp.hpd, selfp.counter, selfp.hpd_irq_o, selfp.hpd_ev_o)) if __name__ == "__main__": dut = HPDPhy(100000) run_simulation(dut, vcd_name="my.vcd", ncycles=1200)
from migen.fhdl.std import * from migen.sim.generic import run_simulation class Mem(Module): def __init__(self): # Initialize the beginning of the memory with integers # from 0 to 19. self.specials.mem = Memory(16, 2**12, init=list(range(20))) def do_simulation(self, selfp): # Read the memory. Use the cycle counter as address. value = selfp.mem[selfp.simulator.cycle_counter] # Print the result. Output is: # 0 # 1 # 2 # ... print(value) # Raising StopSimulation disables the current (and here, only one) # simulation function. Simulator stops when all functions are disabled. if value == 10: raise StopSimulation if __name__ == "__main__": run_simulation(Mem())