def __init__(self, g): Algorithm.__init__(self, g) self.REPAIR_PERIOD = 20 * self.MSG_PERIOD self.RETRY_PERIOD = self.REPAIR_PERIOD self.tables = {} #init tables self.repair()
def test_healthy_sar(): id_list = [2] # healthy mock DB for recommendations using movie 2 as input class healthyDB_Mock: def get_tmdb_info(df): pass with open('backend_tests/sar_test_data.json') as f: data = json.load(f) res = data['Healthy_SAR'] fixed_titles = data['Sar_Titles'] # correct database response for movie 2 def mocked_get_tmdb_info_sar(df): return pd.DataFrame(res) with patch.object(healthyDB_Mock, 'get_tmdb_info', new=mocked_get_tmdb_info_sar): alg_healthy_sar = Algorithm(healthyDB_Mock) for i in range(10): assert alg_healthy_sar.get_sar_recommendations( id_list)['json'][i] == { "Genre": res['Genre'][i], "Imageurl": res['Imageurl'][i], "ItemID": res['ItemID'][i], "Overview": res['Overview'][i], "Title": fixed_titles[i], "UserID": res['UserID'][i], "Year": res['Year'][i], "prediction": res['prediction'][i] }
def main(): in_image_path = 'input_data/house_in.png' ref_image_path = 'input_data/house_prewitt.png' out_image_path = 'output_data/house_prewitt_out.png' img_in = read_image(in_image_path) img_ref = read_image(ref_image_path) # PARAM model_parameters = { "alpha": 1.0, "beta": 2.0, "number_of_ants": 512, "evaporation_rate": 0.05, "pheromone_decay": 0.005, "max_iter": 100, "construction_steps": 40, "epsilon": 0.01, "initial_pheromone": 0.1 } # PARAM algorithm = Algorithm(img_in, img_ref, model_parameters) img_edge = algorithm.run_algorithm(True) print(f'Target fun: {algorithm.model.calculate_ssim(img_edge)}') cv2.imshow('Im edge', img_edge) cv2.imshow('Ref', img_ref) cv2.imshow('Pheromone', algorithm.pheromone_matrix / algorithm.pheromone_matrix.max()) cv2.imwrite(out_image_path, img_edge) cv2.waitKey(0)
class Application: def __init__(self, fileName): self.fileName = fileName def main(self): self.algorithm = Algorithm(self.fileName) best = self.algorithm.run() best.problem.printBoard() def runStat(self): bsts = [] for i in range(30): print("Running test #" + str(i)) self.algorithm = Algorithm(self.fileName) res = self.algorithm.run(False) bsts.append(res.bestOf(10)[0]) res.problem.printBoard() arr = [] for i in range(len(bsts)): arr.append(bsts[i].fitness()) stddev = np.std(arr) average = np.average(arr) best = min(arr) print("Stddev: " + str(stddev)) print("Average: " + str(average)) print("Best: " + str(best)) print("Done!")
def optimize(output_queue, stop_event, trajectory, width=LEVEL_WIDTH, height=LEVEL_HEIGHT, put_period=10, density=0.2): """ Launch optimization. :param output_queue: Queue where the interesting results of the optimization process should be put. :param stop_event: Event that should be set when this function must return. """ algorithm = Algorithm(trajectory=trajectory, width=trajectory.level_width, height=trajectory.level_height, population_size=10, tournament_size=5, mutation_probability=0.01, generations=1000, chromosome_size=100) for best_level in algorithm.run(): try: output_queue.put_nowait((best_level, trajectory)) except queue.Full: print('Warning: output queue is full') if stop_event.is_set(): print('Stop event detected - stopping optimization') break
def __init__(self, env, act_dim, state_dim, memory_capacity, epsilon, update_target): self.env = env self.algo = Algorithm(0.0001, 0.99, act_dim, state_dim, memory_capacity, epsilon, 64) self.memory_capacity = memory_capacity self.update_target = update_target
def __init__(self): # Initialization pygame.init() self.visualizer = Visualizer() self.algorithm = Algorithm() self.speed_scl = 1 self.released = {} self.last_tick = current_time_millis() self.current_tick = current_time_millis() print("------------------------") print(" Controls: ") print("[WASD]: Move the graph.") print("[UP ARROW]: Zoom in.") print("[DOWN ARROW]: Zoom out.") print("[LEFT ARROW]: Slow down.") print("[RIGHT ARROW]: Speed up.") print("------------------------") # Main loop while True: if self.current_tick - self.last_tick > 1000 / SPEED: self.tick() self.last_tick = current_time_millis() else: self.current_tick = current_time_millis()
class TestAlgorithm(unittest.TestCase): def setUp(self): process_time = { 1: [5, 9, 8, 10, 1], 2: [9, 3, 10, 1, 8], 3: [9, 4, 5, 8, 6], 4: [4, 8, 8, 7, 2] } self.process_time_df = pd.DataFrame.from_dict( process_time, orient='index', columns=range(1, (max(process_time.keys()) + 2))) self.algorithm = Algorithm(self.process_time_df) self.total_completion_time = self.algorithm.order_jobs_in_descending_order_of_total_completion_time( ) self.best_order = self.algorithm.initiate_the_algorithm( self.total_completion_time.index[0:2].tolist()) def tearDown(self): self.algorithm = None def test_create_permutations(self): return_permutations = self.algorithm.create_permutations([3, 1, 2], 4) correct_permutations = [[4, 3, 1, 2], [3, 4, 1, 2], [3, 1, 4, 2], [3, 1, 2, 4]] self.assertEqual(return_permutations, correct_permutations) def test_compute_completion_time(self): max_completion_time = self.algorithm.compute_completion_time( [3, 1, 2, 4]) correct_max_completion_time = 58 self.assertEqual(max_completion_time, correct_max_completion_time)
def __init__(self, evaluator, neighbourhood_gen, stop_cond, logger=NullLogger()): Algorithm.__init__(self, evaluator, neighbourhood_gen, stop_cond, logger)
def __init__(self, width, height, square, title, fps, allow_diag): """This class manages the pygame window and interactions with the window to draw the grid and use the algorithm. Args: width (int, optional): The width of the window (must be a multiple of `square`). Defaults to 500. height (int, optional): The height of the window (must be a multiple of `square`). Defaults to 500. square (int, optional): The size of a square in the grid. Defaults to 10. title (str, optional): The title of the window. Defaults to 'A* Algorithm'. win (pygame.Surface, optional): Initial window object. Defaults to None. fps (int, optional): FPS at which the window runs. Defaults to 60. """ # General variables self.width = width self.height = height self.square = square self.fps = fps self.run = True self.start = 0, 0 self.end = height-1, width-1 # Algorithm self.algo = Algorithm((height // square, width // square), allow_diag) # Grid self.grid = np.zeros((height // square, width // square)) # Pygame stuff pg.init() self.win = pg.display.set_mode((width, height)) # Window pg.display.set_caption(title) # Title self.font = pg.font.SysFont('sourcecodepro', 5) self.clock = pg.time.Clock()
class TreeTest(unittest.TestCase): def setUp(self): self.al = Algorithm() self.tree = BinaryTree(1) tree = self.tree tree.left = BinaryTree(2) tree.right = BinaryTree(3) tree = tree.left tree.left = BinaryTree(4) tree.right = BinaryTree(5) tree = self.tree tree = tree.right tree.left = BinaryTree(6) tree.right = BinaryTree(7) tree.right.right = BinaryTree(8) def test_pre_order(self): self.assertEqual(self.al.pre_order(self.tree), self.tree.pre_order()) def test_in_order(self): self.assertEqual(self.al.in_order(self.tree), self.tree.in_order()) def test_last_order(self): self.assertEqual(self.al.last_order(self.tree), self.tree.last_order()) def test_mirror_tree(self): self.al.mirror_tree(self.tree) self.assertEqual(self.tree.pre_order(), [1, 3, 7, 8, 6, 2, 5, 4])
def __init__(self, verbose=False, alpha=.98, start=500000, end=.25, iterations=200): Algorithm.__init__(self, verbose) self.solution = [ ] # using a list to follow convention of previous algo's # Related to the temperature schedule # T = T*alpha is applied every "iterations" self.alpha = alpha # Increase to slow cooling self.start_temp = start # Increase to run algorithm longer self.end_temp = end # At about .25, the probability is near 0 self.iterations_per_temp = iterations # increase to slow cooling self.temperature = start self.temp_iterations = 0 self.elapsed_time = 0 self.start_time = datetime.now() # value and temp stored at each iteration then written to file for graphing self.value_data = [] self.temperature_data = [] self.moves_to_better = 0 self.moves_to_worse = 0
def Opt_KG_experiment(): """ Run experiment on the RTE data set :return: accuracy """ # initialize the prior parameters a0 b0 of the dataset data_file = 'rte.standardized.tsv' init_a0 = 1 init_b0 = 1 # sourcedata = DataSource(data_file, init_a0, init_b0) # initialize the prior parameters c0 d0 of the workers init_c0 = 4 init_d0 = 1 # workers = Worker(data_file, init_c0, init_d0) # Given Budget T Budget_T = np.arange(0,8000,100) # accuracy result of experiment each time accuracy_ = [] # run experiment limited to the given budget T_ for T_ in Budget_T: accuracy_sum = 0 for i in range(0,1): sourcedata = DataSource(data_file, init_a0, init_b0) workers = Worker(data_file, init_c0, init_d0) Opt_KG = Algorithm(sourcedata, workers, T_) H_T, H_complement = Opt_KG.run_Opt_KG() # the number that the positive and negative set result derived from the experiment is accordance with the real data result = 0 # get H* and H*c H_star, H_star_c = sourcedata.get_H_star() for idx in H_T: if idx in H_star: result = result + 1 for idx in H_complement: if idx in H_star_c: result = result + 1 # calculate the accuracy_sum accuracy_sum = accuracy_sum + result / 800 # calculate the accuracy accuracy_mean = accuracy_sum / 1 accuracy_.append(accuracy_mean) # print the accuracy result on the console print('the length of H_t is:' + str(len(H_T)) + ', the length of H_t_c is:' + str(len(H_complement))) print('the length of H* is:' + str(len(H_star)) + ', the length of H*_c is:' + str(len(H_star_c))) print('the length of result is:' + str(result)) print('Budget ' + str(T_) + ' and the accuracy is ' + str(accuracy_[-1])) print('*' * 40) # save the beta distribution dictionary save_beta_dic() # plot plt.figure() plt.plot(Budget_T, accuracy_, color = 'red', linewidth = 2.0, marker = 'D', fillstyle = 'full') plt.xlabel('Budget') plt.ylabel('accuracy') # set y-axis locations and labels plt.yticks(np.arange(0,1,0.05)) plt.title('Opt-KG on RTE') plt.show()
def main(): problem = Problem("data01.in") algoritm = Algorithm(problem, "param.in") #start_time = time.time() algoritm.statistics()
def generate_Model(): if request.method == 'POST': if "filepath" not in request.files: flash('The form has no file part') return redirect(url_for('index')) file_ = request.files['filepath'] if file_.filename == '': flash('No file selected') return redirect(url_for('index')) if file_ and allowed_file(file_.filename): #secure_filename evitará que la ruta del archivo ... filename = secure_filename(file_.filename) file_.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) criterio = request.form['criterio'] seleccion = request.form['selectparents'] #return redirect(url_for('get_file', filename=filename)) name = app.config['UPLOAD_FOLDER'] + '/' + filename algoritmo = Algorithm(name, int(criterio), int(seleccion)) solucion = algoritmo.execute() app.config['solucion'] = solucion.solucion algoritmo.escribirArchivo(solucion.solucion) flash("Modelo Generado Correctamente") else: flash('File extension no permited') return redirect(url_for('index'))
def _complie_data(self): """compile input data 编译运行输入数据 Args: Returns:dict """ _input_algorithm = self._field_data['algorithm']['input'] _algorithm = Algorithm() #执行input算法获取field模板渲染的数据源.会校验时间戳,决定是否通过缓存执行 _input_data_source = _algorithm.execute_algorithm( _input_algorithm['data'], _input_algorithm['lang']) #logging.info(_input_data_source) #执行结果转为py的dict #_input_data_result = self.__format_plugin_source(_field_type,_input_data_source) #field数据注入到input_data_source和submit js _input_html_source = self._field_info['form_html'].replace( '{$field_id}', str(self._field_data['field_id'])).replace( '{$field_name}', self._field_data['field_name']).replace( '{$field_value}', self._field_data['field_value']) _input_submit_js = self._field_info['form_submit'].replace( '{$field_id}', str(self._field_data['field_id'])) _input_html_target = _input_html_source return { 'data_source': _input_data_source, 'html_source': _input_html_source, 'submit_js': _input_submit_js, 'css': self._field_info['form_css'], 'js': self._field_info['form_js'] }
def __init__(self, g): Algorithm.__init__(self, g) self.REPAIR_PERIOD=20*self.MSG_PERIOD self.RETRY_PERIOD=self.REPAIR_PERIOD self.tables={} #init tables self.repair()
def repair(self): transmissions=len(self.g.nodes()) #All the hellos. for n in self.g.nodes(): if self.old_g.nodes().count(n)>0: new_neighborhood=self.g.neighbors(n) old_neighborhood=self.old_g.neighbors(n) transmittedLSA=False for neighbor in new_neighborhood: if old_neighborhood.count(neighbor)==0: (f,t)=Algorithm.util_flood(self.g,n) transmissions+=t transmittedLSA=True break if transmittedLSA: break for neighbor in old_neighborhood: if new_neighborhood.count(neighbor)==0: (f,t)=Algorithm.util_flood(self.g,n) transmissions+=t break else: (f,t)=Algorithm.util_flood(self.g, n) transmissions+=t self.old_g=copy.deepcopy(self.g) return transmissions
def getRecomendation(): data = request.get_json() book = data.get('book') algorithm = Algorithm() data = algorithm.use(book, "corr") return jsonify(data=data)
def setUp(self): self.al = Algorithm() a_list = [] self.ls = [] for i in range(10, 20): for j in range(i): a_list.append(random.uniform(0, 100)) self.ls.append(a_list)
def __init__ (self, num_players, horizon=100): Algorithm.__init__(self, num_players) # Y[i,j] is the proportion of games player i beat over player j # N[i,j] is the number of games i and j have played against each other self.Y = np.zeros((num_players, num_players)) self.N = np.zeros((num_players, num_players)) self.T = horizon self.ranking_procedure = Copeland(num_players, self.Y)
def __init__(self, memory_size, selection_method): # Los bloques adyacentes a un bloque vacio siempre estan llenos # Los bloques adyacentes a un bloque lleno pueden estar vacios o llenos Algorithm.__init__(self, memory_size) self.selection_method = selection_method # Seleccion de bloque vacio (Primer ajuste, mejor ajuste o peor ajuste) self.full = {} # Mapeo de bloques llenos: PCB -> Bloque self.empty = [Block(0, memory_size - 1)] # Lista de bloques vacios
def __init__(self, camera_number, calibrate_marker_coordinate): Thread.__init__(self) self.camera_counter = camera_number self.camera_martix = None self.dist_coeff = None self.transition_matrix_from_camera_to_world = None self.algorithm = Algorithm() self.calibrate_marker_coordinate = calibrate_marker_coordinate
def __init__(self, g): ''' Constructor ''' Algorithm.__init__(self, g) self.tables = {} #init tables for node in self.g.nodes(): self.tables[node]={}
def main(): problem = Problem("in.txt") algorithm = Algorithm(problem) stats, stddev = algorithm.run() survivors = [ x.fitness() for x in algorithm.getIndividuals() ] x = [x for x in range(0, problem.getItCount())] pyplot.plot(stats) pyplot.plot(stddev) pylab.show()
def parse_file(fp): #Check if file validates and the content if validate_file(fp): lines = fp.read().replace('\n', '') if validate_contents(lines): #do JSON stuff, bonus points right here pass else: parse_text = Algorithm(lines) return parse_text.determine_language()
def main(): dr = data_manager.DataManager() dp = displayer.Displayer() cities = dr.read_data_from_file(setup.path_to_file) dp.plot_cities(cities) alg = Algorithm(cities, setup.instances, setup.parents_amount, setup.mutation_chance) alg.proceed() dp.plot_route(alg.children[31].city_route) print(alg.children[31].cost) plt.show()
def __init__(self, strategy="BFS", tree=True, verbose=False): Algorithm.__init__(self, verbose) #self.log_count = 1 self.visited = [] # visisted/explored list for Graph Search self.solution = [] # list of solutions (only 1 if all_solutions=False) self.tree = tree # True for tree search, False for Graph search if not strategy == "BFS" and not strategy == "DFS": return 'ERROR: strategy must be "DFS" or "BFS" (case sensitive)' else: self.strategy = strategy
def test_find_point(): algorithm = Algorithm() im = Image.open("img/101411.png") start_x, start_y, end_x, end_y = algorithm.find_point(im) print("start_point:", start_x, start_y) print("end_point:", end_x, end_y) p1 = (start_x, start_y) p2 = (end_x, end_y) d = algorithm.euclidean_distance(p1, p2) print(d)
def __init__(self, algorithm): self.algorithm = Algorithm(algorithm) self.plain_file = 'file_' + self.algorithm.name + '.in' self.enc_file = 'file_' + self.algorithm.name + '.enc' self.dec_file = 'file_' + self.algorithm.name + '.dec' self.passwords = None self.privkey_files = None self.pubkey_files = None
def test_jump(): algorithm = Algorithm() op = Operation() im = op.screen_cap() start_x, start_y, end_x, end_y = algorithm.find_point(im) start_point = (start_x, start_y) end_point = (end_x, end_y) distance = algorithm.euclidean_distance(start_point, end_point) press_time = algorithm.distance_to_time(distance) op.jump(start_point, end_point, press_time)
def getRecomendation(): # book_name = request.form data = request.get_json() book = data.get('book') # book_name = str(request.form.get('book')) algorithm = Algorithm() data = algorithm.use(book) return jsonify(data=data)
class TestInput(unittest.TestCase): @classmethod def setUpClass(cls): print('setupClass') pass @classmethod def tearDownClass(cls): print('teardownClass') pass def setUp(self): print('setUp') X, y = download() splitRatio = 60000 self.X_train, self.y_train, self.X_test, self.y_test = split(X,y,splitRatio) self.train_accuracy = 72.92166666666667 self.train_confusion_matrix = np.matrix([[5447, 5, 40, 31, 49, 16, 198, 50, 81, 6], [ 3,6440, 127, 54, 3, 29, 25, 36, 24, 1], [ 297, 420,3824, 163, 256, 19, 622, 186, 121, 50], [ 124, 221, 255,4566, 54, 251, 97, 129, 275, 159], [ 104, 128, 26, 54,4546, 342, 206, 133, 96, 207], [ 399, 200, 109,1081, 416,2227, 289, 363, 228, 109], [ 173, 89, 112, 55, 156, 229,5034, 25, 45, 0], [ 213, 192, 205, 39, 160, 17, 26,5058, 60, 295], [ 67, 690, 202, 677, 73, 188, 347, 39,3437, 131], [ 164, 162, 63, 290, 669, 279, 122, 735, 291,3174]]) self.test_accuracy = 73.4 self.test_confusion_matrix = np.matrix([[ 923, 1, 2, 3, 3, 1, 35, 3, 9, 0], [ 0,1084, 23, 11, 0, 0, 5, 4, 8, 0], [ 63, 78, 669, 27, 38, 2, 97, 28, 24, 6], [ 20, 27, 35, 770, 8, 42, 18, 27, 45, 18], [ 15, 21, 3, 8, 750, 60, 45, 23, 18, 39], [ 56, 24, 15, 193, 73, 362, 56, 58, 38, 17], [ 35, 10, 18, 11, 28, 42, 799, 6, 8, 1], [ 23, 40, 52, 6, 21, 4, 7, 821, 8, 46], [ 14, 90, 29, 99, 10, 33, 66, 7, 598, 28], [ 21, 27, 10, 37, 133, 42, 27, 100, 48, 564]]) def tearDown(self): print('tearDown') pass def test_fit(self): np.random.seed(31337) self.ta = Algorithm(self.X_train, self.y_train, self.X_test, self.y_test) self.assertGreaterEqual(round(self.ta.fit()), round(self.train_accuracy)) #self.assertEqual(self.ta.train_confusion_matrix.tolist(), self.train_confusion_matrix.tolist()) def test_predict(self): np.random.seed(31337) self.ta = Algorithm(self.X_train, self.y_train, self.X_test, self.y_test) self.ta.fit() self.assertGreaterEqual(round(self.ta.predict()), round(self.test_accuracy))
def start(self, start, end): print("Waiting for inputs") self.make_grid() run = True drawutil = DrawUtil(WINDOW, self.grid, self.rows, self.width) algorithm = Algorithm(WINDOW, self.grid, self.rows, self.width, start, end) while run: drawutil.draw_screen() for event in pygame.event.get(): if event.type == pygame.QUIT: run = False if pygame.mouse.get_pressed()[0]: # Left click pos = pygame.mouse.get_pos() row, col = self.get_clicked_pos(pos) box = self.grid[row][col] if not start: start = box start.make_start() elif not end and box != start: end = box end.make_end() elif box != end and box != start: box.make_barrier() elif pygame.mouse.get_pressed()[2]: # Right click pos = pygame.mouse.get_pos() row, col = self.get_clicked_pos(pos) box = self.grid[row][col] box.reset() if box == start: start = None elif box == end: end = None if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE and start and end: for row in self.grid: for box in row: box.update_neighbors(self.grid) algorithm.start_algo(start, end) if event.key == pygame.K_c: # Press C to clear grid self.start(None, None)
def setUp(self): self.qc = QCAlgorithm() Singleton.Setup(self.qc) self.qc.Initialize() self.qc.Securities = InternalSecurityManager([(FOO, 5), (BAR, 50)]) self.algorithm1 = Algorithm(name="alg1", allocation=1.0) foo = self.algorithm1.AddEquity(FOO, Resolution.Daily).Symbol bar = self.algorithm1.AddEquity(BAR, Resolution.Daily).Symbol self.algorithm1.Portfolio.SetCash(200) self.algorithm1.Portfolio[foo] = Position(FOO, 10, 5) self.algorithm1.Portfolio[bar] = Position(BAR, 3, 50)
def test_output_polar(self): point_array = [ Point(19.2486849886, 42.0138353124), Point(34.6545353825, 5.95845608147), Point(66.6014654767, 66.0841191785), Point(49.1321252346, 86.6154463314) ] algo = Algorithm(point_array) polar_list = algo.polar_angle_sort(Point(34.6545353825, 5.95845608147)) self.assertEqual(str(polar_list[0]), str(Point(34.6545353825, 5.95845608147)))
def test_segments(self): point_array = [ Point(19, 42), Point(34, 5), Point(66, 66), Point(49, 86) ] algo = Algorithm(point_array) algo.stack = point_array seg_list = algo.segments() self.assertEqual(str(seg_list[0]), str(Segment(Point(19, 42), Point(34, 5))))
def __init__(self): Algorithm.__init__(self) self.digits = '123456789' self.rows = 'ABCDEFGHI' self.cols = self.digits self.squares = self.cross(self.rows, self.cols) self.unitlist = ([self.cross(self.rows, col) for col in self.cols] + [self.cross(row, self.cols) for row in self.rows] + [self.cross(row_square, col_square) for row_square in ('ABC','DEF','GHI') for col_square in ('123','456','789')]) self.units = dict((square, [un for un in self.unitlist if square in un]) for square in self.squares) self.peers = dict((square, set(sum(self.units[square],[]))-set([square])) for square in self.squares)
class LanguageTest(unittest.TestCase): def setUp(self): self.message = "Dit is een fijn bericht" self.algorithm = Algorithm(self.message) def test_algorithm(self): """ Only test for words that are 4 characters or more """ self.assertEqual(self.algorithm._determine_keywords(), ['fijn', 'bericht']) def test_determine_language(self): self.assertEqual(self.algorithm.determine_language(), 'nl')
def __init__(self, num_players, ranking_procedure=Copeland, alpha=0.51, horizon=100): Algorithm.__init__(self, num_players) # W[i,j] is the proportion of games player i beat over player j # U[i,j] is the upper confidence interval self.W = np.zeros((num_players, num_players)) self.U = np.zeros((num_players, num_players)) self.Y = np.zeros((num_players, num_players)) self.N = np.zeros((num_players, num_players)) self.T = horizon # Horizon assert(alpha > 0.5) self.alpha = alpha self.ranking = list(range(num_players)) np.random.shuffle(self.ranking) self.ranking_procedure = ranking_procedure(num_players, self.Y)
def test_polar_angle(self): point_array = [Point(1, 1), Point(2, 2), Point(2, 3), Point(2, 1)] algo = Algorithm(point_array) polar_list = algo.polar_angle_sort(Point(1,1)) self.assertEqual(str(polar_list[0]), str(Point(1, 1))) self.assertEqual(str(polar_list[1]), str(Point(2, 1))) self.assertEqual(str(polar_list[-1]), str(Point(2, 3))) point_array = [Point(1, 1), Point(0, 2), Point(2, 3), Point(2, 1)] algo = Algorithm(point_array) polar_list = algo.polar_angle_sort(Point(1,1)) self.assertEqual(str(polar_list[-1]), str(Point(0,2)))
def __init__(self, title): gtk.Window.__init__(self, title=title) self.set_size_request(0, 600) self.set_resizable(False) self.set_border_width(5) self.connect('delete-event', gtk.main_quit) self.algorithm = Algorithm() self.file_type = 'fasta' self.first_seq = "" self.second_seq = "" self.main_box = gtk.Box(spacing=5, orientation=gtk.Orientation.VERTICAL) self.add(self.main_box) self.add_logo() self.add_file_type_radio_buttons() self.add_first_squence_widgets() self.main_box.pack_start(gtk.Label(), False, False, 0) self.add_second_squence_widgets() self.add_controls_buttons()
def __init__(self, **kwargs): """Takes configuration in kwargs. """ #: An Aspen :class:`~aspen.request_processor.RequestProcessor` instance. self.request_processor = RequestProcessor(**kwargs) pando_chain = Algorithm.from_dotted_name("pando.state_chain") pando_chain.functions = [getattr(f, "placeholder_for", f) for f in pando_chain.functions] #: The chain of functions used to process an HTTP request, imported from #: :mod:`pando.state_chain`. self.state_chain = pando_chain # copy aspen's config variables, for backward compatibility extra = "typecasters renderer_factories default_renderers_by_media_type" for key in list(ASPEN_KNOBS) + extra.split(): self.__dict__[key] = self.request_processor.__dict__[key] # load our own config variables configure(KNOBS, self.__dict__, "PANDO_", kwargs) # add ourself to the initial context of simplates self.request_processor.simplate_defaults.initial_context["website"] = self # load bodyparsers #: Mapping of content types to parsing functions. self.body_parsers = { "application/x-www-form-urlencoded": body_parsers.formdata, "multipart/form-data": body_parsers.formdata, self.media_type_json: body_parsers.jsondata, }
def initializeAlgorithm(populatinSize, dataLength, iterationsNumber, mutationRate, crossoverRate): chromosomeDataFactory = ChromosomeDataFactory() chromosomeDataFactory.dataLength = dataLength chromosomeFactory = ChromosomeFactory() chromosomeFactory.chromosomeDataFactory = chromosomeDataFactory chromosomeFactory.crossoverRate = crossoverRate chromosomeFactory.mutationRate = mutationRate populationFactory = PopulationFactory() populationFactory.chromosomeFactory = chromosomeFactory populationFactory.populationSize = populatinSize algorithm = Algorithm() algorithm.population = populationFactory.create() algorithm.numberOfIterations = iterationsNumber return algorithm
def test_inserted_algorithm_steps_run(sys_path): sys_path.mk(FOO_PY) foo_algorithm = Algorithm.from_dotted_name('foo') def biz(): return {'val': 4} foo_algorithm.insert_after('buz', biz) state = foo_algorithm.run(val=None) assert state == {'val': 4, 'exception': None, 'state': state, 'algorithm':foo_algorithm}
def test_Algorithm_ignores_functions_starting_with_underscore(sys_path): sys_path.mk( ('um.py', 'def um(): pass') , ('foo/__init__.py', '') , ('foo/bar.py', ''' def baz(): pass from um import um as _um def blah(): pass ''')) foo_algorithm = Algorithm.from_dotted_name('foo.bar') import foo.bar assert foo_algorithm.functions == [foo.bar.baz, foo.bar.blah]
def test_Algorithm_includes_imported_functions_and_the_order_is_screwy(sys_path): sys_path.mk( ('um.py', 'def um(): pass') , ('foo/__init__.py', '') , ('foo/bar.py', ''' def baz(): pass from um import um def blah(): pass ''')) foo_algorithm = Algorithm.from_dotted_name('foo.bar') import foo.bar, um assert foo_algorithm.functions == [um.um, foo.bar.baz, foo.bar.blah]
def main(): """ The main function of the program that turns user input into a schedule and uses a genetic algorithm to find an optimal schedule. """ # Container for user input. info = {} # Get the desired term and courses. if DEBUG: info["term"] = "FA16" info["courses"] = ["CSE 12", "CSE 15L", "DOC 1"] elif handleInput(info): return print("Finding schedule data...") # Get the schedule data for the given courses and term. schedule = Schedule() schedule.term = info["term"] schedule.courses = info["courses"] try: scheduleData = schedule.retrieve() except ClassParserError: print("The Schedule of Classes data could not be loaded at this " \ "or you have provided an invalid class.") return # Make sure all of the desired classes were found. for course in info["courses"]: if course not in scheduleData: print("'" + course + "' was not found in the Schedule of Classes!") return # Initiate the population. algorithm = Algorithm(scheduleData) algorithm.initiate(CAPACITY, CROSSOVER, MUTATE, ELITISM) # Run the algorithm through the desired number of generations. generation = 0 highest = 0 while generation < GENERATIONS: algorithm.evolve() generation += 1 print("Generating... " + str(int((generation / GENERATIONS) * 100)) + "%", end="\r") print("\nDone!") algorithm.printFittest()
def merge(n): algorithm = Algorithm() last = algorithm.lastmodel() models = [algorithm.load('model{}'.format(i)) for i in range(last-n+1, last+1)] model = DataGenerator(models) algorithm.predictor = model algorithm.save()
def test_traceback_for_uncleared_exception_reaches_back_to_original_raise(sys_path): sys_path.mk(EXCEPT) foo_algorithm = Algorithm.from_dotted_name('foo') foo_algorithm.remove('clear') try: foo_algorithm.run() except: tb = traceback.format_exc() # We get an extra frame under Python 3, but what we don't want is not # enough frames. assert len(tb.splitlines()) == (8 if PYTHON_2 else 10)
def add_algorithm_input(self, name, low, high): """ Adds a new input trait for the algorithm """ if len(name) == 0 or low >= high: return self.algorithm_inputs.append((name, Range(low, high))) value = (low+high)/2 # Create the new instance and add the input traits to it algorithm = Algorithm() for input in self.algorithm_inputs: algorithm.add_trait(*input) # Set a default value for the new trait setattr(algorithm, name, value) # Copy values from the old instance old = self.algorithm traits = set(old.trait_names()) - {'trait_added', 'trait_modified'} for trait in traits: setattr(algorithm, trait, getattr(old, trait)) self.algorithm = algorithm
def test_function_can_have_default_value_for_exception_to_be_always_called(sys_path): sys_path.mk(EXCEPT) foo_algorithm = Algorithm.from_dotted_name('foo') # Add a both-handling function. def both(exception=None): return {'exception': None, 'um': 'yeah'} foo_algorithm.insert_before('clear', both) # Exception case. assert foo_algorithm.run()['um'] == 'yeah' # Non-exception case. foo_algorithm.remove('bar') assert foo_algorithm.run()['um'] == 'yeah'
def main(): parser = argparse.ArgumentParser(description='Highway builder.') parser.add_argument('-a', required=True, type=float, help='Roads length factor.') parser.add_argument('-b', required=True, type=float, help='Path length factor.') parser.add_argument('-i', default=20, type=int, help='Number of iterations.') args = parser.parse_args() if args.a < 0: print('Roads length factor should be greater or equal 0.') exit() if args.b < 0: print('Path length factor should be greater or equal 0.') exit() if args.i < 1: print('Number of iterations should be greater than 0.') point_tuples = read_cities() alg = Algorithm(point_tuples, roads_length_factor=args.a, paths_length_factor=args.b, iterations=args.i) iters_ended = alg.simulated_annealing() fitness = alg.fitness_function(alg.state) file_name = "result" millis = int(round(time.time() * 1000)) file_name += str(millis) header = str(fitness) \ + "\na = " + str(alg.roads_length_factor) \ + "\nb = " + str(alg.paths_length_factor) \ + "\niterations = " + str(alg.iterations) \ + "\nended after = " + str(iters_ended) \ + "\nsame_state = " + str(alg.max_same_state_iterations) \ + "\n" + str(point_tuples) save_result(alg.state, header, file_name)
def repair(self): #returns out a tuple of (tables, transmissions) #call this function periodically. self.tables={} transmissions=0 #init tables for node in self.g.nodes(): self.tables[node]={} #sender_node generates an OGM for sender_node in self.g.nodes(): (flood,t)=Algorithm.util_flood(self.g,sender_node) transmissions+=t for adj_node in flood.keys(): self.tables[adj_node][sender_node]=flood[adj_node] return transmissions
def find_path(self, origin, dest): # flood the network transmissions=0 (flood,t)=Algorithm.util_flood(self.g,origin) transmissions+=t if flood.keys().count(dest)==0: return (None,transmissions) # generate path now path=[dest] currNode=dest while currNode!=origin: path.append(flood[currNode]) currNode=flood[currNode] transmissions+=1 path.reverse() return (path, transmissions)
def __init__ (self, num_players): Algorithm.__init__(self, num_players)
def setUp(self): self.message = "Dit is een fijn bericht" self.algorithm = Algorithm(self.message)
def __init__(self, argv=None, server_algorithm=None): """Takes an argv list, without the initial executable name. """ self.server_algorithm = server_algorithm self.algorithm = Algorithm.from_dotted_name('aspen.algorithms.website') self.configure(argv)
(node1, node2), (node5, node6), (node9, node10) ] inequality_list = [ (node9, node1) ] # Print message. print ' ... Done' print '' print 'Merging...' print '####################' # Execute the merges. alg = Algorithm(merge_list, inequality_list) alg.merge_nodes() # Print message. print '####################' print ' ... Done' print '' print 'Checking satisfiabilty...' # Check for satisfiability. satisfiable = alg.check_satisfiability() # Print message. if satisfiable: print ' => Satisfiable' else: