How to use initialize_1 method in hypothesis

Best Python code snippet using hypothesis

principal.py

Source:principal.py Github

copy

Full Screen

1from importlib import reload2from decimal import Decimal3from random import sample, uniform, randint4from datetime import datetime5import numpy as np6import pandas as pd7import logging8import problem9import evaluate10from problem import Problem11from evaluate import SolutionEvaluator12def log():13 logFormatter = logging.Formatter("[%(asctime)s] %(message)s", datefmt='%m/%d %I:%M:%S')14 rootLogger = logging.getLogger()15 rootLogger.setLevel(logging.DEBUG)16 17 if not rootLogger.handlers:18 fileHandler = logging.FileHandler(datetime.now().strftime('PSO_%d-%m_%H:%M.log'))19 fileHandler.setFormatter(logFormatter)20 rootLogger.addHandler(fileHandler)21 consoleHandler = logging.StreamHandler()22 consoleHandler.setFormatter(logFormatter)23 rootLogger.addHandler(consoleHandler)24 return rootLogger25rootLogger = log() 26def minimize_comparator(individual_solution, global_solution) -> bool:27 return individual_solution < global_solution28def maximize_comparator(individual_solution, global_solution) -> bool:29 return individual_solution > global_solution30def create_population_uniform_strategy(X, num_particles):31 32 _, n_cols = X.shape33 lower = int((num_particles / 3) * 2)34 35 particles = np.zeros(shape=(num_particles, n_cols + 1))36 for i in range(lower):37 features = sample(range(n_cols), int(round(n_cols*0.2)))38 39 for j in features:40 particles[i,j] = round(Decimal(uniform(0.61,1.0)), 4)41 42 for i in range(lower, num_particles):43 qtd_high = sample(range(n_cols), randint(round(n_cols/2 + 1), n_cols))44 45 for j in qtd_high:46 particles[i,j] = round(Decimal(uniform(0.61, 1.0)),4)47 48 return particles49def create_population_20_50_strategy(X, num_particles):50 51 _, n_cols = X.shape52 particles = np.zeros(shape=(num_particles, n_cols + 1)) 53 lower_group = int((num_particles / 3 ) * 2)54 55 for i in range(lower_group):56 features = sample(range(n_cols), int(round(n_cols * 0.2)))57 for j in features:58 particles[i,j] = round(Decimal(uniform(0.61,1.0)), 4)59 60 for i in range(lower_group, num_particles):61 features = sample(range(n_cols), randint(round(n_cols / 2 + 1), n_cols))62 for j in features:63 particles[i,j] = round(Decimal(uniform(0.61, 1.0)), 4)64 65 return particles 66 67class PSOException(Exception):68 69 def __init__(self,message):70 super(PSOException, self).__init__()71 self.message = message72 73 def __str__(self):74 75 return repr(self.message) 76class PSOSelector(object):77 78 def __init__(self, estimator, w=0.7298, c1=1.49618, c2=1.49618,79 num_particles=30, max_iter=100, max_local_improvement=50,80 maximize_objective=True, initialization='uniform',81 fitness_method='type_2', cv = 3):82 83 self.w = w84 self.c1 = c185 self.c2 = c286 self.num_particles = num_particles87 self.max_iter = max_iter88 self.cv = cv89 self.evaluator_ = None90 self.estimator = estimator91 self.velocity_ = None92 self.solution_ = None93 self.initialize = 094 self.initialize_1 = 095 self.N = None96 self.max_local_improvement = max_local_improvement97 self.local_improvement = 098 self.particles = None99 self.count = []100 self.N_ = 0101 self.iteration_ = 0102 self.pop_ = None103 self.count_global = 0104 self._final_cols = None105 self._final_index = None106 self._setup_initialization(initialization, fitness_method)107 self._setup_solution_comparator(maximize_objective)108 self.selected_features_ = None109 110 def _setup_initialization(self, initialization, type_search):111 112 init_method = {113 'uniform': create_population_uniform_strategy,114 '20_50': create_population_20_50_strategy115 }116 117 init_search = {118 'type_1': self.search_type_1,119 'type_2': self.search_type_2,120 'type_3': self.search_type_3,121 'type_4': self.search_type_4122 } 123 124 self._initialization = initialization125 if initialization not in init_method:126 raise PSOException(f'Invalid method {initialization!r}')127 self.init_method_ = init_method[initialization]128 self.init_search_ = init_search[type_search]129 130 def _setup_solution_comparator(self, maximize_objective):131 132 self.maximize_objective = maximize_objective133 if self.maximize_objective:134 self.is_solution_better = maximize_comparator135 else:136 self.is_solution_better = minimize_comparator137 138 def model_baseline(self, prob):139 n_cols = prob.data.shape[1]140 particle = np.zeros(shape=(1, n_cols + 1))141 particle[:] = 1142 evaluator_ = SolutionEvaluator(prob, 1)143 score = evaluator_.evaluate(particle)144 return score[0]145 def fit(self, X, unused_y, **kargs):146 147 if not isinstance(X, pd.DataFrame):148 raise PSOException('The "X" parameter must be a data frame')149 150 self._initialize(X)151 prob = Problem(X, unused_y, self.estimator,152 self.cv, **kargs)153 154 self.N_ = prob.n_cols155 self.evaluator_ = SolutionEvaluator(prob, self.num_particles)156 score_all = self.model_baseline(prob)157 rootLogger.info((158 f'Score with all features - {score_all[-1]}'))159 self.velocity_ = np.zeros(shape=(self.num_particles, self.N_))160 self.best_global_, self.best_global_[:] = \161 np.zeros(shape=(1, self.N_ + 1)), 'nan'162 163 self.best_individual_, self.best_individual_[:] = \164 np.zeros(shape=(self.num_particles, self.N_ + 1)), 'nan'165 self.solution_ = np.zeros(shape=(self.max_iter + 1, self.N_ + 1))166 167 168 while not self._is_stop_criteria_accepted():169 self.init_search_()170 count_sel_feat = self.count_features(self.best_global_[0])171 172 best_glob = self.best_global_[0]173 self.selected_features_ = np.ma.masked_where(best_glob[:-1]>0.6, best_glob[:-1])174 self.selected_features_, = np.where(self.selected_features_.mask == True)175 colunas = list(prob.data.iloc[:, self.selected_features_].columns)176 rootLogger.info((177 f'Iteration: {self.iteration_}/{self.max_iter} \n , '178 f'Best global metric: {self.best_global_[:, -1]} \n , '179 f'Index features_selected: {self.selected_features_} \n , '180 f'Number of selected features: {count_sel_feat} \n , '181 f'Columns selected: {colunas}'))182 183 184 for i in range(0, self.num_particles):185 self.count.append(self.count_features(186 self.best_individual_[i, :]))187 188 best_glob = self.best_global_[0]189 self.selected_features_ = np.ma.masked_where(best_glob[:-1]>0.6, best_glob[:-1])190 self.selected_features_, = np.where(self.selected_features_.mask == True)191 colunas = list(prob.data.iloc[:, self.selected_features_].columns)192 rootLogger.info((f'Final Index features selected: {self.selected_features_} /n, '193 f'Final Columns selected: {colunas} \n'))194 195 self._final_cols = colunas 196 self._final_index = self.selected_features_197 198 def _initialize(self, X):199 200 self.iteration_ = 0201 self.pop_ = self.init_method_(X, self.num_particles)202 203 def _is_stop_criteria_accepted(self):204 205 no_global_improv = self.local_improvement >= self.max_local_improvement206 max_iter_reached = self.iteration_ >= self.max_iter207 return max_iter_reached or no_global_improv208 209 def search_type_1(self):210 211 self.pop_ = self.evaluator_.evaluate(self.pop_)212 self.calculate_best_individual_type_1(self.pop_)213 self.calculate_best_global_type_1()214 self.solution_[self.iteration_, :] = self.best_global_215 self.update_velocity()216 self.iteration_ += 1217 218 def search_type_2(self):219 220 self.pop_ = self.evaluator_.evaluate(self.pop_)221 self.calculate_best_individual_type_2(self.pop_)222 self.calculate_best_global_type_2()223 self.solution_[self.iteration_, :] = self.best_global_224 self.update_velocity()225 self.iteration_ += 1226 def search_type_3(self):227 228 self.pop_ = self.evaluator_.evaluate(self.pop_)229 self.calculate_best_individual_type_3(self.pop_)230 self.calculate_best_global_type_3()231 self.solution_[self.iteration_, :] = self.best_global_232 self.update_velocity()233 self.iteration_ += 1234 def search_type_4(self):235 236 self.pop_ = self.evaluator_.evaluate(self.pop_)237 self.calculate_best_individual_type_4(self.pop_)238 self.calculate_best_global_type_4()239 self.solution_[self.iteration_, :] = self.best_global_240 self.update_velocity()241 self.iteration_ += 1 242 243 def update_velocity(self):244 245 w = self.w246 c1, c2 = self.c1, self.c2247 248 for i in range(0, len(self.pop_) - 1):249 for j in range(0, self.N_):250 r1= round(uniform(0,1), 2)251 r2 = round(uniform(0, 1), 2)252 pop = self.pop_[i, j]253 inertia = w * self.velocity_[i,j]254 cognitive = c1 * r1 * (self.best_individual_[i,j] - pop)255 social = c2 * r2 * (self.best_global_[0, j] - pop)256 velocity = inertia + cognitive + social257 self.velocity_[i,j] = velocity258 self.pop_[i,j] += velocity259 260 def calculate_best_individual_type_2(self, pop):261 262 if self.initialize == 0:263 for i in range(0, len(pop)):264 for j in range(0, self.N_ + 1):265 self.best_individual_[i,j] = pop[i,j]266 267 self.initialize = 1268 return269 270 for i in range(0, len(pop)):271 candidate_a = pop[i, self.N_]272 candidate_b = self.best_individual_[i, self.N_]273 if self.is_solution_better(candidate_a,candidate_b):274 for j in range(0 , self.N_ + 1):275 self.best_individual_[i,j] = pop[i,j]276 continue 277 278 particle_count = self.count_features(self.pop_[i, :])279 count_best_individual = self.count_features(280 self.best_individual_[i, :])281 282 if particle_count > 0:283 if (candidate_a == candidate_b284 and particle_count < count_best_individual):285 286 for j in range(0, self.N_ + 1):287 self.best_individual_[i,j] = pop[i,j]288 289 290 def calculate_best_global_type_2(self):291 292 if self.initialize_1 == 0:293 for i in range(0, self.N_ + 1):294 self.best_global_[0,i] = self.best_individual_[0, i]295 296 self.initialize_1 = 1297 self.count_global = self.count_features(self.best_global_[0, :])298 299 for i in range(0, self.num_particles): 300 best_ind = self.best_individual_[i, self.N_]301 best_global = self.best_global_[0, self.N_]302 if self.is_solution_better(best_ind,303 best_global):304 305 self.local_improvement = 1306 for j in range(0, self.N_ + 1):307 308 self.best_global_[0,j] = self.best_individual_[i,j]309 310 self.count_global = self.count_features(311 self.best_global_[0, :])312 313 continue314 315 count_best_individual = self.count_features(self.best_individual_[i, :])316 317 if (best_global == best_ind318 and count_best_individual < self.count_global):319 320 self.local_improvement = 1321 self.count_global = 0322 for j in range(0, self.N_ + 1):323 self.best_global_[0, j] = self.best_individual_[i,j]324 325 self.count_global = self.count_features(326 self.best_global_[0, :])327 328 329 def calculate_best_individual_type_1(self,pop):330 if self.initialize == 0:331 for i in range(0, len(pop)):332 for j in range(0, self.N_ + 1):333 self.best_individual_[i,j] = pop[i,j]334 self.initialize = 1335 return336 337 for i in range(0, len(pop)):338 if self.is_solution_better(pop[i,self.N_],339 self.best_individual_[i, self.N_]): 340 for j in range(0, self.N_ + 1):341 self.best_individual_[i, j] = pop[i,j]342 343 344 def calculate_best_global_type_1(self):345 if self.initialize_1 == 0:346 for i in range(0, self.N_ + 1):347 self.best_global_[0,i] = self.best_individual_[0,i]348 self.initialize_1 = 1 349 for i in range(0, len(self.pop_)):350 if self.is_solution_better(self.best_individual_[i, self.N_],351 self.best_global_[0, self.N_]):352 self.local_improvement = 1353 354 for j in range(0, self.N_ + 1):355 self.best_global_[0,j] = self.best_individual_[i,j]356 357 self.local_improvement += 1358 359 def calculate_best_individual_type_3(self, pop):360 361 if self.initialize == 0:362 for i in range(0, len(pop)):363 for j in range(0, self.N_ + 1):364 self.best_individual_[i,j] = pop[i,j]365 366 self.initialize = 1367 return368 369 for i in range(0, len(pop)):370 candidate_a = pop[i, self.N_]371 candidate_b = self.best_individual_[i, self.N_]372 particle_count = self.count_features(self.pop_[i, :])373 count_best_individual = self.count_features(374 self.best_individual_[i, :])375 376 if particle_count > 0:377 if (self.is_solution_better(candidate_a,candidate_b)378 and particle_count <= count_best_individual):379 380 for j in range(0, self.N_ + 1):381 self.best_individual_[i,j] = pop[i,j]382 elif (candidate_a == candidate_b 383 and particle_count < count_best_individual): 384 for j in range(0, self.N_ + 1):385 self.best_individual_[i,j] = pop[i,j] 386 else:387 continue 388 389 def calculate_best_global_type_3(self):390 391 if self.initialize_1 == 0:392 for i in range(0, self.N_ + 1):393 self.best_global_[0,i] = self.best_individual_[0, i]394 395 self.initialize_1 = 1396 self.count_global = self.count_features(self.best_global_[0, :])397 398 for i in range(0, self.num_particles): 399 best_ind = self.best_individual_[i, self.N_]400 best_global = self.best_global_[0, self.N_]401 count_best_individual = self.count_features(self.best_individual_[i, :])402 403 if (self.is_solution_better(best_ind,best_global)404 and count_best_individual <= self.count_global):405 406 self.local_improvement = 1407 for j in range(0, self.N_ + 1):408 self.best_global_[0,j] = self.best_individual_[i,j]409 410 self.count_global = self.count_features(411 self.best_global_[0, :])412 413 elif (best_ind == best_global414 and count_best_individual < self.count_global):415 self.local_improvement = 1416 self.count_global = 0417 for j in range(0, self.N_ + 1):418 self.best_global_[0, j] = self.best_individual_[i,j]419 420 self.count_global = self.count_features(421 self.best_global_[0, :])422 else:423 continue 424 def calculate_best_individual_type_4(self, pop):425 426 if self.initialize == 0:427 for i in range(0, len(pop)):428 for j in range(0, self.N_ + 1):429 self.best_individual_[i,j] = pop[i,j]430 431 self.initialize = 1432 return433 434 for i in range(0, len(pop)):435 candidate_a = pop[i, self.N_]436 candidate_b = self.best_individual_[i, self.N_]437 particle_count = self.count_features(self.pop_[i, :])438 count_best_individual = self.count_features(439 self.best_individual_[i, :])440 441 if particle_count > 0:442 if (self.is_solution_better(candidate_a,candidate_b)443 and particle_count <= count_best_individual):444 445 for j in range(0, self.N_ + 1):446 self.best_individual_[i,j] = pop[i,j]447 elif (self.is_solution_better(candidate_a, 0.95 * candidate_b) 448 and particle_count < count_best_individual): 449 for j in range(0, self.N_ + 1):450 self.best_individual_[i,j] = pop[i,j] 451 else:452 continue 453 454 def calculate_best_global_type_4(self):455 456 if self.initialize_1 == 0:457 for i in range(0, self.N_ + 1):458 self.best_global_[0,i] = self.best_individual_[0, i]459 460 self.initialize_1 = 1461 self.count_global = self.count_features(self.best_global_[0, :])462 463 for i in range(0, self.num_particles): 464 best_ind = self.best_individual_[i, self.N_]465 best_global = self.best_global_[0, self.N_]466 count_best_individual = self.count_features(self.best_individual_[i, :])467 468 if (self.is_solution_better(best_ind,best_global)469 and count_best_individual <= self.count_global):470 471 self.local_improvement = 1472 for j in range(0, self.N_ + 1):473 self.best_global_[0,j] = self.best_individual_[i,j]474 475 self.count_global = self.count_features(476 self.best_global_[0, :])477 478 elif (self.is_solution_better(best_ind, 0.95 * best_global)479 and count_best_individual < self.count_global):480 self.local_improvement = 1481 self.count_global = 0482 for j in range(0, self.N_ + 1):483 self.best_global_[0, j] = self.best_individual_[i,j]484 485 self.count_global = self.count_features(486 self.best_global_[0, :])487 else:488 continue 489 def count_features(self, particle_proportions, threshold=0.6):490 491 count = 0492 for i in range(0, self.N_):493 if particle_proportions[i] > threshold:494 count = count + 1495 return count 496 497 @property 498 def final_cols(self): 499 return self._final_cols 500 @property501 def final_index(self):502 return self._final_index 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 ...

Full Screen

Full Screen

c06_overloading.py

Source:c06_overloading.py Github

copy

Full Screen

...20# import overloading21class Duration:22 """Represents durations in H:M:S format."""23 24 def initialize_1(self, hours, mins=None, secs=None): # WITH OPTIONAL ARGUMENTS25 """Initializes Duration instance. Must be able to process either integer26 H:M:S format or decimal number of hours as inputs. Implementation #1."""27 if mins or secs: # H:M:S format28 if (not isinstance(hours, int) # check type29 or isinstance(hours, bool)):30 msg = "arguments must be integers to use H:M:S format"31 raise TypeError(msg)32 self._hours = hours33 34 if mins:35 if (not isinstance(mins, int) # check type36 or isinstance(mins, bool)):37 msg = "arguments must be integers to use H:M:S format"38 raise TypeError(msg)39 self._mins = mins40 41 else:42 self._mins = 043 if secs:44 if (not isinstance(secs, int) # check type45 or isinstance(secs, bool)):46 msg = "arguments must be integers to use H:M:S format"47 raise TypeError(msg)48 self._secs = secs49 50 else:51 self._secs = 052 else: # decimal format53 if (not isinstance(hours, (int, float)) # check type54 or isinstance(hours, bool)):55 msg = "argument must be a real number to use decimal format"56 raise TypeError(msg) 57 (self._hours, self._mins, self._secs) = self.dec2hms(hours)58 def initialize_2(self, *args): # WITH VARIABLE LENGTH ARGUMENT59 """Initializes Duration instance. Must be able to process either integer60 H:M:S format or decimal number of hours as inputs. Implementation #2."""61 # Create canvas62 self._hours = None63 self._mins = None64 self._secs = None65 # Parse arguments66 if len(args) > 3:67 raise TypeError("expected 1 to 3 arguments")68 69 elif len(args) > 1: # H:M:S format70 for (idx, field) in enumerate(vars(self)):71 72 if idx < len(args): # argument was provided73 if (not isinstance(args[idx], int) # check type74 or isinstance(args[idx], bool)):75 msg = "arguments must be integers to use H:M:S format"76 raise TypeError(msg)77 vars(self)[field] = args[idx] # self.field does not work,78 # as field is a string79 80 else:81 vars(self)[field] = 082 83 elif len(args) > 0: # decimal duration (in hours)84 if (not isinstance(args[0], (int, float)) # check type85 or isinstance(args[0], bool)):86 msg = "argument must be a real number to use decimal format"87 raise TypeError(msg)88 (self._hours, self._mins, self._secs) = self.dec2hms(args[0])89 90 # @overloading91 # def initialize_3(self, hours): # WITH OVERLOADING92 # pass93 def __repr__(self):94 """Returns string representation of calling Duration instance."""95 formstr = "{:02}:{:02}:{:02}"96 return formstr.format(self._hours, self._mins, self._secs)97 @staticmethod98 def dec2hms(number):99 """Converts decimal number of hours to Duration object."""100 if (not isinstance(number, (int, float)) # check type101 or isinstance(number, bool)):102 raise TypeError("argument must be a decimal number")103 104 # Handle sign separately105 if number < 0:106 sign = -1107 number = -number108 else:109 sign = 1110 111 # Compute (% and // operators expect positive numbers)112 hours = sign * round(number // 1)113 mins = sign * round(((number % 1) * 60) // 1)114 secs = sign * round((((number % 1) * 60) % 1) * 60)115 return (hours, mins, secs)116 def hms2dec(self):117 """Converts Duration object to decimal number of hours."""118 return (self._hours + self._mins/60 + self._secs/3600)119 120 121 122 123# -------------------------------- TEST SCRIPT --------------------------------124import misctest as mt125duration_1 = Duration()126duration_2 = Duration()127decimal_1 = 13.25128decimal_2 = 2.425129mt.headprint("Implementation #1")130duration_1.initialize_1(decimal_1)131print(Duration.dec2hms(decimal_2))132duration_2.initialize_1(*Duration.dec2hms(decimal_2))133print("TIME\tHOURS\tHH:MM:SS")134print("duration_1\t{}\t{}".format(decimal_1, duration_1))135print("duration_2\t{}\t{}".format(decimal_2, duration_2))136mt.headprint("Implementation #2")137duration_1.initialize_2(decimal_1)138duration_2.initialize_2(*Duration.dec2hms(decimal_2))139print("TIME\tHOURS\tHH:MM:SS")140print("duration_1\t{}\t{}".format(decimal_1, duration_1))...

Full Screen

Full Screen

test_core.py

Source:test_core.py Github

copy

Full Screen

...40api_token: thisisarandomvalueofapitoken41 """, file=fp)42 with var_dir.as_cwd():43 assert not config.initialized44 initialize_1(config_path=str(test_config))45 assert config.initialized46 assert config.dropbox.api_token == 'thisisarandomvalueofapitoken'47 def test_initialize_1_without_config(self, tmpdir_factory):48 var_dir = tmpdir_factory.mktemp('temp_var')49 test_config = var_dir.join('paper-git.cfg')50 with test_config.open(ensure=True, mode='w') as fp:51 print("""52[dropbox]53api_token: thisisadifferentapitoken54 """, file=fp)55 with var_dir.as_cwd():56 initialize_1()57 assert config.initialized58 assert config.dropbox.api_token == 'thisisadifferentapitoken'59 def test_initialize_2(self, tmpdir_factory):60 var_dir = tmpdir_factory.mktemp('temp_var')61 test_config = var_dir.join('paper-git.cfg')62 with test_config.open(ensure=True, mode='w') as fp:63 print("""64[dropbox]65api_token: thisisanotherapikey66 """, file=fp)67 assert config.dbox is None68 assert config.db.path is None69 with pytest.raises(peewee.OperationalError):70 config.db.db.connect()...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run hypothesis automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful