def __init__(self, setting):
     # Load simulation parameters
     self.sim_param = SimParam(setting)
     # Load simtime
     if setting.dynamictest:
         self.SIMTIME = setting.dynamictest.simtime
     self.freeaccess = False
     if setting.secondwindow.test_values[3]:
         self.freeaccess = True
     # Load the simulation state parameters
     self.sim_state = SimState()
     # Load the result parameters
     self.sim_result = SimResult()
     # Load the class which perfomrs all the methods governing a simple slot
     self.slot = TreeSlot()
     # Load the branch node which keeps track of a tree
     self.branch_node = BranchNode()
     # Create an array of integers of which will contain all active nodes.
     self.active_array = []
     # For gated access, the arrived packets are put into a queue
     self.queue_array = []
     # The number of packets generated in a single slot
     self.packets_gen = 0
     # THe result of a slot
     self.result = 0
     # The current slot no
     self.slot_no = 0
     # Load the parameters for single tree resolution
     self.tree_state = TreeState(self)
Пример #2
0
    def __init__(self, sim_param=SimParam(), no_seed=False):
        """
        Initialize the Simulation object.
        :param sim_param: is an optional SimParam object for parameter pre-configuration
        :param no_seed: is an optional parameter. If it is set to True, the RNG should be initialized without a
        a specific seed.
        """
        self.sim_param = sim_param
        self.sim_state = SimState()
        self.system_state = SystemState(self)
        self.event_chain = EventChain()
        self.sim_result = SimResult(self)
        # TODO Task 2.4.3: Uncomment the line below
        self.counter_collection = CounterCollection(self)
        # TODO Task 3.1.2: Uncomment the line below and replace the "None"

        if no_seed:
            #if the mean = 1.0, then 1/lambda_ = 1.0 -> lambda_ = 1
            self.rng = RNG(ExponentialRNS(1.0),
                           ExponentialRNS(1. / float(self.sim_param.RHO)))
        else:
            self.rng = RNG(
                ExponentialRNS(1.0, self.sim_param.SEED_IAT),
                ExponentialRNS(1. / float(self.sim_param.RHO),
                               self.sim_param.SEED_ST))
Пример #3
0
    def __init__(self, slice_param):
        """
        Initialize the Slice Simulation object.
        :param slice_param: is an optional SliceParam object for parameter pre-configuration
        :param no_seed: is an optional parameter. If it is set to True, the RNG should be initialized without a
        a specific seed.
        """
        self.slice_param = slice_param
        self.sim_state = SimState()
        self.slice_result = SliceResult(self)
        self.event_chain_slice_manager = EventChain()
        self.slice_manager = SliceManager(self)

        self.user_list = []
        self.server_list = []
        self.server_list_dict = {}
 def reset(self, setting):
     self.sim_param = SimParam(setting)
     if setting.dynamictest:
         self.SIMTIME = setting.dynamictest.simtime
     self.freeaccess = False
     if setting.secondwindow.test_values[3]:
         self.freeaccess = True
     self.sim_state = SimState()
     self.sim_result = SimResult()
     self.slot = TreeSlot()
     self.active_array = []
     self.queue_array = []
     self.packets_gen = 0
     self.result = 0
     self.slot_no = 0
     self.tree_state = TreeState(self)
     self.branch_node.reset()
 def reset(self):
     """
     Reset the Simulation object.
     """
     self.sim_state = SimState()
     self.system_state = SystemState(self)
     self.event_chain = EventChain()
     self.sim_result = SimResult(self)
     self.counter_collection = CounterCollection(self)
     self.rng.iat_rns.set_parameters(1.)
     self.rng.st_rns.set_parameters(1. / float(self.sim_param.RHO))
Пример #6
0
 def reset(self, no_seed=False):
     """
     Reset the Simulation object.
     :param no_seed: is an optional parameter. If it is set to True, the RNG should be reset without a
     a specific seed.
     """
     self.sim_state = SimState()
     self.system_state = SystemState(self)
     self.event_chain = EventChain()
     self.sim_result = SimResult(self)
     # TODO Task 2.4.3: Uncomment the line below
     self.counter_collection = CounterCollection(self)
     # TODO Task 3.1.2: Uncomment the line below and replace the "None"
     """
Пример #7
0
 def __init__(self, sim_param=SimParam(), no_seed=False):
     """
     Initialize the Simulation object.
     :param sim_param: is an optional SimParam object for parameter pre-configuration
     :param no_seed: is an optional parameter. If it is set to True, the RNG should be initialized without a
     a specific seed.
     """
     self.sim_param = sim_param
     self.sim_state = SimState()
     self.system_state = SystemState(self)
     self.event_chain = EventChain()
     self.sim_result = SimResult(self)
     # TODO Task 2.4.3: Uncomment the line below
     self.counter_collection = CounterCollection(self)
     # TODO Task 3.1.2: Uncomment the line below and replace the "None"
     """
Пример #8
0
 def reset(self, no_seed=False):
     """
     Reset the Simulation object.
     :param no_seed: is an optional parameter. If it is set to True, the RNG should be reset without a
     a specific seed.
     """
     self.sim_state = SimState()
     self.system_state = SystemState(self)
     self.event_chain = EventChain()
     self.sim_result = SimResult(self)
     # TODO Task 2.4.3: Uncomment the line below
     self.counter_collection = CounterCollection(self)
     # TODO Task 3.1.2: Uncomment the line below and replace the "None"
     if no_seed:
         self.rng = RNG(ExponentialRNS(1.0), ExponentialRNS(1./float(self.sim_param.RHO)))
     else:
         self.rng = RNG(ExponentialRNS(1.0, self.sim_param.SEED_IAT), ExponentialRNS(1./float(self.sim_param.RHO),self.sim_param.SEED_ST))
 def reset(self, no_seed=False):
     """
     Reset the Simulation object.
     :param no_seed: is an optional parameter. If it is set to True, the RNG should be reset without a
     a specific seed.
     """
     self.sim_state = SimState()
     self.system_state = SystemState(self)
     self.event_chain = EventChain()
     self.sim_result = SimResult(self)
     self.counter_collection = CounterCollection(self)
     if no_seed:
         self.rng = RNG(ExponentialRNS(1),
                        ExponentialRNS(1. / float(self.sim_param.RHO)))
     else:
         self.rng = RNG(
             ExponentialRNS(1, self.sim_param.SEED_IAT),
             ExponentialRNS(1. / float(self.sim_param.RHO),
                            self.sim_param.SEED_ST))
Пример #10
0
 def __init__(self, sim_param=SimParam(), no_seed=False):
     """
     Initialize the Simulation object.
     :param sim_param: is an optional SimParam object for parameter pre-configuration
     :param no_seed: is an optional parameter. If it is set to True, the RNG should be initialized without a
     a specific seed.
     """
     self.sim_param = sim_param
     self.sim_state = SimState()
     self.system_state = SystemState(self)
     self.event_chain = EventChain()
     self.sim_result = SimResult(self)
     self.counter_collection = CounterCollection(self)
     if no_seed:
         self.rng = RNG(ExponentialRNS(1),
                        ExponentialRNS(1. / float(self.sim_param.RHO)))
     else:
         self.rng = RNG(
             ExponentialRNS(1, self.sim_param.SEED_IAT),
             ExponentialRNS(1. / float(self.sim_param.RHO),
                            self.sim_param.SEED_ST))
class Simulation(object):
    """
    This Holds the entire Simulation object, whose parameters we update according to the outcomes
    """
    def __init__(self, setting):
        # Load simulation parameters
        self.sim_param = SimParam(setting)
        # Load simtime
        if setting.dynamictest:
            self.SIMTIME = setting.dynamictest.simtime
        self.freeaccess = False
        if setting.secondwindow.test_values[3]:
            self.freeaccess = True
        # Load the simulation state parameters
        self.sim_state = SimState()
        # Load the result parameters
        self.sim_result = SimResult()
        # Load the class which perfomrs all the methods governing a simple slot
        self.slot = TreeSlot()
        # Load the branch node which keeps track of a tree
        self.branch_node = BranchNode()
        # Create an array of integers of which will contain all active nodes.
        self.active_array = []
        # For gated access, the arrived packets are put into a queue
        self.queue_array = []
        # The number of packets generated in a single slot
        self.packets_gen = 0
        # THe result of a slot
        self.result = 0
        # The current slot no
        self.slot_no = 0
        # Load the parameters for single tree resolution
        self.tree_state = TreeState(self)

    def reset(self, setting):
        self.sim_param = SimParam(setting)
        if setting.dynamictest:
            self.SIMTIME = setting.dynamictest.simtime
        self.freeaccess = False
        if setting.secondwindow.test_values[3]:
            self.freeaccess = True
        self.sim_state = SimState()
        self.sim_result = SimResult()
        self.slot = TreeSlot()
        self.active_array = []
        self.queue_array = []
        self.packets_gen = 0
        self.result = 0
        self.slot_no = 0
        self.tree_state = TreeState(self)
        self.branch_node.reset()

    def do_simulation_simple_tree_dynamic(self):
        """
        Free access simulation, is run until the SIMTIME and thats it

        """
        # Run simulation for the number of slots
        self.tree_state.reset(self)
        for self.slot_no in range(1, self.SIMTIME):
            # Generate a packet according to poisson distribution
            self.packets_gen = np.random.poisson(self.sim_param.lmbda)
            # Add the number of packets to the active packet array
            packetlist.add_packets_to_tree(self)
            # Simulate the processes that would happen in the tx and rx in one slot, update the active array accordingly
            self.slot.oneslotprocess(self)
            # Update the metrics in sim_state depending on the result
            self.tree_state.update_metrics(self)
        # Update the results
        self.sim_state.update_metrics(self)
        self.sim_result.get_result(self)

    def do_simulation_simple_tree_static(self, collided_packets):
        """
        Static Simulation, when the number of in initial collided packets is given, it is essentially a single tree res
        :param collided_packets: the no of packets in the resolution

        """
        # Load active array with the collided packets
        if collided_packets > self.sim_param.K:
            self.packets_gen = collided_packets
            packetlist.add_packets_to_tree(self)
            self.tree_state.reset(self)
            # Run the simulation as long as all packets are processed and tree is over
            while self.tree_state.gate_open:
                # Increment the slot
                self.slot_no += 1
                # Simulate the processes that would happen in the tx and rx in one slot, update the active array accordingly
                self.slot.oneslotprocess(self)
                # Update the simstate metrics according to the result of the simulation
                self.tree_state.update_metrics(self)
                # check if all the packets are processed and the tree is at its last branch
                if len(self.active_array) == 0 and len(
                        self.branch_node.branch_status) == 0:
                    self.tree_state.gate_open = False
            # update the metrics from a tree to the simulation state
            self.sim_state.update_metrics(self)
            # Update the results
            self.sim_result.get_result(self)
        else:
            self.sim_result.throughput = 0
            self.sim_result.magic_throughput = 0

    def do_simulation_gated_access(self):
        """
        Gated access, when a resolution is ongoing, the other packets wait in a buffer

        """
        # Run the simulation where we at least simulate for the simtime and then wait for the last tree to be resolved.
        while self.tree_state.gate_open or self.slot_no < self.SIMTIME:
            # Generate a packet according to poisson distribution
            self.packets_gen = np.random.poisson(self.sim_param.lmbda)
            # Add the packet to the queue
            if self.slot_no < self.SIMTIME:
                packetlist.add_packets_to_queue(self)
            # if the active array is empty i.e the tree is resolved
            if len(self.active_array) == 0 and len(
                    self.branch_node.branch_status) == 0:
                # Update the Sim_state class for the previous tree
                if self.slot_no != 0:
                    self.sim_state.update_metrics(self)
                # Transfer the queue to the active array
                packetlist.copy_queue_to_active(self)
                # Clear the queue
                self.queue_array = []
                # Reset all the parameters as we start a new tree
                self.tree_state.reset(self)
                # Reset the branches of the tree
                self.branch_node.reset()
                if len(self.active_array) == 0:
                    self.tree_state.gate_open = False
            self.slot_no += 1
            # Simulate the processes that would happen in the tx and rx in one slot, update the active array accordingly
            self.slot.oneslotprocess(self)
            # Update the metrics in sim_state depending on the result
            self.tree_state.update_metrics(self)
        # Update the results
        self.sim_result.get_result(self)
Пример #12
0
 def reset(self):
     """
     Reset the Simulation object.
     """
     self.sim_state = SimState()
     self.slice_result = SliceResult(self)
Пример #13
0
class SliceSimulation(object):

    def __init__(self, slice_param):
        """
        Initialize the Slice Simulation object.
        :param slice_param: is an optional SliceParam object for parameter pre-configuration
        :param no_seed: is an optional parameter. If it is set to True, the RNG should be initialized without a
        a specific seed.
        """
        self.slice_param = slice_param
        self.sim_state = SimState()
        self.slice_result = SliceResult(self)
        self.event_chain_slice_manager = EventChain()
        self.slice_manager = SliceManager(self)

        self.user_list = []
        self.server_list = []
        self.server_list_dict = {}

    def insert_users(self, user_list):
        self.user_list = user_list
        self.server_list = []
        self.server_list_dict = {}
        for i in self.user_list:
            temp_server = Server(self, i, EventChain())
            self.server_list.append(temp_server)
            self.server_list_dict.update({i.user_id: self.server_list[-1]})

    def reset(self):
        """
        Reset the Simulation object.
        """
        self.sim_state = SimState()
        self.slice_result = SliceResult(self)

    def remove_upcoming_events(self):
        """
        Check the timestamps of oldest events from each event chain of users and SliceManager
        Find the smallest timestamp and remove only the events with this timestamp
        Return current_events[]
        """
        current_events = []
        current_events_dict = {}
        t_arr = []
        for i in self.server_list:      # t_arr includes timestamps of oldest events in all event_chains
            #t_arr.append(i.event_chain.event_list[0].timestamp)
            if len(i.event_chain.event_list)!=0:
                t_arr.append(float(i.event_chain.copy_oldest_event().timestamp))
            else:
                t_arr.append(np.inf)
        #t_arr.append(self.event_chain_slice_manager.event_list[0].timestamp)  # last element of t_arr belongs event_chain_slice_manager
        t_arr.append(float(self.event_chain_slice_manager.copy_oldest_event().timestamp))
        t_arr = np.array(t_arr)
        current_events_idx = (t_arr == t_arr.min())

        for i in range(len(current_events_idx) - 1):
            if current_events_idx[i]:
                current_events.append(self.server_list[i].event_chain.remove_oldest_event())  # remove oldest elements from event chains
                current_events_dict.update({current_events[-1]: self.server_list[i]})

        if current_events_idx[-1]:
            current_events.append(self.event_chain_slice_manager.remove_oldest_event())     # remove oldest element from event_chain_slice_manager
            current_events_dict.update({current_events[-1]: self.event_chain_slice_manager})

        return current_events, current_events_dict

    def prep_next_round(self, RB_mapping):
        """
        Prepares the Simulation object for the next round.
        """
        self.sim_state.prep_next_round()
        for i in self.server_list:
            i.server_state.prep_next_round()
        self.slice_param.RB_mapping = RB_mapping
        #self.slice_result = SliceResult(self)  # server results are not reset due to counters
        # self.rng.iat_rns.set_parameters(1.)
        # self.rng.st_rns.set_parameters(1. / float(self.slice_param.RHO))

    def simulate_one_round(self):  
        """
        Do one simulation run. Initialize simulation and create first and last event.
        After that, one after another event is processed.
        :return: SliceResult object
        """
        self.sim_state.t_round_start = self.sim_state.now

        # insert first and last event
        self.event_chain_slice_manager.insert(RoundTermination(self, self.sim_state.now + self.slice_param.T_C))

        # insert periodic RB_Allocation events
        t_arr = np.arange(self.sim_state.now, self.sim_state.now + self.slice_param.T_C, self.slice_param.T_SM)
        for t in t_arr:
            self.event_chain_slice_manager.insert(RB_Allocation(self, t))

        # insert packet arrivals from traffic lists of users
        for u in self.user_list:
            tmp = u.traffic_list_dict[self.slice_param.SLICE_ID]
            tmp_traffic_list = filter(lambda item: (
                    self.sim_state.now <= item.timestamp < self.sim_state.now + self.slice_param.T_C),
                            tmp)
            tmp_server = self.server_list_dict[u.user_id]
            for pa in tmp_traffic_list:
                #t_drop = pa.timestamp + self.slice_param.DELAY_REQ
                #pd = PacketDrop(self, t_drop)
                tmp_server.event_chain.insert(pa)
                #tmp_server.event_chain.insert(pd)

        # start simulation (run)
        while not self.sim_state.stop:
            # remove upcoming events
            [current_events, current_events_dict] = self.remove_upcoming_events()
            if len(current_events) != len(current_events_dict):
                raise RuntimeError("ERROR: Event to server mapping error.")

            for e in current_events:
                if e:
                    # if event exists and timestamps are ok, process the event
                    if self.sim_state.now <= e.timestamp:
                        self.sim_state.now = e.timestamp

                        if not (e.priority == 4 or e.priority == 5):    # dont count for for slice manager events
                            current_events_dict[e].counter_collection.count_queue()
                        e.process(current_events_dict[e])
                        #if e.timestamp % 1000 == 0:
                        #    print("TIMESTAMP: " + str(e.timestamp) + ",PRIORITY " + str(e.priority))
                    else:
                        print("NOW: " + str(self.sim_state.now) + ", EVENT TIMESTAMP: " + str(e.timestamp) + " " + str(e.priority))
                        raise RuntimeError("ERROR: TIMESTAMP OF EVENT IS SMALLER THAN CURRENT TIME.")

                else:
                    print("Event chain is empty. Abort")
                    self.sim_state.stop = True

        #  gather results for slice_result object and all servers results
        self.server_results = []
        self.server_results_dict = {}
        for i in self.user_list:
            tmp_server = self.server_list_dict[i.user_id]
            self.server_results.append(tmp_server.server_result.gather_results)
            self.server_results_dict.update({i.user_id: self.server_results[-1]})

        self.slice_result.gather_results(self.server_results)
        #return self.slice_result

    def simulate_one_slot(self):
        """

        """
        # insert RB_Allocation event
        self.event_chain_slice_manager.insert(RB_Allocation(self, self.sim_state.now))

        # insert packet arrivals from traffic lists of users
        for i in self.user_list:
            tmp = i.traffic_list_dict[self.slice_param.SLICE_ID]
            tmp_traffic_list = filter(lambda item: (
                    self.sim_state.now <= item.timestamp < self.sim_state.now + self.slice_param.T_SM),
                            tmp)
            tmp_server = self.server_list_dict[i.user_id]
            for j in tmp_traffic_list:
                tmp_server.event_chain.insert(j)

        # start simulation (run)
        while not self.sim_state.stop:
            # remove upcoming events
            [current_events, current_events_dict] = self.remove_upcoming_events()
            if len(current_events) != len(current_events_dict):
                raise RuntimeError("ERROR: Event to server mapping error.")

            for e in current_events:
                if e.timestamp == 80:
                    msa = 3
                if e.priority == 0:
                    msa = 3
                if e:
                    # if event exists and timestamps are ok, process the event
                    if self.sim_state.now <= e.timestamp:
                        self.sim_state.now = e.timestamp

                        if not (e.priority == 4 or e.priority == 5):    # dont count for for slice manager events
                            current_events_dict[e].counter_collection.count_queue()
                        e.process(current_events_dict[e])
                        if e.timestamp % 1000 == 0:
                            print("TIMESTAMP: " + str(e.timestamp) + ",PRIORITY " + str(e.priority))
                    else:
                        print("NOW: " + str(self.sim_state.now) + ", EVENT TIMESTAMP: " + str(e.timestamp) + " " + str(e.priority))
                        raise RuntimeError("ERROR: TIMESTAMP OF EVENT IS SMALLER THAN CURRENT TIME.")

                else:
                    print("Event chain is empty. Abort")
                    self.sim_state.stop = True

        #  gather results for slice_result object and all servers results
        self.server_results = []
        self.server_results_dict = {}
        for i in self.user_list:
            tmp_server = self.server_list_dict[i.user_id]
            self.server_results.append(tmp_server.server_result.gather_results)
            self.server_results_dict.update({i.user_id: self.server_results[-1]})

        self.slice_result.gather_results(self.server_results)
        return self.slice_result