Example #1
0
 def __init__(self):
     self.animate_alarm = None
     self.model = GraphModel()
     self.view = GraphView(self)
     # use the first mode as the default
     mode = self.get_modes()[0]
     self.model.set_mode(mode)
     # update the view
     self.view.on_mode_change(mode)
     self.view.update_graph(True)
    def __init__(self):
        QWidget.__init__(self)
        self.model = None
        self.setWindowTitle("Cross Docking Project")
        self.setGeometry(400, 400, 400, 400)

        self.set_buttons()
        self.set_layout()

        self.truck_image_list = {}
        self.truckDataWindow = None

        self.data = DataStore()
        self.model = None

        self.current_iteration = 1
        self.iteration_limit = 100
        self.current_data_set = 0

        self.algorithms = None

        self.solution_choice = None

        self.scn = QGraphicsScene()
        self.simulation = GraphView(self.scn)
Example #3
0
class GraphController:
    """
    A class responsible for setting up the model and view and running
    the application.
    """
    def __init__(self):
        self.animate_alarm = None
        self.model = GraphModel()
        self.view = GraphView(self)
        # use the first mode as the default
        mode = self.get_modes()[0]
        self.model.set_mode(mode)
        # update the view
        self.view.on_mode_change(mode)
        self.view.update_graph(True)

    def get_modes(self):
        """Allow our view access to the list of modes."""
        return self.model.get_modes()

    def set_mode(self, m):
        """Allow our view to set the mode."""
        rval = self.model.set_mode(m)
        self.view.update_graph(True)
        return rval

    def get_data(self, offset, range):
        """Provide data to our view for the graph."""
        return self.model.get_data(offset, range)

    def main(self):
        self.loop = urwid.MainLoop(self.view, self.view.palette)
        self.loop.run()

    def animate_graph(self, loop=None, user_data=None):
        """update the graph and schedule the next update"""
        self.view.update_graph()
        self.animate_alarm = self.loop.set_alarm_in(UPDATE_INTERVAL,
                                                    self.animate_graph)

    def stop_animation(self):
        """stop animating the graph"""
        if self.animate_alarm:
            self.loop.remove_alarm(self.animate_alarm)
        self.animate_alarm = None
class MainWindow(QWidget):
    """
    Main window class for capraz_sevkiyat project
    """
    def __init__(self):
        QWidget.__init__(self)
        self.model = None
        self.setWindowTitle("Cross Docking Project")
        self.setGeometry(400, 400, 400, 400)

        self.set_buttons()
        self.set_layout()

        self.truck_image_list = {}
        self.truckDataWindow = None

        self.data = DataStore()
        self.model = None

        self.current_iteration = 1
        self.iteration_limit = 100
        self.current_data_set = 0

        self.algorithms = None

        self.solution_choice = None

        self.scn = QGraphicsScene()
        self.simulation = GraphView(self.scn)

    def set_buttons(self):
        self.new_data_set_button = QPushButton('New Data Set')
        self.load_data_set_button = QPushButton('Load Data Set')
        self.save_data_set_button = QPushButton('Save Data Set')

        self.truck_data_button = QPushButton('Truck Data')
        self.system_data_button = QPushButton('System Data')
        self.algorithm_data_button = QPushButton('Algorithm Data')

        self.generate_data_set_button = QPushButton('Generate Data Set')
        self.show_data_button = QPushButton('Show Data Set')
        self.print_gams_button = QPushButton('Print gams output')

        self.data_set_ready_button = QPushButton('Data Set Ready')

        self.solve_step_button = QPushButton('Solve Next Step')
        self.solve_iteration_button = QPushButton('Solve Next Iteration')
        self.solve_next_data_set_button = QPushButton('Solve Next Data Set')

        self.show_logger_button = QPushButton('Show Logger')
        self.show_simulation_button = QPushButton('Show Simulation')
        self.show_data_table = QPushButton('Show Run Time Data Table')

        self.data_set_number = QSpinBox()
        self.data_set_number.setMinimum(0)

        self.new_data_set_button.clicked.connect(self.new_data_set)
        self.load_data_set_button.clicked.connect(self.load_data)
        self.save_data_set_button.clicked.connect(self.save_data)

        self.truck_data_button.clicked.connect(self.show_truck_data)
        self.system_data_button.clicked.connect(self.show_system_data)
        self.algorithm_data_button.clicked.connect(self.show_algorithm_data)

        self.generate_data_set_button.clicked.connect(self.generate_data_set)
        self.show_data_button.clicked.connect(self.show_data)
        self.print_gams_button.clicked.connect(self.print_gams)

        self.data_set_ready_button.clicked.connect(self.data_set_ready)

        self.show_logger_button.clicked.connect(self.show_logger)
        self.show_data_table.clicked.connect(self.show_runtime_table)

        self.solve_next_data_set_button.clicked.connect(self.data_set_button)
        self.solve_iteration_button.clicked.connect(self.iteration_button)
        self.solve_step_button.clicked.connect(self.step_button)
        self.data_set_number.valueChanged.connect(self.set_data_set_number)

    def set_layout(self):
        self.data_set_layout = QGridLayout()
        self.data_set_layout.addWidget(self.new_data_set_button, 1 ,1)
        self.data_set_layout.addWidget(self.load_data_set_button, 1 ,2)
        self.data_set_layout.addWidget(self.save_data_set_button, 1 ,3)

        self.data_set_layout.addWidget(self.truck_data_button, 2 ,1)
        self.data_set_layout.addWidget(self.system_data_button, 2 ,2)
        self.data_set_layout.addWidget(self.algorithm_data_button, 2 ,3)

        self.data_set_layout.addWidget(self.generate_data_set_button, 3, 1)
        self.data_set_layout.addWidget(self.show_data_button, 3, 2)
        self.data_set_layout.addWidget(self.print_gams_button, 3, 3)

        self.data_set_layout.addWidget(self.data_set_ready_button, 4, 1)

        self.solver_layout = QGridLayout()
        self.solver_layout.addWidget(self.solve_step_button, 1, 1)
        self.solver_layout.addWidget(self.solve_iteration_button, 1, 2)
        self.solver_layout.addWidget(self.solve_next_data_set_button, 1, 3)
        self.solver_layout.addWidget(self.data_set_number, 1, 4)

        self.interaction_layout = QGridLayout()
        self.interaction_layout.addWidget(self.show_logger_button, 1, 1)
        self.interaction_layout.addWidget(self.show_simulation_button, 1, 3)
        self.interaction_layout.addWidget(self.show_data_table, 1, 4)

        self.layout = QVBoxLayout()
        self.layout.addLayout(self.data_set_layout)
        self.layout.addLayout(self.solver_layout)
        self.layout.addLayout(self.interaction_layout)

        self.setLayout(self.layout)
        self.pause_bool = False

    def new_data_set(self):
        """
        :return:
        """
        self.data = DataStore()

    def load_data(self):
        """
        loads prev saved data
        :return:
        """
        file_name, _ = QFileDialog.getOpenFileName(self, 'Open file', '/home')
        self.data = pickle.load(open(file_name, 'rb'))

    def save_data(self):
        """
        saves current data
        :return:
        """
        file_name, _ = QFileDialog.getSaveFileName(self, 'Save file', '/home')
        pickle.dump(self.data,  open(file_name, 'wb'))

    def generate_data_set(self):
        # ask if sure

        self.data.arrival_times = []
        self.data.boundaries = []
        self.model = Solver(self.data)

        for i in range(len(self.data.data_set_list)):
            self.model.current_data_set = i
            self.model.set_data()

    def show_data(self):
        self.data_show = ShowData(self.data)
        self.data_show.exec_()

    def print_gams(self):
        file_name, _ = QFileDialog.getSaveFileName(self, 'Open file', '/home')
        for i in range(len(self.data.data_set_list)):
            gams_writer(file_name + str(i), i, self.data )

    def show_truck_data(self):
        """
        shows data about the trucks
        :return:
        """
        self.truckDataWindow = TruckDataWindow(self.data)
        self.truckDataWindow.exec_()

    def show_system_data(self):
        """
        shows data set
        :return:
        """
        self.dataWindow = DataSetWindow(self.data)
        self.dataWindow.exec_()

    def show_algorithm_data(self):
        pass

    def data_set_ready(self):
        # setup for one data set
        self.algorithms = Algorithms()
        self.model = Solver(self.data)
        self.model.current_data_set = self.current_data_set
        self.model.load_data_set()
        self.algorithms.set_algorithms(self.model)

    def show_logger(self):
        self.logger = LogData()
        root = logging.getLogger()
        root.setLevel(logging.INFO)

        ch = logging.StreamHandler(self.logger)
        ch.setLevel(logging.INFO)
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        ch.setFormatter(formatter)
        root.addHandler(ch)
        self.logger.show()
        logging.info('Logger Started')

    def data_set_button(self):
        self.solution_choice = 'data_set'

        self.solve_dataset()

    def iteration_button(self):
        self.solution_choice = 'iteration'
        self.solution_type_choice()
        self.solve_dataset()

    def step_button(self):
        self.solution_choice = 'step'
        self.solution_type_choice()
        self.solve_dataset()

    def set_data_set_number(self):
        self.current_data_set = self.data_set_number.value()

    def solve_dataset(self):
        """
        solves one data set
        :return:
        """
        logging.info('Data Set Number: {0}'.format(self.current_data_set))
        self.model.current_data_set = self.current_data_set
        if self.data_set_bool:
            #print('one_set')1
            if self.current_iteration == 1 and self.model.current_time == 0:
                self.model.load_data_set()
            self.solve_iteration()

            if self.current_data_set == len(self.data.data_set_list):
            #    print('finish')
                self.current_iteration = 1
                self.current_data_set = 0
                self.trial_time = 0
        else:
            while self.current_data_set < len(self.data.data_set_list):
                if self.pause_bool:
                    break
                self.model.load_data_set()
                self.solve_iteration()
            #   print(self.current_data_set)
            self.current_data_set = 0

    def solve_iteration(self):
        """
        solves one iteration
        :return:
        """
        if self.iteration_bool:
            if self.model.current_time == 0:

                if self.current_iteration == 1:
                    self.algorithms.start()
                    self.model.set_sequence(self.algorithms.solution_sequence)
                    self.solve_whole_step()
                    self.model.reset()
                    self.algorithms.next()
                    self.model.set_sequence(self.algorithms.solution_sequence)
                else:
                    self.algorithms.next()
                    self.model.set_sequence(self.algorithms.solution_sequence)
            self.solve_step()

            if self.current_iteration == self.iteration_limit:
                self.log_results()
                self.current_iteration = 1
        else:
            while self.current_iteration < self.iteration_limit:
                if self.pause_bool:
                    break

                if self.model.current_time == 0:
                    if self.current_iteration == 1:
                        self.algorithms.start()
                    else:
                        self.algorithms.next()
                    self.model.set_sequence(self.algorithms.solution_sequence)
                # next sequence
                self.solve_step()
            self.current_iteration = 1
            self.log_results()

    def solve_step(self):
        if self.step_bool:
            self.solve_one_step()
        else:
            self.solve_whole_step()

    def solve_whole_step(self):
        """
        solves one iterations
        :return:
        """
        while not self.model.finish:
            # if self.model.current_time > 800:
            #
            #     break
            if self.pause_bool:
                break
            self.model.next_step()

            #finished
        for truck in itertools.chain(self.model.outbound_trucks.values(), self.model.compound_trucks.values()):
            truck.calculate_error()

        if self.runtime_table:
            self.runtime_table.update_tables()
            self.runtime_table.activateWindow()

        #add reset
        self.model.finish = False
        self.algorithms.solution_sequence['error'] = self.add_errors()
        self.model.reset()
        if self.current_iteration > 1:
            self.algorithms.calculate()
        self.current_iteration += 1

    def solve_one_step(self):
        """
        goes one time step forward
        :return:
        """

        self.model.next_step()
        # self.simulation.update_image()

        if self.runtime_table:
            self.runtime_table.update_tables()
            self.runtime_table.activateWindow()

        if self.model.finish:
            #finished
            logging.info("Finished iteration {0}".format(self.current_iteration))
            for truck in self.model.outbound_trucks.values():
                truck.calculate_error()
            self.add_errors()
            self.model.reset()
            # add reset
            self.current_iterpation += 1
            self.model.finish = False
            # update algorithm
            self.algorithms.solution_sequence['error'] = self.add_errors()
            self.algorithms.calculate()

    def add_errors(self):
        """
        adds absolute values of the errors

        :return:
        """
        total_error = 0
        for truck in itertools.chain(self.model.outbound_trucks.values(), self.model.compound_trucks.values()):
            total_error += abs(truck.error)
        logging.info("Error: {0}\n".format(total_error))
        return total_error

    def show_runtime_table(self):
        """
        shows data table of the
        :return:
        """
        self.runtime_table = TruckDataTable(self.algorithms, self.model)
        self.runtime_table.show()

    def simulation_cycle(self):
        i = 0
        for inbound_trucks in self.model.inbound_trucks.values():
            truck_name = inbound_trucks.truck_name
            self.truck_image_list[truck_name] = self.scn.addPixmap(self.truckPixmap)
            self.truck_image_list[truck_name].scale(0.2,0.2)
            self.truck_image_list[truck_name].setPos(-600,i*100)
            i = i +1
        self.simulation.show()

    def solution_type_choice(self):
        """
        update bools for the choosen solution type
        :return:
        """

        if self.solution_choice == 'solve':
            self.solve_bool = True
            self.data_set_bool = False
            self.iteration_bool = False
            self.step_bool = False

        elif self.solution_choice == 'data_set':
            self.solve_bool = True
            self.data_set_bool = True
            self.iteration_bool = False
            self.step_bool = False
            self.data_set_ready()

        elif self.solution_choice == 'iteration':
            self.solve_bool = True
            self.data_set_bool = True
            self.iteration_bool = True
            self.step_bool = False

        elif self.solution_choice == 'step':
            self.solve_bool = True
            self.data_set_bool = True
            self.iteration_bool = True
            self.step_bool = True

    def print_simulation_data(self):
        logging.info("Iteration Number: {0}\n".format(self.current_iteration))
        logging.info("Inbound Sequence: {0}\n".format(self.algorithms.solution_sequence['inbound']))
        logging.info("Outbound Sequence: {0}\n".format(self.algorithms.solution_sequence['outbound']))
        logging.info("Error value: {0}\n".format(self.algorithms.solution_sequence['error']))

    def log_results(self):
        logging.info("Best result:")
        logging.info("Inbound Sequence: {0}\n".format(self.algorithms.best_sequence['inbound']))
        logging.info("Outbound Sequence: {0}\n".format(self.algorithms.best_sequence['outbound']))
        logging.info("Error value: {0}\n".format(self.algorithms.best_sequence['error']))
Example #5
0
    from event import collision

    filename = os.path.join(FILE_DIR,
                            "../../ia/event/goals/navigation/map.xml")
    try:
        offset = sys.argv[1]
    except:
        offset = 0
    start = time.time()
    other_bot = Bot()
    other_bot.name = 'other'
    other_bot["getRayon"] = 200
    used_bot = Bot()
    used_bot.name = 'used'
    used_bot["getRayon"] = 120
    ennemy1 = Bot()
    ennemy1.name = 'en1'
    ennemy2 = Bot()
    ennemy2.name = 'en2'
    ennemy1["getPosition"] = (1800, 1500)
    ennemy1["getRayon"] = 200
    ennemy2["getPosition"] = (2200, 500)
    ennemy1["getRayon"] = 120
    ng = navigation.PathFinding([used_bot, other_bot, ennemy1, ennemy2],
                                filename)
    col = collision.Collision([used_bot, other_bot, ennemy1, ennemy2])
    print("init time : %s" % (time.time() - start))

    v = GraphView(ng, col, other_bot, used_bot)
    v.mainloop()
Example #6
0
	from event.goals import navigation
	from event import collision
	
	filename = os.path.join(FILE_DIR, "../../ia/event/goals/navigation/map.xml")
	try:
		offset = sys.argv[1]
	except:
		offset = 0
	start = time.time()
	other_bot = Bot()
	other_bot.name = 'other'
	other_bot["getRayon"] = 200
	used_bot = Bot()
	used_bot.name = 'used'
	used_bot["getRayon"] = 120
	ennemy1 = Bot()
	ennemy1.name = 'en1'
	ennemy2 = Bot()
	ennemy2.name = 'en2'
	ennemy1["getPosition"] = (1800, 1500)
	ennemy1["getRayon"] = 200
	ennemy2["getPosition"] = (2200, 500)
	ennemy1["getRayon"] = 120
	ng = navigation.PathFinding([used_bot, other_bot, ennemy1, ennemy2], filename)
	col = collision.Collision([used_bot, other_bot, ennemy1, ennemy2])
	print("init time : %s" % (time.time() - start))
	
	v = GraphView(ng, col, other_bot, used_bot)
	v.mainloop()

Example #7
0
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.setWindowModality(QtCore.Qt.ApplicationModal)
        MainWindow.resize(1100, 574)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
                                           QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            MainWindow.sizePolicy().hasHeightForWidth())
        MainWindow.setSizePolicy(sizePolicy)
        self.centralWidget = QtWidgets.QWidget(MainWindow)
        self.centralWidget.setObjectName("centralWidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.centralWidget)
        self.verticalLayout.setContentsMargins(11, 11, 11, 11)
        self.verticalLayout.setSpacing(6)
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setSpacing(6)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.importButton = QtWidgets.QPushButton(self.centralWidget)
        self.importButton.setObjectName("importButton")
        self.horizontalLayout.addWidget(self.importButton)
        spacerItem = QtWidgets.QSpacerItem(40, 20,
                                           QtWidgets.QSizePolicy.Expanding,
                                           QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        self.label_9 = QtWidgets.QLabel(self.centralWidget)
        self.label_9.setObjectName("label_9")
        self.horizontalLayout.addWidget(self.label_9)
        self.intervalSpinBox = QtWidgets.QDoubleSpinBox(self.centralWidget)
        self.intervalSpinBox.setMaximum(9.99)
        self.intervalSpinBox.setSingleStep(0.01)
        self.intervalSpinBox.setProperty("value", 0.1)
        self.intervalSpinBox.setObjectName("intervalSpinBox")
        self.horizontalLayout.addWidget(self.intervalSpinBox)
        self.generationCounter = QtWidgets.QLabel(self.centralWidget)
        self.generationCounter.setMinimumSize(QtCore.QSize(140, 0))
        self.generationCounter.setLayoutDirection(QtCore.Qt.LeftToRight)
        self.generationCounter.setAutoFillBackground(False)
        self.generationCounter.setAlignment(QtCore.Qt.AlignRight
                                            | QtCore.Qt.AlignTrailing
                                            | QtCore.Qt.AlignVCenter)
        self.generationCounter.setObjectName("generationCounter")
        self.horizontalLayout.addWidget(self.generationCounter)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setSpacing(6)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.label = QtWidgets.QLabel(self.centralWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum,
                                           QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.label.sizePolicy().hasHeightForWidth())
        self.label.setSizePolicy(sizePolicy)
        self.label.setObjectName("label")
        self.horizontalLayout_2.addWidget(self.label)
        self.antsQuantitySpinBox = QtWidgets.QSpinBox(self.centralWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum,
                                           QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.antsQuantitySpinBox.sizePolicy().hasHeightForWidth())
        self.antsQuantitySpinBox.setSizePolicy(sizePolicy)
        self.antsQuantitySpinBox.setMinimum(1)
        self.antsQuantitySpinBox.setMaximum(9999)
        self.antsQuantitySpinBox.setProperty("value", 5)
        self.antsQuantitySpinBox.setObjectName("antsQuantitySpinBox")
        self.horizontalLayout_2.addWidget(self.antsQuantitySpinBox)
        self.label_2 = QtWidgets.QLabel(self.centralWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum,
                                           QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.label_2.sizePolicy().hasHeightForWidth())
        self.label_2.setSizePolicy(sizePolicy)
        self.label_2.setObjectName("label_2")
        self.horizontalLayout_2.addWidget(self.label_2)
        self.generationsQuantitySpinBox = QtWidgets.QSpinBox(
            self.centralWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum,
                                           QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.generationsQuantitySpinBox.sizePolicy().hasHeightForWidth())
        self.generationsQuantitySpinBox.setSizePolicy(sizePolicy)
        self.generationsQuantitySpinBox.setMinimum(1)
        self.generationsQuantitySpinBox.setMaximum(9999)
        self.generationsQuantitySpinBox.setProperty("value", 100)
        self.generationsQuantitySpinBox.setObjectName(
            "generationsQuantitySpinBox")
        self.horizontalLayout_2.addWidget(self.generationsQuantitySpinBox)
        self.label_3 = QtWidgets.QLabel(self.centralWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum,
                                           QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.label_3.sizePolicy().hasHeightForWidth())
        self.label_3.setSizePolicy(sizePolicy)
        self.label_3.setObjectName("label_3")
        self.horizontalLayout_2.addWidget(self.label_3)
        self.alphaSpinBox = QtWidgets.QDoubleSpinBox(self.centralWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum,
                                           QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.alphaSpinBox.sizePolicy().hasHeightForWidth())
        self.alphaSpinBox.setSizePolicy(sizePolicy)
        self.alphaSpinBox.setMaximum(1.0)
        self.alphaSpinBox.setSingleStep(0.01)
        self.alphaSpinBox.setProperty("value", 0.4)
        self.alphaSpinBox.setObjectName("alphaSpinBox")
        self.horizontalLayout_2.addWidget(self.alphaSpinBox)
        self.label_4 = QtWidgets.QLabel(self.centralWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum,
                                           QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.label_4.sizePolicy().hasHeightForWidth())
        self.label_4.setSizePolicy(sizePolicy)
        self.label_4.setObjectName("label_4")
        self.horizontalLayout_2.addWidget(self.label_4)
        self.betaSpinBox = QtWidgets.QDoubleSpinBox(self.centralWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum,
                                           QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.betaSpinBox.sizePolicy().hasHeightForWidth())
        self.betaSpinBox.setSizePolicy(sizePolicy)
        self.betaSpinBox.setMaximum(1.0)
        self.betaSpinBox.setSingleStep(0.01)
        self.betaSpinBox.setProperty("value", 0.5)
        self.betaSpinBox.setObjectName("betaSpinBox")
        self.horizontalLayout_2.addWidget(self.betaSpinBox)
        self.label_5 = QtWidgets.QLabel(self.centralWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum,
                                           QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.label_5.sizePolicy().hasHeightForWidth())
        self.label_5.setSizePolicy(sizePolicy)
        self.label_5.setObjectName("label_5")
        self.horizontalLayout_2.addWidget(self.label_5)
        self.evaportationRatioSpinBox = QtWidgets.QDoubleSpinBox(
            self.centralWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum,
                                           QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.evaportationRatioSpinBox.sizePolicy().hasHeightForWidth())
        self.evaportationRatioSpinBox.setSizePolicy(sizePolicy)
        self.evaportationRatioSpinBox.setMaximum(1.0)
        self.evaportationRatioSpinBox.setSingleStep(0.01)
        self.evaportationRatioSpinBox.setProperty("value", 0.25)
        self.evaportationRatioSpinBox.setObjectName("evaportationRatioSpinBox")
        self.horizontalLayout_2.addWidget(self.evaportationRatioSpinBox)
        self.label_6 = QtWidgets.QLabel(self.centralWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum,
                                           QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.label_6.sizePolicy().hasHeightForWidth())
        self.label_6.setSizePolicy(sizePolicy)
        self.label_6.setObjectName("label_6")
        self.horizontalLayout_2.addWidget(self.label_6)
        self.pheromoneZeroSpinBox = QtWidgets.QDoubleSpinBox(
            self.centralWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum,
                                           QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.pheromoneZeroSpinBox.sizePolicy().hasHeightForWidth())
        self.pheromoneZeroSpinBox.setSizePolicy(sizePolicy)
        self.pheromoneZeroSpinBox.setMaximum(1.0)
        self.pheromoneZeroSpinBox.setSingleStep(0.01)
        self.pheromoneZeroSpinBox.setProperty("value", 0.05)
        self.pheromoneZeroSpinBox.setObjectName("pheromoneZeroSpinBox")
        self.horizontalLayout_2.addWidget(self.pheromoneZeroSpinBox)
        self.label_7 = QtWidgets.QLabel(self.centralWidget)
        self.label_7.setObjectName("label_7")
        self.horizontalLayout_2.addWidget(self.label_7)
        self.startNodeComboBox = QtWidgets.QComboBox(self.centralWidget)
        self.startNodeComboBox.setMinimumSize(QtCore.QSize(100, 0))
        self.startNodeComboBox.setObjectName("startNodeComboBox")
        self.horizontalLayout_2.addWidget(self.startNodeComboBox)
        self.label_8 = QtWidgets.QLabel(self.centralWidget)
        self.label_8.setObjectName("label_8")
        self.horizontalLayout_2.addWidget(self.label_8)
        self.endNodeComboBox = QtWidgets.QComboBox(self.centralWidget)
        self.endNodeComboBox.setMinimumSize(QtCore.QSize(100, 0))
        self.endNodeComboBox.setObjectName("endNodeComboBox")
        self.horizontalLayout_2.addWidget(self.endNodeComboBox)
        spacerItem1 = QtWidgets.QSpacerItem(40, 20,
                                            QtWidgets.QSizePolicy.Expanding,
                                            QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem1)
        self.solveButton = QtWidgets.QPushButton(self.centralWidget)
        self.solveButton.setObjectName("solveButton")
        self.horizontalLayout_2.addWidget(self.solveButton)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.frameLabel = GraphView(self.centralWidget)
        sizePolicy = QtWidgets.QSizePolicy(
            QtWidgets.QSizePolicy.Fixed,
            QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frameLabel.sizePolicy().hasHeightForWidth())
        self.frameLabel.setSizePolicy(sizePolicy)
        self.frameLabel.setMinimumSize(QtCore.QSize(1, 200))
        self.frameLabel.setMaximumSize(QtCore.QSize(1472, 828))
        self.frameLabel.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))
        self.frameLabel.setStyleSheet(
            "QWidget { background:rgb(200,200,200); }")
        self.frameLabel.setScaledContents(True)
        self.frameLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.frameLabel.setObjectName("frameLabel")
        self.verticalLayout.addWidget(self.frameLabel)
        MainWindow.setCentralWidget(self.centralWidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
    def __init__(self, status_bar):
        """
        init text screen for info
        :return:
        """
        QWidget.__init__(self)
        self.data = None
        self.infoText = QTextEdit()
        self.infoText.setReadOnly(True)
        self.scn = QGraphicsScene()
        self.simulation = GraphView(self.scn)

        self.status_bar = status_bar
        # solution types
        self.solution_list = {}
        self.solution_list['iteration'] = self.solve_iteration
        self.solution_list['step'] = self.solve_step
        self.solution_list['data_set'] = self.solve_dataset
        self.solution_list['solve'] = self.solve

        self.solution_type = 'iteration'

        # cycle booleans
        self.solve_bool = False
        self.step_bool = False
        self.iteration_bool = False
        self.data_set_bool = False
        self.pause_bool = False

        # buttons
        self.play_button = QPushButton("Play")
        self.play_button.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))

        self.stop_button = QPushButton("Stop")
        self.stop_button.setIcon(self.style().standardIcon(QStyle.SP_MediaStop))

        self.pause_button = QPushButton("Pause")
        self.pause_button.setIcon(self.style().standardIcon(QStyle.SP_MediaPause))

        self.solution_type_combo = QComboBox()
        self.solution_type_combo.addItems(self.solution_list.keys())

        self.new_data_set_button = QPushButton("New Data Set")

        self.play_button.setDisabled(True)
        self.stop_button.setDisabled(True)
        self.pause_button.setDisabled(True)
        self.solution_type_combo.setDisabled(True)

        self.play_button.clicked.connect(self.solve)
        self.pause_button.clicked.connect(self.pause)

        # setup layout
        self.layout = QGridLayout()
        self.data_set_layout = QGridLayout()

        self.data_set_layout.addWidget(self.new_data_set_button)
        self.layout.addLayout(self.data_set_layout, 1,1)
        # self.layout.addWidget(self.infoText, 1, 1, 1)
        # self.layout.addWidget(self.simulation, 1, 2)
        self.h_layout = QHBoxLayout()
        self.h_layout.addWidget(self.play_button)
        self.h_layout.addWidget(self.stop_button)
        self.h_layout.addWidget(self.pause_button)
        self.h_layout.addWidget(self.solution_type_combo)
        self.layout.addLayout(self.h_layout, 2, 1)

        # self.layout.addWidget(self.simulation, 1, 2)
        self.setLayout(self.layout)
        self.model = None
        self.data = DataStore()
        self.current_iteration = 1
        self.iteration_limit = 100
        self.current_data_set = 0
        self.data_string = ''
        self.algorithms = Algorithms()
        self.algo_screen = ChooseAlgo()

        self.trial_time = 0
class GeneralInfo(QWidget):
    """
    General information screen in main gui
    """
    def __init__(self, status_bar):
        """
        init text screen for info
        :return:
        """
        QWidget.__init__(self)
        self.data = None
        self.infoText = QTextEdit()
        self.infoText.setReadOnly(True)
        self.scn = QGraphicsScene()
        self.simulation = GraphView(self.scn)

        self.status_bar = status_bar
        # solution types
        self.solution_list = {}
        self.solution_list['iteration'] = self.solve_iteration
        self.solution_list['step'] = self.solve_step
        self.solution_list['data_set'] = self.solve_dataset
        self.solution_list['solve'] = self.solve

        self.solution_type = 'iteration'

        # cycle booleans
        self.solve_bool = False
        self.step_bool = False
        self.iteration_bool = False
        self.data_set_bool = False
        self.pause_bool = False

        # buttons
        self.play_button = QPushButton("Play")
        self.play_button.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))

        self.stop_button = QPushButton("Stop")
        self.stop_button.setIcon(self.style().standardIcon(QStyle.SP_MediaStop))

        self.pause_button = QPushButton("Pause")
        self.pause_button.setIcon(self.style().standardIcon(QStyle.SP_MediaPause))

        self.solution_type_combo = QComboBox()
        self.solution_type_combo.addItems(self.solution_list.keys())

        self.new_data_set_button = QPushButton("New Data Set")

        self.play_button.setDisabled(True)
        self.stop_button.setDisabled(True)
        self.pause_button.setDisabled(True)
        self.solution_type_combo.setDisabled(True)

        self.play_button.clicked.connect(self.solve)
        self.pause_button.clicked.connect(self.pause)

        # setup layout
        self.layout = QGridLayout()
        self.data_set_layout = QGridLayout()

        self.data_set_layout.addWidget(self.new_data_set_button)
        self.layout.addLayout(self.data_set_layout, 1,1)
        # self.layout.addWidget(self.infoText, 1, 1, 1)
        # self.layout.addWidget(self.simulation, 1, 2)
        self.h_layout = QHBoxLayout()
        self.h_layout.addWidget(self.play_button)
        self.h_layout.addWidget(self.stop_button)
        self.h_layout.addWidget(self.pause_button)
        self.h_layout.addWidget(self.solution_type_combo)
        self.layout.addLayout(self.h_layout, 2, 1)

        # self.layout.addWidget(self.simulation, 1, 2)
        self.setLayout(self.layout)
        self.model = None
        self.data = DataStore()
        self.current_iteration = 1
        self.iteration_limit = 100
        self.current_data_set = 0
        self.data_string = ''
        self.algorithms = Algorithms()
        self.algo_screen = ChooseAlgo()

        self.trial_time = 0

    def init_solution(self, data=DataStore()):
        """
        Starts solution for a data set
        :param data: data store
        :return:
        """
        self.play_button.setDisabled(False)
        self.stop_button.setDisabled(False)
        self.pause_button.setDisabled(False)
        self.solution_type_combo.setDisabled(False)

        self.data = data
        self.model = Solver(self.data)
        self.simulation.init_image(self.model)
        self.print_start_data()
        numbers = {'inbound': self.data.number_of_inbound_trucks, 'outbound': self.data.number_of_outbound_trucks,
                   'compound': self.data.number_of_compound_trucks, 'receive': self.data.number_of_receiving_doors,
                   'shipping': self.data.number_of_shipping_doors}
        self.algorithms.set_algorithms(self.model)
        self.model.set_data(0)

    def solution_type_choice(self):
        """
        update bools for the choosen solution type
        :return:
        """
        choice = self.solution_type_combo.currentText()
        if choice == 'solve':
            self.solve_bool = True
            self.data_set_bool = False
            self.iteration_bool = False
            self.step_bool = False

        elif choice == 'data_set':
            self.solve_bool = True
            self.data_set_bool = True
            self.iteration_bool = False
            self.step_bool = False

        elif choice == 'iteration':
            self.solve_bool = True
            self.data_set_bool = True
            self.iteration_bool = True
            self.step_bool = False

        elif choice == 'step':
            self.solve_bool = True
            self.data_set_bool = True
            self.iteration_bool = True
            self.step_bool = True

    def choose_algorithm(self):
        """
        choose and algorithm
        :return:
        """
        self.algo_screen.exec_()
        self.iteration_limit = self.algo_screen.iteration_number
        #get algorithm

    def pause(self):
        self.pause_bool = True

    def solve(self):
        """
        solves all of the data sets
        :return:
        """
        self.pause_bool = False
        self.solution_type_choice()
        # print('solve')
        self.solve_dataset()

    def solve_dataset(self):
        """
        solves one data set
        :return:
        """
        if self.data_set_bool:
            #print('one_set')1
            if self.current_iteration == 1 and self.model.current_time == 0:
                self.model.set_data(self.current_data_set)
            self.solve_iteration()

            if self.current_data_set == len(self.data.data_set_list):
            #    print('finish')
                self.current_iteration = 1
                self.current_data_set = 0
                self.trial_time = 0
        else:
            while self.current_data_set < len(self.data.data_set_list):
                if self.pause_bool:
                    break
                self.model.set_data(self.current_data_set)
                self.solve_iteration()
                self.current_data_set += 1
            #   print(self.current_data_set)
            self.current_data_set = 0

    def solve_iteration(self):
        """
        solves one iteration
        :return:
        """

        if self.iteration_bool:
            #print('one_iteration')
            if self.model.current_time == 0:

                if self.current_iteration == 1:
                    print('start')
                    self.algorithms.start()
                    self.model.set_sequence(self.algorithms.solution_sequence)
                    self.solve_whole_step()
                    self.algorithms.next()
                    self.model.set_sequence(self.algorithms.solution_sequence)
                else:
                    self.algorithms.next()
                    self.model.set_sequence(self.algorithms.solution_sequence)
                self.print_simulation_data()
            self.solve_step()

            if self.current_iteration == self.iteration_limit:
                self.current_data_set += 1
                self.current_iteration = 1
        else:
            while self.current_iteration < self.iteration_limit:
                if self.pause_bool:
                    break

                self.print_simulation_data()
                if self.model.current_time == 0:
                    if self.current_iteration == 1:
                        self.algorithms.start()
                    else:
                        self.algorithms.next_sequence()
                    self.model.set_sequence(self.algorithms.solution_sequence)
                # next sequence
                self.solve_step()
                self.current_iteration += 1
            #print(self.current_iteration)
            self.current_iteration = 1
            #print('whole_iteration')

    def solve_step(self):
        if self.step_bool:
            self.solve_one_step()
        else:
            self.solve_whole_step()

    def solve_whole_step(self):
        """
        solves one iterations
        :return:
        """
        while not self.model.finish:
            if self.model.current_time > 800:
                print('time limit')
                break
            if self.pause_bool:
                break
            self.model.next_step()

            #finished
        for truck in itertools.chain(self.model.outbound_trucks.values(), self.model.compound_trucks.values()):
            truck.calculate_error()

        #add reset
        self.model.finish = False
        self.algorithms.solution_sequence['error'] = self.add_errors()
        self.model.reset_trucks()
        if self.current_iteration > 1:
            self.algorithms.calculate()
        self.current_iteration += 1
        #self.print_results()

    def solve_one_step(self):
        """
        goes one time step forward
        :return:
        """

        self.model.next_step()
        self.simulation.update_image()

        if self.model.finish:
            #finished
            for truck in self.model.outbound_trucks.values():
                truck.calculate_error()
            self.model.reset_trucks()
            # add reset
            self.add_errors()
            #self.print_results()
            self.current_iteration += 1
            self.model.finish = False
            self.algorithms.current_sequence['error'] = self.add_errors()
            self.algorithms.calculate()

    def add_errors(self):
        """
        adds absolute values of the errors

        :return:
        """
        total_error = 0
        for truck in itertools.chain(self.model.outbound_trucks.values(), self.model.compound_trucks.values()):
            total_error += abs(truck.error)
        print('total error', total_error)
        return total_error

    def print_start_data(self):
        """
        prints the configuration info one time
        :return:
        """
        self.infoText.clear()
        self.data_string = ''
        self.data_string += "Number of inbound Trucks: {0}\n".format(self.data.number_of_inbound_trucks)
        self.data_string += "Number of outbound Trucks: {0}\n".format(self.data.number_of_outbound_trucks)
        self.data_string += "Number of compound Trucks: {0}\n".format(self.data.number_of_compound_trucks)
        self.data_string += "Number of receiving doors: {0}\n".format(self.data.number_of_receiving_doors)
        self.data_string += "Number of shipping doors: {0}\n".format(self.data.number_of_shipping_doors)
        #
        # data set
        self.infoText.setText(self.data_string)

    def step_time(self):
        pass

    def next_iteration(self):
        """
        increase iteration if limit not reached
        :return:
        """
        if self.current_iteration < self.iteration_limit:
            self.current_iteration += 1
        else:
            self.current_iteration = 0
            self.next_data_set()

    def next_data_set(self):
        pass

    def print_simulation_data(self):
        self.infoText.clear()
        self.data_string = ''
        self.data_string += "Iteration Number: {0}\n".format(self.current_iteration)
        self.data_string += "Inbound Sequence: {0}\n".format(self.algorithms.solution_sequence['inbound'])
        self.data_string += "Outbound Sequence: {0}\n".format(self.algorithms.solution_sequence['outbound'])
        # time
        # data set number
        # error value
        # sequence
        self.infoText.setText(self.data_string)

    def print_results(self):
        self.infoText.clear()
        for truck in self.model.outbound_trucks.values():
            print('bounds', truck.bounds)
            print('error', truck.error)
            print('finish', truck.finish_time)