Example #1
0
def display_recommend():
    # Load the user-book ratings
    rd = ReadData(500000, 1000, 100)
    (sparse_ratings, books_used, deleted_users) = rd.load_ratings_data()

    # Obtain the filled matrix using iterative singular value thresholding
    a = Algorithms(sparse_ratings)
    (ratings_with_nan, filled_ratings) = a.isvt()

    # Recommend books to a user who exists in the system: User #59. Changing the user ID will result in error.
    books_user = recommend_n_books(sparse_ratings, filled_ratings, books_used,
                                   59)
    vd1 = VisualizeData(books_user)
    vd1.display_book_info()

    # Recommend books to a user who does not exist in the system, using norm calculations: User #1004.
    # Changing the user ID will result in error.
    rec_n = UsingNorm(sparse_ratings, filled_ratings, books_used, 1004)
    books_norm = rec_n.rec_new_user_norm()
    vd2 = VisualizeData(books_norm[1])
    vd2.display_book_info()

    # Recommend books to a user who does not exist in the system, using kmeans clustering: User #1004.
    # Changing the user ID will result in error.
    rec_km = UsingKMeans(sparse_ratings, filled_ratings, books_used, 1004,
                         deleted_users)
    books_km = rec_km.rec_new_user_kmeans()
    vd3 = VisualizeData(books_km)
    vd3.display_book_info()
Example #2
0
def best_of_experiments(acids_sequence, n, m, folding=None):
    """Take a sequence of acids. Give it a certain folding. Try to fold the
    protein m times to improve this folding. Print the resulting score. Repeat
    this n times. Return the best result.
    """
    print('Start folding:', folding)
    best_score = 1
    for _ in range(n):
        protein = Protein(acids_sequence)
        if folding == 'cube_folding':
            if not Algorithms.cube_folding(protein, shift='', d3=True):
                print("failed to get a cube folding as start")
                continue
        elif folding == 'random_folding':
            if not Algorithms.random_folding(protein):
                print("failed to get a random folding as start")
                continue
        start_score = Algorithms.score(protein)
        if not Algorithms.fold_n_times(m, protein):
            print("failed to fold n times")
        end_score = Algorithms.score(protein)
        if end_score < best_score:
            best_score = end_score
            best_result = [acid.copy() for acid in protein.acids]
        print(
            'Start with score:\t{}\t\tEnd with score:\t{}\t\tBest score:\t{}'.
            format(start_score, end_score, best_score))
    protein.acids = best_result
    return protein
Example #3
0
def run_algorithms(list, algorithm):

    # Creating a sort object
    sort = Algorithms(list)

    if algorithm == 'insertionsort' or algorithm == 'insertsort':
        return sort.InsertSort()

    elif algorithm == 'selectionsort' or algorithm == 'selectsort':
        return sort.SelectSort()

    elif algorithm == 'countingsort' or algorithm == 'countsort':
        return sort.CountSort()

    elif algorithm == 'shellsort':
        return sort.ShellSort()

    elif algorithm == 'quicksort':
        return sort.QuickSort(list, 0, len(list))

    elif algorithm == 'mergesort':
        return sort.MergeSort(list)

    elif algorithm == 'heapsort':
        return sort.HeapSort(list)

    elif algorithm == 'radixsort':
        return sort.RadixSort()

    else:
        tools.error(algorithm)
        sys.exit(2)
Example #4
0
    def get(self, numbers):
        algorithm = Algorithms()
        result = []

        for num in range(1, int(numbers) + 1):
            result.append(algorithm.fizzbuzz(num))

        return result
Example #5
0
    def test_getLinkLoad_createsLoadsValuesOnEveryLink(self):
        network = self.__createNetwork()

        self.__interceptSeed()
        chromosome = dap.createChromosome(network)
        linkLoadList = dap.getLinkLoad(network, chromosome)

        self.assertEqual(linkLoadList, [91, 63, 44, 101, 61])
Example #6
0
    def test_getMaximumLoad_returnsTheBiggestValueFromTheList(self):
        network = self.__createNetwork()

        self.__interceptSeed()
        chromosome = dap.createChromosome(network)
        linkLoadList = dap.getLinkLoad(network, chromosome)

        maximumLoad = dap.getMaximumLoad(linkLoadList, network.links)

        self.assertEqual(maximumLoad, -3)
Example #7
0
    def test_getBestParents_returnsFourChromosomes(self):
        network = self.__createNetwork()
        configuration = self.testConfiguration()

        self.__interceptSeed()
        initialGeneration = dap.createFirstGeneration(network, configuration)
        controllers = dap.createDAPChromControllers(network, initialGeneration)
        controllers.sort(key=lambda c: c.maximumLoad)

        bestParents = dap.getBestParents(controllers)
        highestMaximumLoads = list(map(lambda x: x.maximumLoad, bestParents))

        self.assertEqual(highestMaximumLoads, [-34, -30, -29, -25])
Example #8
0
 def layoutUi(self):
     #
     # tool button
     self.menu = QtWidgets.QMenu()
     self.actionAddResource = QtWidgets.QAction('add resource')
     self.actionRemoveResource = QtWidgets.QAction('remove resource')
     for item in [self.actionAddResource, self.actionRemoveResource]:
         self.menu.addAction(item)
     self.toolButton.setMenu(self.menu)
     #
     # databases
     self.installed_path = os.path.join(
         os.path.abspath(os.path.dirname(sys.argv[0])), 'installed')
     with os.scandir(self.installed_path) as dir:
         installed_resources = [d.name for d in dir if d.is_dir()]
     self.resourceBox.addItems(installed_resources)
     #
     self.read_reference_database()
     #
     # manual setup of 'sort by' combo box
     self.sortBox.addItems(['full year', 'season', 'month'])
     #
     # available algorithms come from package algorithms
     self.algorithms = Algorithms()
     #
     # set algorithm aliases
     self.algoBox.addItems(self.algorithms.available_algorithms.keys())
Example #9
0
class Main:

    transactions = []
    transactions.append(Transaction(57247, 0.0887, 1))
    transactions.append(Transaction(98732, 0.1856, 2))
    transactions.append(Transaction(134928, 0.2307, 3))
    transactions.append(Transaction(77275, 0.1522, 4))
    transactions.append(Transaction(29240, 0.0532, 5))
    transactions.append(Transaction(15440, 0.0250, 6))
    transactions.append(Transaction(70820, 0.1409, 7))
    transactions.append(Transaction(139603, 0.2541, 8))
    transactions.append(Transaction(63718, 0.1147, 9))
    transactions.append(Transaction(143807, 0.2660, 10))
    transactions.append(Transaction(190457, 0.2933, 11))
    transactions.append(Transaction(40572, 0.686, 12))

    sizes = [
        57247, 98732, 134928, 77275, 29240, 15440, 70820, 139603, 63718,
        143807, 190457, 40572
    ]
    fees = [
        0.0887, 0.1856, 0.2307, 0.1522, 0.0532, 0.0250, 0.1409, 0.2541, 0.1147,
        0.2660, 0.2933, 0.0686
    ]
    sizes.sort(reverse=True)
    fees.sort(reverse=True)

    algo = Algorithms(sizes)
    algo.runSort()
    print(sizes)
Example #10
0
def test_bfs_1():
  config = [1, 2, 5, 3, 4, 0, 6, 7, 8]
  size = int(math.sqrt(len(config)))
  puzzle_state = PuzzleState(config, size)
  start_state_hash = Utilities.hashed_state(puzzle_state)
  start_state = puzzle_state

  def generate_node(node_options):
    return Node(**node_options)

  def compute_state_cost(state, state_hash):
    return 1

  def update_stats(max_search_depth = None, increment_expanded = False):
    pass

  result = Algorithms.search(
    expand = Utilities.expand,
    goal_state_check = Utilities.goal_state_check,
    hashed_state = Utilities.hashed_state,
    compute_state_cost = compute_state_cost,
    update_stats = update_stats,
    generate_node = generate_node,
    start_state_hash = start_state_hash,
    start_state = start_state,
    search_type = "bfs"
  )

  assert result.state.config == (0, 1, 2, 3, 4, 5, 6, 7, 8)
 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 main():

    sm = sys.argv[1].lower()

    begin_state = sys.argv[2].split(",")

    begin_state = tuple(map(int, begin_state))

    size = int(math.sqrt(len(begin_state)))

    hard_state = PuzzleState(begin_state, size)

    args = {
        "client_defined_expand": Utilities.expand,
        "client_defined_goal_state_check": Utilities.goal_state_check,
        "client_defined_hashed_state": Utilities.hashed_state,
        "client_defined_compute_state_cost": Utilities.compute_state_cost,
        "start_state_hash": sm,
        "start_state": hard_state,
    }

    if sm == "bfs":

        result = Algorithms.search_wrapper(
            **args,
            search_type = "bfs"
        )

    elif sm == "dfs":

        result = Algorithms.search_wrapper(
            **args,
            search_type = "dfs"
        )

    elif sm == "ast":

        result = Algorithms.search_wrapper(
            **args,
            search_type = "astar"
        )

    else:

        print("Enter valid command arguments !")
    
    Reporter.write_output(file_name = "output.txt", **result)
Example #13
0
def do_all():
    algorithms = ["depthfirst", "breadthfirst", "dijkstra", "Astar"]
    images = ["tiny", "braid200", "normal", "small", "combo400"]

    for a in algorithms:
        for i in images:
            start(Algorithms().__getitem__(a),
                  Images().__getitem__(i), i + '_' + a)
Example #14
0
    def decode_private_key(self, blob):
        alg = blob[0]
        if Algorithms(alg) != Algorithms.RABIN:
            raise ValueError("Wrong key algorithm")

        p = bytes_to_int(blob[1:][:len(blob[1:]) // 2])
        q = bytes_to_int(blob[1:][len(blob[1:]) // 2:])

        return p, q
    def decode_private_key(self, blob):
        alg = blob[0]
        if Algorithms(alg) != Algorithms.RSA:
            raise ValueError("Wrong key algorithm")

        d_len = bytes_to_int(blob[1:3] if blob[2] != 0 else blob[1:2])
        n_len = bytes_to_int(blob[3:5] if blob[4] != 0 else blob[3:4])

        return bytes_to_int(blob[5:5+d_len]), bytes_to_int(blob[-n_len:])
Example #16
0
def main():
    al = Algorithms()
    images = Images()
    parser = argparse.ArgumentParser()
    parser.add_argument("Algorithm",
                        help="Selected Algorithm to use for pathfinding",
                        default=al.default,
                        choices=al.options,
                        nargs='?')
    parser.add_argument("Image",
                        help="Selected Image for pathfinding",
                        default=images.default,
                        choices=images.options,
                        nargs='?')
    parser.add_argument("output_name", nargs='?', default="algorithm")
    args = parser.parse_args()
    # print(args)
    start(al.__getitem__(args.Algorithm), images.__getitem__(args.Image),
          args.output_name)
    def ac3(initial_puzzle_state):
        if (len(initial_puzzle_state) != 81):
            raise Exception("Puzzle must be 81 characters long")

        return Algorithms.ac3(
            initial_puzzle_state=initial_puzzle_state,
            client_defined_revise_domains=Sudoku.revise_domains,
            client_defined_get_domains_for_index=Sudoku.get_domains_for_index,
            client_defined_get_neighbors_for_index=Sudoku.
            get_neighbors_for_index,
            client_defined_is_puzzle_complete=Sudoku.is_puzzle_complete,
            client_defined_unassigned_value="0")
    def backtracking_search(initial_puzzle_state):
        puzzle_state = initial_puzzle_state

        return Algorithms.backtracking_search(
            puzzle_state=puzzle_state,
            client_defined_get_domains_for_index=Sudoku.get_domains_for_index,
            client_defined_get_neighbors_for_index=Sudoku.
            get_neighbors_for_index,
            client_defined_is_puzzle_complete=Sudoku.is_puzzle_complete,
            client_defined_unassigned_value="0",
            client_defined_does_puzzle_follow_constraints=Sudoku.
            does_puzzle_follow_constraints,
        )
Example #19
0
def algorithm_evaluation():

    rd = ReadData(500000, 1000, 100)
    (sparse_ratings, books_used, deleted_users) = rd.load_ratings_data()

    # Obtain the filled matrix using iterative singular value thresholding and view mse per iteration
    a = Algorithms(sparse_ratings)
    (ratings_with_nan, filled_ratings_isvt) = a.isvt()
    e = Evaluate(5, 10)
    mse_isvt = e.performance_eval_isvt(ratings_with_nan, filled_ratings_isvt)

    # Obtain the filled matrix using non-negative matrix factorization and view mse per iteration
    filled_ratings_nmf = a.nmf()
    mse_nmf = e.performance_eval_nmf(sparse_ratings, filled_ratings_nmf)

    # Vary hold-out set and find average mse for each algorithm
    hos = [5, 10, 15, 20]
    e_isvt = []
    e_nmf = []
    for i in hos:
        e2 = Evaluate(5, i)
        mse_isvt = e2.performance_eval_isvt(ratings_with_nan,
                                            filled_ratings_isvt,
                                            plot=False)
        e_isvt.append(mse_isvt)

        mse_nmf = e2.performance_eval_nmf(sparse_ratings,
                                          filled_ratings_nmf,
                                          plot=False)
        e_nmf.append(mse_nmf)

    plt.plot(hos, e_isvt, label="Soft Impute")
    plt.plot(hos, e_nmf, label="NMF")
    plt.xlabel("Hold-Out Set %")
    plt.ylabel("Mean Squared Error")
    plt.legend()
    plt.show()
    def performance_eval_nmf(self, sparse, filled, plot=True):
        """
        hold out a certain percent of the ratings and observe how well the algorithm approximates those ratings
        """
        mse = []
        for k in range(self.n_iter):
            test = sparse.copy()
            a = Algorithms(test)
            n_ratings = np.size(sparse) - len(np.where(sparse==0)[0])
            holdout_count = int(self.holdout_percent*n_ratings/100)
            for subs in range(holdout_count):
                m = 0
                while m == 0:
                    i = random.randint(0,len(sparse)-1)
                    j = random.randint(0,len(sparse[0])-1)
                    if test[i][j] != 0:
                        temp = test[i][j]
                        test[i][j] = 0
                        if np.all(test[i]==0) or np.all(test[:][j]==0):
                            test[i][j] = temp
                        else:
                            m = 1        
            completed = a.nmf()
            mse.append(mean_squared_error(filled, completed)) 

        if plot:

            # plot mean squared error per iteration
            x = [i for i in range(1,self.n_iter+1)]
            plt.plot(x, mse)
            plt.xlabel("Iterations")
            plt.ylabel("Mean Squared Error")
            plt.title("Non-Negative Matrix Factorization")
            plt.show()
        
        return np.average(mse)
 def __init__(self, algorithm, data, frame):
     n = len(data)
     m = max(data)
     self.algorithm = algorithm
     self.data = data
     self.frame = frame
     self.sorting_algorithm_ref = Algorithms.reference(algorithm, data)
     self.figure, self.ax = plt.subplots()
     self.rectangles = self.ax.bar(range(n), self.data, align="edge")
     self.ax.set_xlim(0, n)
     self.ax.set_ylim(0, m + 10)
     self.ax.set_yticklabels([])
     self.ax.set_xticklabels([])
     self.ax.set_title(self.algorithm.value)
     self.text = self.ax.text(0.01, 0.97, "", transform=self.ax.transAxes)
     self.iteration = [0]
     self.canvas = FigureCanvasTkAgg(self.figure, master=self.frame)
     self.anim = None
Example #22
0
def test_bfs_wrapper_1():
  config = [1, 2, 5, 3, 4, 0, 6, 7, 8]
  size = int(math.sqrt(len(config)))
  puzzle_state = PuzzleState(config, size)
  start_state_hash = Utilities.hashed_state(puzzle_state)
  start_state = puzzle_state

  result = Algorithms.search_wrapper(
    client_defined_expand = Utilities.expand,
    client_defined_goal_state_check = Utilities.goal_state_check,
    client_defined_hashed_state = Utilities.hashed_state,
    start_state_hash = start_state_hash,
    start_state = start_state,
    search_type = "bfs"
  )

  assert result["path_to_goal"] == ["Up", "Left", "Left"]
  assert result["cost_of_path"] == 3
  assert result["search_depth"] == 3
Example #23
0
def test_bfs_wrapper_2():
  config = [6, 1, 8, 4, 0, 2, 7, 3, 5]
  size = int(math.sqrt(len(config)))
  puzzle_state = PuzzleState(config, size)
  start_state_hash = Utilities.hashed_state(puzzle_state)
  start_state = puzzle_state

  result = Algorithms.search_wrapper(
    client_defined_expand = Utilities.expand,
    client_defined_goal_state_check = Utilities.goal_state_check,
    client_defined_hashed_state = Utilities.hashed_state,
    start_state_hash = start_state_hash,
    start_state = start_state,
    search_type = "bfs"
  )

  assert result["path_to_goal"] == [
    'Down',
    'Right',
    'Up',
    'Up',
    'Left',
    'Down',
    'Right',
    'Down',
    'Left',
    'Up',
    'Left',
    'Up',
    'Right',
    'Right',
    'Down',
    'Down', 
    'Left',
    'Left',
    'Up',
    'Up'
  ]
  assert result["cost_of_path"] == 20
  assert result["nodes_expanded"] == 54094
  assert result["search_depth"] == 20
  assert result["max_search_depth"] == 21
Example #24
0
def test_astar_wrapper_2():
  config = [8, 6, 4, 2, 1, 3, 5, 7, 0]
  size = int(math.sqrt(len(config)))
  puzzle_state = PuzzleState(config, size)
  start_state_hash = Utilities.hashed_state(puzzle_state)
  start_state = puzzle_state

  result = Algorithms.search_wrapper(
    client_defined_expand = Utilities.expand,
    client_defined_goal_state_check = Utilities.goal_state_check,
    client_defined_hashed_state = Utilities.hashed_state,
    client_defined_compute_state_cost = Utilities.compute_state_cost,
    start_state_hash = start_state_hash,
    start_state = start_state,
    search_type = "astar"
  )

  assert result["path_to_goal"] == ['Left', 'Up', 'Up', 'Left', 'Down', 'Right', 'Down', 'Left', 'Up', 'Right', 'Right', 'Up', 'Left', 'Left', 'Down', 'Right', 'Right', 'Up', 'Left', 'Down', 'Down', 'Right', 'Up', 'Left', 'Up', 'Left']
  assert result["cost_of_path"] == 26
  assert result["nodes_expanded"] == 1585
  assert result["search_depth"] == 26
  assert result["max_search_depth"] == 26
Example #25
0
def test_dfs_wrapper_3():
  config = [8, 6, 4, 2, 1, 3, 5, 7, 0]
  size = int(math.sqrt(len(config)))
  puzzle_state = PuzzleState(config, size)
  start_state_hash = Utilities.hashed_state(puzzle_state)
  start_state = puzzle_state

  result = Algorithms.search_wrapper(
    client_defined_expand = Utilities.expand,
    client_defined_goal_state_check = Utilities.goal_state_check,
    client_defined_hashed_state = Utilities.hashed_state,
    start_state_hash = start_state_hash,
    start_state = start_state,
    search_type = "dfs"
  )

  assert result["path_to_goal"][0] == "Up"
  assert result["path_to_goal"][1] == "Up"
  assert result["path_to_goal"][2] == "Left"
  assert result["cost_of_path"] == 9612
  assert result["nodes_expanded"] == 9869
  assert result["search_depth"] == 9612
  assert result["max_search_depth"] == 9612
Example #26
0
    def decode(self, blob: bytes) -> Certificate:
        offset = 0
        alg_id = Algorithms(blob[offset])
        offset += 1

        """4 bytes for serial number"""
        serial_number = bytes_to_int(blob[offset:offset+4])
        offset += 4

        pub_key_len = bytes_to_int(blob[offset:offset+4])
        offset += 4

        public_key = blob[offset:offset+pub_key_len]
        offset += pub_key_len

        private_key_len = bytes_to_int(blob[offset:offset+4])
        offset += 4

        private_key = blob[offset:offset+private_key_len]
        offset += private_key_len

        signature = blob[offset:]

        return Certificate(alg_id, public_key, private_key, serial_number, signature)
Example #27
0
    def getScores(self,
                  xTrain,
                  xTest,
                  yTrain,
                  yTest,
                  trainSize=1,
                  randomSeeds=[1, 2, 3, 4, 5],
                  selectedAlgorithms=['logReg', 'svm', 'dt', 'rf', 'ann']):
        algs = Algorithms()
        logReg = algs.logisticRegression()
        svm = algs.SVM()
        dt = algs.DecisionTree()
        rf = algs.RandomForest()
        ann = algs.ANN(epochs=5)

        # available algorithms ([name, implementation])
        algorithms = {
            'logReg': ['Logistic Regression', logReg],
            'svm': ['SVM', svm],
            'dt': ['Decision Tree', dt],
            'rf': ['Random Forest', rf],
            'ann': ['ANN', ann],
        }

        predictions = {}

        for selected in selectedAlgorithms:
            [algName, alg] = algorithms[selected]
            noOfSamples, trainScores, testScores = self.calculateAverageScores(
                xTrain, xTest, yTrain, yTest, alg, algName, trainSize,
                randomSeeds)
            predictions[algName] = (trainScores, testScores)

            print('\nAverage train/test accuracy:', trainScores[0],
                  testScores[0], '\n')

        return noOfSamples, predictions
Example #28
0
def test():
    start(Algorithms().__getitem__('dijkstra'),
          Images().__getitem__('tiny'), 'test')
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 #30
0
    def decode_public_key(self, blob):
        alg = blob[0]
        if Algorithms(alg) != Algorithms.RABIN:
            raise ValueError("Wrong key algorithm")

        return bytes_to_int(blob[1:])
Example #31
0
 def init_algorithms(self):
     self.algorithms = Algorithms(self)
Example #32
0
 def create_battles(self):
     for target in self.targets:
         self.battles.append(
             Algorithms.subsets_sum_for_attack(self.possible_moves, target))
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)
    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