Exemple #1
0
def test_6():
    n_in = 3
    n_out = 5
    n_ex = 10
    xlen = 500
    fir_len = 30

    X = np.random.randn(n_ex, xlen, n_in)
    Y = np.zeros((n_ex, xlen, n_out))
    firs = np.random.randn(fir_len, n_in, n_out)
    bs = np.random.randn(n_out)

    for i in range(0, n_ex):
        for j in range(0, n_in):
            for k in range(0, n_out):
                Y[i, :, k] += convolve(firs[:, j, k], X[i, :, j])

    for i in range(0, n_ex):
        for k in range(0, n_out):
            Y[i, :, k] += bs[k]

    dft_r = Model([FIR(n_in, n_out, fir_len)])
    dft_r.fit(X, Y)

    f1 = firs
    f2 = dft_r.layers[0].W

    if np.max(np.abs(f1 - f2)) <= 1e-8 and np.max(
            np.abs(bs - dft_r.layers[0].b)) <= 1e-8:
        return True
    else:
        return False
Exemple #2
0
def main():

    # init model and gui
    size = 15

    s1 = ['B', 'W']
    s2 = ['Black win!', 'White win!']

    fir = FIR(size)
    gui = FirGui(size, fir)

    # read
    with open('config.txt', 'r') as f:
        s = [int(x) for x in f.read().split()]

    # ready init ai
    ai_init = [AIRand, AIDefender1, AIDefender2, AIDefender3]

    # init players list
    player = []
    ais = []
    for i in range(2):
        x = s[i]
        if x == -1:
            player.append(gui.run)
        else:
            ai = ai_init[x](i+1, fir)
            player.append(ai.run)
            ais.append(ai)
    
    # main loop
    while True:

        gui.draw_board()

        while True:

            index = fir.turn - 1

            print(s1[index])

            result = player[index]()
            gui.draw_board()

            if result == 2:
                print(s2[index])
                gui.draw_win()
                break

            # time.sleep(0.5)

        gui.run()

        # re start
        fir.clear()
        for a in ais:
            a.reset()
        print('New')
 def H(self):
     length = len(self.Y)
     ext_A = self.A * length
     ext_C = self.C * length
     count_N = 10
     fir = FIR(count_N, ext_A, ext_C, self.Y)
     fir.batch_ufir()
     self.noise = fir.noise
     return fir.hmknoise
Exemple #4
0
    def FIR_Test(self, N=10, plot=False):
        fir = FIR(N, self.A, self.C, self.Y)

        length = len(self.Y)
        fir.batch_ufir()
        yest = [0 for i in range(N - 1)] + fir.y_est
        if plot:
            n = np.arange(0, length, 1)
            plt.ylabel("SignalAmplitude")
            plt.title("Ideal vs. Estimation (N = %d)" % N)
            p1, = plt.plot(n, self.Y_read)
            p2, = plt.plot(n, yest)
            plt.legend(handles=[p1, p2, ], labels=["Ideal", "Estimation"], loc="best")
            plt.savefig(r"E:\GIT\Filter\FIRFilter\test_plot\N = %d" % N, dpi=600)
            plt.show()
        return yest
Exemple #5
0
 def __init__(self, dut, num_samples, input_width, tap_width):
     self.clk = Clock(dut.clk, 40)
     self.clk_en = ClockEnable(dut.clk, dut.clk_2mhz_pos_en, dut.rst_n, 20)
     self.dut = dut
     self.inputs = random_samples(input_width, num_samples)
     self.downsample_factor = 20
     self.fir = FIR(
         numtaps=120,
         bands=[0, 1e6, 1.5e6, 20e6],
         band_gain=[1, 0],
         fs=40e6,
         pass_db=0.5,
         stop_db=-40,
     )
     self.norm_shift = self.fir.tap_normalization_shift()
     self.taps = self.fir.taps
     self.outputs = self.gen_outputs()
Exemple #6
0
def test_5():
    X = np.random.randn(3, 1000, 1)
    Y = np.zeros_like(X)
    fir = np.random.randn(30)
    b = 1.336
    for i in range(0, X.shape[0]):
        Y[i, :, 0] = convolve(fir, X[i, :, 0]) + b

    dft_r = Model([FIR(1, 1, len(fir))])
    dft_r.fit(X, Y)

    f1 = fir
    f2 = dft_r.layers[0].W[:, 0, 0]
    if np.max(
            np.abs(f1 - f2)) <= 1e-6 and np.abs(b - dft_r.layers[0].b) <= 1e-6:
        return True
    else:
        return False
Exemple #7
0
def duc(clearn, dac_clock, dac2x_clock, loopen, loopback, fifo_empty, fifo_re,
        fifo_dvld, fifo_rdata, fifo_underflow, system_txen, system_txstop,
        system_ddsen, system_filteren, system_interp, system_shift, system_fcw,
        system_correct_i, system_correct_q, system_gain_i, system_gain_q,
        underrun, sample, dac_en, dac_data, dac_last, rx_fifo_full, rx_fifo_we,
        rx_fifo_wdata, rxen, rxstop, rxfilteren, decim, system_rx_correct_i,
        system_rx_correct_q, rx_overrun, rx_sample, adc_idata, adc_qdata,
        adc_last, fir_coeff_ram_addr, fir_coeff_ram_din0, fir_coeff_ram_din1,
        fir_coeff_ram_blk, fir_coeff_ram_wen, fir_coeff_ram_dout0,
        fir_coeff_ram_dout1, fir_delay_line_i_ram_addr,
        fir_delay_line_i_ram_din, fir_delay_line_i_ram_blk,
        fir_delay_line_i_ram_wen, fir_delay_line_i_ram_dout,
        fir_delay_line_q_ram_addr, fir_delay_line_q_ram_din,
        fir_delay_line_q_ram_blk, fir_delay_line_q_ram_wen,
        fir_delay_line_q_ram_dout, system_firen, system_fir_bank1,
        system_fir_bank0, system_fir_N, **kwargs):
    """The Digital Up Converter.    

    :param clearn: Reset signal, completely resets the dsp chain.
    :param dac_clock: The sampling clock.
    :param dac2x_clock: Twice the sampling clock.
    :param loopen: Enable the loopback device.
    :param loopback: The loopback signature to the digital down converter.
    :param fifo_empty: Input signal that the fifo is empty.
    :param fifo_re: Output signal to enable a sample read.
    :param fifo_dvld: Input signal that FIFO data is valid.
    :param fifo_rdata: Input sample data.
    :param fifo_underflow: Input signal that fifo underflowed.
    :param system_txen: Enable transmit.
    :param system_txstop: Stop the transmitter.
    :param system_ddsen: Enable the DDS.
    :param system_filteren: Enable the CIC filter.
    :param system_interp: Interpolation rate.
    :param system_fcw: Set the frequency control word of the DDS.
    :param system_correct_i: Set the i-Channel AQM DC Offset Correction.
    :param system_correct_q: Set the q-Channel AQM DC Offset Correction.
    :param system_gain_i: Set the i-channel AQM gain correction.
    :param system_gain_q: Set the q-channel AQM gain correction.
    :param underrun: Output of number of underruns to RFE.
    :param sample: The sample.
    :param dac_en: Enable DAC on valid data signal.
    :param dac_data: The interleaved DAC data.
    :param dac_last: The last sample going out on the DAC, stops the transmit.
    :returns: A MyHDL synthesizable module.
    """

    dspsim = kwargs.get('dspsim', None)

    # DIGIAL UP CONVERTER
    interp_default = kwargs.get('interp', 1)

    sync_txen = Signal(bool(0))
    txen = Signal(bool(0))
    sync_txstop = Signal(bool(0))
    txstop = Signal(bool(0))
    sync_ddsen = Signal(bool(0))
    ddsen = Signal(bool(0))
    sync_filteren = Signal(bool(0))
    filteren = Signal(bool(0))
    sync_interp = Signal(intbv(interp_default)[len(system_interp):])
    interp = Signal(intbv(interp_default)[len(system_interp):])
    sync_shift = Signal(intbv(0)[len(system_shift):])
    shift = Signal(intbv(0)[len(system_shift):])
    sync_firen = Signal(bool(0))
    firen = Signal(bool(0))
    sync_fir_bank0 = Signal(bool(0))
    fir_bank0 = Signal(bool(0))
    sync_fir_bank1 = Signal(bool(0))
    fir_bank1 = Signal(bool(0))
    sync_fir_N = Signal(intbv(0, min=system_fir_N.min, max=system_fir_N.max))
    fir_N = Signal(intbv(0, min=system_fir_N.min, max=system_fir_N.max))
    sync_fcw = Signal(intbv(0)[len(system_fcw):])
    fcw = Signal(intbv(0)[len(system_fcw):])
    sync_correct_i = Signal(intbv(0)[len(system_correct_i):])
    correct_i = Signal(intbv(0)[len(system_correct_i):])
    sync_correct_q = Signal(intbv(0)[len(system_correct_q):])
    correct_q = Signal(intbv(0)[len(system_correct_q):])
    sync_gain_i = Signal(intbv(int(1.0 * 2**9 + .5))[10:])
    gain_i = Signal(intbv(int(1.0 * 2**9 + .5))[10:])
    sync_gain_q = Signal(intbv(int(1.0 * 2**9 + .5))[10:])
    gain_q = Signal(intbv(int(1.0 * 2**9 + .5))[10:])
    sync_rx_correct_i = Signal(intbv(0)[len(system_rx_correct_i):])
    rx_correct_i = Signal(intbv(0)[len(system_rx_correct_i):])
    sync_rx_correct_q = Signal(intbv(0)[len(system_rx_correct_q):])
    rx_correct_q = Signal(intbv(0)[len(system_rx_correct_q):])

    sample_valid = sample.valid
    sample_last = sample.last
    sample_i = sample.i
    sample_q = sample.q

    rx_sample_valid = rx_sample.valid
    rx_sample_last = rx_sample.last
    rx_sample_i = rx_sample.i
    rx_sample_q = rx_sample.q

    adc_sample = Signature("adc",
                           True,
                           bits=10,
                           valid=rxen,
                           last=adc_last,
                           i=adc_idata,
                           q=adc_qdata)

    truncated_1 = Signature("truncated1", True, bits=9)
    truncator_1 = truncator(clearn, dac_clock, sample, truncated_1)
    duc_chain = (truncator_1, )

    if kwargs.get('dds_enable', True):
        if_out = Signature("if_out", True, bits=9)
        dds_args = clearn, dac_clock, ddsen, truncated_1, if_out, fcw
        dds = DDS(*dds_args, num_samples=DDS_NUM_SAMPLES)
        duc_chain = duc_chain + (dds, )
    else:
        if_out = truncated_1

    if kwargs.get('fir_enable', True):
        filtered = Signature("filtered", True, bits=9)
        fir_0 = FIR(clearn, dac_clock, if_out, filtered, fir_coeff_ram_addr,
                    fir_coeff_ram_din0, fir_coeff_ram_din1, fir_coeff_ram_blk,
                    fir_coeff_ram_wen, fir_coeff_ram_dout0,
                    fir_coeff_ram_dout1, fir_delay_line_i_ram_addr,
                    fir_delay_line_i_ram_din, fir_delay_line_i_ram_blk,
                    fir_delay_line_i_ram_wen, fir_delay_line_i_ram_dout,
                    fir_delay_line_q_ram_addr, fir_delay_line_q_ram_din,
                    fir_delay_line_q_ram_blk, fir_delay_line_q_ram_wen,
                    fir_delay_line_q_ram_dout, firen, fir_bank1, fir_bank0,
                    fir_N)
        duc_chain = duc_chain + (fir_0, )
    else:
        filtered = if_out

    upsampled = Signature("upsampled", True, bits=9)
    upsampler_0 = upsampler(clearn, dac_clock, filtered, upsampled, interp)
    duc_chain = duc_chain + (upsampler_0, )

    if kwargs.get('cic_enable', True):
        rate_changed = Signature("rate_changed", True, bits=10)
        cic_0 = cic(clearn,
                    dac_clock,
                    filtered,
                    rate_changed,
                    interp,
                    shift,
                    cic_order=kwargs.get('cic_order', 4),
                    cic_delay=kwargs.get('cic_delay', 1),
                    sim=dspsim)
        duc_chain = duc_chain + (cic_0, )

        processed = Signature("processed", True, bits=10)
        processed_mux = iqmux(clearn, dac_clock, filteren, upsampled,
                              rate_changed, processed)
        duc_chain = duc_chain + (processed_mux, )
    else:
        processed = upsampled

    rf_out = processed

    tx_loopback = pass_through_with_enable(clearn, dac_clock, rf_out, loopback,
                                           loopen)
    duc_chain = duc_chain + (tx_loopback, )

    if kwargs.get('conditioning_enable', True):
        gain_corrected = Signature("gain_corrected", True, bits=10)
        gain_corrector_0 = gain_corrector(clearn, dac_clock, gain_i, gain_q,
                                          rf_out, gain_corrected)
        duc_chain = duc_chain + (gain_corrector_0, )

        corrected = Signature("offset_corrected", True, bits=10)
        offset_corrector_0 = offset_corrector(clearn, dac_clock, correct_i,
                                              correct_q, gain_corrected,
                                              corrected)
        duc_chain = duc_chain + (offset_corrector_0, )

    else:
        corrected = rf_out

    offset = Signature("binary_offset", False, bits=10)
    offseter = binary_offseter(clearn, dac_clock, corrected, offset)
    duc_chain = duc_chain + (offseter, )

    interleaver_0 = interleaver(clearn, dac_clock, dac2x_clock, offset, dac_en,
                                dac_data, dac_last)
    duc_chain = duc_chain + (interleaver_0, )

    # DIGITAL DOWN CONVERTER
    rx_offset_corrected = Signature("rx_offset_corrected", True, bits=10)
    rx_offset_corrector = offset_corrector(clearn, dac_clock, rx_correct_i,
                                           rx_correct_q, adc_sample,
                                           rx_offset_corrected)
    ddc_chain = (rx_offset_corrector, )

    downsampled = Signature("downsampled", True, bits=10)
    downsampled_i = downsampled.i
    downsampled_q = downsampled.q
    downsampled_valid = downsampled.valid
    downsampler_0 = downsampler(clearn, dac_clock, rx_offset_corrected,
                                downsampled, decim)
    ddc_chain = ddc_chain + (downsampler_0, )

    @always_seq(dac_clock.posedge, reset=clearn)
    def synchronizer():
        sync_txen.next = system_txen
        txen.next = sync_txen
        sync_txstop.next = system_txstop
        txstop.next = sync_txstop
        sync_ddsen.next = system_ddsen
        ddsen.next = sync_ddsen
        sync_filteren.next = system_filteren
        filteren.next = sync_filteren
        sync_interp.next = system_interp
        interp.next = sync_interp
        sync_shift.next = system_shift
        shift.next = sync_shift
        sync_firen.next = system_firen
        firen.next = sync_firen
        sync_fir_bank1.next = system_fir_bank1
        fir_bank1.next = sync_fir_bank1
        sync_fir_bank0.next = system_fir_bank0
        fir_bank0.next = sync_fir_bank0
        sync_fir_N.next = system_fir_N
        fir_N.next = sync_fir_N
        sync_fcw.next = system_fcw
        fcw.next = sync_fcw
        sync_correct_i.next = system_correct_i
        correct_i.next = sync_correct_i
        sync_correct_q.next = system_correct_q
        correct_q.next = sync_correct_q
        sync_gain_i.next = system_gain_i
        gain_i.next = sync_gain_i
        sync_gain_q.next = system_gain_q
        gain_q.next = sync_gain_q
        sync_rx_correct_i.next = system_rx_correct_i
        rx_correct_i.next = sync_rx_correct_i
        sync_rx_correct_q.next = system_rx_correct_q
        rx_correct_q.next = sync_rx_correct_q

    interp_counter = Signal(intbv(0)[32:])
    done = Signal(bool(0))

    decim_counter = Signal(intbv(0)[32:])
    rx_done = Signal(bool(0))

    @always_seq(dac_clock.posedge, reset=clearn)
    def consumer():
        if txen:
            if interp_counter == 0:
                interp_counter.next = interp - 1
                if fifo_empty:
                    if txstop:
                        done.next = True
                        fifo_re.next = False
                    else:
                        underrun.next = underrun + 1
                        done.next = False
                        fifo_re.next = False
                else:
                    done.next = False
                    fifo_re.next = True
            else:
                interp_counter.next = interp_counter - 1
                fifo_re.next = False

    @always_seq(dac_clock.posedge, reset=clearn)
    def producer():
        if rxen and downsampled_valid:
            if rx_fifo_full:
                if rxstop:
                    rx_done.next = True
                    rx_fifo_we.next = False
                else:
                    rx_overrun.next = rx_overrun + 1
                    rx_done.next = False
                    rx_fifo_we.next = False
            else:
                rx_done.next = False
                rx_fifo_we.next = True
        else:
            rx_done.next = False
            rx_fifo_we.next = False

    @always_seq(dac_clock.posedge, reset=clearn)
    def sampler():
        if txen:
            if done:
                sample_i.next = 0
                sample_q.next = 0
                sample_valid.next = True
                sample_last.next = True
            elif fifo_dvld:
                sample_i.next = fifo_rdata[16:].signed()
                sample_q.next = fifo_rdata[32:16].signed()
                sample_valid.next = True
                sample_last.next = False
            else:
                sample_i.next = 0
                sample_q.next = 0
                sample_valid.next = False
                sample_last.next = False
        else:
            sample_i.next = 0
            sample_q.next = 0
            sample_valid.next = False
            sample_last.next = False

        if rxen and downsampled_valid:
            rx_fifo_wdata.next = concat(downsampled_q[9], downsampled_q[9],
                                        downsampled_q[9], downsampled_q[9],
                                        downsampled_q[9], downsampled_q[9],
                                        downsampled_q[10:], downsampled_i[9],
                                        downsampled_i[9], downsampled_i[9],
                                        downsampled_i[9], downsampled_i[9],
                                        downsampled_i[9], downsampled_i[10:])
        else:
            rx_fifo_wdata.next = 0

    return (
        synchronizer,
        consumer,
        producer,
        sampler,
    ) + duc_chain + ddc_chain
Exemple #8
0
    with open("env.sh", "a") as f:
        f.write("export {}={}\n".format(varname, value))
    print("Setting environment variable '{}' to value '{}'.".format(
        varname, value))


try:
    os.remove("env.sh")
except OSError:
    pass

# FIR roms
fir = FIR(
    numtaps=120,
    bands=[0, 0.5e6, 1e6, 20e6],
    band_gain=[1, 0],
    fs=40e6,
    pass_db=0.5,
    stop_db=-40,
)

tap_bits = 16
input_bits = 12
downsample_factor = 20
fir.write_poly_taps_files(["src/roms/fir/"], tap_bits, downsample_factor, True,
                          False)
fir.print_response("freq_response.dat")
set_env("FIR_TAP_WIDTH", tap_bits)
set_env("FIR_NORM_SHIFT", fir.tap_normalization_shift())
fir_output_bits = fir.output_bit_width(input_bits)
set_env("FIR_OUTPUT_WIDTH", fir_output_bits)