def __init__(self, fftSize, samp_rate, measureTime, gain, c_freq, config, user, window): self.user = user self.fftSize = int(fftSize) self.samp_rate = float(samp_rate) self.bandwidth = self.samp_rate self.measureTime = int(measureTime) self.gain = int(gain) self.c_freq = float(c_freq) self.index = '' self.config = config self.configfil = "/home/" + self.user + "/GNURadio-FFTS/FFTS.config" self.loops = 1 self.switched = 1 self.measureTimeTotPow = 5 self.adjust = 0 self.window = window #Initate GnuRadio flowgraph self.receiver = Receiver(self.fftSize, self.samp_rate, self.gain, self.c_freq, self.window) #Creates usrp object from receiver self.usrp = self.receiver.uhd_usrp_source_0 ######### GPIO INIT ######### ############################# num_bits = 11 mask = (1 << num_bits) - 1 ######### Initiate SR and DV pin ############## #Defines whether this pin is controlled automatically by FPGA,1, or manual,0 self.usrp.set_gpio_attr("FP0", "CTRL", 0x0, mask) #Defines whether this pin is an output(1) or input(0) self.usrp.set_gpio_attr("FP0", "DDR", 0x0, mask)
def listening(self): msg = '' conversor = Conversor() while (True): receiver = Receiver(1) byteRecebido = receiver.listening receiver = Receiver(0.5) confirmByte = receiver.listening if (confirmByte): msg += conversor.bin_to_str(byteRecebido) print("LISTENING: ", msg)
class Controller: #https://www.tutorialspoint.com/python/python_multithreading.htm def runThreads(self): self.threadTransmiter = Transmiter(1, "TRANS", 5, 1, self) self.threadReceiver = Receiver(1, "REC", 2, 2) self.threadTransmiter.start() self.threadReceiver.start() #JAKIES METODY DO OBSLUGI TYCH WATKOW def printNIC(self): print("NIC") self.threadReceiver.printNICREC()
def transmission(self, pacote, flag): self.sem.acquire() dadoRecebido = '' try: for palavra in pacote.quantDados: for letra in palavra: while not (self.correctByte): receiver = Receiver(1) pool = ThreadPool(processes=1) async_call = pool.apply_async(receiver.listening) self.camadaFisica.emitir(letra, flag) arquivoRecebido = async_call.get() arquivoRecebido = self.conversor.bin_to_str( arquivoRecebido) if (arquivoRecebido == letra): self.correctByte = True print("arquivo Recebido: ", arquivoRecebido) dadoRecebido += arquivoRecebido self.camadaFisica.correct(self.correctByte) else: self.camadaFisica.correct(self.correctByte) self.correctByte = False print("MENSAGEM FINAL RECEBIDA:", dadoRecebido) finally: self.sem.release()
def __init__(self): super(TwoBOneQTransmitter, self).__init__() self.sender = Sender.Sender(self) self.receiver = Receiver.Receiver(self) self.mainwindow = Interface.mainWindow.Ui_mainwindow() self.mainwindow.setupUi(self) self.mainwindow.receive_button.clicked.connect( lambda: self.showReceiver()) self.mainwindow.send_button.clicked.connect(lambda: self.showSender()) self.show()
def showReadyFrame(self): self.parID = self.editParticipantID.text() self.fileName = self.parID.split("_")[0] + "_" + self.parID.split( "_")[1] ''' SIMULATOR ''' if self.initAll == False and self.summary == False: # Initializing the NetClient self.netclient = NetClient(self.quitNetclient) self.netclient.glanceWarningSignal.connect( self.setGlanceWarning, QtCore.Qt.QueuedConnection) self.netclient.glanceDangerSignal.connect( self.setGlanceDanger, QtCore.Qt.QueuedConnection) self.netclient.glanceResetSignal.connect( self.resetGlance, QtCore.Qt.QueuedConnection) self.netclient.start() # Initializing the RECEIVER self.receiver = Receiver(self.netclient, self.parID_signal) self.receiver.terminateScreen.connect(self.showEndDrive, QtCore.Qt.QueuedConnection) self.receiver.start() self.parID_signal.emit(self.fileName) self.initAll = True # GUI part self.introframe.hide() self.feedbackframe.hide() self.gameframe.hide() self.endframe.hide() self.readyframe.show() self.resetGlance() # Only create the file if it does not exist if not os.path.exists( '../../participantData/Gamification/%s.csv' % self.fileName): with open( '../../participantData/Gamification/%s.csv' % self.fileName, 'wb') as csvfile: toFile = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL) toFile.writerow( ['Trial#', 'Phrase Selected', 'isCorrect', 'Interactions'])
def __init__(self): self.peerID = self.genID() self.caches = Caches.Caches(self.peerID) self.sender = Sender.Sender() self.receiver = Receiver.Receiver(self.peerID, ("0.0.0.0", 5000), self.caches) self.handler = Handler.Handler(self.peerID, self.caches) self.t1 = threading.Thread(target=self.receiver.multicast).start() self.t2 = threading.Thread(target=self.receiver.unicast).start() self.t3 = threading.Thread(target=self.receiver.receive_files).start() self.lock = Lock()
def RunSatellite(): # Add the FOR loops first buffer = Buffer.Buffer(10) buff = buffer.getBuffer() satellie = Satellite.Satellite(buff, 10) satellie.start() satellie.join() receiver = Receiver.Receiver(buff, 10) receiver.start() receiver.join()
encode=a.compress("test.txt") #create packet b = Transmitter(encode) chunks=b.chunks packet = b.encode() final_packet=[] for p in packet: check=Packet(p) # print(check.checksum) # print(check.total_data) final_packet.append(check.get_final_packet()) #send file c = Receiver() count = 0 packet == packet[::-1] while not c.isDone() and count<len(packet): received=final_packet[count] print(received) check=Packet(received, sent = True) print(check.check_checksum()) if check.check_checksum(): temp=check.get_received_packet() temp=bytearray(temp,'utf8') c.receive_packet(temp) count+=1 de=c.decoded_chunks
def test_eye_diagram_no_channel(receiver, transmitter, SAVED=False): plt.figure() receiver.plot_eye_diagram_no_channel(transmitter) if SAVED: myplt.save_current('eye_rx_%s_no_ch_2.png' % receiver.name, 'PLOT') if __name__ == "__main__": T_pulse = 1 # sec Fs = 32 # samples/sec per pulse alpha = 0.5 K = 4 noise_var = 0 hs_tx = tx.HalfSineTransmitter(T_pulse, Fs) hs_rx = rx.MatchedReceiver(hs_tx) srrc_tx = tx.SRRCTransmitter(alpha, T_pulse, Fs, K) srrc_rx = rx.MatchedReceiver(srrc_tx) # channel impulse responses - modeled as an LTI system with finite impulse response h_test = np.array([1, 1 / 2, 3 / 4, -2 / 7]) ch_test = chnl.Channel(h_test, np.ones(1), Fs, T_pulse, 'Test') transmitters = [hs_tx, srrc_tx] receivers = [hs_rx, srrc_rx] random_bits = np.random.randint(2, size=10) # to test transmission for receiver, transmitter in zip(receivers, transmitters): print('Working on- Receiver: ', receiver.name, ', Transmitter: ',
def __init__(self): self.emitter = Em.Emitter() self.canal = Ca.Canal() self.receiver = Re.Receiver()
class Measurement: #Constructor def __init__(self, fftSize, samp_rate, measureTime, gain, c_freq, config, user, window): self.user = user self.fftSize = int(fftSize) self.samp_rate = float(samp_rate) self.bandwidth = self.samp_rate self.measureTime = int(measureTime) self.gain = int(gain) self.c_freq = float(c_freq) self.index = '' self.config = config self.configfil = "/home/" + self.user + "/GNURadio-FFTS/FFTS.config" self.loops = 1 self.switched = 1 self.measureTimeTotPow = 5 self.adjust = 0 self.window = window #Initate GnuRadio flowgraph self.receiver = Receiver(self.fftSize, self.samp_rate, self.gain, self.c_freq, self.window) #Creates usrp object from receiver self.usrp = self.receiver.uhd_usrp_source_0 ######### GPIO INIT ######### ############################# num_bits = 11 mask = (1 << num_bits) - 1 ######### Initiate SR and DV pin ############## #Defines whether this pin is controlled automatically by FPGA,1, or manual,0 self.usrp.set_gpio_attr("FP0", "CTRL", 0x0, mask) #Defines whether this pin is an output(1) or input(0) self.usrp.set_gpio_attr("FP0", "DDR", 0x0, mask) def set_loops(self, loops): self.loops = loops #Set optimal gain to utilize full dynamic range of ADC def meas_adjust(self): histData = [] print "Adjusting gain" self.config.set('CTRL','state','adjusting') with open(self.configfil, 'wb') as configfile: self.config.write(configfile) self.receiver.start() timedat = 1 #Read samples for 1 second on current gain gain = 18 #Gain start value self.set_gain(gain) while gain < 31 and gain != -1: print gain L = [] L1 = [] L2 = [] end = time.time() + timedat while time.time() <= end: time.sleep(10 / (self.samp_rate)) L.append(self.receiver.get_probe_var()) for i in L: if i > 0.5: L1.append(i) else: L2.append(i) hundra = len(L) print (len(L1)/float(hundra)) if (len(L1)/float(hundra)) < 0.05: #As long as the samples above the value 0.5 are under 5% of all collected samples continue to increase gain gain += 1 self.set_gain(gain) print self.usrp.get_gain(0) del L, L1, L2 elif gain == 30: histData = L i = -1 break else: histData = L i = -1 del L, L1, L2 break print "Final gain: " print self.usrp.get_gain(0) self.receiver.stop() self.receiver.wait() self.config.set('USRP','gain', str(self.usrp.get_gain(0))) self.config.set('CTRL','state','ready') with open(self.configfil, 'wb') as configfile: self.config.write(configfile) np.save('/home/' + user + '/Documents/sampleDist.npy', histData) #Start measurement def measure_start(self): if self.adjust == 1: #Adjust gain? self.meas_adjust() else: self.date = ephem.now().tuple() #Date for FITS-file self.receiver.start() self.sig_time = 0 self.ref_time = 0 self.totpowTime = 0 self.config.set('CTRL','abort','0') self.config.set('CTRL','state','integrating') with open(self.configfil, 'wb') as configfile: self.config.write(configfile) index = 0 start = time.time() while index < self.loops: self.set_index(index) if self.switched == 1: self.measure_switch_in() else: self.loops = 1 self.measure_tot_pow() self.counter = 0 self.sigCount = 0 self.refCount = 0 if int(self.config.get('CTRL','abort')) != 1: tc = Analyze(self.sigCount, self.refCount, index, self.fftSize, self.c_freq, self.samp_rate, self.switched, self.user) index += 1 stop = time.time() print "Total time: " print stop - start edit = 0 if int(self.config.get('CTRL','abort')) != 1: td = Finalize(index, self.fftSize, self.c_freq, self.samp_rate, edit, self.sig_time, self.ref_time, self.switched, self.totpowTime, self.user, self.date) self.receiver.stop() self.receiver.wait() files = glob.glob('/tmp/ramdisk/*') for f in files: if f.endswith(self.index): os.remove(f) else: continue self.config.set('CTRL','state','ready') with open(self.configfil, 'wb') as configfile: self.config.write(configfile) def measure_tot_pow(self): #If dumpfile exists remove it try: os.remove('/tmp/ramdisk/dump1') os.remove('/tmp/ramdisk/dump2') except OSError: pass self.date = ephem.now().tuple() self.receiver.lock() self.receiver.signal_file_sink_1.open("/tmp/ramdisk/totPow") self.receiver.unlock() print self.measureTimeTotPow t_end = time.time() + self.measureTimeTotPow start = time.time() while time.time() <= t_end: if int(self.config.get('CTRL','abort')) == 1: break self.receiver.blks2_selector_0.set_output_index(1) #Stream to signal sink end = time.time() self.totpowTime += end-start self.receiver.blks2_selector_0.set_output_index(0) #Null sink, shouldnt be necessary but just in case self.receiver.lock() self.receiver.signal_file_sink_1.close() self.receiver.unlock() #Measure and collect FFT files, Dicke-switched def measure_switch_in(self): #If dumpfile exists remove it try: os.remove('/tmp/ramdisk/dump1') os.remove('/tmp/ramdisk/dump2') except OSError: pass #SR pin logic, observe that pin logic might vary with with FPGA image S = int('00011',2) R = int('00010',2) #DV pin logic SN = int('00001',2) RN = int('00000',2) self.sigCount = 1 self.refCount = 1 #First sig/ref file sink self.receiver.lock() self.receiver.signal_file_sink_1.open("/tmp/ramdisk/sig0" + self.index) self.receiver.signal_file_sink_2.open("/tmp/ramdisk/ref0" + self.index) self.receiver.unlock() countTwo = 0 while countTwo == 0: if self.usrp.get_gpio_attr("FP0", "READBACK", 0) == S: #Stream to sig sink if datavalid = 1 and SR = 1 countTwo = 1 t_end = time.time() + self.measureTime while time.time() <= t_end: if int(self.config.get('CTRL','abort')) == 1: break elif self.usrp.get_gpio_attr("FP0", "READBACK", 0) == S: time.sleep(2e-3) #Blanking for GnuRadio delay start1 = time.time() self.receiver.blks2_selector_0.set_output_index(1) #Stream to signal sink while self.usrp.get_gpio_attr("FP0", "READBACK", 0) == S: #File sink closes if Datavalid = 0 continue stop1 = time.time() self.sig_time += stop1-start1 print 'sig' self.receiver.blks2_selector_0.set_output_index(0) #Null sink, shouldnt be necessary but just in case self.receiver.lock() self.receiver.signal_file_sink_1.close() self.receiver.signal_file_sink_1.open("/tmp/ramdisk/sig" + str(self.sigCount) + self.index) self.receiver.unlock() self.sigCount += 1 while self.usrp.get_gpio_attr("FP0", "READBACK", 0) == SN or self.usrp.get_gpio_attr("FP0", "READBACK") == RN: continue elif self.usrp.get_gpio_attr("FP0", "READBACK") == R: time.sleep(2e-3) start2 = time.time() self.receiver.blks2_selector_0.set_output_index(2) # Stream to reference sink while self.usrp.get_gpio_attr("FP0", "READBACK", 0) == R: #Close file sink datavalid = 0 continue stop2 = time.time() self.ref_time += stop2-start2 print 'ref' self.receiver.blks2_selector_0.set_output_index(0) #Null sink self.receiver.lock() self.receiver.signal_file_sink_2.close() self.receiver.signal_file_sink_2.open("/tmp/ramdisk/ref" + str(self.refCount) + self.index) self.receiver.unlock() self.refCount += 1 while self.usrp.get_gpio_attr("FP0", "READBACK", 0) == RN or self.usrp.get_gpio_attr("FP0", "READBACK") == SN: continue #Set integration time def set_int_time(self, int_time): self.measureTime = int(int_time) def set_adjust(self, adjust): self.adjust = int(adjust) def set_switched(self, switched): self.switched = int(switched) def set_time_totPow(self, totPowTime): self.measureTimeTotPow = int(totPowTime) #Set USRP gain def set_gain(self, gain): self.gain = int(gain) self.usrp.set_gain(self.gain) #Set the number of FFT channels def set_channels(self, channels): self.fftSize = int(channels) #Set USRP center frequency def set_c_freq(self, c_freq): self.c_freq = float(c_freq)*1e6 self.usrp.set_center_freq(self.c_freq) #Set the sampling frequency equivalent to bandwidth since I/Q samples, however aliasing might occur for high/low freq def set_samp_rate(self, samp_rate): self.samp_rate = float(samp_rate)*1e6 self.usrp.set_samp_rate(self.samp_rate) def set_index(self, count): self.index = str(count)
RelaySet.append(Relay.Relay(configFile,connectionBeforewithPort,connectionAfterwithPort,idx+2)) #startBob: BobIP=iplist[7] connectionBeforeB=connectionBefore.get(BobIP) connectionAfterB=connectionAfter.get(BobIP) connectionAfterwithPort = [] for afterIP in connectionAfterB: connectionAfterwithPort.append((afterIP, portList[iplist.index(afterIP)])) connectionBeforewithPort = [] for beforeIP in connectionBeforeB: connectionBeforewithPort.append((beforeIP, portList[iplist.index(beforeIP)])) configFile='config/host_Bob'+'.ini' SenderBob=Receiver.Receiver(configFile,connectionBeforewithPort,connectionAfterwithPort) #StartAlice: AliceIP=iplist[0] connectionBeforeA=connectionBefore.get(AliceIP) connectionAfterA=connectionAfter.get(AliceIP) connectionAfterwithPort = [] for afterIP in connectionAfterA: connectionAfterwithPort.append((afterIP, portList[iplist.index(afterIP)])) connectionBeforewithPort = [] for beforeIP in connectionBeforeA: connectionBeforewithPort.append((beforeIP, portList[iplist.index(beforeIP)])) configFile='config/host_Alice'+'.ini' SenderAlice=Sender.Sender(configFile,connectionBeforewithPort,connectionAfterwithPort)
def make_receiver(self, origin, cube_dimension, material): return Receiver.Receiver(self, origin, cube_dimension, material)
def __init__(self): #Will need some fun things here. Maybe encryption agreement? self.transmitter = Sender() self.receiver = Receiver()
class SineClient: def __init__(self): #Will need some fun things here. Maybe encryption agreement? self.transmitter = Sender() self.receiver = Receiver() def console(self): #User control interface. Determines if the client would like to send or receive, and subsequently #whether the client would like to send a file or a plain text message. print "text - Send plain text message \r\n",\ "data - Specify a file to send \r\n",\ "recv - Listen for messages \r\n",\ "util - Utilities and tools \r\n", \ "quit - Exit Sine Language \r\n" userIn = raw_input("Please select an option from above \r\n") def textInput(): s = struct.Struct('c') message = raw_input("Please enter a message to send. \r\n") output = "" while(len(message) >= 1): letter = message[0] message = message[1:] output += s.pack(letter) hex = binascii.hexlify(output) print 'Packed Value :', hex, " Length : ", len(hex) self.transmitter.send("text", hex) # Take a file path and attempt to transfer an entire file def dataInput(): return # Listen for valid messages def listen(): self.receiver.execute() return # Cool stuff to go here? def utilities(): return # About screen def about(): self.clearScreen() print "This program is a revision of Sine Language,\r\n",\ "a project from the 10/13 Carleton College Hackathon.\r\n", \ "Original Authors: Liz Shank and Alex Calamaro \r\n",\ "Inquiries to: [email protected] \r\n" def exitApp(): self.clearScreen() sys.exit() options = { "text" : textInput, "data" : dataInput, "recv" : listen, "util" : utilities, "about": about, "quit" : exitApp, } try: options[userIn]() except KeyError: print "Invalid input." return def listener(self): #Make a class for this return def addHeader(self, message, type): #adds a header with one char representing the type, n chars representing length # and a # representing start of data return def binToHex(self,binInput): #returns hexadecimal representation of binary input. print binInput return def hexToBin(self, hexInput): #returns binary representation of hexadecimal input. return def clearScreen(self): os.system(['clear','cls'][os.name=='nt']) def main(self): self.clearScreen() print "Welcome to Sine Language! \r\n",\ self.console()
def run(self): receiver.receive()
import NetworkProcess import Receiver import Sender import senderTest """ TODO: Implement an internet application program Create instances of the Sender, Receiver and NetworkProcess classes Create a loop, where the handleEvent functions of these instances are called 100 times """ send = Sender.Sender() # Creates new instance of Sender class receive = Receiver.Receiver() # Creates new instance of Receiver class netpro = NetworkProcess.NetworkProcess(send, receive) x = 0 while x < 100: send.handleEvent() netpro.handleEvent() receive.handleEvent() x += 1
def feedback_update_simulation(sim_param_dict, add_on_path=""): """ Perform simulation having the dictionary of parameters. This one is used on the case of time step study and the performances of feedback loop :param sim_param_dict: A dictionary containing all parameters necessary for the simulation """ # Simulation parameters eb_n0_db = sim_param_dict["sim_parameters"]["eb_n0_db"] nb_time_step = sim_param_dict["sim_parameters"]["nb_time_step"] chan_freq_update = sim_param_dict["channel_parameters"][ "chan_param_freq_update"] time_array = np.linspace(0, nb_time_step, nb_time_step) ser = np.zeros(nb_time_step) gamma_values = np.zeros(nb_time_step) beta_values = np.zeros(nb_time_step) # Compute the snr_db value. snr_db = eb_n0_db + 10 * np.log( sim_param_dict["channel_coding"]["rho"] * np.log2(sim_param_dict["modulation"]["modulation_order"])) # Creation of the trellis if sim_param_dict["channel_coding"]["rho"] != 1: # print("rho value is ", sim_param_dict["channel_coding"]["rho"]) trellis = Trellis( sim_param_dict["channel_coding"]["mem_size"], sim_param_dict["channel_coding"]["g_matrix"], ) else: # No coding trellis = None # Creation of the emitter emiter = Emitter( cp_len=sim_param_dict["modulation"]["cp_length"], nb_carriers=sim_param_dict["modulation"]["nb_carriers"], modulation_order=sim_param_dict["modulation"]["modulation_order"], trellis=trellis, nb_off_carriers=sim_param_dict["modulation"]["off_carrier"], ) # Creation of the receiver receiver = Receiver( cp_len=sim_param_dict["modulation"]["cp_length"], nb_carriers=sim_param_dict["modulation"]["nb_carriers"], modulation_order=sim_param_dict["modulation"]["modulation_order"], trellis=trellis, nb_off_carriers=sim_param_dict["modulation"]["off_carrier"], equalizer_type=sim_param_dict["equalizer"], pre_equalizer_path=sim_param_dict["pre_equalizer"]["model_path"], ) print((sim_param_dict["channel_parameters"]["non_lin_coeff"])) # Creation of the AWGN Channel awgn_channel = Channel( mean=0, var=0, non_lin_coeff=sim_param_dict["channel_parameters"]["non_lin_coeff"], iq_imbalance=sim_param_dict["channel_parameters"]["iq_imbalance"], # Not sure that this will work : have to test in the case of a non array type channel_taps=sim_param_dict["channel_parameters"]["channel_taps"], ) # Creation of the filepath filename = generate_path_name_from_param_dict_ser(sim_param_dict, add_on_path) print("Results will be printed in : ", filename) # Creation of the PHY Layer phy_layer = PhyLayer(emiter, receiver, awgn_channel, sim_param_dict["pre_equalizer"]["feed_back_freq"]) # Set the snr for the channel for once. phy_layer.channel.set_var(eb_n0_db, sim_param_dict["modulation"]["modulation_order"]) # For the moment, we consider that the noise variance is not estimated # but is Genie aided. if sim_param_dict["equalizer"] == "MMSE": receiver.equalizer.set_noise_var(phy_layer.channel.var) # Parameters of the iteration process. ind_time_step = 0 # Launch the simulation while we do not fill the vector of time steps. while (ind_time_step < nb_time_step): # Record the value of gamma and iq gamma_values[ind_time_step] = phy_layer.channel.gamma beta_values[ind_time_step] = phy_layer.channel.beta # Generation of the frames frame = np.random.randint(0, high=2, size=sim_param_dict["frame_length"]) # Send the frame to the physical layer and get the number of errors at the symbol level errors_num, nb_symb = phy_layer.process_frame_ser(frame) # If we have reached the frequency threshhold we update the value of if np.remainder(ind_time_step, chan_freq_update) == 0: # Select a new random value of non-linearity phy_layer.channel.random_update_non_lin( sim_param_dict["channel_parameters"]["non_lin_coeff_set"], sim_param_dict["channel_parameters"]["iq_imbalance_set"]) print("New parameter gamma is ", phy_layer.channel.gamma, "beta is ", phy_layer.channel.beta, " at t = ", ind_time_step) # Update error vectors. ser[ind_time_step] = errors_num / nb_symb if ((ind_time_step % 100) == 0): #print("[MonteCarlo.py::feedback_update_simulation::276]The number of symbols is :", nb_symb) print( "At ", np.floor(100 * ind_time_step / nb_time_step), " %", ", SER = ", ser[ind_time_step], " for Eb/N0 = ", eb_n0_db, " dB", ", SNR = ", snr_db, "dB", " at time step", ind_time_step, ) ber_dict = { "sim_param": sim_param_dict, "results": { "eb_n0_db": eb_n0_db, "snr_db": snr_db, "time_array": time_array, "ser": ser, "gamma_values": gamma_values, "beta_values": beta_values, }, } # Save results in file with open(filename, "wb") as handle: pickle.dump(ber_dict, handle) # Increase the time step ind_time_step += 1 # Display results figures TODO : Implements a function that performs that in Utils. plt.plot(time_array, ser, "b") plt.yscale("log") plt.title("BER results") plt.xlabel("Eb/N0 (dB)") plt.ylabel("SER") plt.grid(True) plt.show()
def monte_carlo_simulation(sim_param_dict, add_on_path=""): """ Perform the global simulation having the dictionary of parameters. :param sim_param_dict: A dictionary containing all parameters necessary for the simulation """ max_test = (sim_param_dict["m_c_parameters"]["min_error_frame"] / sim_param_dict["m_c_parameters"]["targeted_fer"]) # Simulation parameters eb_n0_db = np.array( range( sim_param_dict["m_c_parameters"]["min_eb_n0"], sim_param_dict["m_c_parameters"]["max_eb_n0"], sim_param_dict["m_c_parameters"]["step_db"], )) ber = np.zeros(len(eb_n0_db)) fer = np.zeros(len(eb_n0_db)) ser = np.zeros(len(eb_n0_db)) # Compute the snr_db vector snr_db = eb_n0_db + 10 * np.log( sim_param_dict["channel_coding"]["rho"] * np.log2(sim_param_dict["modulation"]["modulation_order"])) # Creation of the trellis if sim_param_dict["channel_coding"]["rho"] != 1: # print("rho value is ", sim_param_dict["channel_coding"]["rho"]) trellis = Trellis( sim_param_dict["channel_coding"]["mem_size"], sim_param_dict["channel_coding"]["g_matrix"], ) else: # No coding trellis = None # Creation of the emiter emiter = Emitter( cp_len=sim_param_dict["modulation"]["cp_length"], nb_carriers=sim_param_dict["modulation"]["nb_carriers"], modulation_order=sim_param_dict["modulation"]["modulation_order"], trellis=trellis, nb_off_carriers=sim_param_dict["modulation"]["off_carrier"], ) # Creation of the receiver receiver = Receiver( cp_len=sim_param_dict["modulation"]["cp_length"], nb_carriers=sim_param_dict["modulation"]["nb_carriers"], modulation_order=sim_param_dict["modulation"]["modulation_order"], trellis=trellis, nb_off_carriers=sim_param_dict["modulation"]["off_carrier"], equalizer_type=sim_param_dict["equalizer"], pre_equalizer_path=sim_param_dict["pre_equalizer"]["model_path"], ) # Creation of the AWGN Channel awgn_channel = Channel( mean=0, var=0, non_lin_coeff=sim_param_dict["channel_parameters"]["non_lin_coeff"], iq_imbalance=sim_param_dict["channel_parameters"]["iq_imbalance"], channel_taps=sim_param_dict["channel_parameters"]["channel_taps"], ) # Creation of the filepath filename = generate_path_name_from_param_dict(sim_param_dict, add_on_path) print("Results will be printed in : ", filename) # Creation of the PHY Layer phy_layer = PhyLayer(emiter, receiver, awgn_channel, sim_param_dict["pre_equalizer"]["feed_back_freq"]) nb_tries = 0 ind_eb_n0 = 0 # Launch the simulation while (ind_eb_n0 < len(eb_n0_db)) and (not (ind_eb_n0 > 0) or (ber[ind_eb_n0 - 1] > 0 and nb_tries < max_test)): # Init variables nb_tries = 0 nb_frame_error = 0 global_error_nb = 0 # Set the snr for the channel phy_layer.channel.set_var( eb_n0_db[ind_eb_n0], sim_param_dict["modulation"]["modulation_order"]) # For the moment, we consider that the noise variance is not estimated # but is Genie aided. if sim_param_dict["equalizer"] == "MMSE": receiver.equalizer.set_noise_var(phy_layer.channel.var) # Monte-Carlo method while (nb_tries < max_test) and ( nb_frame_error < sim_param_dict["m_c_parameters"]["min_error_frame"]): # Generation of the frames frame = np.random.randint(0, high=2, size=sim_param_dict["frame_length"]) # Send the frame to the physical layer recieved_frame = phy_layer.process_frame(frame) # Counting errors errors_num = np.sum(recieved_frame != frame) # Look at the number of mistake if errors_num > 0: # Add the number of frame errors nb_frame_error = nb_frame_error + 1 global_error_nb = global_error_nb + errors_num # Increase the number of tries nb_tries = nb_tries + 1 # Update error vectors ber[ind_eb_n0] = global_error_nb / (nb_tries * sim_param_dict["frame_length"]) fer[ind_eb_n0] = nb_frame_error / nb_tries # ser[ind_eb_n0] = print( "At ", np.floor(100 * ind_eb_n0 / len(eb_n0_db)), " %", ", BER = ", ber[ind_eb_n0], ", FER = ", fer[ind_eb_n0], " for Eb/N0 = ", eb_n0_db[ind_eb_n0], " dB", ", SNR = ", snr_db[ind_eb_n0], "dB", " nb_tries = ", nb_tries, ) # Increase the snr index ind_eb_n0 += 1 ber_dict = { "sim_param": sim_param_dict, "results": { "eb_n0_db": eb_n0_db, "snr_db": snr_db, "ber": ber, "fer": fer }, } # Save results in file with open(filename, "wb") as handle: pickle.dump(ber_dict, handle) # TODO : Use the function of utils when they will be well-implemented # Display results figures plt.plot(eb_n0_db, ber, "b") plt.yscale("log") plt.title("BER results") plt.xlabel("Eb/N0 (dB)") plt.ylabel("BER") plt.grid(True) plt.show() plt.plot(snr_db, fer, "b") plt.yscale("log") plt.title("FER results") plt.xlabel("SNR (dB)") plt.ylabel("FER") plt.grid(True) plt.show()
x_plot = Plot.Plot(plot_frame1, "both", "left", "True") y_plot = Plot.Plot(plot_frame1, "both", "right", "True") z_plot = Plot.Plot(plot_frame2, "both", "left", "True") throttle_plot = Plot.Plot(plot_frame2, "both", "right", "True") config = Config.Config("config.ini") controller = Controller.Controller(root, "x", "bottom", "False", sender, config) plot_handler = PlotHandler.PlotHandler(x_plot, y_plot, z_plot, throttle_plot) recorder = Recorder.Recorder(args.recordpath) def d(event): plot_handler.redraw() root.bind('<Configure>', d) if args.mode == 0: recorder.start_recording() receiver = Receiver.Receiver(client_socket, plot_handler, recorder, controller) elif args.mode == 1: receiver = Receiver.Receiver(client_socket, plot_handler, None, controller) recorder.playback_recording(receiver, args.recordpath) else: print("unrecognized mode") tk.mainloop()
class Measurement: #Constructor def __init__(self, fftSize, samp_rate, measureTime, gain, c_freq, config, user, window): self.user = user self.fftSize = int(fftSize) self.samp_rate = float(samp_rate) self.bandwidth = self.samp_rate self.measureTime = int(measureTime) self.gain = int(gain) self.c_freq = float(c_freq) self.index = '' self.config = config self.configfil = "/home/" + self.user + "/GNURadio-FFTS/FFTS.config" self.loops = 1 self.switched = 1 self.measureTimeTotPow = 5 self.adjust = 0 self.window = window #Initate GnuRadio flowgraph self.receiver = Receiver(self.fftSize, self.samp_rate, self.gain, self.c_freq) self.receiver.blks2_selector_0.set_output_index(1) self.receiver.blks2_selector_1.set_output_index(1) #Creates usrp object from receiver self.usrp = self.receiver.uhd_usrp_source_0 self.receiver.start() ######### GPIO INIT ######### ############################# num_bits = 11 mask = (1 << num_bits) - 1 ######### Initiate SR and DV pin ############## #Defines whether this pin is controlled automatically by FPGA,1, or manual,0 self.usrp.set_gpio_attr("FP0", "CTRL", 0x0, mask) #Defines whether this pin is an output(1) or input(0) self.usrp.set_gpio_attr("FP0", "DDR", 0x0, mask) def set_loops(self, loops): self.loops = loops #Set optimal gain to utilize full dynamic range of ADC def meas_adjust(self, channel): histData = [] print "Adjusting gain" self.config.set('CTRL', 'state', 'adjusting') with open(self.configfil, 'wb') as configfile: self.config.write(configfile) timedat = 1.5 #Read samples for 1 second on current gain gain = 5 #Gain start value self.set_gain(gain, channel) while gain < 31 and gain != -1: print gain L = [] L1 = [] L2 = [] end = time.time() + timedat while time.time() <= end: time.sleep(100 / (self.samp_rate)) if channel == 0: L.append(self.receiver.get_probe_var()) else: L.append(self.receiver.get_probe_var_1()) for i in L: if i > 0.5: L1.append(i) else: L2.append(i) hundra = len(L) print(len(L1) / float(hundra)) if ( len(L1) / float(hundra) ) < 0.05: #As long as the samples above the value 0.5 are under 5% of all collected samples continue to increase gain gain += 1 self.set_gain(gain, channel) print "Set gain on channel" + str(channel) + ": " print self.usrp.get_gain(channel) del L, L1, L2 elif gain == 30: histData = L i = -1 break else: histData = L i = -1 del L, L1, L2 break print "Final gain channel " + str(channel) + ": " print self.usrp.get_gain(channel) self.config.set('USRP', 'gain_ch' + str(channel), str(self.usrp.get_gain(channel))) self.config.set('CTRL', 'state', 'ready') with open(self.configfil, 'wb') as configfile: self.config.write(configfile) np.save( '/home/' + self.user + '/Documents/sampleDist_ch' + str(channel) + '.npy', histData) #Start measurement def measure_start(self): if self.adjust == 1: #Adjust gain? self.meas_adjust(0) self.meas_adjust(1) else: self.date = ephem.now().tuple() #Date for FITS-file self.sig_time = 0 self.ref_time = 0 self.totpowTime = 0 self.config.set('CTRL', 'abort', '0') self.config.set('CTRL', 'state', 'integrating') with open(self.configfil, 'wb') as configfile: self.config.write(configfile) index = 0 start = time.time() while index < self.loops: self.set_index(index) if self.switched == 1 and int(self.config.get('CTRL', 'abort')) != 1: self.measure_switch_in() elif self.switched != 1 and int( self.config.get('CTRL', 'abort')) != 1: self.measure_tot_pow() self.counter = 0 self.sigCount = 0 self.refCount = 0 if int(self.config.get('CTRL', 'abort')) != 1: tc = Analyze(self.sigCount, self.refCount, index, self.fftSize, self.c_freq, self.samp_rate, self.switched, self.user) index += 1 stop = time.time() print "Total time: " print stop - start edit = 0 if int(self.config.get('CTRL', 'abort')) != 1: td = Finalize(index, self.fftSize, self.c_freq, self.samp_rate, edit, self.sig_time, self.ref_time, self.switched, self.totpowTime, self.user, self.date, self.sigCount) files = glob.glob('/tmp/ramdisk/*') for f in files: if f.endswith(self.index): os.remove(f) else: continue self.config.set('CTRL', 'state', 'ready') with open(self.configfil, 'wb') as configfile: self.config.write(configfile) def measure_tot_pow(self): try: os.remove('/tmp/ramdisk/dump1') os.remove('/tmp/ramdisk/dump2') os.remove('/tmp/ramdisk/dump3') os.remove('/tmp/ramdisk/dump4') except OSError: pass self.date = ephem.now().tuple() self.receiver.signal_file_sink_1.open("/tmp/ramdisk/sig0_0" + self.index) self.receiver.signal_file_sink_3.open("/tmp/ramdisk/sig1_0" + self.index) print self.measureTimeTotPow t_end = time.time() + self.measureTimeTotPow start = time.time() while time.time() <= t_end and int(self.config.get('CTRL', 'abort')) != 1: continue self.receiver.signal_file_sink_1.close() self.receiver.signal_file_sink_3.close() end = time.time() self.totpowTime += end - start #Measure and collect FFT files, Dicke-switched def measure_switch_in(self): #If dumpfile exists remove it try: os.remove('/tmp/ramdisk/dump1') os.remove('/tmp/ramdisk/dump2') os.remove('/tmp/ramdisk/dump3') os.remove('/tmp/ramdisk/dump4') except OSError: pass #SR pin logic, observe that pin logic might vary with with FPGA image S = int('00011', 2) R = int('00010', 2) #DV pin logic SN = int('00001', 2) RN = int('00000', 2) self.sigCount = 0 self.refCount = 0 countTwo = 0 while countTwo == 0: if self.usrp.get_gpio_attr( "FP0", "READBACK" ) == S: #Stream to sig sink if datavalid = 1 and SR = 1 countTwo = 1 t_end = time.time() + self.measureTime while time.time() <= t_end: if int(self.config.get('CTRL', 'abort')) == 1: break elif self.usrp.get_gpio_attr("FP0", "READBACK") == S: time.sleep(2e-3) #Blanking for GnuRadio delay start1 = time.time() self.receiver.signal_file_sink_1.open( "/tmp/ramdisk/sig0_" + str(self.sigCount) + self.index) self.receiver.signal_file_sink_3.open( "/tmp/ramdisk/sig1_" + str(self.sigCount) + self.index) while self.usrp.get_gpio_attr( "FP0", "READBACK" ) == S and int(self.config.get( 'CTRL', 'abort')) != 1 and time.time( ) <= t_end: #File sink closes if Datavalid = 0 continue self.receiver.signal_file_sink_1.close() self.receiver.signal_file_sink_3.close() stop1 = time.time() self.sig_time += stop1 - start1 print 'sig' self.sigCount += 1 while self.usrp.get_gpio_attr( "FP0", "READBACK") == SN or self.usrp.get_gpio_attr( "FP0", "READBACK") == RN: continue elif self.usrp.get_gpio_attr("FP0", "READBACK") == R: time.sleep(2e-3) start2 = time.time() self.receiver.signal_file_sink_1.open( "/tmp/ramdisk/ref0_" + str(self.refCount) + self.index) self.receiver.signal_file_sink_3.open( "/tmp/ramdisk/ref1_" + str(self.refCount) + self.index) while self.usrp.get_gpio_attr( "FP0", "READBACK" ) == R and int(self.config.get( 'CTRL', 'abort')) != 1 and time.time( ) <= t_end: #Close file sink datavalid = 0 continue self.receiver.signal_file_sink_1.close() self.receiver.signal_file_sink_3.close() stop2 = time.time() self.ref_time += stop2 - start2 print 'ref' self.refCount += 1 while self.usrp.get_gpio_attr( "FP0", "READBACK") == RN or self.usrp.get_gpio_attr( "FP0", "READBACK") == SN: continue else: break #Set integration time def set_int_time(self, int_time): self.measureTime = int(int_time) def set_adjust(self, adjust): self.adjust = int(adjust) def set_switched(self, switched): self.switched = int(switched) def set_time_totPow(self, totPowTime): self.measureTimeTotPow = int(totPowTime) #Set USRP gain def set_gain(self, gain, channel): self.gain = int(gain) self.usrp.set_gain(self.gain, channel) #Set the number of FFT channels def set_channels(self, channels): self.fftSize = int(channels) #Set USRP center frequency def set_c_freq(self, c_freq): self.c_freq = float(c_freq) * 1e6 self.usrp.set_center_freq(self.c_freq, 0) self.usrp.set_center_freq(self.c_freq, 1) #Set the sampling frequency equivalent to bandwidth since I/Q samples, however aliasing might occur for high/low freq def set_samp_rate(self, samp_rate): self.samp_rate = float(samp_rate) * 1e6 self.usrp.set_samp_rate(self.samp_rate) self.usrp.set_bandwidth(self.samp_rate, 0) self.usrp.set_bandwidth(self.samp_rate, 1) def set_index(self, count): self.index = str(count)
signal_cf=1700, clock_cf=2000, fdev=500, fs=48000, packet_size=128 + 16 + 32) print("done creating signal") from Receiver import * from Transmitter import * from HuffmanCode import * from checksum import * from sound import transmit, receive from bitarray import bitarray from checksum import Packet as Pack a = HuffmanCode() c = Receiver() print("started decoding") packets = receiveFromSignal(sig, packet_size=8 + 16 + 8, baud=400, signal_cf=1700, clock_cf=2000, fdev=500, fs=48000, duration=30, taps=15, width=100) print(packets) count = 0 acc = 0 print("ended decoding")
def conduct_experiment(self): """Провести эксперимент по имитации приемо-передачи. Эксперимент проводится count раз, затем вычисляется мат.ожидание и дисперсия битовой ошибки """ self.file.write("\n\n============ New imitation ===========") print "\n\n============ New imitation ===========" # Входные данные # Проводим инициализацию открытых атрибутов-данных класса данными из формы # Все данные из формы в формате Qstring переводим в питоновский string, а затем в float self.FD = int(str(self.ui.FD.text()) ) # Частота дискретизации аналогового несущего сигнала self.FDD = int(str(self.ui.FDD.text()) ) # Частота дискретизации цифрового исходного сигнала self.FC = int(str(self.ui.FC.text())) # Частота несущей self.N = int(str(self.ui.N.text())) # Количество передающихся символов self.SPEED = float(str( self.ui.SPEED.text())) # Символьная скорость (частота символов) self.duration = 1 / self.SPEED # Длительность импульса self.time_signal = self.N * self.duration # Длительность исходного сигнала из <N импульсов self.A_NOISE = float(str(self.ui.A_NOISE.text())) # Амплитуда шума self.A_SIGNAL = float(str( self.ui.A_SIGNAL.text())) # Амплитуда сигнала self.DETECTION_THRESHOLD = float( str(self.ui.DETECTION_THRESHOLD.value())) # Порог детектирования # Локальные переменные count = self.ui.EXPER_COUNT.value( ) # Необходимое количество экспериментов bit_error = [ ] # В списке храниться апостериорной вероятность битовой ошибки при каждом эксперименте # Проводим эксперимент <count> раз и вичисляем апостериорной вероятность битовой ошибки при каждом эксперименте for x in xrange(count): self.file.write("\n\nExperiment #" + str(x)) print "\nExperiment #", x # Конструируем объекты приемника и передатчика self.sender_obj = Sender(self.FD, self.FDD, self.FC, self.N, self.SPEED, self.A_NOISE, self.A_SIGNAL) self.receiver_obj = Receiver(self.FD, self.N, self.SPEED, self.DETECTION_THRESHOLD, self.file) # Имитируем передатчик self.sender_obj.generate_signal() self.sender_obj.encode_signal() self.sender_obj.genetare_noise() self.sender_obj.modulate_signal() # Имитируем приемник self.receiver_obj.demodulate_signal(self.sender_obj.noise_ASK) self.receiver_obj.decode_signal() # Сравниваем декодированную последовательность и исходную. # Считаем количество ошибочных битов error = 0.0 # Количество ошибочных битов for x in xrange(len(self.receiver_obj.decode_code)): if self.receiver_obj.decode_code[ x] != self.sender_obj.source_sequence[x]: error += 1 print "Decode sequence: ", self.receiver_obj.decode_code self.file.write("\nDecode sequence: " + str(self.receiver_obj.decode_code)) print "Source sequence: ", self.sender_obj.source_sequence self.file.write("\nSource sequence: " + str(self.sender_obj.source_sequence)) # Вычисление апостериорной вероятности появления битовой ошибки в эксперименте. # Вычисляется как отношение количества ошибочных битов к длине последовательности. # Вычисленная вероятноть заноситься в список <bit_error> при каждом эксперименте # для формирования выборки if error != 0: bit_error.append(error / len(self.receiver_obj.decode_code)) print "Sequences are not matched" self.file.write("\nSequences are not matched") else: bit_error.append(0) # Вычисление мат. ожидания вероятности появления битовой ошибки # Считаем как среднеарифметическое значение expected_value = 0.0 # Мат.ожидание for x in xrange(count): expected_value += bit_error[x] expected_value /= float(count) self.ui.EXPECTED_VALUE.setText(str(expected_value)) self.file.write("\n\nExpected value: " + str(expected_value)) print "\nExpected value: ", expected_value # Вычисление дисперсии вероятности появления битовой ошибки # Дисперсия вычисляется по формуле: (sum(Xi^2) - sum(Xi)^2 / n) / n - 1 sum_of_squares = 0.0 for x in xrange(count): sum_of_squares += bit_error[x]**2 square_of_the_sum = 0.0 for x in xrange(count): square_of_the_sum += bit_error[x] square_of_the_sum *= square_of_the_sum dispersion = (sum_of_squares - square_of_the_sum / count) / (count - 1) self.ui.DISPERSION.setText(str(dispersion)) self.file.write("\nDispersion: " + str(dispersion)) print "Dispersion: ", dispersion
class MainWindow(QMainWindow, Ui_MainWindow): parID_signal = QtCore.Signal(str) quitNetclient = QtCore.Signal() def __init__(self, parent=None): # Initialize the constructor super(MainWindow, self).__init__(parent) # Removes glances file - not needed if os.path.exists('GlancesNetclient.csv'): os.remove("GlancesNetclient.csv") # Define variables # Change to True to recreate post-drive screen self.summary = False self.initAll = False self.endDrive = False txtList = np.genfromtxt('largeSet.txt', dtype='str', delimiter='\n') ansList = np.genfromtxt('largeAnsSet.txt', dtype='int', delimiter='\n') # Creates the list of words with corresponding answer keys self.responseList = np.vstack((txtList, ansList)).T rnd = np.random.randint(0, self.responseList.shape[0] / 10) self.allList = self.responseList[rnd * 10:rnd * 10 + 10, :] self.counter = 0 # Defines the counter to go over list of phrases and answers self.response = np.nan # Keeps track of the response self.trialNum = 0 # Keeps track of the trial number self.interact = 0 # Keeps track of the number of interactions # Set up the GUI self.setupUi(self) # Show the application in fullscreen self.showFullScreen() # Setting the frames to be full screen desktop = QDesktopWidget() width = desktop.geometry().width() height = desktop.geometry().height() # Create the graph object self.graph = Graph(width, height) # Hide all the frames except the initial self.introframe.show() self.readyframe.hide() self.feedbackframe.hide() self.gameframe.hide() self.endframe.hide() # Position and resize the frames. self.introframe.move(0, 0) self.introframe.resize(width, height) self.readyframe.move(0, 0) self.readyframe.resize(width, height) self.feedbackframe.move(0, 0) self.feedbackframe.resize(width, height) self.gameframe.move(0, 0) self.gameframe.resize(width, height) self.endframe.move(0, 0) self.endframe.resize(width, height) ''' BUTTONS ''' # Button "DONE" on click QtCore.QObject.connect(self.btnDone, QtCore.SIGNAL("clicked()"), self.showReadyFrame) # Moving UP/DOWN buttons QtCore.QObject.connect(self.btnUp, QtCore.SIGNAL("clicked()"), self.moveUp) QtCore.QObject.connect(self.btnDown, QtCore.SIGNAL("clicked()"), self.moveDown) self.btnUp.setEnabled(False) self.btnUp.setStyleSheet("QPushButton{background-color:#B0B0B0;}") # Selecting buttons QtCore.QObject.connect(self.btnLabelUp, QtCore.SIGNAL("clicked()"), self.Uphighlight) QtCore.QObject.connect(self.btnLabelDown, QtCore.SIGNAL("clicked()"), self.Downhighlight) # Button "SUBMIT" on click QtCore.QObject.connect(self.btnSubmit, QtCore.SIGNAL("clicked()"), self.submitFun) # Button "START" on click QtCore.QObject.connect(self.btnStart, QtCore.SIGNAL("clicked()"), self.showGameFrame) # Button "END" on click QtCore.QObject.connect(self.goButton, QtCore.SIGNAL("clicked()"), self.showPostDrive) ''' HIGHLIGHTING BUTTONS ''' # This modifies the highligh sequence of the labels def Uphighlight(self): self.btnLabelUp.setStyleSheet( "QPushButton{border:0px;margin:0px;padding:0px;color:white;background-color:blue;text-align:left;}" ) self.btnLabelDown.setStyleSheet( "QPushButton{border:0px;margin:0px;padding:0px;color:black;background-color:white;text-align:left;}" ) self.response = self.counter # Increase counter for interactions with screen self.interact += 1 def Downhighlight(self): self.btnLabelDown.setStyleSheet( "QPushButton{border:0px;margin:0px;padding:0px;color:white;background-color:blue;text-align:left;}" ) self.btnLabelUp.setStyleSheet( "QPushButton{border:0px;margin:0px;padding:0px;color:black;background-color:white;text-align:left;}" ) tmp = self.counter self.response = tmp + 1 # Increase counter for interactions with screen self.interact += 1 ''' UP/DOWN BUTTONS ''' # Functions for moving up or down in the text file def moveUp(self): if self.counter == 0: self.counter = 0 else: self.counter = self.counter - 2 if self.counter == 0: self.btnUp.setEnabled(False) self.btnUp.setStyleSheet( "QPushButton{background-color:#B0B0B0;}") self.btnDown.setEnabled(True) self.btnDown.setStyleSheet("QPushButton{background-color:" ";}") # Modifying labels from buttons self.response = np.nan self.btnLabelUp.setStyleSheet( "QPushButton{border:0px;margin:0px;padding:0px;color:black;background-color:white;text-align:left;}" ) self.btnLabelDown.setStyleSheet( "QPushButton{border:0px;margin:0px;padding:0px;color:black;background-color:white;text-align:left;}" ) # Setting up labels counter = self.counter self.btnLabelUp.setText( QtGui.QApplication.translate("MainWindow", self.allList[counter, 0], None, QtGui.QApplication.UnicodeUTF8)) self.btnLabelDown.setText( QtGui.QApplication.translate("MainWindow", self.allList[counter + 1, 0], None, QtGui.QApplication.UnicodeUTF8)) # Increase counter for interactions with screen self.interact += 1 def moveDown(self): if self.counter == len(self.allList) - 2: self.counter = len(self.allList) - 2 else: self.counter = self.counter + 2 if self.counter == len(self.allList) - 2: self.btnDown.setEnabled(False) self.btnDown.setStyleSheet( "QPushButton{background-color:#B0B0B0;}") self.btnUp.setEnabled(True) self.btnUp.setStyleSheet("QPushButton{background-color:" ";}") # Modifying labels from buttons self.response = np.nan self.btnLabelUp.setStyleSheet( "QPushButton{border:0px;margin:0px;padding:0px;color:black;background-color:white;text-align:left;}" ) self.btnLabelDown.setStyleSheet( "QPushButton{border:0px;margin:0px;padding:0px;color:black;background-color:white;text-align:left;}" ) # Setting up labels counter = self.counter self.btnLabelUp.setText( QtGui.QApplication.translate("MainWindow", self.allList[counter, 0], None, QtGui.QApplication.UnicodeUTF8)) self.btnLabelDown.setText( QtGui.QApplication.translate("MainWindow", self.allList[counter + 1, 0], None, QtGui.QApplication.UnicodeUTF8)) # Increase counter for interactions with screen self.interact += 1 ''' SHOW/HIDE FRAMES ''' # Showing all required frames def showReadyFrame(self): self.parID = self.editParticipantID.text() self.fileName = self.parID.split("_")[0] + "_" + self.parID.split( "_")[1] ''' SIMULATOR ''' if self.initAll == False and self.summary == False: # Initializing the NetClient self.netclient = NetClient(self.quitNetclient) self.netclient.glanceWarningSignal.connect( self.setGlanceWarning, QtCore.Qt.QueuedConnection) self.netclient.glanceDangerSignal.connect( self.setGlanceDanger, QtCore.Qt.QueuedConnection) self.netclient.glanceResetSignal.connect( self.resetGlance, QtCore.Qt.QueuedConnection) self.netclient.start() # Initializing the RECEIVER self.receiver = Receiver(self.netclient, self.parID_signal) self.receiver.terminateScreen.connect(self.showEndDrive, QtCore.Qt.QueuedConnection) self.receiver.start() self.parID_signal.emit(self.fileName) self.initAll = True # GUI part self.introframe.hide() self.feedbackframe.hide() self.gameframe.hide() self.endframe.hide() self.readyframe.show() self.resetGlance() # Only create the file if it does not exist if not os.path.exists( '../../participantData/Gamification/%s.csv' % self.fileName): with open( '../../participantData/Gamification/%s.csv' % self.fileName, 'wb') as csvfile: toFile = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL) toFile.writerow( ['Trial#', 'Phrase Selected', 'isCorrect', 'Interactions']) def showGameFrame(self): self.btnUp.setStyleSheet("QPushButton{background-color:#B0B0B0;}") self.btnDown.setStyleSheet("QPushButton{background-color:" ";}") self.btnUp.setEnabled(False) self.btnDown.setEnabled(True) # Set up the initial words counter = self.counter self.btnLabelUp.setText( QtGui.QApplication.translate("MainWindow", self.allList[counter, 0], None, QtGui.QApplication.UnicodeUTF8)) self.btnLabelDown.setText( QtGui.QApplication.translate("MainWindow", self.allList[counter + 1, 0], None, QtGui.QApplication.UnicodeUTF8)) self.response = np.nan self.btnLabelUp.setStyleSheet( "QPushButton{border:0px;margin:0px;padding:0px;color:black;background-color:white;text-align:left;}" ) self.btnLabelDown.setStyleSheet( "QPushButton{border:0px;margin:0px;padding:0px;color:black;background-color:white;text-align:left;}" ) self.introframe.hide() self.readyframe.hide() self.feedbackframe.hide() self.endframe.hide() self.gameframe.show() self.trialNum += 1 self.interact += 1 self.resetGlance() def submitFun(self): if self.endDrive == True: self.showEndDrive() else: if np.isnan(self.response): self.interact += 1 # Increase counter for interactions with screen if not np.isnan(self.response): # Incorrect response - Keeps on playing the game if int(self.allList[self.response, 1]) == 0: self.lblFeedback.setText( QtGui.QApplication.translate( "MainWindow", "Incorrect", None, QtGui.QApplication.UnicodeUTF8)) self.gameframe.hide() self.feedbackframe.show() self.interact += 1 # Increase counter for interactions with screen timer = QtCore.QTimer() correctVal = False if self.summary == False: timer.singleShot(1000, self.showGameFrame) else: timer.singleShot(1000, self.showEndDrive) # Correct response - Goes back to "Task Is Ready" Screen if int(self.allList[self.response, 1]) == 1: self.lblFeedback.setText( QtGui.QApplication.translate( "MainWindow", "Correct", None, QtGui.QApplication.UnicodeUTF8)) self.gameframe.hide() self.feedbackframe.show() self.interact += 1 # Increase counter for interactions with screen timer = QtCore.QTimer() correctVal = True timer.singleShot(1000, self.showReadyFrame) # Writing results to file with open( '../../participantData/Gamification/%s.csv' % self.fileName, 'ab') as csvfile: toFile = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL) toFile.writerow([ '%d' % self.trialNum, '%s' % self.allList[self.response, 0], '%s' % self.allList[self.response, 1], '%d' % self.interact ]) # Randomizing the next trial if correct if correctVal == True: rnd = np.random.randint(0, self.responseList.shape[0] / 10) self.allList = self.responseList[rnd * 10:rnd * 10 + 10, :] correctVal = False self.counter = 0 # Resets counter for answers self.interact = 0 # Resets counter for interactions with screen def showEndDrive(self): self.label_loading.setStyleSheet( "QLabel{background-color:white; color:white;}") self.endDrive = True self.introframe.hide() self.readyframe.hide() self.feedbackframe.hide() self.gameframe.hide() self.endframe.show() with open('../../participantData/Gamification/%s.csv' % self.fileName, 'ab') as csvfile: toFile = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL) toFile.writerow(['%d' % self.interact]) ''' SIMULATOR ''' if self.summary == False: self.quitNetclient.emit() self.netclient.glanceWarningSignal.disconnect( self.setGlanceWarning) self.netclient.glanceDangerSignal.disconnect(self.setGlanceDanger) self.netclient.glanceResetSignal.disconnect(self.resetGlance) self.netclient.exit(0) self.receiver.exit(0) def setGlanceWarning(self): # Change the style of the glance self.lblGlance.setStyleSheet( "background-color:#f0ad4e; margin:0px 250px; padding-bottom:30px;") self.lblGlance_2.setStyleSheet( "background-color:#f0ad4e; margin:0px 250px; padding-bottom:30px;") # self.lblGlance_2.setStyleSheet("background-color:#f0ad4e; margin:0px 350px; padding-bottom:30px; max-height: 64px;") def setGlanceDanger(self): # Change the style of the glance self.lblGlance.setStyleSheet( "background-color:#d9534f; margin:0px; padding-bottom:30px;") self.lblGlance_2.setStyleSheet( "background-color:#d9534f; margin:0px; padding-bottom:30px;") # self.lblGlance_2.setStyleSheet("background-color:#d9534f; margin:0px 100px; padding-bottom:30px; max-height: 64px;") def resetGlance(self): # Change the style of the glance self.lblGlance.setStyleSheet( "background-color:white; margin:0px; padding-bottom:30px;") self.lblGlance_2.setStyleSheet( "background-color:white; margin:0px; padding-bottom:30px;") def showPostDrive(self): self.goButton.setEnabled(False) self.label_loading.setStyleSheet("QLabel{background-color:" "; color:" ";}") timer = QtCore.QTimer() timer.singleShot(50, self.endGraph) def endGraph(self): self.graph.createGraph(self.parID, 18, 32) self.setCentralWidget(self.graph)
def runThreads(self): self.threadTransmiter = Transmiter(1, "TRANS", 5, 1, self) self.threadReceiver = Receiver(1, "REC", 2, 2) self.threadTransmiter.start() self.threadReceiver.start()
random_bits = np.random.randint(2, size=10) # to test transmission # channel impulse responses - modeled as an LTI system with finite impulse response #h_test = np.array([1, 1/2, 3/4, -2/7]) #ch_test = chnl.Channel(h_test, np.ones(1), Fs, T_pulse, 'Test') #ch_test = chnl.IndoorChannel(Fs, T_pulse) ch_test = chnl.OutdoorChannel(Fs, T_pulse) eq_zf = eqz.ZFEqualizer(ch_test, Fs, T_pulse) eq_mmse = eqz.MMSEEqualizer(ch_test, Fs, T_pulse, noise_var=noise_var) equalizers = [eq_zf, eq_mmse] # transmitter and receiver - #tx_test = tx.HalfSineTransmitter(T_pulse, Fs) tx_test = tx.SRRCTransmitter(alpha, T_pulse, Fs, K) rx_test = rx.MatchedReceiver(tx_test) for equalizer in equalizers: print('Working on- Equalizer: ', equalizer.name, ', Channel: ', ch_test.name, ' ...') #test_equalizer_response(equalizer, noise = noise_var, SAVED = True) #test_equalization_only_channel(equalizer, ch_test, , random_bits, Fs) #test_equalization_no_noise(equalizer, ch_test, tx_test, rx_test, random_bits) test_eye_diagram(equalizer, ch_test, tx_test, rx_test, noise_var=noise_var, SAVED=True) #test_sampling(equalizer, ch_test, tx_test, rx_test, random_bits)
class MainWindowClass(QtGui.QMainWindow): """Класс главного окна программы. Наследуется от QMainWindow, содержит в себе класс интерфейса Ui_MainWindow. Класс Ui_MainWindow сгенерирован при помощи команды <pyuic4> из файла form.ui. Описание формы form.ui сгенерировано через Designer, идущего в составе PyQt4 """ def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) # Сигналы и слоты self.connect(self.ui.CONDUCT_EXPERIMENT, QtCore.SIGNAL('clicked()'), self.conduct_experiment) # Проведение эксперимента self.connect(self.ui.PLOT_GRAPH, QtCore.SIGNAL('clicked()'), self.plot_graph) # Построение графиков # Дескриптор файла, в котором храниться лог self.file = open("log.txt", 'w') def __del__(self): self.file.close() def conduct_experiment(self): """Провести эксперимент по имитации приемо-передачи. Эксперимент проводится count раз, затем вычисляется мат.ожидание и дисперсия битовой ошибки """ self.file.write("\n\n============ New imitation ===========") print "\n\n============ New imitation ===========" # Входные данные # Проводим инициализацию открытых атрибутов-данных класса данными из формы # Все данные из формы в формате Qstring переводим в питоновский string, а затем в float self.FD = int(str(self.ui.FD.text()) ) # Частота дискретизации аналогового несущего сигнала self.FDD = int(str(self.ui.FDD.text()) ) # Частота дискретизации цифрового исходного сигнала self.FC = int(str(self.ui.FC.text())) # Частота несущей self.N = int(str(self.ui.N.text())) # Количество передающихся символов self.SPEED = float(str( self.ui.SPEED.text())) # Символьная скорость (частота символов) self.duration = 1 / self.SPEED # Длительность импульса self.time_signal = self.N * self.duration # Длительность исходного сигнала из <N импульсов self.A_NOISE = float(str(self.ui.A_NOISE.text())) # Амплитуда шума self.A_SIGNAL = float(str( self.ui.A_SIGNAL.text())) # Амплитуда сигнала self.DETECTION_THRESHOLD = float( str(self.ui.DETECTION_THRESHOLD.value())) # Порог детектирования # Локальные переменные count = self.ui.EXPER_COUNT.value( ) # Необходимое количество экспериментов bit_error = [ ] # В списке храниться апостериорной вероятность битовой ошибки при каждом эксперименте # Проводим эксперимент <count> раз и вичисляем апостериорной вероятность битовой ошибки при каждом эксперименте for x in xrange(count): self.file.write("\n\nExperiment #" + str(x)) print "\nExperiment #", x # Конструируем объекты приемника и передатчика self.sender_obj = Sender(self.FD, self.FDD, self.FC, self.N, self.SPEED, self.A_NOISE, self.A_SIGNAL) self.receiver_obj = Receiver(self.FD, self.N, self.SPEED, self.DETECTION_THRESHOLD, self.file) # Имитируем передатчик self.sender_obj.generate_signal() self.sender_obj.encode_signal() self.sender_obj.genetare_noise() self.sender_obj.modulate_signal() # Имитируем приемник self.receiver_obj.demodulate_signal(self.sender_obj.noise_ASK) self.receiver_obj.decode_signal() # Сравниваем декодированную последовательность и исходную. # Считаем количество ошибочных битов error = 0.0 # Количество ошибочных битов for x in xrange(len(self.receiver_obj.decode_code)): if self.receiver_obj.decode_code[ x] != self.sender_obj.source_sequence[x]: error += 1 print "Decode sequence: ", self.receiver_obj.decode_code self.file.write("\nDecode sequence: " + str(self.receiver_obj.decode_code)) print "Source sequence: ", self.sender_obj.source_sequence self.file.write("\nSource sequence: " + str(self.sender_obj.source_sequence)) # Вычисление апостериорной вероятности появления битовой ошибки в эксперименте. # Вычисляется как отношение количества ошибочных битов к длине последовательности. # Вычисленная вероятноть заноситься в список <bit_error> при каждом эксперименте # для формирования выборки if error != 0: bit_error.append(error / len(self.receiver_obj.decode_code)) print "Sequences are not matched" self.file.write("\nSequences are not matched") else: bit_error.append(0) # Вычисление мат. ожидания вероятности появления битовой ошибки # Считаем как среднеарифметическое значение expected_value = 0.0 # Мат.ожидание for x in xrange(count): expected_value += bit_error[x] expected_value /= float(count) self.ui.EXPECTED_VALUE.setText(str(expected_value)) self.file.write("\n\nExpected value: " + str(expected_value)) print "\nExpected value: ", expected_value # Вычисление дисперсии вероятности появления битовой ошибки # Дисперсия вычисляется по формуле: (sum(Xi^2) - sum(Xi)^2 / n) / n - 1 sum_of_squares = 0.0 for x in xrange(count): sum_of_squares += bit_error[x]**2 square_of_the_sum = 0.0 for x in xrange(count): square_of_the_sum += bit_error[x] square_of_the_sum *= square_of_the_sum dispersion = (sum_of_squares - square_of_the_sum / count) / (count - 1) self.ui.DISPERSION.setText(str(dispersion)) self.file.write("\nDispersion: " + str(dispersion)) print "Dispersion: ", dispersion def plot_graph(self): """Построить графики """ # plot_signal(x, y, title, (list)labelx, (list)labley, position) plot_signal(arange(0, self.time_signal, (1.0 / self.FDD)), self.sender_obj.source_signal, 'Random source sequence', 'time', '', 1) plot_signal( arange(0, len(self.sender_obj.encoded_signal) * self.duration, (1.0 / self.FD)), self.sender_obj.noise_ASK, 'Noised ASK', 'time', '', 3) plot_signal( arange(0, len(self.receiver_obj.receive_sequence) * self.duration, (1.0 / self.FD)), self.receiver_obj.rectified_ASK, 'Rectified ASK', 'time', '', 5) # Для того, что бы отобразить декодированную последователоность символов, представим их в виде импульсов # длительности <duration> decode_signal = [] for x in range(0, len(self.receiver_obj.decode_code)): decode_signal += [ self.receiver_obj.decode_code[x] for y in arange(0, self.duration, (1.0 / self.FDD)) ] plot_signal( arange(0, len(self.receiver_obj.decode_code) * self.duration, (1.0 / self.FDD)), decode_signal, 'Decode sequence', 'time', '', 7) # Отображение графиков pylab.show()
import Receiver import threading import WalshTableGenerator import Analysis if __name__ == '__main__': totalReceiver = int(input('Enter number of receivers : ')) wTable = WalshTableGenerator.getWalshTable(totalReceiver) output_file = "to.txt" receiverThreadPool = [] receiverList = [] for index in range(0, totalReceiver): new_receiver = Receiver.Receiver(index, output_file, wTable[index]) receiverList.append(new_receiver) new_receiver_thread = threading.Thread( target=new_receiver.startReceive, args=()) receiverThreadPool.append(new_receiver_thread) new_receiver_thread.start() for index in range(0, totalReceiver): receiverThreadPool[index].join() pktCount = 0 totalTime = 0 for index in range(0, totalReceiver): pktCount += receiverList[index].report.pktCount totalTime += receiverList[index].report.totalTime totalTime /= totalReceiver
import Sender import Receiver if __name__ == "__main__": res = Sender.Sender(open("./history.text", "w+"), open("./accepted.txt", "w+"), open("./unaccepted.txt", "w+")) res.enable(Receiver.Receiver()) print(res.times) res.history.close() res.accepted.close() res.unaccepted.close()
bit = readInput(file_name) sder = sender.Sender(bit) # sder.plotByChanel(n_chanel=0) # sder.plotByChanel(n_chanel=1) time_domain = sder.generateTimeDomain() sder.plotTimeDomain() # print('time_domain:') # print(time_domain) print('---------------------') recver = receiver.Receiver(time_domain, n_sample=sder.N_SAMPLE, n_subcarrier=sder.N_SUB_CARRIER) recver.generateFrequencyDomain() recver.plotGraph() # print('avgImX:') # print(avgImX) # print('avgImX size = {}'.format(len(avgImX))) # for i, val in enumerate(avgImX): # if np.abs(val) > 0.01: # print(i, val) # # print('avgReX:') # print(avgReX) # print('avgReX size = {}'.format(len(avgReX))) # for i, val in enumerate(avgReX):