Example #1
0
class Simulator():
    def __init__(self, step=60000, maxIteration=0):
        self._counter = 0
        self._maxIteration = maxIteration
        self._step = step
        self._clock = 0  # clock = counter * step
        self._DATE_FORMAT = "%Y-%m-%d %H:%M:%S %Z%z"

        self._run = True
        self.world = World()

        # logging
        LOG_FORMAT = "%(levelname)s - %(message)s"
        logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT)

    def update(self):
        if self._maxIteration != 0:
            if self._counter >= self._maxIteration:
                logging.critical("Max iteration reached. Stop simulation.")
                self._stop()

        try:
            self.world.update(self._step)
            message = "{date} {isdaytime} Distance traveled {distance} miles.".format(
                date=self.world.time.strftime(self._DATE_FORMAT),
                isdaytime="Daylight" if GLOBAL['isDayTime'] else "Night",
                distance=round(self.world.distanceTraveled, 1))
            logging.info(message)

        except DestinationReached:
            totalTimeTaken = self.world.time - self.world.model.departDatetime
            message = "Destination reached at {date} after {time} ({clock} cycles of simulation)".format(
                date=self.world.time.strftime(self._DATE_FORMAT),
                time=str(totalTimeTaken),
                clock=self._clock)
            logging.critical(message)
            logging.debug("Max payload = {} Distance = {}".format(
                self.world.payloadAllowed,
                round(self.world.path.getPathLength(), 1)))
            self._stop()

        except PowerSourceDepletion:
            logging.error("Power depleted. Stop simulation.")
            self._stop()

        except:
            logging.error("Exception on updating world. Stop simulation.")
            self._stop()

        self._counter += 1
        self._clock += self._step

    def isRunning(self):
        return self._run

    def getClock(self):
        return self._clock

    def _stop(self):
        self._run = False
Example #2
0
    def __init__(self, step=60000, maxIteration=0):
        self._counter = 0
        self._maxIteration = maxIteration
        self._step = step
        self._clock = 0  # clock = counter * step
        self._DATE_FORMAT = "%Y-%m-%d %H:%M:%S %Z%z"

        self._run = True
        self.world = World()

        # logging
        LOG_FORMAT = "%(levelname)s - %(message)s"
        logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT)
Example #3
0
File: run.py Project: mrknmc/cslp
def main(argv):
    if not argv:
        print('No input file supplied!')
        return
    cwd = os.getcwd()
    input_f = os.path.join(cwd, argv[0])
    if len(argv) > 1:
        output_f = os.path.join(cwd, argv[1])
        sys.stdout = open(output_f, 'w')
    try:
        world = World(input_f)
        world.start()
    except IOError:
        print('Input file does not exist!')
    except SimulationException as e:
        print(e)
Example #4
0
    def _simulate(self, instance_creator: InstanceCreator, request_generator: RequestGenerator,
                  load_generator: LoadGenerator = None, log_progress=False) -> (SimulatorResult, list):
        """
        Runs a single simulation. To process the incoming requests by the request_generator (quantity per simulation
        step determinted by the load_generator), new instances are created using the instance_creator.
        :param instance_creator: InstanceCreator, to create instances
        :param request_generator: RequestGenerator, to create requests
        :param load_generator: LoadGenerator, to generate load
        :return: SimulatorResult
        """
        world = World(instance_creator)

        simulator = Simulator(self.config, world, request_generator, log_progress)
        result, requests = simulator.run(load_generator)

        return result, requests
Example #5
0
    def __init__(self):
        '''Initialize the simulator'''

        random.seed()
        
        self.world = World()

        self.humans = dict({
            'randy': SimHuman(
                first_name = 'Randy',
                last_name = 'Hook',
                serial_number = self.world.generate_new_serial_number()
            ),
            'kenny': SimHuman(
                first_name = 'Kenny',
                last_name = 'Hook',
                serial_number = self.world.generate_new_serial_number()
            )
        });

        self.agents = dict({
            'guardian': SimGuardianAgent(
                name = 'Guardian',
                serial_number = self.world.generate_new_serial_number(),
                owner = self.humans['randy'],
                subowners = [],
                chain_of_command = []
            ),
            'wheelchair': SimWheelchairAgent(
                name = 'Chair',
                serial_number = self.world.generate_new_serial_number(),
                owner = self.humans['randy'],
                subowners = [
                    self.humans['kenny']
                ],
                chain_of_command = []
            )
        });

        self.agents['guardian'].set_agencies()
        self.agents['guardian'].set_sensors()

        self.agents['wheelchair'].chain_of_command = [self.agents['guardian']]
        self.agents['wheelchair'].location = self.world.rooms['living_room']
        self.agents['wheelchair'].set_agencies()
        self.agents['wheelchair'].set_sensors()

        self.humans['kenny'].location = self.agents['wheelchair'].location

        self.tobii = Tobii()
        self.tobii.location =  self.agents['wheelchair'].location

        self.scripts = dict()
        self.scripts['wheelchair_to_room'] = dict({
            'time': 1000,
            'sensory_data': SimSensoryData(
                data_type = 'audio',
                data = 'Chair. Take me to my room.',
                origin = self.humans['kenny']
            )
        });

        self.setup_display()

        self.sim_time = 0
        self.update_delta_milliseconds = 100
        self.start_simulation()
Example #6
0
class Simulator(Frame, Observer):
    '''Simulator class'''

    def __init__(self):
        '''Initialize the simulator'''

        random.seed()
        
        self.world = World()

        self.humans = dict({
            'randy': SimHuman(
                first_name = 'Randy',
                last_name = 'Hook',
                serial_number = self.world.generate_new_serial_number()
            ),
            'kenny': SimHuman(
                first_name = 'Kenny',
                last_name = 'Hook',
                serial_number = self.world.generate_new_serial_number()
            )
        });

        self.agents = dict({
            'guardian': SimGuardianAgent(
                name = 'Guardian',
                serial_number = self.world.generate_new_serial_number(),
                owner = self.humans['randy'],
                subowners = [],
                chain_of_command = []
            ),
            'wheelchair': SimWheelchairAgent(
                name = 'Chair',
                serial_number = self.world.generate_new_serial_number(),
                owner = self.humans['randy'],
                subowners = [
                    self.humans['kenny']
                ],
                chain_of_command = []
            )
        });

        self.agents['guardian'].set_agencies()
        self.agents['guardian'].set_sensors()

        self.agents['wheelchair'].chain_of_command = [self.agents['guardian']]
        self.agents['wheelchair'].location = self.world.rooms['living_room']
        self.agents['wheelchair'].set_agencies()
        self.agents['wheelchair'].set_sensors()

        self.humans['kenny'].location = self.agents['wheelchair'].location

        self.tobii = Tobii()
        self.tobii.location =  self.agents['wheelchair'].location

        self.scripts = dict()
        self.scripts['wheelchair_to_room'] = dict({
            'time': 1000,
            'sensory_data': SimSensoryData(
                data_type = 'audio',
                data = 'Chair. Take me to my room.',
                origin = self.humans['kenny']
            )
        });

        self.setup_display()

        self.sim_time = 0
        self.update_delta_milliseconds = 100
        self.start_simulation()

    def display_output(self, messages):
        if not isinstance(messages, list):
            message = messages
            messages = list();
            messages.append(message)

        for m in messages:
            self.text_output.insert(INSERT, "\n" + str(m))

    def process_command(self):
        '''Process a command from the simulator command line'''

        self.text_output.insert(INSERT, "\n[input]" + self.input_main.get())

        i = self.input_main.get()
        if i == 'quit':
            self.quit_simulation()
        elif i == 'audio':
            self.text_output.insert(INSERT, "\n[audio]")

        self.input_main_text.set('')

    def quit_simulation(self):
        # shut down the bots
        for a in self.agents:
            self.agents[a].shut_down()

        #quit()

    def run_scripts(self):
        # check for scripts that are due and run them
        scripts_run = list()
        for s in self.scripts:
            if self.sim_time > self.scripts[s]['time']:
                scripts_run.append(s)

                # send the script to each agent
                #
                # right now we are forcing each agent to handle each script. the agent will determine if it is able to handle the script.
                # we could eventually have the simulator be more realistic by broadcasting events and each agent would have sim sensors
                # monitoring the environment for events it can react to.
                for a in self.agents:
                    self.agents[a].queue_sensory_data(self.scripts[s]['sensory_data'])

        # remove any scripts that were just run so they don't run again
        for s in scripts_run:
            del self.scripts[s]

    def setup_display(self):
        Frame.__init__(self)
        self.grid()

        self.text_output = Text(self)
        self.output_scrollbar = Scrollbar(self, orient=VERTICAL, command=self.text_output.yview)
        self.text_output.option_add('yscrollcommand', self.output_scrollbar.set)

        self.text_output.grid(row=0, column=0)
        self.output_scrollbar.grid(row=0, column=1, sticky=N+S)

        self.input_main_label = Label(self, text='Command Line')
        self.input_main_label.grid(row=1, column=0)
        self.input_main_text = StringVar()
        self.input_main = Entry(self, textvariable=self.input_main_text)
        self.input_main.grid(row=2, column=0)
        self.send_command = Button(self, text='Send', command=self.process_command)
        self.send_command.grid(row=3, column=0)


    def start_simulation(self):
        '''Start the simulation'''

        # make the simulation an observer of each agent's memory activity
        for a in self.agents:
            self.agents[a].memory.attach_observer(self)

        # start up the bots
        for a in self.agents:
            self.agents[a].start_up()

        self.after(self.update_delta_milliseconds, self.update_sim)
        self.mainloop()

        return

    def update_from_observable(self, notification):
        self.display_output('[' + notification.message_from + '](' + notification.from_function + ') ' + notification.message)

    def update_sim(self):
        # increment the time counter
        self.sim_time = self.sim_time + self.update_delta_milliseconds

        self.run_scripts()

        # tell each agent to update itself
        for a in self.agents:
            self.agents[a].update(self.sim_time)

        # run this function again after time
        self.after(self.update_delta_milliseconds, self.update_sim)