def testMidterm():

    assembler = Assembler("../testMidterm.in")
    simulator = Simulator()

    assembler.instructions[0].execCycles = 4

    # todo: specify instruction starting point.Currently assume 0.
    # Write instructions into instruction memory.
    for i in range(len(assembler.instructions)):
        simulator.instrMemory.write(i, assembler.instructions[i])

    # Initialize some registers and data memory
    intRegisters = simulator.registerDict[RegType.GP_INT]
    floatRegisters = simulator.registerDict[RegType.GP_INT]
    for i in range(len(intRegisters)):
        simulator.registerDict[RegType.GP_INT][i].write(i)
    for i in range(len(floatRegisters)):
        simulator.registerDict[RegType.GP_FLOAT][i].write(float(i))
    for i in range(simulator.dataMemory.totalSize):
        simulator.dataMemory.write(i, i)

    # Keep calling tick until finished
    while not simulator.finished(
    ) and simulator.controlUnit.cycleCounter < 100:
        simulator.tick()

    with open("tmp", 'w') as f:
        json.dump(simulator.frameList,
                  f,
                  default=lambda obj: obj.__dict__,
                  indent=4)
    mainwindow = Ui_MainWindow()
    mainwindow.uiStart()
Beispiel #2
0
 def __init__(self, onj=None, *args, **kwargs):
     super(MainWindow, self).__init__(*args, **kwargs)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.messageController = MessageController()
     self.simSettings = SimulatorSettings()
     self.sim = Simulator(self.simSettings, self.messageController)
     self.con = Controller(self.simSettings, self.sim.hospitalsLocations(),
                           self.sim.ambulancesDistribution(),
                           self.messageController)
     self.ui.Mplwidget
     self.ui.Mplwidget.draw_hospital_on_map(self.con.Hospitals)
     self.ui.hospwidget
     self.ui.hospwidget.draw_all_hosp_inf(self.con.Hospitals)
     self.tablica_komunikatow = []
     self.control_events = []
     self.observ_from_message = []
     self.ui.start.clicked.connect(self.start_sim)
     self.ui.pauza.clicked.connect(self.stop_sim)
     self.ui.reset.clicked.connect(self.reset_sim)
     self.ui.delay_time.setValue(50)
     self.ui.delay_time.valueChanged.connect(self.change_interval)
     self.timer = QtCore.QTimer(self,
                                interval=self.ui.delay_time.value(),
                                timeout=self.simulation)
     self.printedCar = []
     self.printedVirus = []
     self.iterationsNumber = 0
Beispiel #3
0
def main():
    fline = open("seed.txt").readline().rstrip()
    ranseed = int(fline)
    np.random.seed(ranseed)
    random.seed(ranseed)

    preferences_df = loadPreferences()
    thresholds_df = loadThresholds()
    profession_df = loadProfessions()
    actions_df = loadActions()
    tasks_df = loadTasks()

    trace_days = 2
    tracing_percentage = 0.3
    smartphone_owner_percentage = 0.75
    quarantine_days = 14

    timerun = 0  #0 if we want snapshots, any other value if we don'tc
    beginmodel = 1  #the day from which we want the simulation to start
    snapdays = [
        10, 14, 15, 16, 17, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 40, 50,
        60, 70, 80, 90, 100, 110, 120
    ]  #the days we want the snapshots of (index always from original day 1)
    #outfile = open("Outputarray.txt","w+")
    #outfile.write(str(snapdays))
    Simulator.start_simulation(trace_days, tracing_percentage,
                               smartphone_owner_percentage, quarantine_days,
                               preferences_df, profession_df, actions_df,
                               tasks_df, thresholds_df, timerun, snapdays,
                               beginmodel)
Beispiel #4
0
def main():
    simulation_setting = read_settings(SIMULATION_SETTING)
    world_setting = read_settings(ENVIRONMENT_SETTING)
    agent_setting = read_settings(AGENT_SETTING)
    infection_setting = read_settings(INFECTION_MODEL_SETTING)

    simulator = Simulator(
        simulation_setting, world_setting, agent_setting, infection_setting
    )
    simulator.run()
class Main:

    def __init__(self):
        # Initialise world
        left_def = {'x' : 20, 'y' : 160, 'angle':1.1, 'velocity': 0}
        left_atk = {'x' : 300, 'y' : 150, 'angle':1.5, 'velocity': 0}
        right_def = {'x' : 450, 'y' : 110, 'angle':4, 'velocity': 0}
        right_atk = {'x' : 180, 'y' : 85, 'angle':3.14, 'velocity': 0}
        ball = {'x' : 450, 'y' : 150, 'angle':1.5, 'velocity': 4}
        initial_state = {'our_defender':left_def, 'our_attacker':left_atk, 'their_attacker':right_atk, 'their_defender':right_def, 'ball':ball}

        # Set up planner(s)
        left_def_planner = Planner('left', 2, attacker=False)
        left_atk_planner = None #Planner('left', 2, attacker=True)
        right_def_planner = Planner('right', 2, attacker=False)
        right_atk_planner = Planner('right', 2, attacker=True)

        # Create simulator
        self.sim = Simulator(left_def=left_def_planner,left_atk=left_atk_planner, right_def=right_def_planner,
                             right_atk=right_atk_planner, world=initial_state, fps=FPS)

        # Create visualisor
        self.disp = Visualise(labels=SHOWLABELS)
        self.disp.set_world(self.sim.get_world_new())
        self.disp.show()

        self.control_loop()

    def control_loop(self):
        """
        The main loop for the control system. Runs until ESC is pressed.

        Takes a frame from the camera; processes it, gets the world state;
        gets the actions for the robots to perform;  passes it to the robot
        controllers before finally updating the GUI.
        """
        clock = pygame.time.Clock()
        counter = 0
        sim = self.sim
        while True:
            if counter % 5  == 0: # Not allowed to read a command every frame
                self.sim.read_commands(delay=DELAY)
            sim.step()
            self.disp.set_world(sim.get_world_new())
            if counter % 5 == 0:
                self.disp.read_messages()
            self.disp.show()
            counter = counter + 1
            clock.tick(FPS)
Beispiel #6
0
def main():
    messageController = MessageController()

    simSettings = SimulatorSettings()
    sim = Simulator(simSettings, messageController)

    con = Controller(simSettings, sim.hospitalsLocations(), messageController)
    con.printState()

    for i in range(1000):
        sim.simulatorMianLoop()
        con.controllerMainLoop()
        in_data = input()
        if in_data == 'y':  #write y to show the current state
            con.printState()
    def __init__(self):
        # Initialise world
        left_def = {'x' : 20, 'y' : 160, 'angle':1.1, 'velocity': 0}
        left_atk = {'x' : 300, 'y' : 150, 'angle':1.5, 'velocity': 0}
        right_def = {'x' : 450, 'y' : 110, 'angle':4, 'velocity': 0}
        right_atk = {'x' : 180, 'y' : 85, 'angle':3.14, 'velocity': 0}
        ball = {'x' : 450, 'y' : 150, 'angle':1.5, 'velocity': 4}
        initial_state = {'our_defender':left_def, 'our_attacker':left_atk, 'their_attacker':right_atk, 'their_defender':right_def, 'ball':ball}

        # Set up planner(s)
        left_def_planner = Planner('left', 2, attacker=False)
        left_atk_planner = None #Planner('left', 2, attacker=True)
        right_def_planner = Planner('right', 2, attacker=False)
        right_atk_planner = Planner('right', 2, attacker=True)

        # Create simulator
        self.sim = Simulator(left_def=left_def_planner,left_atk=left_atk_planner, right_def=right_def_planner,
                             right_atk=right_atk_planner, world=initial_state, fps=FPS)

        # Create visualisor
        self.disp = Visualise(labels=SHOWLABELS)
        self.disp.set_world(self.sim.get_world_new())
        self.disp.show()

        self.control_loop()
Beispiel #8
0
 def reset_sim(self):
     del self.messageController
     del self.simSettings
     del self.sim
     del self.con
     self.ui.Mplwidget.clean_hospital_on_map()
     self.ui.hospwidget.clean_all_hosp_inf()
     self.clear_widget_scrol()
     self.messageController = MessageController()
     self.simSettings = SimulatorSettings()
     self.sim = Simulator(self.simSettings, self.messageController)
     self.con = Controller(self.simSettings, self.sim.hospitalsLocations(),
                           self.sim.ambulancesDistribution(),
                           self.messageController)
     self.ui.Mplwidget.draw_hospital_on_map(self.con.Hospitals)
     self.ui.hospwidget.draw_all_hosp_inf(self.con.Hospitals)
     self.printedCar.clear()
     self.printedVirus.clear()
     self.iterationsNumber = 0
Beispiel #9
0
from Simulator.AbstractHW import RegType
from Simulator.Simulator import Simulator
from Simulator.Assembler import Assembler
import json

from View.ui.mainwindow import Ui_MainWindow

if __name__ == '__main__':
    assembler = Assembler("testLec9ScoreboardingExample.in")
    simulator = Simulator()

    # todo: specify instruction starting point.Currently assume 0.
    # Write instructions into instruction memory.
    for i in range(len(assembler.instructions)):
        simulator.instrMemory.write(i, assembler.instructions[i])

    # Initialize some registers and data memory
    intRegisters = simulator.registerDict[RegType.GP_INT]
    floatRegisters = simulator.registerDict[RegType.GP_INT]
    for i in range(len(intRegisters)):
        simulator.registerDict[RegType.GP_INT][i].write(i)
    for i in range(len(floatRegisters)):
        simulator.registerDict[RegType.GP_FLOAT][i].write(float(i))
    for i in range(simulator.dataMemory.totalSize):
        simulator.dataMemory.write(i, i)

    # Keep calling tick until finished
    while not simulator.finished() and simulator.controlUnit.cycleCounter < 1000:
        simulator.tick()

    with open("tmp", 'w') as f:
Beispiel #10
0
class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, onj=None, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.messageController = MessageController()
        self.simSettings = SimulatorSettings()
        self.sim = Simulator(self.simSettings, self.messageController)
        self.con = Controller(self.simSettings, self.sim.hospitalsLocations(),
                              self.sim.ambulancesDistribution(),
                              self.messageController)
        self.ui.Mplwidget
        self.ui.Mplwidget.draw_hospital_on_map(self.con.Hospitals)
        self.ui.hospwidget
        self.ui.hospwidget.draw_all_hosp_inf(self.con.Hospitals)
        self.tablica_komunikatow = []
        self.control_events = []
        self.observ_from_message = []
        self.ui.start.clicked.connect(self.start_sim)
        self.ui.pauza.clicked.connect(self.stop_sim)
        self.ui.reset.clicked.connect(self.reset_sim)
        self.ui.delay_time.setValue(50)
        self.ui.delay_time.valueChanged.connect(self.change_interval)
        self.timer = QtCore.QTimer(self,
                                   interval=self.ui.delay_time.value(),
                                   timeout=self.simulation)
        self.printedCar = []
        self.printedVirus = []
        self.iterationsNumber = 0
        #self.con.printState()

    @QtCore.pyqtSlot()
    def start_sim(self):
        QtCore.QTimer.singleShot(0, self.simulation)
        self.timer.start()

    @QtCore.pyqtSlot()
    def stop_sim(self):
        self.timer.stop()

    def reset_sim(self):
        del self.messageController
        del self.simSettings
        del self.sim
        del self.con
        self.ui.Mplwidget.clean_hospital_on_map()
        self.ui.hospwidget.clean_all_hosp_inf()
        self.clear_widget_scrol()
        self.messageController = MessageController()
        self.simSettings = SimulatorSettings()
        self.sim = Simulator(self.simSettings, self.messageController)
        self.con = Controller(self.simSettings, self.sim.hospitalsLocations(),
                              self.sim.ambulancesDistribution(),
                              self.messageController)
        self.ui.Mplwidget.draw_hospital_on_map(self.con.Hospitals)
        self.ui.hospwidget.draw_all_hosp_inf(self.con.Hospitals)
        self.printedCar.clear()
        self.printedVirus.clear()
        self.iterationsNumber = 0
        #self.con.printState()

    def change_interval(self):
        self.timer.setInterval(self.ui.delay_time.value())

    def simulation(self):
        self.sim.simulatorMianLoop(self.tablica_komunikatow,
                                   self.control_events)
        if self.messageController.readAllObservableEventsForSimulation():
            self.observ_from_message.append(
                self.messageController.readAllObservableEventsForSimulation())

        if len(self.observ_from_message) > 0:
            #print(self.observ_from_message)
            #if len(self.observ_from_message[0])>1:
            #    self.timer.stop()
            for event in self.observ_from_message[0]:
                #print(event)
                if event[0] == 'E1o':
                    self.ui.Mplwidget.draw_accident_on_map(tuple(event[1][0]))
                    self.printedVirus.append(tuple(event[1][0]))
                elif event[
                        0] == 'E4o':  #Karetka dojechała na miejsce zgłoszenia - usuń ze szpitala
                    self.ui.Mplwidget.remove_car_from_map(
                        (self.con.Hospitals[event[1][0] - 1].location[0] + 1,
                         self.con.Hospitals[event[1][0] - 1].location[1] + 1))
                    self.printedCar.remove(
                        (self.con.Hospitals[event[1][0] - 1].location[0] + 1,
                         self.con.Hospitals[event[1][0] - 1].location[1] + 1))
                    self.ui.Mplwidget.draw_car_on_map(tuple(event[1][2]))
                    self.printedCar.append(tuple(event[1][2]))
                elif event[
                        0] == 'E9o':  #Karetka wróciła do szpitala bez chorego
                    self.ui.Mplwidget.remove_car_from_map(
                        (self.con.Hospitals[event[1][0] - 1].location[0] + 1,
                         self.con.Hospitals[event[1][0] - 1].location[1] + 1))
                    self.printedCar.remove(
                        (self.con.Hospitals[event[1][0] - 1].location[0] + 1,
                         self.con.Hospitals[event[1][0] - 1].location[1] + 1))
                elif event[
                        0] == 'E6o':  #Karetka wróciła do szpitala z chorym - usuń ze szpitala
                    self.ui.Mplwidget.remove_car_from_map(
                        (self.con.Hospitals[event[1][0] - 1].location[0] + 1,
                         self.con.Hospitals[event[1][0] - 1].location[1] + 1))
                    self.printedCar.remove(
                        (self.con.Hospitals[event[1][0] - 1].location[0] + 1,
                         self.con.Hospitals[event[1][0] - 1].location[1] + 1))
                elif event[
                        0] == 'E10o':  #Karetka wraca do szpitala bez chorego
                    self.ui.Mplwidget.remove_accident_from_map(
                        tuple(event[1][2]))
                    self.printedCar.remove(tuple(event[1][2]))
                    self.ui.Mplwidget.remove_car_from_map(tuple(event[1][2]))
                    self.printedVirus.remove(tuple(event[1][2]))
                    self.ui.Mplwidget.draw_car_on_map(
                        (self.con.Hospitals[event[1][0] - 1].location[0] + 1,
                         self.con.Hospitals[event[1][0] - 1].location[1] + 1))
                    self.printedCar.append(
                        (self.con.Hospitals[event[1][0] - 1].location[0] + 1,
                         self.con.Hospitals[event[1][0] - 1].location[1] + 1))
            self.observ_from_message.clear()

        if len(self.control_events) > 0:
            #print(self.control_events)
            for event in self.control_events[0]:
                #print('control', event)
                if event[0] == 'E1c':  #Karetka wyjeżdża ze szpitala
                    self.ui.Mplwidget.draw_car_on_map(
                        (self.con.Hospitals[event[1][0] - 1].location[0] + 1,
                         self.con.Hospitals[event[1][0] - 1].location[1] + 1))
                    self.printedCar.append(
                        (self.con.Hospitals[event[1][0] - 1].location[0] + 1,
                         self.con.Hospitals[event[1][0] - 1].location[1] + 1))
                elif event[0] == 'E2c':  #Karetka wraca do szpitala z chorym
                    self.ui.Mplwidget.remove_accident_from_map(
                        tuple(event[1][1]))
                    self.ui.Mplwidget.remove_car_from_map(tuple(event[1][1]))
                    self.printedCar.remove(tuple(event[1][1]))
                    self.printedVirus.remove(tuple(event[1][1]))
                    self.ui.Mplwidget.draw_car_on_map(
                        (self.con.Hospitals[event[1][0] - 1].location[0] + 1,
                         self.con.Hospitals[event[1][0] - 1].location[1] + 1))
                    self.printedCar.append(
                        (self.con.Hospitals[event[1][0] - 1].location[0] + 1,
                         self.con.Hospitals[event[1][0] - 1].location[1] + 1))
                else:
                    self.ui.Mplwidget.draw_car_on_map(
                        (self.con.Hospitals[event[1][1] - 1].location[0] + 1,
                         self.con.Hospitals[event[1][1] - 1].location[1] + 1))
                    self.printedCar.append(
                        (self.con.Hospitals[event[1][1] - 1].location[0] + 1,
                         self.con.Hospitals[event[1][1] - 1].location[1] + 1))
            self.control_events.clear()

        self.update_hospital_state(self.con.Hospitals)
        self.con.controllerMainLoop(self.tablica_komunikatow)
        #print(0.4*self.simSettings.numberOfAmbulances)
        if len(self.tablica_komunikatow) > 0:
            count_ambulances = 0
            for hospitals in self.con.Hospitals:
                count_ambulances += np.in1d(hospitals.ambulances, 6).sum()
            if self.tablica_komunikatow[0][0] == '!' and (
                    not self.sim.stability() or count_ambulances <
                    0.4 * self.simSettings.numberOfAmbulances):
                self.timer.stop()
                self.con.printState()
                print("System przestał być wydolny po ", self.iterationsNumber,
                      " iteracjach")
        self.update_widgets_scrol()
        self.iterationsNumber += 1
        #self.con.printState()
        #print("Karetki: ",self.printedCar)
        #print("Zgłosze: ",self.printedVirus)

    def update_widgets_scrol(self):
        for elem in self.tablica_komunikatow:
            object = QLabel(elem)
            self.ui.verticalLayout_2.addWidget(object)
        self.tablica_komunikatow = []

    def clear_widget_scrol(self):
        while self.ui.verticalLayout_2.count():
            item = self.ui.verticalLayout_2.takeAt(0)
            widget = item.widget()
            if widget is not None:
                widget.setParent(None)

    def update_hospital_state(self, hospitals):
        index = self.ui.hospwidget.glayout.count()
        for i in range(len(hospitals)):
            count_ambulances = np.in1d(hospitals[i].ambulances, 6).sum()
            self.ui.hospwidget.glayout.children()[i].itemAt(
                1).widget().setText(str(count_ambulances))
            self.ui.hospwidget.glayout.children()[i].itemAt(
                2).widget().changecolor(hospitals[i].personnel)
            self.ui.hospwidget.glayout.children()[i].itemAt(
                3).widget().changecolor(hospitals[i].volume)