def MPSK(v, M, Ts, T, itermG=False): # Geração do sinal MQAM """ v = mensagem de Entrada M = nº da modulação T = periodo do quadro """ print("Modulação Iniciada") modcpy = commod.PSKModem(M) a2 = modcpy.modulate(v) qam_real = [] qam_img = [] for i in a2: qam_real += [i.real] * Ts qam_img += [i.imag] * Ts print(np.array(qam_real) + 1j*np.array(qam_img)) m = [] q = [] i = [] f, t = crr.Generic_Carrier(T) print(f"{f} , {t}") if itermG == True: plot_message(qam_real, qam_img) for k in range(0,len(qam_real)): yr=qam_real[k]*np.cos(2*np.pi*f*t) yim=qam_img[k]*np.sin(2*np.pi*f*t) y=[a + b for a, b in zip(yr, yim)] m = m+y q = q + list(yr) i = i + list(yim) print("Modulação Terminada") return np.array(m), np.array(q), np.array(i)# s(t), T
def __init__(self, power=30): self.txPower = power self.bandwith = 400e6 #hertz self.centerFreq = 700e6 #hertz self.modulation = 4 self.nsubcarriers = 16 self.sensibility = -110 #dBm self.modulator = mod.PSKModem(self.modulation)
def De_MPSK(signal, M, Ts, T, itermG=False):# D-MPSK """ signal = sinal modulado M = nº da modulação key = chave de desentrelaçamento da constelação T = período do cada quadro """ modcpy = commod.PSKModem(M) msg = crr.CarrierDemodeMPSK(signal, Ts, T, modcpy, itermG) return msg
def get_modem(self) -> mod.Modem: """ Gets the modem that is going to be used for this particular WiFi simulation according to the MCS """ bits_per_symbol = [2, 4, 4, 16, 16, 64, 64, 64, 256, 256] if self.mcs <= 2: # BPSK for mcs 0 # QPSK for mcs 1 a 2 return mod.PSKModem(bits_per_symbol[self.mcs]) else: # Modem : QAMModem return mod.QAMModem(bits_per_symbol[self.mcs])
def transmitMessage(self): msg = Message() msg.loremIpsum(8) modulator = mod.PSKModem(self.modulation) a = [bin(ord(x))[2:].zfill(8) for x in msg.payload] binary = [int(j) for i in a for j in i] constellation = modulator.modulate(binary) symbol = np.array([ constellation[i * self.nsubcarriers:(i + 1) * self.nsubcarriers] for i in range(int(len(constellation) / self.nsubcarriers)) ]) #[i for i in constellation] signal = ofdm_tx(symbol, 64, self.nsubcarriers, 0) while True: yield self.scenario.timeout(self.period) self.scenario.sendThroughChannel(signal, self)
def wava(upperbound, snr, trellis): BPSK_Mode = cm.PSKModem(2) last_state1 = 0 last_metric1 = 0 last_state2 = 0 last_metric2 = 0 BitErrors = 0 for i in range(upperbound): message_bits = np.random.randint(0, 2, 128) # tail biting encode tbencodedbits = tb_encoder.conv_encode_tb(message_bits, trellis) # BPSK BPSK_bits = BPSK_Mode.modulate(tbencodedbits) # through the channel receive_code_channel = cch.awgn(BPSK_bits, snr) # demodulate receive_code = BPSK_Mode.demodulate(receive_code_channel, demod_type='hard') # no tail viterbi decoded_bits_notb = tb_encoder.viterbi_decoder_notail( receive_code, trellis, last_state1, last_metric1) decoded_bits_tb = tb_viterbi.tb_viterbi_decode(receive_code, trellis, last_state2, last_metric2) # decoded_bits_notb = async_result1.get() # decoded_bits_tb = async_result2.get() # reset the values of last state last_state1 = decoded_bits_notb[1] last_metric1 = decoded_bits_notb[2] last_state2 = decoded_bits_tb[1] last_metric2 = decoded_bits_tb[2] print(i) # compare these two results if np.array_equal(decoded_bits_tb[0], decoded_bits_notb[0]): result1 = decoded_bits_notb[0] elif i == upperbound - 1: result1 = decoded_bits_tb[0] else: continue BitErrors = str(array(message_bits) ^ result1).count('1') print(BitErrors) break return BitErrors
def __init__(self, power=30): self.txPower = power self.bandwith = 400e6 #hertz self.centerFreq = 700e6 #hertz self.modulation = 4 self.nsubcarriers = 16 self.sensibility = -110 #dBm self.modulator = mod.PSKModem(self.modulation) self.x = 0 self.y = 0 self.antennaGain = 8 self.users = [] self.SNRThreshold = float(sys.argv[3]) self.period = 0 self.noiseFigure = 10*np.log10(BANDWIDTH*1.38e-23*290)
def stack_runner(IterationTimes, snr, index, metrics): memory = array([8]) g_matrix = array([[0o515, 0o677]]) trellis = cc.Trellis(memory, g_matrix) BPSKMod = cm.PSKModem(2) CodeError = 0 total_result = 0.0 for i in range(IterationTimes): # encode # set the message size message_bits = np.random.randint(0, 2, 128) # print(message_bits) encoded_code = cc.conv_encode(message_bits, trellis) BPSK_modedbits = BPSKMod.modulate(encoded_code) AWGNreceived_bits = cch.awgn(BPSK_modedbits, snr + 3, 0.5) result = stack_soft_decoder(AWGNreceived_bits, metrics, trellis) print("pass: {}, {}".format(i, index)) if len(result) != 136: continue else: BitErrors = str( array(message_bits) ^ array(result[0:len(message_bits)])).count('1') # print(result) # print(BitErrors) # print(result_int) # print(message_bits_int) BER = BitErrors / 128 if BitErrors > 0: CodeError += 1 total_result += BER # i += 1 # print(i) # print(result) CER = CodeError / IterationTimes AverageBER = total_result / IterationTimes return CER
def __init__(self, const_size: int = 4, f_symbol: int = 128, f_sample: int = int(8e3), f_carrier: int = int(1e3)): """ Initialize the audio component of a modulator/demodulator using IQ modulation of complex QAM symbols. :param const_size: number of points in QPSK constellation :param f_symbol: symbol frequency (symbols per second) :param f_carrier: carrier frequency for the signal :param f_sample: sample rate for DAC/ADC """ # instantiate the QAM map for 4QPSK from commpy import modulation as mod self._modem = mod.PSKModem(const_size) # define basic parameters self._f_symbol = f_symbol self._f_sample = f_sample self._f_carrier = f_carrier self._w_carrier = 2 * np.pi * self._f_carrier # angular frequency of raw carrier self._symbol_period = 1 / self._f_symbol # seconds per symbol self._upsmple_factor = int(self._symbol_period * self._f_sample) # samples per symbol # compute/construct filter FIR coefficents and delays rrc_delay, self._rrc_fir = self._construct_rrc_filter() lp_delay, self._lp_fir = self._construct_lowpass_filter() self._filter_delay_samples = int( (2 * rrc_delay + lp_delay) * self._f_sample) logging.info( 'Instantiated IQModem with const_size {CS}, f_symbol {FSY}, f_sample {FSA}, and f_carrier {FC}' .format( CS=const_size, FSY=f_symbol, FSA=f_sample, FC=f_carrier, ))
def get_modem(self) -> mod.Modem: """ Gets the modem that is going to be used for this particular WiFi simulation according to the MCS """ qpsks = [ 2, 4, 4, 16, 64, 64, 64, 256, 256 ] if self.mcs == 0: # BPSK return mod.PSKModem(2) else: # Modem : QPSK return mod.QAMModem(qpsks[self.mcs])
def newmethodrunner(iterationtimes, eb_n0, index, metrics): memory = array([8]) g_matrix = array([[0o515, 0o677]]) trellis = cc.Trellis(memory, g_matrix) BPSKMod = cm.PSKModem(2) # set the message size total_error = 0 cer = 0 for d in range(iterationtimes): message_bits = np.random.randint(0, 2, 128) result = 0 # print(message_bits) encoded_code = tb_encoder.conv_encode_tb(message_bits, trellis) BPSK_modedbits = BPSKMod.modulate(encoded_code) r_code = cch.awgn(BPSK_modedbits, eb_n0 + 3, 0.5) # r_code = BPSKMod.demodulate(AWGNreceived_bits, demod_type='hard') # part_code = BPSKMod.demodulate(r_code[240:], demod_type='hard') part_decode = shortviterbi1.short_viterbi(np.append(r_code[240:], r_code[0:64]), trellis, 'unquantized')[0] # part_decode = message_bits[120:] # print(part_decode) # print(len(part_decode)) initial_code = part_decode[0:8][::-1] # initial_code = message_bits[120:][::-1] initial_state = bitarray2dec(initial_code) # print(initial_state) initial_metric = 0 result = stack_decoder_fixed_tb(r_code, metrics, trellis, initial_state, initial_metric)[0] print("pass: {}, {}".format(d, index)) # print(result) bit_error = str(message_bits ^ array(result)).count('1') if bit_error > 0: cer += 1 # print(bit_error) total_error += bit_error averageber = total_error/(iterationtimes * 128) a_cer = cer/iterationtimes return a_cer, averageber
def signalGeneration(SIGNAL_NUM=50000): ''' init params ---------------------- params: X: signals with I and Q series Y: labels with the 5 classes, 0-1 5-dim vectors Z: SNRs classes = ['BPSK', 'QPSK', '8PSK', 'QAM16', 'QAM64'] ''' X = np.zeros([SIGNAL_NUM, 2, SYMBOL_NUM * SYMBOL_RATE]) Y = np.zeros([SIGNAL_NUM, 5]) Z = np.zeros([SIGNAL_NUM]) #X2 = np.zeros([SIGNAL_NUM, 2, SYMBOL_NUM*SYMBOL_RATE]) for iterator in xrange(SIGNAL_NUM): pid = os.getpid() print('pid:%d, iterator:%d' % (pid, iterator)) ''' generate 5 modulationTypes randomly generate #SYMBOL_NUM# symbols randomly construct constellation ''' modulationType = np.random.random_integers(1, 5, 1) label = np.zeros(5) label[modulationType - 1] = 1 Y[iterator] = label if modulationType == 1: '''BPSK''' inputSeries = np.random.random_integers(0, 1, SYMBOL_NUM * CONST_BPSK) modulationSeries = modulation.PSKModem(2).modulate(inputSeries) modulationSeries = interpolation(modulationSeries, SYMBOL_RATE) elif modulationType == 2: '''QPSK''' inputSeries = np.random.random_integers(0, 1, SYMBOL_NUM * CONST_QPSK) modulationSeries = modulation.PSKModem(4).modulate(inputSeries) modulationSeries = interpolation(modulationSeries, SYMBOL_RATE) elif modulationType == 3: '''8PSK''' inputSeries = np.random.random_integers(0, 1, SYMBOL_NUM * CONST_8PSK) modulationSeries = modulation.PSKModem(8).modulate(inputSeries) modulationSeries = interpolation(modulationSeries, SYMBOL_RATE) elif modulationType == 4: '''QAM16''' inputSeries = np.random.random_integers(0, 1, SYMBOL_NUM * CONST_QAM16) modulationSeries = modulation.QAMModem(16).modulate(inputSeries) modulationSeries = interpolation(modulationSeries, SYMBOL_RATE) elif modulationType == 5: '''QAM64''' inputSeries = np.random.random_integers(0, 1, SYMBOL_NUM * CONST_QAM64) modulationSeries = modulation.QAMModem(64).modulate(inputSeries) modulationSeries = interpolation(modulationSeries, SYMBOL_RATE) else: print 'incorrect modulationType' break '''use RRC''' [t, hRRC] = cp.filters.rrcosfilter(33, 0.4, 1, SYMBOL_RATE) signal = np.convolve(modulationSeries, hRRC, mode='same') '''add phrase, freq offset''' OFFSET_F = 0.01 OFFSET_PH = float(np.random.randint(0, 314)) / 100 signal = cp.add_frequency_offset( signal, SYMBOL_RATE, OFFSET_F * float(np.random.randint(8, 15)) / 10) signal = signal * np.exp(-OFFSET_PH * 1j) '''channel''' '''rayleigh channel''' H_CHANNEL = [ 0.342997170285018 + 2.75097576175635j, 0.342995668431465 + 2.75097418548155j, 0.342991162874393 + 2.75096945665969j, 0.342983653624566 + 2.75096157529839j, 0.342973140699920 + 2.75095054141035j, 0.342959624125568 + 2.75093635501332j, 0.342943103933798 + 2.75091901613016j, 0.342923580164072 + 2.75089852478880j, 0.342901052863027 + 2.75087488102222j, 0.342875522084475 + 2.75084808486853j ] signal = np.convolve(signal, H_CHANNEL, mode='same') '''noise by quantitative SNR''' snr = SNRs[np.random.randint(0, len(SNRs))] Z[iterator] = snr #signal2 = signal signal = awgn(signal, snr) '''regulization''' length = np.zeros([len(signal)]) for i in xrange(len(signal)): length[i] = np.sqrt( np.power(np.imag(signal[i]), 2) + np.power(np.real(signal[i]), 2)) maxLen = length[np.where(length == np.max(length))] signal = signal / maxLen[0] '''reconstruction''' signalI = np.real(signal) signalQ = np.imag(signal) X[iterator][0] = signalI X[iterator][1] = signalQ #X2[iterator][0] = np.real(signal2) #X2[iterator][1] = np.imag(signal2) return [X, Y, Z]