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)
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()
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())
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)
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)
def get(self, numbers): algorithm = Algorithms() result = [] for num in range(1, int(numbers) + 1): result.append(algorithm.fizzbuzz(num)) return result
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:])
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 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 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 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
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)
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)
from algorithms import Algorithms import math import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D algo = Algorithms() fig = plt.figure() ax = fig.add_subplot(111, projection='3d') def main(): # hill_climb() hill_climb_random_restarts() # simulated_annealing() # plt.show() def crazyFunction(x, y): r = math.sqrt((x**2) + (y**2)) a1 = math.sin((x**2) + (3 * (y**2))) a2 = 0.1 + (r**2) b = (x**2) + (5 * (y**2)) c = math.exp(1 - (r**2)) return float((a1 / a2) + (b * (c / 2))) def hill_climb(): FUNCTION = crazyFunction STEP_SIZE = 0.001
def test(): start(Algorithms().__getitem__('dijkstra'), Images().__getitem__('tiny'), 'test')
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:])
def init_algorithms(self): self.algorithms = Algorithms(self)
def setUp(self, path_follower): super(UAV, self).setUp() # SUA Algorithm tuning parameters # ---------------------------- self.chi_inf = pi / 2 self.k_path = 0.0125 self.k_orbit = 3.5 self.R = 30 # fillet radius (m) (This should be set to the min radius) # ---------------------------- self.path_follower = path_follower self.chi = 0.0 self.chi_c = 0.0 self.h_c = 0.0 self.Va_c = 18 # start with a constant airspeed self.current_waypoint = 0 self.tab = Table() self.dp_list = [] self.alg = Algorithms() self.output = AttitudeController() self.e_crosstrack = Float32() self.waypoints = Waypoints() self.path_params = PathParameters() self.position = mat([0, 0, 0]).T self.W = None self.Chi_waypoint = None rospy.Subscriber('attitude_bridge/state_data', StateData, self.att_state_callback) self.pub = rospy.Publisher('attitude_bridge/commanded', AttitudeController, queue_size=1) self.crosstrack_pub = rospy.Publisher('crosstrack_error', Float32, queue_size=1) self.waypoint_pub = rospy.Publisher('waypoints', Waypoints, queue_size=10) self.path_pub = rospy.Publisher('path_params', PathParameters, queue_size=10) # read waypoint file self.read_plan() self.calc_Chi_waypoint() if self.path_follower: self.path_params.header.stamp = rospy.Time.now() self.path_params.r = traj.r self.path_params.q = traj.q self.path_params.c = traj.c self.path_params.rho = traj.rho self.path_params.lamb = traj.lamb path_params_rate = rospy.Rate(0.5) for i in range(0, 3): self.path_pub.publish(self.path_params) path_params_rate.sleep() # start running algorithms self.pub_thread = Thread(target=self.waypoint_publisher, args=()) self.pub_thread.daemon = True self.pub_thread.start()
from algorithms import Algorithms WINDOW_WIDTH = 500 WINDOW_HEIGHT = 500 BAR_HEIGHT_RANGE = (10, 40) BAR_COLOR_RANGE = (0, 255) BAR_AMOUNT = 60 pygame.init() display_surface = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) pygame.display.set_caption("Sorting Algorithm Visualizer") pygame.display.update() clock = pygame.time.Clock() algo = Algorithms(WINDOW_WIDTH, WINDOW_HEIGHT, BAR_HEIGHT_RANGE, BAR_COLOR_RANGE, BAR_AMOUNT, display_surface) running = False while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if not running: display_surface.fill((0, 0, 0)) keys = pygame.key.get_pressed() if keys[pygame.K_SPACE]: running = True display_surface.fill((0, 0, 0))
from flask import Flask, render_template, request, redirect, url_for, flash, jsonify # from flask_mysqldb import MySQL import json from algorithms import Algorithms app = Flask(__name__) # datos de navegacion app.secret_key = 'mysecretkey' alg = Algorithms() @app.route('/') def Index(): return render_template('index.html') @app.route('/search_method', methods=['POST']) def search_method(): exec_alg = None if request.method == 'POST': data = json.loads(request.data) if data['method'] == 'bpa': exec_alg = alg.bpa(data['ei'], data['ef']) if data['method'] == 'bpp': exec_alg = alg.bpp(data['ei'], data['ef'], data['bpp_limit']) if data['method'] == 'hill': exec_alg = alg.hill_climbing(data['ei'], data['ef']) if data['method'] == 'ram':
def test_merge_sort(): input = [7, 2, 8, 9, 0, 3, 5, 1, 4, 6] result = Algorithms().merge_sort(input) assert (result == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
def test(): start(Algorithms().__getitem__('Astar'), Images().__getitem__('combo400'), 'algorithm')
#%% import pandas as pd import networkx as nwx from algorithms import Algorithms __author__ = 'Gabriel Luciano Gomes - RA 265673, Paulo Junio Reis Rodrigues RA - 265674' __email__ = '{g265673, p265674}@dac.unicamp.br' algorithms = Algorithms() def executeMethods(G, fileName, db): # Degree Distribution # algorithms.averageDistance(G) algorithms.connectedComponents(G) largest_cc = algorithms.retrieveLargestComponent(G) # algorithms.plotNormalScale(G, # "User Degree Distribution", "user_distribution.png", db.user_id.unique()) # algorithms.plotNormalScale(G, # "Game Degree Distribution", "game_distribution.png", db.game_name.unique()) # algorithms.clusteringCoefficient(G) # algorithms.plotLoglogScale(largest_cc, fileName) # algorithms.degreeCorrelationMatrix(largest_cc) # algorithms.clusteringCoefficient(largest_cc) algorithms.assortativityCoefficient(largest_cc) # algorithms.randomFailures(largest_cc, 0.05) # algorithms.drawNetwork(largest_cc) # algorithms.plotCommunities(largest_cc)
def test2(): images = ["tiny", "braid200", "normal", "small", "combo400"] for i in images: start(Algorithms().__getitem__('depthfirst'), Images().__getitem__(i), i + '_' + 'depthfirst')