def index(): user = get_current_user() date = datetime.now().strftime('%A, %B %d') year = datetime.utcnow().year if not user: return render_template('login.html', app_id=FACEBOOK_APP_ID, channel_url=channel(), name=FACEBOOK_APP_NAME, year=year) if user.consented: try: graph = facebook.GraphAPI(user.get_short_term_token().access_token) profile = graph.get_object('me') # Decide what form we want to show the user if user.has_answered_advanced_questions_recently(): mood_form = BasicMoodForm() else: mood_form = AdvancedMoodForm() return render_template('index.html', access_token=user.get_short_term_token() \ .access_token, app_id=FACEBOOK_APP_ID, channel_url=channel(), date=date, mood_form=mood_form, me=profile, name=FACEBOOK_APP_NAME, user=user, year=year) except facebook.GraphAPIError: return render_template('login.html', app_id=FACEBOOK_APP_ID, channel_url=channel(), name=FACEBOOK_APP_NAME, year=year) else: graph = facebook.GraphAPI(user.get_short_term_token().access_token) profile = graph.get_object('me') return render_template('consent.html', consent_form=ConsentForm(), me=profile, user=user)
# Train Decoder # ----------------- for idx in range(args.num_train_Dec): optimizer_Dec.zero_grad() # Sample noise as generator input #z = Variable(Tensor(np.random.normal(0, 1, (imgs.shape[0], args.latent_dim)))) u = torch.randint(0, 2, (args.block_len, 1), dtype=torch.float).to(device) # Generate a batch of images gen_imgs = generator(real_imgs, u) # Loss measures generator's ability to fool the discriminator received_imgs = channel(gen_imgs, args.noise_std, channel_type=args.channel_type, device=device) decoded_info = decoder(received_imgs) # train decoder only for decoder. dec_loss = BCELoss(decoded_info, u) dec_loss.backward() optimizer_Dec.step() # --------------------- # Train Discriminator # --------------------- for idx in range(args.num_train_D): optimizer_D.zero_grad()
from math import sqrt from utils import channel, binary_channel, hamming_distance, get_distribution, np_to_number from utils import compute_mutual, compute_joint, compute_marginal_z, uniform_error_channel from utils import verify_encoder_decoder, verify_encoder_channel_decoder, get_many_z_bsc from tqdm import tqdm import matplotlib.pyplot as plt from itertools import product from mpl_toolkits.mplot3d import Axes3D print("TASK 1\n") x = np.array([1, 0, 0, 1, 0, 0, 0]) z = [] y = [] for i in tqdm(range(10**6)): legitimate, eve = channel(x) y.append(legitimate) z.append(eve) y_unique, y_counts = np.unique(y, return_counts=True, axis=0) z_unique, z_counts = np.unique(z, return_counts=True, axis=0) combinations = np.concatenate([y, z], axis=1) comb_unique, comb_counts = np.unique(combinations, return_counts=True, axis=0) p_z = np.zeros((2**7)) p_y = np.zeros((2**7)) p_yz = np.zeros((2**14)) y_unique = [np_to_number(i) for i in y_unique] z_unique = [np_to_number(i) for i in z_unique] comb_unique = [np_to_number(i) for i in comb_unique] p_z[z_unique] = z_counts / np.sum(z_counts) p_y[y_unique] = y_counts / np.sum(y_counts)
def __init__(self): grc_wxgui.top_block_gui.__init__(self, title="Communication System Graphical Analyzer (LAPS/UFCG)") ################################################## # Default Variables ################################################## self.sps = 2 self.snr = 20 self.symbol_rate = 140000 self.mod_type = "DBPSK" self.view = 1 self.band= 200 self.excess_bw=0.35 self.fading_flag = False self.fdts = -8 self.fading_state_rx = False ################################################## # Blocks Definition ################################################## #A bit stream of 1's is generated at the source, scrambled, #modulated and sent to the input of an AWGN channel. #random.seed(42) #self.source = gr.vector_source_b([random.randint(0, 2) for i in range(0,10^8)], True) self.source = gr.vector_source_b((1,), True, 1) self.thottle = gr.throttle(gr.sizeof_char,10e5) self.scrambler = gr.scrambler_bb(0x40801, 0x92F72, 20) #Taxa de simbolos constante self.pack = gr.unpacked_to_packed_bb(1, gr.GR_MSB_FIRST) self.modulator = utils.mods[self.mod_type](self.sps,excess_bw=self.excess_bw) self.channel = utils.channel(1/10.0**(self.snr/10.0),self.band,self.symbol_rate,self.sps) #The noisy signal is demodulated, descrambled and the BER #is estimated by the ber_estim block using the receiver #density of 0 bits. self.demodulator = utils.demods[self.mod_type](self.sps,excess_bw=self.excess_bw) self.descrambler = gr.descrambler_bb(0x40801, 0x92F72, 20) self.char2float = gr.char_to_float() self.mov_average = gr.moving_average_ff(524288, 1/524288., 10000) self.ber = utils.ber_estim() #self.ber = utils.ber_estim_simple(3) ################################################## # GUI Elements Definition ################################################## #Defines an adds FFT Window to GUI self.fft = fftsink.fft_sink_c(self.GetWin(), sample_rate=self.symbol_rate*self.sps, baseband_freq=5e6) self.GridAdd(self.fft.win, 0,3,4,3) self.ctr= gr.complex_to_real(1) #Defines and adds SNR slider to GUI _snr_sizer = wx.BoxSizer(wx.HORIZONTAL) self._snr_text_box = forms.text_box(parent=self.GetWin(), sizer=_snr_sizer, value=self.snr, callback=self.callback_snr, label=" SNR (dB)", converter=forms.float_converter(), proportion=0) self._snr_slider = forms.slider(parent=self.GetWin(), sizer=_snr_sizer, value=self.snr, callback=self.callback_snr, minimum=0, maximum=20, style=wx.RA_HORIZONTAL, proportion=1) self.GridAdd(_snr_sizer, 4, 3, 1, 3) #Defines and adds bandwidth slider to GUI band_sizer = wx.BoxSizer(wx.HORIZONTAL) self.band_text_box = forms.text_box(parent=self.GetWin(), sizer=band_sizer, value=self.band, callback=self.callback_band, label="Bandwidth (kHz)", converter=forms.float_converter(), proportion=0) self.band_slider = forms.slider(parent=self.GetWin(), sizer=band_sizer, value=self.band, callback=self.callback_band, minimum=30, maximum=200, style=wx.RA_HORIZONTAL, proportion=1) self.GridAdd(band_sizer, 5, 3, 1, 3) #Defines and adds Rayleigh GUI elements fading_sizer = wx.BoxSizer(wx.HORIZONTAL) self.fading_text_box = forms.text_box(parent=self.GetWin(), sizer=fading_sizer, value=self.fdts, callback=self.callback_fading, label='Fading/log(FdTs)', converter=forms.float_converter(), proportion=0) self.fading_slider = forms.slider(parent=self.GetWin(), sizer=fading_sizer, value=self.fdts, callback=self.callback_fading, minimum=-8, maximum=-2, style=wx.RA_HORIZONTAL, proportion=1) self.GridAdd(fading_sizer, 6, 3, 1, 3) #Defines and adds modulation type chooser to GUI self._mod_type_chooser = forms.radio_buttons(parent=self.GetWin(), value=self.mod_type, callback=self.set_mod_type, label="Modulation", choices=["DBPSK", "DQPSK", "D8PSK"], labels=["DBPSK", "DQPSK", "D8PSK"], style=wx.RA_HORIZONTAL) self.GridAdd(self._mod_type_chooser, 7, 4, 1, 2) #Defines and adds signal source chooser self.sig_src_chooser = forms.radio_buttons(parent=self.GetWin(), value=self.view, callback=self.callback_view, label="Signal Source", choices=[0,1], labels=["Transmitter","Receiver"], style=wx.RA_VERTICAL) self.GridAdd(self.sig_src_chooser, 7,3,1,1) #Definition of the of constellation window and attachment to the GUI self.constel = constsink.const_sink_c(self.GetWin(), title="RX Constellation Plot", sample_rate=self.symbol_rate, const_size=256, mod=self.mod_type) self.GridAdd(self.constel.win,0,0,8,3) #Definition of the constellation sink window and attachment to the GUI self.number_sink = bersink.number_sink_f(self.GetWin(), sample_rate=self.symbol_rate) self.GridAdd(self.number_sink.win,8,0,1,6) ################################################## # Blocks Connections ################################################## #The necessary block connections to the system work as described above. self.connect(self.source, self.scrambler , self.thottle, self.pack) #self.connect(self.source , self.thottle, self.pack) self.connect(self.pack, self.modulator, self.channel, self.demodulator) self.connect(self.channel, self.fft) self.connect(self.demodulator.diffdec, self.constel) self.connect(self.demodulator, self.descrambler, self.char2float, self.mov_average) self.connect(self.mov_average, self.ber, self.number_sink)
foutput = netED(fake_enc.detach()).view(-1) errED_fake2 = criterion(foutput, labelf) errED_fake2.backward() errED_2 = errED_fake2 - errED_fake1 errED = (errED_1 + errED_2) / 2.0 optimizerED.step() ########## Train decoder, maximize decinfoloss ################################ netDec.zero_grad() # forward pass fake encoded images #fake_enc = netE(fake_img.detach(),u) # add noise to image nfake_enc = channel(fake_enc.detach(), args.noise) foutput = netDec(nfake_enc) errDec_fakeenc = criterion(foutput,u) errDec_fakeenc.backward() fber = errors_ber(foutput, u) #forward pass real encoded images # add noise to enc image nenc_img = channel(enc_img.detach(), args.noise) routput = netDec(nenc_img) errDec_realenc = criterion(routput,u) errDec_realenc.backward() rber = errors_ber(routput, u) errDec = (errDec_fakeenc + errDec_realenc)/2.0 #errDec.backward()
def __init__(self): grc_wxgui.top_block_gui.__init__( self, title="Communication System Graphical Analyzer (LAPS/UFCG)") ################################################## # Default Variables ################################################## self.sps = 2 self.snr = 20 self.symbol_rate = 140000 self.mod_type = "DBPSK" self.view = 1 self.band = 200 self.excess_bw = 0.35 self.fading_flag = False self.fdts = -8 self.fading_state_rx = False ################################################## # Blocks Definition ################################################## #A bit stream of 1's is generated at the source, scrambled, #modulated and sent to the input of an AWGN channel. #random.seed(42) #self.source = gr.vector_source_b([random.randint(0, 2) for i in range(0,10^8)], True) self.source = gr.vector_source_b((1, ), True, 1) self.thottle = gr.throttle(gr.sizeof_char, 10e5) self.scrambler = gr.scrambler_bb(0x40801, 0x92F72, 20) #Taxa de simbolos constante self.pack = gr.unpacked_to_packed_bb(1, gr.GR_MSB_FIRST) self.modulator = utils.mods[self.mod_type](self.sps, excess_bw=self.excess_bw) self.channel = utils.channel(1 / 10.0**(self.snr / 10.0), self.band, self.symbol_rate, self.sps) #The noisy signal is demodulated, descrambled and the BER #is estimated by the ber_estim block using the receiver #density of 0 bits. self.demodulator = utils.demods[self.mod_type]( self.sps, excess_bw=self.excess_bw) self.descrambler = gr.descrambler_bb(0x40801, 0x92F72, 20) self.char2float = gr.char_to_float() self.mov_average = gr.moving_average_ff(524288, 1 / 524288., 10000) self.ber = utils.ber_estim() #self.ber = utils.ber_estim_simple(3) ################################################## # GUI Elements Definition ################################################## #Defines an adds FFT Window to GUI self.fft = fftsink.fft_sink_c(self.GetWin(), sample_rate=self.symbol_rate * self.sps, baseband_freq=5e6) self.GridAdd(self.fft.win, 0, 3, 4, 3) self.ctr = gr.complex_to_real(1) #Defines and adds SNR slider to GUI _snr_sizer = wx.BoxSizer(wx.HORIZONTAL) self._snr_text_box = forms.text_box(parent=self.GetWin(), sizer=_snr_sizer, value=self.snr, callback=self.callback_snr, label=" SNR (dB)", converter=forms.float_converter(), proportion=0) self._snr_slider = forms.slider(parent=self.GetWin(), sizer=_snr_sizer, value=self.snr, callback=self.callback_snr, minimum=0, maximum=20, style=wx.RA_HORIZONTAL, proportion=1) self.GridAdd(_snr_sizer, 4, 3, 1, 3) #Defines and adds bandwidth slider to GUI band_sizer = wx.BoxSizer(wx.HORIZONTAL) self.band_text_box = forms.text_box(parent=self.GetWin(), sizer=band_sizer, value=self.band, callback=self.callback_band, label="Bandwidth (kHz)", converter=forms.float_converter(), proportion=0) self.band_slider = forms.slider(parent=self.GetWin(), sizer=band_sizer, value=self.band, callback=self.callback_band, minimum=30, maximum=200, style=wx.RA_HORIZONTAL, proportion=1) self.GridAdd(band_sizer, 5, 3, 1, 3) #Defines and adds Rayleigh GUI elements fading_sizer = wx.BoxSizer(wx.HORIZONTAL) self.fading_text_box = forms.text_box( parent=self.GetWin(), sizer=fading_sizer, value=self.fdts, callback=self.callback_fading, label='Fading/log(FdTs)', converter=forms.float_converter(), proportion=0) self.fading_slider = forms.slider(parent=self.GetWin(), sizer=fading_sizer, value=self.fdts, callback=self.callback_fading, minimum=-8, maximum=-2, style=wx.RA_HORIZONTAL, proportion=1) self.GridAdd(fading_sizer, 6, 3, 1, 3) #Defines and adds modulation type chooser to GUI self._mod_type_chooser = forms.radio_buttons( parent=self.GetWin(), value=self.mod_type, callback=self.set_mod_type, label="Modulation", choices=["DBPSK", "DQPSK", "D8PSK"], labels=["DBPSK", "DQPSK", "D8PSK"], style=wx.RA_HORIZONTAL) self.GridAdd(self._mod_type_chooser, 7, 4, 1, 2) #Defines and adds signal source chooser self.sig_src_chooser = forms.radio_buttons( parent=self.GetWin(), value=self.view, callback=self.callback_view, label="Signal Source", choices=[0, 1], labels=["Transmitter", "Receiver"], style=wx.RA_VERTICAL) self.GridAdd(self.sig_src_chooser, 7, 3, 1, 1) #Definition of the of constellation window and attachment to the GUI self.constel = constsink.const_sink_c(self.GetWin(), title="RX Constellation Plot", sample_rate=self.symbol_rate, const_size=256, mod=self.mod_type) self.GridAdd(self.constel.win, 0, 0, 8, 3) #Definition of the constellation sink window and attachment to the GUI self.number_sink = bersink.number_sink_f(self.GetWin(), sample_rate=self.symbol_rate) self.GridAdd(self.number_sink.win, 8, 0, 1, 6) ################################################## # Blocks Connections ################################################## #The necessary block connections to the system work as described above. self.connect(self.source, self.scrambler, self.thottle, self.pack) #self.connect(self.source , self.thottle, self.pack) self.connect(self.pack, self.modulator, self.channel, self.demodulator) self.connect(self.channel, self.fft) self.connect(self.demodulator.diffdec, self.constel) self.connect(self.demodulator, self.descrambler, self.char2float, self.mov_average) self.connect(self.mov_average, self.ber, self.number_sink)
def post_mood(): current_user = get_current_user() if current_user: short_term_token = current_user.get_short_term_token().access_token try: graph = facebook.GraphAPI(short_term_token) profile = graph.get_object('me') # Decide what form we want to show the user if current_user.has_answered_advanced_questions_recently(): form = BasicMoodForm() if form.validate_on_submit(): mood_rating = form.moods.data mood = Mood(rating=mood_rating) current_user.moods.append(mood) db.session.commit() return redirect('/') else: return render_template('index.html', access_token=short_term_token, app_id=FACEBOOK_APP_ID, channel_url=channel(), form=form, me=profile, name=FACEBOOK_APP_NAME, user=current_user) else: form = AdvancedMoodForm() if form.validate_on_submit(): mood_rating = form.moods.data hospital = form.hospital.data hospital_reason = form.hospital_reason.data medication = form.medication.data medication_reason = form.medication_reason.data mood = Mood(rating=mood_rating, hospital=hospital, hospital_bipolar_related=hospital_reason, medication=medication, medication_bipolar_related=medication_reason) current_user.moods.append(mood) db.session.commit() return redirect('/') else: return render_template('index.html', access_token=short_term_token, app_id=FACEBOOK_APP_ID, channel_url=channel(), form=form, me=profile, name=FACEBOOK_APP_NAME, user=current_user) except facebook.GraphAPIError: pass return render_template('login.html', app_id=FACEBOOK_APP_ID, channel_url=channel(), name=FACEBOOK_APP_NAME)