def __init__(self, in_th, min_th, max_th, delta_th, k):
        """
        CTOR
        @param in_th Initial threshold.
        @param min_th Minimum threshold.
        @param max_th Maximum threshold.
        @param k Bayesian k factor.
        """
        Logger.register('bayes_decision', ['threshold', 'decision', 'risk']) 

        self._feedback = self._feedback_prev =  -1
        self._delta_th = delta_th
        self._min_th_limit = min_th
        self._max_th_limit = max_th

        self._k = k
        self._th = in_th

        self.init(in_th)


	self._th_dec = {}

	self._xx = {};
	self._xx[0] = {0: "00", 1: "01"}
	self._xx[1] = {0: "10", 1: "11"}
    def __init__(self, th=0):
        """
        CTOR
        @param th Decision threshold.
        """
        ThresholdAlgorithm.__init__(self, th)
        Logger.register('energy_decision', ['energy', 'decision'])

	self._xx = {};
	self._xx[0] = {0: "00", 1: "01"}
	self._xx[1] = {0: "10", 1: "11"}
Пример #3
0
 def __init__(self, number_cpes, feedback_control, increase_rate, decrease_rate):
     """
     CTOR
     @param number_cpes Number of cpes.
     @param feedback_control
     @param increase_rate The increase rate (float).
     @param decrease_rate The decrease rate (float).
     """
     self._fb_cycle = 0
     self._reward = [1.0] * number_cpes
     self._total_idle = self._total_occ = 0
     Logger.register('sdc', ['decision', ])
Пример #4
0
    def __init__(self, name="PktBitRate"):
        """
        CTOR
        @param name Instance name.
        """
        OpERABase.__init__(self, name)

        self._pkts = {'cur': 0, 'total': 0, 'counting': 0, 'accumulated': 0}
        self._bps = {'cur': 0, 'total': 0, 'counting': 0}

        # OpERA base method
        self.register_scheduling(self._tick, delay_sec=1)  # pylint: disable=E1101

        Logger.register(name, ['bps', 'pkts', 'pkt_accumulated'])
    def __init__(self, threshold, waveforms=WAVEFORMS):
        """
        CTOR
        @param threshold Decision threshold
        @param waveforms Array of known patterns
        """
        ThresholdAlgorithm.__init__(self, threshold=threshold)

	self._waveforms = waveforms

        Logger.register('waveform_decision', ['decision', ])

	self._xx = {};
	self._xx[0] = {0: "00", 1: "01"}
	self._xx[1] = {0: "10", 1: "11"}
Пример #6
0
	def __init__(self, input_len, algo1, algo2):
		gr.sync_block.__init__(self,
			name="hier",
			in_sig = [np.dtype((np.float32, input_len)), np.dtype((np.complex64, input_len))],  #pylint: disable=E1101
			#in_sig = [np.dtype((np.float32, input_len)), np.dtype((np.float32, input_len))],  #pylint: disable=E1101
			out_sig= None   #pylint: disable=E1101
		 )

		self.algo1 = algo1
		self.algo2 = algo2

		Logger.register('hier', ['decision',] )

		self._xx = {};
		self._xx[0] = {0: "00", 1: "01"}
		self._xx[1] = {0: "10", 1: "11"}
Пример #7
0
    def __init__(self, Np, P, L, th=0):
        """
        CTOR
        @param Np
        @param P
        @param L
        @param th Decision threshold.
        """
        ThresholdAlgorithm.__init__(self, th)

        Logger.register('cyclo_decision', ['decision', ])

        from opera import cyclo_fam_calcspectrum_vcf
        self._algorithm = cyclo_fam_calcspectrum_vcf(Np, P, L)

	self._xx = {};
	self._xx[0] = {0: "00", 1: "01"}
	self._xx[1] = {0: "10", 1: "11"}
Пример #8
0
    def __init__(self,
                 name="SNREstimator",
                 algorithm=SVR,
                 alpha=0.001):
        """
        CTOR
        @param name
        @param algorithm
        @param alpha
        """
        self._estimator = digital.probe_mpsk_snr_est_c(algorithm, 10000, alpha)

        UHDGenericArch.__init__(self,
                                name=name,
                                input_signature=self._estimator.input_signature(),
                                output_signature=self._estimator.output_signature())

        Logger.register(name, ['snr', ])

        self.register_scheduling(lambda: Logger.append(name, 'snr', self.get_snr()), delay_sec=0.2)  #pylint: disable=E1101
    def __init__(self, learner, manager, a_feedback_strategy):
        """
        CTOR
        @param learner Algorithm that will be adjusted.
        @param manager
        @param a_feedback_strategy FeedbackTimeStrategy object.
        """
        AbstractAlgorithm.__init__(self)

        self._learner = learner
        self._manager = manager
        self._strategy = a_feedback_strategy

        self._valid_feedback = True

        self._count = 0
        self._iteraction = 0
        self._time = 0

        # Debug information
        Logger.register('feedback_algorithm', ['total_feedback', 'activation', 'count', 'time'])
    def __init__(self, algorithm, _type=np.float32):
        """
        CTOR
        @param algorithm
        @param _type
        @param learner Algorithm that will be adjusted. ???????????
        @param a_feedback_strategy FeedbackTimeStrategy object.  ????????????
        """
        gr.sync_block.__init__(self,
                               name='bayes_decision',
                               in_sig=[np.dtype((np.float32, 1024)),
                                       np.dtype((_type, 1024))],      #pylint: disable=E1101
                               out_sig=None,  #pylint: disable=E1101
                               )

        self._algorithm = algorithm

        self._count = 0
        self._iteraction = 0
        self._time = 0

        # Debug information
        Logger.register('bayes_decision', ['hypothesis', 'activation', 'count', 'time'])
        Logger.register('feedback_algorithm', ['total_feedback', ])
Пример #11
0
def receiver_loop(tb, channel_list, channel, options):
    """
    UP LOOP
    @param tb
    @param channel_list
    @param channel
    @param options
    """

    import xmlrpclib
    from SimpleXMLRPCServer import SimpleXMLRPCServer

    class MyNamespace:
        """

        """
        pass

    g_namespace = MyNamespace()
    g_namespace.tb = tb
    g_namespace.options = options
    g_namespace.server_run = True

    class StoppableXMLRPCServer(SimpleXMLRPCServer):
        """Override of TIME_WAIT"""
        allow_reuse_address = True

        def __init__(self, options):
            SimpleXMLRPCServer.__init__(self, options)
            self.stop = False

        def serve_forever(self):
            while not self.stop:
                self.handle_request()
            print 'exiting server'

        def shutdown(self):
            self.stop = True
            return 0

    server = StoppableXMLRPCServer((options.slave_addr, 8000))
    g_namespace.th = Thread(target=server.serve_forever )

    # Flag que indica quando a execucao deve parar
    # Flag that indicates when the execution must stop.
    g_namespace.run = False
    g_namespace.interferer_channel = 0


    def set_channel(channel):
        """
        RPC for changing the channel.
        @param channel
        """

        print "Received command to handoff to channel  ", channel

        if not g_namespace.options.tx_only:
            g_namespace.tb.tx.center_freq = channel_list[channel]
        g_namespace.tb.rx.center_freq = channel_list[channel]

        g_namespace.interferer_channel = channel
        return 1

    def close_app():
        """
        Closes the app.
        """

        print "Received command to close"
        g_namespace.run = False
        return 1

    def client_started():
        """
        Notifies that the execution has started.
        """
        g_namespace.run = True
        return 1

    Logger.register('receiver', ['channel', 'pkt', 'start_time'])
    Logger.set('receiver', 'start_time', time.time())

    # Registra funcoes no servidor XML e inicia thread do servidor
    # Registers functions in the XML server and starts the server thread.
    server.register_function(set_channel, 'set_channel')
    server.register_function(close_app, 'close_app')
    server.register_function(client_started, 'client_started')

    g_namespace.th.start()
    print "Receiver listening for commands in port 8000"
    print "\t... Waiting for client_started call"

    while g_namespace.run == False:
        1;
    print "\t...client connected"

    global t_rcv, t_cor

    channel = 0

    # Enquanto nao recebeu a notificacao de parada, continua a execucao
    # While the stop notify is not received, continues the execution.
    while g_namespace.run:
        print " ... r: ", t_rcv, ", c: ", t_cor
        time.sleep(1)
        if not options.tx_only:
            Logger.append('receiver', 'channel', channel, time.time())

    Logger.append('receiver', 'pkt', t_rcv)

    print "Shutting down Server"
    server.shutdown()
    print "\t ... Server exited"
Пример #12
0
def transmitter_loop(tb, channel_list, channel, options):
    """
    US LOOP
    @param tb
    @param channel_list
    @param channel
    @param options
    """

    # Connect to slave device
    import xmlrpclib
    proxy = xmlrpclib.ServerProxy("http://%s:8000/" % options.slave_addr)

    start_t = time.time()
    proxy.client_started()
    proxy.set_channel(channel)

    Logger.register('transmitter', ['channel', 'status', 'pkt'])


    class TNamespace():
        """

        """
        pass

    # Sensing -> TX loop
    t_namespace = TNamespace()
    t_namespace.pkt_s = 0
    t_namespace.status = 0


    while time.time() < (start_t + options.duration):
        can_transmit = True

        if not options.tx_only:
            # Sense
            decision, t_namespace.status = tb.rx.sense_channel(channel_list[channel], options.sensing_duration)

            # Update
            print t_namespace.status
            if t_namespace.status > 0.000005:  # GMSK threahold
            #if t_namespace.status > 0.000000005 :
                print str(channel_list[channel]) + ' is occupied'

                t_now = time.clock()

                ## Q-NOISE AQUI.
                channel = (channel + 1) % len(channel_list)
                ####
                can_transmit = False

                # Change channel
                proxy.set_channel(channel)
                tb.tx.center_freq = channel_list[channel]
                tb.rx.center_freq = channel_list[channel]

        # Transmit
        if can_transmit:
            payload = 0
            if options.pkt_size > 1:
                bytelist = [1] * (options.pkt_size/4)
                payload = pack('%sH' % len(bytelist), *bytelist)
            else:
                bytelist = ['a', ]
                payload = pack('%sc' % 1, *bytelist)

            # thred sending packets
            def send_thread():
                while t_namespace.pkt_sending:
                    tb.tx.send_pkt(payload)
                    t_namespace.pkt_s += 1
                #t_namespace.count += 1

            # init thread
            th = Thread(target=send_thread)
            t_namespace.pkt_sending = True
            th.start()

            # wait for options.sending_duration 
            time.sleep(options.sending_duration)

            # stop sending
            t_namespace.pkt_sending = False
            th.join()

        Logger.append('transmitter', 'channel',  channel)
        Logger.append('transmitter', 'status',   t_namespace.status)
        Logger.append('transmitter', 'pkt',      t_namespace.pkt_s)

    proxy.close_app()
Пример #13
0
def cognitive_radio_loop(options, radio, channel_list):
    """
    Program loop here.
    @param options
    @param radio A RadioDevice instance.
    @param channel_list List of Channel objects.
    """

    # Export my server
    command = callback_radio(radio)

    my_rpc = RPCExporter(addr=("143.54.83.30", 8000 + options.my_id))
    my_rpc.register_function('command', command)
    my_rpc.start()

    # Wait broker start
    while not command.run:
        1

    ####
    #Import OTHER RADIOS RPCS
    ####
    rpc_arr = []
    RADIOS = [0, 3]
    for i in RADIOS:
            rpc_cli = RPCImporter(addr="http://%s:%d" % (HOSTS_IP[i], 8000 + i))
            rpc_cli.register_function('command')
            rpc_arr.append(rpc_cli)

    # Import PassiveRadio RPC calls
    bs_rpc = RPCImporter(addr="http://%s:9000" % (options.broker_ip))
    bs_rpc.register_function('command')

    # Register parameters for transmission
    Logger.register('radio', ['tx_pkts', 'rx_pkts', 'rx2_pkts' , 'channel', 'operation', 'receiver', 'starving',
                              'total_tx', 'total_rx', 'total_starving'])
    # loop
    pkt_len = options.pkt_len
    payload = struct.pack('%sB' % pkt_len, *[options.my_id] * pkt_len)

    print '##### Entering Transmitter loop'
    c_starving = 0

    while command.run:
        """
        ######## FUNCOES:
        ######## Functions:

        ---- BW do canal
        ---- channel's bandwidth.
        radio.get_bandwidth()

        ---- Num. simbolos na modulacao
        ---- Number of symbols in the modulation.
        radio.{tx,rx}.symbols()

        ---- B/S da modulacao
        ---- B/S of the modulation.
        radio.{tx,rx}.bits_per_symbol()

        ---- Pkt/s NO ULTIMO SEGUNDO
        ---- Pkt/s in the last second.
        radio.{tx,rx}.counter.get_pkts()

        ---- b/s NO ULTIMO SEGUNDO.
        ---- b/s in the last second.
        radio.{tx,rx}.counter.get_bps()

        ---- Pacotes acumulados desde a ultima chamada.
        ---- Accumulated packages since the last call.
        radio.{tx,rx}.counter.get_pkt_accumulated(clear = False)

        ---- Troca de canal. channel eh um objeto Channel
        ---- Channel changing. channel is a Channel object
        radio.set_channel(channel)
        #################
        """

        # sense
        while not command.sense and command.run:
            1
        if not command.run:
            break

        sense_data = []

        radio.set_gain(0)
        for channel in channel_list:
            decision, energy = radio.ss.sense_channel(channel, 0.1)
            sense_data.append((decision, float(energy), channel.get_channel()))
            print 'Channel energy: ', energy

        bs_rpc.command([options.my_id, 'sense_data', sense_data])

        while not command.transmission:
            1

        # tx pkts is the number of packets transmitted
        # globs.instant_rx is the number of packets received.
        #   Is global cause it is hard to be synchronized with the TX dev when WE are the RX
        #   The easiest way is to let the TX dev control when get this value. And we do it in the RPC server method
        tx_pkts = globs.instant_rx = 0

        time.sleep(options.sending_duration)
        bs_rpc.command([options.my_id, 'transmission_res', (tx_pkts, globs.instant_rx)])

    Logger.set('radio', 'total_tx', globs.total_tx)
    Logger.set('radio', 'total_rx', globs.total_rx)
    Logger.set('radio', 'total_starving', globs.total_starving)
Пример #14
0
    def __init__(self, alpha=0.3, gamma=1.0, epsilon=0.1, verbose=False,
                 min_th=0.0, max_th=100.0, delta_th=1.0):
        """
        CTOR
        @param alpha
        @param gamma
        @param epsilon Probability of executing a random action
        @param verbose
        @param min_th The lowest threshold
        @param max_th The highest threshold
        @param delta_th
        """

        #  "The learning rate determines to what extent the newly
        #  acquired information will override the old information. A factor of 0
        #  will make the agent not learn anything, while a factor of 1 would make
        #  the agent consider only the most recent information."
        self.alpha = float(alpha)

        # According to Wikipedia: "The discount factor determines the importance
        # of future rewards. A factor of 0 will make the agent "opportunistic" by only
        # considering current rewards, while a factor approaching 1 will make it
        # strive for a long-term high reward."
        self.gamma = float(gamma)

        # Probabilidade de executar uma acao randomicamente.
        # Probability of executing a random action
        self.epsilon = float(epsilon)

        #
        self.verbose = verbose

        # min_th is the lowest threshold
        self.min_th = min_th

        # max_th is the highest threshold
        self.max_th = max_th

        # gap is the... gap between states, so, the number of states
        #  will be (max_th - min_th) / gap
        self.gap = delta_th

        # The feedback
        self._feedback = 0.0

        # Number of Increase Actions in sequence
        self.action_i = 0
        # Number of Decrease Actions in sequence
        self.action_d = 0

        # Set to '1' when a feedback is received
        self.feedback_received = True

        # Count how many feedbacks are received by the algorithm.
        # Used only for info gathering
        self.feedback_counter = 0

        #
        self.cycle_counter = 0
        self.cycle_counter_max = int(406383 / 8)

        # Execution Time of this class
        self.m_time = 0.0

        # Enum for actions
        self.action = Actions()

        # Load in self.actions the possible actions
        self.actions = self.get_action_list()
        # Load in self.states the possible actions
        self.states = self.get_state_list()

        # How many states?
        self.nstates = len(self.states)
        # Max jump
        self.max_jump = int(self.nstates / 50)

        # Map the threshold value to the index of this threshold in self.states
        self.state_map = {'0.0': 0}
        for i in range(self.nstates):
            self.state_map[self.states[i]] = i

        # How many actions I'm using?
        self.nactions = len(self.actions)

        # Build an empty q_table with size (nactions * nstates)
        self.q_table = self.build_q_table()

        # Guess what?
        self.s = self.get_initial_state()
        self.a = self.e_greedy_selection(self.s)

        # May be messy
        if self.verbose:
            self.print_q_table()

        Logger.register('bayes_learning', ['hypothesis', 'feedback', 'state', 'reward', 'action'])
Пример #15
0
def cognitive_radio_loop(options, radio, channel_list):
    """
    Program loop here.
    @param options
    @param radio A RadioDevice instance.
    @param channel_list List of Channel objects.
    """

    # Export my server
    command = callback_radio(radio)

    my_rpc = RPCExporter(addr=("143.54.83.30", 8000 + options.my_id))
    my_rpc.register_function('command', command)
    my_rpc.start()

    # Wait broker start
    while not command.run:
        1

    ####
    #Import OTHER RADIOS RPCS
    ####
    rpc_arr = []
    for i in [0, 1, 2, 3]:
            rpc_cli = RPCImporter(addr="http://%s:%d" % (HOSTS_IP[i], 8000 + i))
            rpc_cli.register_function('command')
            rpc_arr.append(rpc_cli)

    # Import PassiveRadio RPC calls
    bs_rpc = RPCImporter(addr="http://%s:9000" % (options.broker_ip))
    bs_rpc.register_function('command')

    # Register parameters for transmission
    Logger.register('radio', ['tx_pkts', 'rx_pkts', 'rx2_pkts', 'channel', 'operation', 'receiver', 'starving',
                              'total_tx', 'total_rx', 'total_starving'])
    # loop
    pkt_len = options.pkt_len
    payload = struct.pack('%sB' % pkt_len, *[options.my_id] * pkt_len)

    print '##### Entering Transmitter loop'
    c_starving = 0

    while command.run:
        """
        ######## FUNCOES:

        ---- BW do canal
        ---- Channel's bandwidth.
        radio.get_bandwidth()

        ---- Num. simbolos na modulacao
        --- Number of symbols in the modulation.
        radio.{tx,rx}.symbols()

        ---- B/S da modulacao
        ---- B/S of the modulation
        radio.{tx,rx}.bits_per_symbol()

        ---- Pkt/s NO ULTIMO SEGUNDO
        ---- Pkt/s in the last second.
        radio.{tx,rx}.counter.get_pkts()

        ---- b/s NO ULTIMO SEGUNDO.
        ---- b/s in the last second.
        radio.{tx,rx}.counter.get_bps()

        ---- Pacotes acumulados desde a ultima chamada.
        ---- Accumulated packages since the last call.
        radio.{tx,rx}.counter.get_pkt_accumulated(clear = False)

        ---- Troca de canal. channel eh um objeto Channel
        ---- Channel changing. channel is a Channel object.
        radio.set_channel(channel)
        #################
        """

        # sense
        while not command.sense and command.run:
            1
        if not command.run:
            break

        sense_data = []

        radio.set_gain(0)
        for channel in channel_list:
            decision, energy = radio.ss.sense_channel(channel, 0.1)
            sense_data.append((decision, float(energy), channel.get_channel()))

        bs_rpc.command([options.my_id, 'sense_data', sense_data])

        # CHOOSE RECEIVER
        #while not command.request_transmission:
        #    1

        # Select a receiver randomly
        #opt  = [0, 1, 2, 3]
        #opt.remove(options.my_id)
        #receiver = random.choice(opt)
        #print '##### DEVICE %d requesting TX to %d' % (options.my_id, receiver)

        #bs_rpc.command([options.my_id, 'request_tx', receiver])
        #radio.set_gain(radios_gain[radio.id])

        # REQUEST CHANNEL
        while not command.request_channel:
            1
        receiver, operation, channel_idx = bs_rpc.command([options.my_id, 'request_channel', 9999])

        # Configure radio. Go to distant frequency if 'idle'
        if channel_idx > -1 or operation == OPERATIONS['idle']:
            if channel_idx > -1:
                radio.set_channel(channel_list[channel_idx])
            else:
                radio.set_channel(CHANNEL_IDLE)

        while not command.transmission:
            1

        # tx pkts is the number of packets transmitted
        # globs.instant_rx is the number of packets received.
        #   Is global cause it is hard to be synchronized with the TX dev when WE are the RX
        #   The easiest way is to let the TX dev control when get this value. And we do it in the RPC server method
        tx_pkts = globs.instant_rx = 0

        if operation == OPERATIONS['tx']:
            # change rx freq to another freq or we will receiver our own packets
            radio.rx.radio.set_channel(CHANNEL_IDLE)
            print "##### ... %d - TRANSMITTING - CHANNEL %d - TO: %d" % (options.my_id, channel_idx, receiver)
            tx_pkts = PktSender.flood_by_time(duration=options.sending_duration,
                                              tx_pkt_arch=radio.tx,
                                              payload=payload)
            globs.instant_rx = rpc_arr[receiver].command((options.my_id, 'get_accumulated', True))

            print "##### ... Transmitted %d/%d pkts in Channel %d" % (tx_pkts, globs.instant_rx, channel_idx)
            globs.total_tx += tx_pkts
            c_starving = 0

        elif operation == OPERATIONS['rx']:
            print "##### ... %d - RECEIVING - CHANNEL %d" % (options.my_id, channel_idx)
            receiver = 10

            globs.wait_for_get = True
            while globs.wait_for_get:
                time.sleep(0.2)

            tx_pkts = 0
            globs.total_rx += globs.instant_rx

            c_starving += 1
            globs.total_starving += 1
        elif operation == OPERATIONS['idle']:
            print '##### ... %d is IDLE' % options.my_id
            receiver = -1
            time.sleep(options.sending_duration)
            c_starving += 1
            globs.total_starving += 1

        bs_rpc.command([options.my_id, 'transmission_res', (tx_pkts, globs.instant_rx)])

        _idle = 0 if operation != OPERATIONS['idle'] else -1
        Logger.append('radio', 'tx_pkts', tx_pkts if _idle > -1 else _idle)
        Logger.append('radio', 'rx_pkts',  globs.instant_rx if operation == OPERATIONS['tx'] else _idle)
        Logger.append('radio', 'rx2_pkts', globs.instant_rx if operation == OPERATIONS['rx'] else _idle)
        Logger.append('radio', 'channel', channel_idx)
        Logger.append('radio', 'operation', operation)
        Logger.append('radio', 'receiver', receiver)
        Logger.append('radio', 'starving', c_starving)

    Logger.set('radio', 'total_tx', globs.total_tx)
    Logger.set('radio', 'total_rx', globs.total_rx)
    Logger.set('radio', 'total_starving', globs.total_starving)
Пример #16
0
                        radio.sensing._component.set_center_freq(1)
                        print "--- Setting ch_status to 1"
                        Logger._ch_status = 1
                    else:
                        radio.sensing._component.set_center_freq(0)
                        print "--- Setting ch_status to 0"
                        Logger._ch_status = 0

                    if t_tot == 0:
                        tb.start()
                    time.sleep(t_next)

                    t_tot += t_next
                    if t_tot >= 10.0:
                        break
                ################################################################################
                tfin = time.clock()
                tb.stop()
                tb.wait()
                enable = False

                Logger.register("global", ["clock"])
                Logger.set("global", "clock", tfin - tin)

                _sdir = "/%s_%02d_%02d/" % (options.sensing, options.ph1 * 10, pfa)
                _dir = "single/ebn0_{ebn0}".format(ebn0=ebn0)
                Logger.dump(_dir, _sdir, options.it)
                Logger.clear_all()
                with open("log.txt", "a+") as log:
                    log.write(_dir + _sdir)
Пример #17
0
				Logger._ch_status = 1
			    else:
				radio.ed._component.set_center_freq(0)
				print "--- Setting ch_status to 0"
				Logger._ch_status = 0

			    if t_tot == 0:
				tb.start()
			    time.sleep(t_next)

			    t_tot += t_next
			    if t_tot >= 10.0:
			   	break;
################################################################################
			tb.stop()
			tb.wait()
			tfin = time.clock()
			enable = False

			Logger.register('global', ['clock', ])
			Logger.set('global', 'clock', tfin - tin)
			
			_sdir = '/ata_%s_%02d_%02d/' % (options.sensing, options.ph1 * 10, pfa)
			_dir =  "single/ebn0_{ebn0}".format(ebn0=ebn0)
			Logger.dump(_dir, _sdir, options.it)
			Logger.clear_all()
			# wait for thread model_channel finish
			#t_mc.join()
			with open("log.txt", "a+") as log:
				log.write(_dir +  _sdir )
Пример #18
0
def execute_sensing_decision(hit_rate, num_steps):
    """
    Execution of the sensing_decision module.
    @param hit_rate A list with the hit ratio for every cpe. Example: hit_rate = [90, 78, 32] - the first cpe has a
    hit ratio of 90%, the second has a hit ratio of 78% and the third has a hit ratio of 32%.
    @param num_steps Number of executions of the sensing_result
    """

    feedback_control = 5
    increase_rate = 0.1
    decrease_rate = 0.1
    num_cpes = len(hit_rate)

    list_str_cpes = []

    for i in range(num_cpes):
        list_str_cpes.append("cpe" + str(i+1))

    # save strings in the Logger
    Logger._enable = True
    Logger.register("reward", list_str_cpes)

    sdc = SDController(num_cpes, feedback_control, increase_rate, decrease_rate)    

    # each element of this array is also an array. the array of the index 0 (ie, array_hit[0]) corresponds to the hit_
    # rate[0] and so on.
    cpe_array = [0] * num_steps
    
    array_hit = []

    # num_cpes is the length of array_hit
    for i in range(num_cpes):
        # need to append as a list because otherwise if we modify some subarray, ALL arrays are modified too.
        array_hit.append(list(cpe_array))

    # list of lists, where the random indexes will be.
    list_indexes = []
    for i in range(num_cpes):
        list_indexes.append(list([]))

    # set some random positions of the arrays to one.
    for i in range(num_cpes):
        while len(list_indexes[i]) < (num_steps - (num_steps * hit_rate[i]/100)):
            rand = random.randint(0, num_steps-1)
            if rand not in list_indexes[i]:
                list_indexes[i].append(rand)
                array_hit[i][rand] = 1

    for step in range(num_steps):
        sensing_result = []
            
        for cpe in range(num_cpes):
            sensing_result.append(array_hit[cpe][step])
            Logger.append("reward", list_str_cpes[cpe], sdc._reward[cpe])    
    

        sdc.sensing_decision(sensing_result, num_cpes)    

    Logger.dump('./dump', '/cpes', 0)

    print "\n\n REWARD\n\n"
    for cpe in range(num_cpes):
        print "reward cpe %i: " %(cpe+1) + str(sdc._reward[cpe])

    print "TOTAL HIT RATE: ", float(sdc._total_idle/float(num_steps))
Пример #19
0

if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option("", "--test-duration", type="int", default=600,
                      help="Test Duration.")
    parser.add_option("", "--iteration", type="int", default=0,
                      help="Iteration")
    parser.add_option("", "--sending-duration", type="int", default=5,
                      help="Sending duration during each transmittion.")

    (options, args) = parser.parse_args()

    globs.options = options

    Logger._enable = True
    Logger.register('bs', ['channel_count', 'links', 'it_dur', 'total_iterations', 'interference_count',
                           'interference_time', 'interference_hit_count', 'interference_hit_time', 'decision_time',
                           'tx_and_rx_pkts'])
    main(options)

    Logger.set('bs', 'channel_count', globs.p_channels_count)
    Logger.set('bs', 'total_iterations', globs.p_total_iterations)
    Logger.set('bs', 'interference_count', globs.p_channels_interference_count)
    Logger.set('bs', 'interference_time', globs.p_channels_interference_time)
    Logger.set('bs', 'interference_hit_count', globs.p_channels_interference_hit_count)
    Logger.set('bs', 'interference_hit_time', globs.p_channels_interference_hit_time)

    Logger.dump('./results/', 'bs_burst_' + str(options.sending_duration) + '_it_' + str(options.iteration))
    os._exit(1)
Пример #20
0
def transmitter_loop(tb, channel_list, channel, options):
    """
    US LOOP
    @param tb
    @param channel_list
    @param channel
    @param options
    """

    # Q-Noise+ Parameters
    lookback = 3
    beta = 0.1
    eps = 0.1

    history_weight = [0.2, 0.35, 0.45]
    noise_weight = 0.8
    alpha = 0.2  # alpha + noise+weith = 1
    epochs = 100
    #Q-Noise+
    learner = qnoise.Learner(channel_list, lookback, alpha, beta, eps, history_weight, noise_weight)

    # Connect to slave device
    import xmlrpclib
    proxy = xmlrpclib.ServerProxy("http://%s:8000/" % options.slave_addr)
    start_t = time.time()
    proxy.client_started()
    proxy.set_channel(channel)

    Logger.register('transmitter', ['channel', 'status', 'pkt'])


    class TNamespace():
        """

        """
        pass

    # Sensing -> TX loop
    t_namespace = TNamespace()
    t_namespace.pkt_s = 0
    t_namespace.status = 0
    t_namespace.iteration = 0

    
    t_namespace.ss_result = {}
    for ch in channel_list:
        t_namespace.ss_result[ch.channel] = [0, 0, 0]

    ch_qvalue = 0
    while time.time() < (start_t + options.duration):
        can_transmit = True

        t_namespace.pkt_r = t_namespace.pkt_s = 0

        # Sense
        print '### START SENSING CHANNEL'
        t_namespace.status = tb.rx.sense_channel(channel_list[channel], options.sensing_duration)

        # Update
        #print t_namespace.status
        if t_namespace.status > 0.000005:  # GMSK threahold
        #if t_namespace.status > 0.000000005 :
            print str(channel_list[channel]) + ' is occupied'

            t_now = time.clock()

            can_transmit = True

            # Change channel
            #proxy.set_channel( channel )

        # Transmit
        if can_transmit:
            payload = 0
            if options.pkt_size > 1:
                bytelist = [1] * (options.pkt_size/4)
                payload = pack('%sH' % len(bytelist), *bytelist)
            else:
                bytelist = ['a', ]
                payload = pack('%sc' % 1, *bytelist)

            # thread sending packets
            def send_thread():
                t_namespace.pkt_s = 0
                #while t_namespace.pkt_sending:
                while t_namespace.pkt_s < 200:
                    tb.tx.send_pkt(payload)
                    t_namespace.pkt_s += 1
                    #print 't: ', t_namespace.pkt_s
                    time.sleep(0.03)
                #t_namespace.count += 1

            # init thread
            th = Thread(target=send_thread)
            proxy.start_rcv()
            t_namespace.pkt_sending = True
            th.start()

            # wait for options.sending_duration 
            #time.sleep( options.sending_duration )

            # stop sending
            t_namespace.pkt_sending = False
            th.join()

            t_namespace.pkt_r = proxy.get_rcv()

            print 'pkt_s = ', t_namespace.pkt_s
            print 'pkt_r = ', t_namespace.pkt_r

        ch_qvalue = learner.evaluate(channel_list[channel].channel, t_namespace.pkt_s, t_namespace.pkt_r,
                                     t_namespace.status)

        t_namespace.ss_result[channel+1] = [t_namespace.status, 0 if can_transmit else 1, ch_qvalue]
        channel = learner.choose_next_channel(channel_list[channel].channel) - 1   # -1 cause we use the index in the array.
        print "Using channel  ", channel_list[channel]
        proxy.set_channel(channel)
        tb.tx.radio.center_freq = channel_list[channel]

        Logger.append('transmitter', 'channel',  channel)
        Logger.append('transmitter', 'status',   t_namespace.status)
        Logger.append('transmitter', 'pkt',      t_namespace.pkt_s)

        dump_qlearner(t_namespace.iteration, t_namespace.ss_result, noise_weight)
        t_namespace.iteration += 1

    proxy.close_app()