Best Python code snippet using hypothesis
2kyu_befunge_interpreter.py
Source:2kyu_befunge_interpreter.py
...106 col = 0107 else:108 self.matrix[row][col] = c109 col += 1110 def __pop(self):111 try:112 res = self.stack.pop()113 except:114 res = 0115 return res116 def __push(self, s):117 self.stack.append(s)118 def __direction(self, direction):119 self.current_direction = direction120 def __push_num(self):121 self.__push(int(self.matrix[self.current_row][self.current_col]))122 def __add(self):123 x = self.__pop()124 y = self.__pop()125 self.__push(x + y)126 def __subtract(self):127 x = self.__pop()128 y = self.__pop()129 self.__push(y - x)130 def __multiple(self):131 x = self.__pop()132 y = self.__pop()133 self.__push(x * y)134 def __divide(self):135 x = self.__pop()136 y = self.__pop()137 if y == 0:138 self.__push(0)139 else:140 self.__push(round(y / x, 0))141 def __mod(self):142 x = self.__pop()143 y = self.__pop()144 if x == 0:145 self.__push(0)146 else:147 self.__push(y % x)148 def __not(self):149 x = self.__pop()150 if x == 0:151 self.__push(1)152 else:153 self.__push(0)154 def __gt(self):155 x = self.__pop()156 y = self.__pop()157 if y > x:158 self.__push(1)159 else:160 self.__push(0)161 def __moving_right(self):162 self.__direction('>')163 def __moving_left(self):164 self.__direction('<')165 def __moving_up(self):166 self.__direction('^')167 def __moving_down(self):168 self.__direction('v')169 def __moving_random_direction(self):170 direction = ['>', '<', '^', 'v']171 self.__direction(direction)172 self.BEFUNGE_CODE_TABLE[random.choice(direction)]()173 def __moving_by_cond_right_left(self):174 x = self.__pop()175 if x == 0:176 self.BEFUNGE_CODE_TABLE['>']()177 else:178 self.BEFUNGE_CODE_TABLE['<']()179 def __moving_by_cond_up_down(self):180 x = self.__pop()181 if x == 0:182 self.BEFUNGE_CODE_TABLE['v']()183 else:184 self.BEFUNGE_CODE_TABLE['^']()185 def __string_mode(self):186 self.__moving()187 n = ord(str(self.matrix[self.current_row][self.current_col]))188 while n != 34:189 self.__push(n)190 self.__moving()191 n = ord(str(self.matrix[self.current_row][self.current_col]))192 def __duplicate(self):193 x = self.__pop()194 self.__push(x)195 self.__push(x)196 def __swap(self):197 x = self.__pop()198 y = self.__pop()199 self.__push(x)200 self.__push(y)201 def __discard(self):202 self.__pop()203 def __end(self):204 self.is_ended = True205 def __get_integer(self):206 self.result.append(str(self.__pop()))207 def __get_char(self):208 self.result.append(chr(self.__pop()))209 def __trampoline(self):210 self.__moving()211 def __put_to_xy(self):212 x = self.__pop()213 y = self.__pop()214 v = self.__pop()215 self.matrix[x][y] = chr(v)216 def __get_from_xy(self):217 y = self.__pop()218 x = self.__pop()219 self.__push(ord(self.matrix[y][x]))220 def __nothing(self):221 pass222 def __moving(self, count=1):223 if self.current_direction == '>':224 self.current_col += count225 elif self.current_direction == '<':226 self.current_col -= count227 elif self.current_direction == '^':228 self.current_row -= count229 elif self.current_direction == 'v':230 self.current_row += count231class TestBefunge(unittest.TestCase):232 def test_befunge_is_valid(self):...
Mopso.py
Source:Mopso.py
1# encoding: utf-823import time4import numpy as np5from util import update, drawCurve, testFunc, NDsort6import memory_profiler as mem78class Mopso:9 def __init__(self, num_pop, max_, min_, threshold, grid_div=10):10 self.__grid = grid_div11 self.__num_pop = num_pop # ç§ç¾¤ç²åæ°é12 self.__threshold = threshold13 self.__max = max_14 self.__min = min_1516 # self.max_v = (max_-min_)*0.5 #é度ä¸é17 # self.min_v = (max_-min_)*(-1)*0.5 #é度ä¸é18 self.__max_v = 100 * np.ones(len(max_), ) # é度ä¸ä¸é,é度ä¸åå¨ä¸ä¸éï¼å æ¤è®¾ç½®å¾å¤§19 self.__min_v = -100 * np.ones(len(min_), )2021 self.__pop = None22 self.__v = None23 self.__fit = None24 self.__pop_pbest = None25 self.__fit_pbest = None26 self.__pop_gbest = None27 self.__fit_gbest = None28 self.__archive_pop = None29 self.__archive_fit = None3031 self.__draw = drawCurve.DrawParetoCurve()3233 def evaluation_fitness(self):34 self.__fit = testFunc.obj_func("value", "DTLZ2", 2, self.__pop)3536 def initialize(self):37 """38 åå§åç²å群39 :return:40 """41 # åå§åç²åä½ç½® pop[i]42 # self.__num_pop ç²å群æ°é43 self.__pop = self.__init_loc(self.__num_pop, self.__max, self.__min)44 # åå§åç²åé度 å
¨045 self.__v = self.__init_v(self.__num_pop, self.__max_v, self.__min_v)46 # 计ç®éåºåº¦47 self.evaluation_fitness()48 # åå§å个ä½æä¼49 # TODO 第äºä¸ªåæ°åºè¯¥æ¯é度ï¼50 self.__pop_pbest, self.__fit_pbest = self.__init_pbest(self.__pop, self.__fit)51 # åå§åå¤é¨åæ¡£52 self.__archive_pop, self.__archive_fit = self.__init_archive(self.__pop, self.__fit)53 # åå§åå
¨å±æä¼54 self.__pop_gbest, self.__fit_gbest = update.update_gbest(self.__archive_pop, self.__archive_fit, self.__grid,55 self.__num_pop)5657 def update(self):58 """59 æ´æ°ç²åé度ãä½ç½®ãéåºåº¦ã个ä½æä¼ãå¤é¨åæ¡£ãå
¨å±æä¼60 :return:61 """62 self.__v = update.update_v(self.__v, self.__min_v, self.__max_v, self.__pop, self.__pop_pbest, self.__pop_gbest)63 self.__pop = update.update_pop(self.__pop, self.__v, self.__min, self.__max)6465 self.evaluation_fitness()6667 self.__pop_pbest, self.__fit_pbest = update.update_pbest(self.__pop, self.__fit, self.__pop_pbest,68 self.__fit_pbest)6970 self.__archive_pop, self.__archive_fit = update.update_archive(self.__pop, self.__fit, self.__archive_pop,71 self.__archive_fit,72 self.__threshold, self.__grid)7374 self.__pop_gbest, self.__fit_gbest = update.update_gbest(self.__archive_pop, self.__archive_fit, self.__grid,75 self.__num_pop)7677 def run(self, iterate):78 # å¼å§æ¶é´æ³79 beg = time.time()80 print(f'è¿è¡åå ç¨å
åï¼{mem.memory_usage()}')81 self.initialize()82 self.__draw.show(self.__pop, self.__fit, self.__archive_pop, self.__archive_fit, -1)83 for i in range(iterate):84 self.update() # æ´æ°ç§ç¾¤85 # numpy.round() è¿åæµ®ç¹æ°çåèäºå
¥å¼86 print('第', i+1, '代已å®æï¼èè´¹æ¶é´: ', np.round(time.time() - beg, 2), "s")87 self.__draw.show(self.__pop, self.__fit, self.__archive_pop, self.__archive_fit, i)88 print(f'è¿è¡åå ç¨å
åï¼{mem.memory_usage()}')89 return self.__archive_pop, self.__archive_fit9091 @staticmethod92 def __init_loc(pop, pop_max, pop_min):93 # åå§åç²åä½ç½®94 dim = len(pop_max) # è¾å
¥åæ°ç»´åº¦95 # numpy.random.uniform(low, high, size) ä»åååå¸ä¸éæºéæ ·ï¼sizeæ¯è¾åºæ ·æ¬æ°é96 return np.random.uniform(0, 1, (pop, dim)) * (pop_max - pop_min) + pop_min9798 @staticmethod99 def __init_v(pop, v_max, v_min):100 v_dim = len(v_max) # 维度101 # v_ = np.random.uniform(0,1,(particals,v_dim))*(v_max-v_min)+v_min102 return np.zeros((pop, v_dim))103104 @staticmethod105 def __init_pbest(pop, fit):106 return pop, fit107108 @staticmethod109 def __init_archive(pop, fit):110 # NDSort()[0] ååºç¬¬ä¸ç»è¿åå¼ï¼å¦ææ¯1åæ¯ç¬¬ä¸å±çç²å111 front_index = NDsort.NDSort(fit, pop.shape[0])[0] == 1112 front_index = np.reshape(front_index, (-1,)) # ç©éµè½¬æè¡åé113114 # curr_archiving_in = pop[front_index]115 # curr_archiving_fit = fit[front_index]116117 # pareto_c = pareto.Pareto_(pop,fitness_)118 # curr_archiving_in_,curr_archiving_fit_ = pareto_c.pareto()
...
bssa.py
Source:bssa.py
1from salp import Salp2from accuracy import cal_cost_knn, cal_cost_svm3import numpy as np4import logging 5import os6from copy import deepcopy7logger = logging.getLogger("main.bssa")8class BSSA:9 10 def __init__(self, pop, dim, tf, ub, lb, upate_strategy):11 self.__pop = [Salp(dim, ub, lb) for i in range(pop)]12 self.__tf = tf13 self.__ub = ub14 self.__lb = lb15 self.__selected_features_history = []16 self.__cost_history = []17 self.__acc_history = []18 self.__update_strategy = upate_strategy19 self.__cost_func = cal_cost_svm20 21 def get_pop(self):22 return self.__pop23 def set_pop(self, pop):24 self.__pop = pop25 def get_best_salp(self):26 return self.__pop[0]27 def get_best_position(self):28 return self.__pop[0].get_position()29 def get_best_selected(self):30 return np.round(self.get_best_position())31 def get_best_cost(self):32 return self.__pop[0].get_cost()33 def replace_with_worst_salp(self, best_salp):34 self.__pop = sorted(self.__pop, key=lambda x:x.get_cost())35 self.__pop[-1].set_position(best_salp.get_position())36 self.__pop[-1].set_cost(best_salp.get_cost())37 38 def reset_history(self):39 self.__cost_history = []40 self.__selected_features_history = []41 self.__acc_history = []42 def get_cost_history(self):43 return self.__cost_history44 def get_selected_features_history(self):45 return self.__selected_features_history46 def get_acc_history(self):47 return self.__acc_history48 def train(self, max_iteration, train_data, train_target, test_data, test_target):49 us = self.__update_strategy50 tf = self.__tf51 cf = self.__cost_func52 #measure accuracy and sort respect to the fitness53 for s in self.__pop:54 c, _, _ = cf(s.get_position(), train_data, train_target)55 s.set_cost(c)56 self.__pop = sorted(self.__pop, key=lambda x:x.get_cost())57 for s in self.__pop:58 logger.debug("cost is {}".format(s.get_cost()))59 #select the best one as food60 food = self.__pop[0]61 #it should be sorted62 for i in range(max_iteration):63 c1 = us(i, max_iteration)64 for this_s, pre_s, j in zip(self.__pop[1:], 65 self.__pop[-1:] + self.__pop[1:-1], 66 range(len(self.__pop))):67 if j<= len(self.__pop)/2.0:68 c2 = np.random.rand(this_s.get_dim())69 c3 = np.random.rand(this_s.get_dim())70 c3 = np.array(list(map(lambda x:-1 if x<0.5 else 1, c3)))71 this_s.set_position(food.get_position() + c1*c2*c3)72 else:73 this_s.set_position((this_s.get_position() + pre_s.get_position())/2)74 for s in self.__pop:75 u = self.__ub76 l = self.__lb77 pos = s.get_position()78 pos = np.array(list(map(lambda x:l if x<l else(u if x>u else x), pos)))79 s.set_position(pos)80 c, _, _ = cf(s.get_position(), train_data, train_target)81 s.set_cost(c)82 if c < food.get_cost():83 food.set_position(s.get_position())84 food.set_cost(s.get_cost())85 logger.debug("best changed to this cost {} last cost {}".format(s.get_cost(), food.get_cost())) 86 87 _, e, f = cf(food.get_position(), train_data, train_target)88 self.__acc_history.append(1 - e)89 self.__selected_features_history.append(f)90 self.__cost_history.append(food.get_cost())91 logger.info("iter {} cost {} pid {} ppid {}".format(i, food.get_cost(), os.getpid(), os.getppid()))...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!