ofdmtxrx.py 12.4 KB
Newer Older
Rahman's avatar
Rahman committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
#!/usr/bin/python3
"""
 ofdmTxRx.py

 OFDM Modulation/Demodulation library

---------------------------------------------------------------------
 Copyright © 2018-2019. Rice University.
 RENEW OPEN SOURCE LICENSE: http://renew-wireless.org/license
---------------------------------------------------------------------
"""

import numpy as np
import numpy.matlib
import random
import matplotlib.pyplot as plt


class ofdmTxRx:
    """
    OFDM Library
    """

    def __init__(self):
        self.n_ofdm_syms = 100
        self.mod_order = 4
        self.cp_length = 16

    def bpsk_mod(self, val):
        """
        BPSK Modulation

        ARGS
            - val: Integer value (data symbol) between 0 and 1

        RETURNS:
            - iq: Complex data symbol
        """
        mod_vec = [-1, 1]
        a = mod_vec[val]
        b = 0
        iq = np.complex(a, b)

        iq = 1 / np.sqrt(2) * iq
        return iq

    def qpsk_mod(self, val):
        """
        QPSK Modulation

        ARGS
            - val: Integer value (data symbol) between 0 and 3 (i.e., 0:1:3)

        RETURNS:
            - iq: Complex data symbol
        """
        mod_vec = [-1, 1]
        a = mod_vec[val >> 1]
        b = mod_vec[val % 2]
        iq = np.complex(a, b)

        iq = 1 / np.sqrt(2) * iq
        return iq

    def qam16_mod(self, val):
        """
        16QAM Modulation

        ARGS
            - val: Integer value (data symbol) between 0 and 15 (i.e., 0:1:15)

        RETURNS:
            - iq: Complex data symbol
        """
        mod_vec = [-3, -1, 3, 1]
        a = mod_vec[val >> 2]
        b = mod_vec[val % 4]
        iq = np.complex(a, b)

        iq = 1 / np.sqrt(10) * iq
        return iq

    def qam64_mod(self, val):
        """
        64QAM Modulation

        ARGS
            - val: Integer value (data symbol) between 0 and 63 (i.e., 0:1:63)

        RETURNS:
            - iq: Complex data symbol
        """
        mod_vec = [-7, -5, -1, -3, 7, 5, 1, 3]
        a = mod_vec[val >> 3]
        b = mod_vec[val % 8]
        iq = np.complex(a, b)

        iq = 1 / np.sqrt(43) * iq
        return iq

    def bpsk_dem(self, iq):
        """
        BPSK Demodulation

        ARGS
            - iq: Complex data symbol

        RETURNS:
            - val: Integer value (data symbol) between 0 and 1
        """
        val = np.double(np.real(iq) > 0)
        return val

    def qpsk_dem(self, iq):
        """
        QPSK Demodulation

        ARGS
            - iq: Complex data symbol

        RETURNS:
            - val: Integer value (data symbol) between 0 and 3 (i.e., 0:1:3)
        """
        val = np.double(2 * (np.real(iq) > 0) + 1 * (np.imag(iq) > 0))
        return val

    def qam16_dem(self, iq):
        """
        16QAM Demodulation

        ARGS
            - iq: Complex data symbol

        RETURNS:
            - val: Integer value (data symbol) between 0 and 15 (i.e., 0:1:15)
        """

        val = (8 * (np.real(iq) > 0)) + \
              (4 * (abs(np.real(iq)) < 0.6325)) + \
              (2 * (np.imag(iq) > 0)) + \
              (1 * (abs(np.imag(iq)) < 0.6325))
        return val

    def qam64_dem(self, iq):
        """
        64QAM Demodulation

        ARGS
            - iq: Complex data symbol

        RETURNS:
            - val: Integer value (data symbol) between 0 and 63 (i.e., 0:1:63)
        """
        val = (32 * (np.real(iq) > 0)) + \
              (16 * (abs(np.real(iq)) < 0.6172)) + \
              (8 * ((abs(np.real(iq)) < 0.9258) and (abs(np.real(iq)) > 0.3086))) + \
              (4 * (np.imag(iq) > 0)) + \
              (2 * (abs(np.imag(iq)) < 0.6172)) + \
              (1 * ((abs(np.imag(iq)) < 0.9258) and (abs(np.imag(iq)) > 0.3086)))
        return val

162
    def generate_data(self, n_ofdm_syms=100, mod_order=4, cp_length=16, datastream=[]):
Rahman's avatar
Rahman committed
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
        """
        Generate random data stream of n_ofdm_syms number of symbols,
        and modulate according to mod_order.

        ARGS:
            - n_ofdm_syms: Number of OFDM symbols
            - mod_order: Modulation Order
                2 - BPSK
                4 - QPSK
                16 - 16QAM
                64 - 64QAM
            - cp_length: Length of cyclic prefix

        RETURNS:
            - signal: Time domain signal after IFFT and added Cyclic Prefix
            - data: Modulated data stream (Constellation)
            - data_i: Random data to be transmitted
            - sc_idx_all: Indexes for both data and pilot subcarriers
        """
        # Data and Pilot Subcarriers
        # data_sc = [1:6, 8:20, 22:26, 38:42, 44:56, 58:63];
        # pilot_sc = [7, 21, 43, 57]
        num_subcarriers = 64
        data_subcarriers = list(range(1, 7)) + list(range(8, 21)) + list(range(22, 27)) + \
                           list(range(38, 43)) + list(range(44, 57)) + list(range(58, 64))
        pilot_subcarriers = [7, 21, 43, 57]
        n_data_syms = n_ofdm_syms * len(data_subcarriers)  # One data sym per data-subcarrier per ofdm symbol
190 191 192 193 194 195 196 197

        if not datastream:
            data_i = [random.randint(0, mod_order-1) for i in range(n_data_syms)]  # includes end-points
        else:
            # Prepend datastream to rest of randomly generated data symbols
            data_i_tmp = [random.randint(0, mod_order-1) for i in range(n_data_syms-len(datastream))]
            data_i = np.concatenate((datastream, data_i_tmp))

Rahman's avatar
Rahman committed
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
        data = np.zeros(len(data_i), dtype=complex)

        for x in range(len(data_i)):
            if mod_order == 2:
                data[x] = self.bpsk_mod(data_i[x])
            elif mod_order == 4:
                data[x] = self.qpsk_mod(data_i[x])
            elif mod_order == 16:
                data[x] = self.qam16_mod(data_i[x])
            elif mod_order == 64:
                data[x] = self.qam64_mod(data_i[x])
            else:
                raise Exception("Modulation Order Not Supported. Valid orders: 2/4/16/64 for BPSK, QPSK, 16QAM, 64QAM")

        # Data
        data_matrix = np.reshape(data, (len(data_subcarriers), n_ofdm_syms), order="F")

        # Pilots
        pilots = np.array([1, 1, -1, 1]).reshape(4, 1, order="F")
        pilots_matrix = np.matlib.repmat(pilots, 1, n_ofdm_syms)

        # Full Matrix
        ifft_matrix = np.zeros((num_subcarriers, n_ofdm_syms)).astype(complex)
        ifft_matrix[pilot_subcarriers] = pilots_matrix
        ifft_matrix[data_subcarriers] = data_matrix

        # IFFT
        signal = np.fft.ifft(ifft_matrix, n=num_subcarriers, axis=0)

        # Add Cyclic Prefix
        cp = np.array([])
        if cp_length > 0:
            cp = signal[-cp_length:, :]

        signal = np.vstack([cp, signal]) if cp.size else signal

        # Matrix --> Vector
        signal = np.squeeze(np.reshape(signal, (1, signal.size), order="F"))

        # Subcarriers
        sc_idx_all = [data_subcarriers, pilot_subcarriers]

        return signal, data_matrix, data_i, sc_idx_all, pilots_matrix

    def demodulation(self, in_data, mod_order):
        """
        Demodulate data stream of n_ofdm_syms number of symbols, according to mod_order.
        """
        data_i = in_data
        data = np.zeros(len(data_i))
        for x in range(len(data_i)):
            if mod_order == 2:
                data[x] = self.bpsk_dem(data_i[x])
            elif mod_order == 4:
                data[x] = self.qpsk_dem(data_i[x])
            elif mod_order == 16:
                data[x] = self.qam16_dem(data_i[x])
            elif mod_order == 64:
                data[x] = self.qam64_dem(data_i[x])
            else:
                raise Exception("Modulation Order Not Supported. Valid orders: 2/4/16/64 for BPSK, QPSK, 16QAM, 64QAM")

        return data

    def cfo_correction(self, rxSignal, lts_start, lts_syms_len, fft_offset):
        """
        Apply Carrier Frequency Offset

        Input:
            rxSignal     - Received IQ Signal
            lts_start    - Sample where LTS begins
            lts_syms_len - Length of LTS Symbol
            fft_offset   - Number of CP samples for FFT

        Output:
            coarse_cfo_est - CFO estimate
        """
        # Get LTS
        lts = rxSignal[lts_start: lts_start + lts_syms_len]
277 278 279 280 281 282

        # Verify number of samples
        if len(lts) != 160:
            coarse_cfo_est = 0
            return coarse_cfo_est

Rahman's avatar
Rahman committed
283 284 285 286 287 288 289 290 291 292 293 294 295
        lts_1 = lts[-64 + -fft_offset + np.array(range(97, 161))]
        lts_2 = lts[-fft_offset + np.array(range(97, 161))]
        # Compute CFO
        tmp = np.unwrap(np.angle(lts_2 * np.conjugate(lts_1)))
        coarse_cfo_est = np.mean(tmp)
        coarse_cfo_est = coarse_cfo_est / (2 * np.pi * 64)
        return coarse_cfo_est

    def sfo_correction(self, rxSig_freq_eq, pilot_sc, pilots_matrix, n_ofdm_syms):
        """
        Apply Sample Frequency Offset

        Input:
296
            rxSig_freq_eq - Equalized, frequency domain received signal
Rahman's avatar
Rahman committed
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
            pilot_sc      - Pilot subcarriers (indexes)
            pilots_matrix - Pilots in matrix form
            n_ofdm_syms   - Number of OFDM symbols

        Output:
            rxSig_freq_eq - Frequency domain signal after SFO correction
        """
        # Extract pilots and equalize them by their nominal Tx values
        pilot_freq = rxSig_freq_eq[pilot_sc, :]
        pilot_freq_corr = pilot_freq * pilots_matrix
        # Compute phase of every RX pilot
        pilot_phase = np.angle(np.fft.fftshift(pilot_freq_corr))
        pilot_phase_uw = np.unwrap(pilot_phase)
        # Slope of pilot phase vs frequency of OFDM symbol
        pilot_shift = np.fft.fftshift(pilot_sc)
        pilot_shift_diff = np.diff(pilot_shift)
        pilot_shift_diff_mod = np.remainder(pilot_shift_diff, 64).reshape(len(pilot_shift_diff), 1)
        pilot_delta = np.matlib.repmat(pilot_shift_diff_mod, 1, n_ofdm_syms)
        pilot_slope = np.mean(np.diff(pilot_phase_uw, axis=0) / pilot_delta, axis=0)
        # Compute SFO correction phases
        tmp = np.array(range(-32, 32)).reshape(len(range(-32, 32)), 1)
        tmp2 = tmp * pilot_slope
        pilot_phase_sfo_corr = np.fft.fftshift(tmp2, 1)
        pilot_phase_corr = np.exp(-1j * pilot_phase_sfo_corr)
        # Apply correction per symbol
        rxSig_freq_eq = rxSig_freq_eq * pilot_phase_corr
        return rxSig_freq_eq

    def phase_correction(self, rxSig_freq_eq, pilot_sc, pilots_matrix):
        """
        Apply Phase Correction

        Input:
            rxSig_freq_eq - Equalized, time domain received signal
            pilot_sc      - Pilot subcarriers (indexes)
            pilots_matrix - Pilots in matrix form

        Output:
            phase_error   - Computed phase error
        """
        # Extract pilots and equalize them by their nominal Tx values
        pilot_freq = rxSig_freq_eq[pilot_sc, :]
        pilot_freq_corr = pilot_freq * pilots_matrix
        # Calculate phase error for each symbol
        phase_error = np.angle(np.mean(pilot_freq_corr, axis=0))
        return phase_error


if __name__ == '__main__':
    """
    Example on how to generate and modulate a data stream consisting of random values
    """
    ofdm_obj = ofdmTxRx()

    n_ofdm_syms = 100
    mod_order = 2
    cp_length = 16
    sig_t_bpsk, data_bpsk, tx_data_1, sc_idx_1, x0 = ofdm_obj.generate_data(n_ofdm_syms, mod_order, cp_length)
    mod_order = 4
    sig_t_qpsk, data_qpsk, tx_data_2, sc_idx_2, x1 = ofdm_obj.generate_data(n_ofdm_syms, mod_order, cp_length)
    mod_order = 16
    sig_t_16qam, data_16qam, tx_data_3, sc_idx_3, x2 = ofdm_obj.generate_data(n_ofdm_syms, mod_order, cp_length)
    mod_order = 64
    sig_t_64qam, data_64qam, tx_data_4, sc_idx_4, x3 = ofdm_obj.generate_data(n_ofdm_syms, mod_order, cp_length)

    plt.figure(1)
    plt.subplot(2, 2, 1)
    plt.scatter(np.real(data_bpsk), np.imag(data_bpsk))
    plt.subplot(2, 2, 2)
    plt.scatter(np.real(data_qpsk), np.imag(data_qpsk))
    plt.subplot(2, 2, 3)
    plt.scatter(np.real(data_16qam), np.imag(data_16qam))
    plt.subplot(2, 2, 4)
    plt.scatter(np.real(data_64qam), np.imag(data_64qam))
    plt.show()

    plt.figure(2)
    plt.subplot(2, 2, 1)
    plt.plot(np.abs(sig_t_bpsk))
    plt.subplot(2, 2, 2)
    plt.plot(np.abs(sig_t_qpsk))
    plt.subplot(2, 2, 3)
    plt.plot(np.abs(sig_t_16qam))
    plt.subplot(2, 2, 4)
    plt.plot(np.abs(sig_t_64qam))
    plt.show()