How to use pop_values method in autotest

Best Python code snippet using autotest_python Github


Full Screen

1"""Differential Evolution Optimization2:Author: Robert Kern3Copyright 2005 by Robert Kern.4"""5import numpy as np6# Licence:7# Copyright (c) 2001, 2002 Enthought, Inc.8# 9# All rights reserved.10# 11# Redistribution and use in source and binary forms, with or without12# modification, are permitted provided that the following conditions are met:13# 14# a. Redistributions of source code must retain the above copyright notice,15# this list of conditions and the following disclaimer.16# b. Redistributions in binary form must reproduce the above copyright17# notice, this list of conditions and the following disclaimer in the18# documentation and/or other materials provided with the distribution.19# c. Neither the name of the Enthought nor the names of its contributors20# may be used to endorse or promote products derived from this software21# without specific prior written permission.22# 23# 24# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"25# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE26# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE27# ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR28# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL29# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR30# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER31# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT32# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY33# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH34# DAMAGE.35# Notes: for future modifications:36# Ali, M. M., and A. Toern. Topographical differential evolution using37# pre-calculated differentials. _Stochastic and Global Optimization_. 1--17.38#39# A good scale value:40# F = max(l_min, 1-min(abs(f_min/f_max), abs(f_max/f_min)))41# ~ 0.3 <= l_min <= 0.442# ~ f_min and f_max are the minimum and maximum values in the initial43# population.44#45# Pre-calculated differentials:46# Keep a set of differentials A.47# For each x_i of the population S:48# Every M steps, randomly select 3 points x_r1, x_r2, x_r3 from S (not x_i).49# Compute new x_i using x_r1 + F*(x_r2-x_r3).50# Store differential in A.51# Each other step:52# Randomly select x_r1 from S and a differential vector from A.53# Crossover.54#55# Convergence criterion:56# f_max - f_min < eps57#58# Topographical DEPD:59# Two populations S and Sa (auxiliary).60# Phase counter t = 0 and array shift[:] = False.61# Stopping condition: e.g. t >= 4.62# g << N, number of nearest neighbors to search for graph minima.63# Ng << N, number of points for graph.64# For each x_i in S, do DEPD as described above to get y_i.65# if f(y_i) < f(x_i):66# if shift[i] is False:67# shift[i] = True68# S[i] = y_i69# else:70# Sa[i] = y_i71# if alltrue(shift,axis=0):72# Find graph minima of f(x) using the Ng best points in S.73# Do local search from each minimum.74# Replace worst Ng points in S with best Ng points in Sa.75# If best from this phase is better than previous best, t=0.76# Else: t += 1.77# shift[:] = False78# Next generation.79class DiffEvolver(object):80 """Minimize a function using differential evolution.81 Constructors82 ------------83 DiffEvolver(func, pop0, args=(), crossover_rate=0.5, scale=None,84 strategy=('rand', 2, 'bin'), eps=1e-6)85 func -- function to minimize86 pop0 -- sequence of initial vectors87 args -- additional arguments to apply to func88 crossover_rate -- crossover probability [0..1] usually 0.5 or so89 scale -- scaling factor to apply to differences [0..1] usually > 0.590 if None, then calculated from pop0 using a heuristic91 strategy -- tuple specifying the differencing/crossover strategy92 The first element is one of 'rand', 'best', 'rand-to-best' to specify93 how to obtain an initial trial vector.94 The second element is either 1 or 2 (or only 1 for 'rand-to-best') to95 specify the number of difference vectors to add to the initial trial.96 The third element is (currently) 'bin' to specify binomial crossover.97 eps -- if the maximum and minimum function values of a given generation are98 with eps of each other, convergence has been achieved.99 prng -- a RandomState instance. By default, this is the global100 numpy.random instance.101 DiffEvolver.frombounds(func, lbound, ubound, npop, crossover_rate=0.5,102 scale=None, strategy=('rand', 2, 'bin'), eps=1e-6)103 Randomly initialize the population within given rectangular bounds.104 lbound -- lower bound vector105 ubound -- upper bound vector106 npop -- size of population107 Public Methods108 --------------109 solve(newgens=100)110 Run the minimizer for newgens more generations. Return the best parameter111 vector from the whole run.112 Public Members113 --------------114 best_value -- lowest function value in the history115 best_vector -- minimizing vector116 best_val_history -- list of best_value's for each generation117 best_vec_history -- list of best_vector's for each generation118 population -- current population119 pop_values -- respective function values for each of the current population120 generations -- number of generations already computed121 func, args, crossover_rate, scale, strategy, eps -- from constructor122 """123 def __init__(self, func, pop0, args=(), crossover_rate=0.5, scale=None,124 strategy=('rand', 2, 'bin'), eps=1e-6, prng=np.random):125 self.func = func126 self.population = np.array(pop0)127 self.npop, self.ndim = self.population.shape128 self.args = args129 self.crossover_rate = crossover_rate130 self.strategy = strategy131 self.eps = eps132 self.prng = prng133 self.pop_values = [self.func(m, *args) for m in self.population]134 bestidx = np.argmin(self.pop_values)135 self.best_vector = self.population[bestidx]136 self.best_value = self.pop_values[bestidx]137 if scale is None:138 self.scale = self.calculate_scale()139 else:140 self.scale = scale141 self.generations = 0142 self.best_val_history = []143 self.best_vec_history = []144 self.bound = None145 self.jump_table = {146 ('rand', 1, 'bin'): (self.choose_rand, self.diff1, self.bin_crossover),147 ('rand', 2, 'bin'): (self.choose_rand, self.diff2, self.bin_crossover),148 ('best', 1, 'bin'): (self.choose_best, self.diff1, self.bin_crossover),149 ('best', 2, 'bin'): (self.choose_best, self.diff2, self.bin_crossover),150 ('rand-to-best', 1, 'bin'):151 (self.choose_rand_to_best, self.diff1, self.bin_crossover),152 }153 def clear(self):154 self.best_val_history = []155 self.best_vec_history = []156 self.generations = 0157 self.pop_values = [self.func(m, *self.args) for m in self.population]158 def frombounds(cls, func, lbound, ubound, npop, crossover_rate=0.5,159 scale=None, strategy=('rand', 2, 'bin'), eps=1e-6, prng=np.random):160 lbound = np.asarray(lbound)161 ubound = np.asarray(ubound)162 pop0 = prng.uniform(lbound, ubound, size=(npop, len(lbound)))163 return cls(func, pop0, crossover_rate=crossover_rate, scale=scale,164 strategy=strategy, eps=eps, prng=prng)165 frombounds = classmethod(frombounds)166 def set_boundaries(self, lbound, ubound, mode='mirror'):167 boundary_table = {'skip': None,168 'reject': self.bound_reject,169 'limit': self.bound_limit,170 'mirror': self.bound_mirror,171 'halfway': self.bound_halfway,172 'old': self.bound_old173 }174 self.bound = boundary_table[mode]175 self.lbound = lbound176 self.ubound = ubound177 def calculate_scale(self):178 rat = abs(max(self.pop_values)/self.best_value)179 rat = min(rat, 1./rat)180 return max(0.3, 1.-rat)181 def bin_crossover(self, oldgene, newgene):182 mask = self.prng.rand(self.ndim) < self.crossover_rate183 return np.where(mask, newgene, oldgene)184 def select_samples(self, candidate, nsamples):185 possibilities = list(range(self.npop))186 possibilities.remove(candidate)187 return self.prng.permutation(possibilities)[:nsamples]188 def diff1(self, candidate):189 i1, i2 = self.select_samples(candidate, 2)190 return self.scale * (self.population[i1] - self.population[i2])191 def diff2(self, candidate):192 i1, i2, i3, i4 = self.select_samples(candidate, 4)193 return self.scale * (self.population[i1] - self.population[i2] +194 self.population[i3] - self.population[i4])195 def choose_best(self, candidate):196 return self.best_vector197 def choose_rand(self, candidate):198 i = self.select_samples(candidate, 1)[0]199 return self.population[i]200 def choose_rand_to_best(self, candidate):201 return ((1-self.scale) * self.population[candidate] +202 self.scale * self.best_vector)203 def bound_halfway(self, candidate, trial):204 trial =[trial < self.lbound,205 trial > self.ubound,206 True],207 [(self.population[candidate]+self.lbound)/2,208 (self.population[candidate]+self.ubound)/2,209 trial])210 return trial211 def bound_reject(self, candidate, trial):212 if np.any(trial < self.lbound) or np.any(trial > self.ubound):213 return None214 else:215 return trial216 def bound_old(self, candidate, trial):217 trial =[trial < self.lbound,218 trial > self.ubound,219 True],220 [self.population[candidate],221 self.population[candidate],222 trial])223 return trial224 def bound_limit(self, candidate, trial):225 trial =[trial < self.lbound,226 trial > self.ubound,227 True],228 [self.lbound,229 self.ubound,230 trial])231 return trial232 def bound_mirror(self, candidate, trial):233 trial =[trial < self.lbound,234 trial > self.ubound,235 True],236 [self.lbound + (self.lbound - trial),237 self.ubound - (trial - self.ubound),238 trial])239 return trial240 def get_trial(self, candidate):241 chooser, differ, crosser = self.jump_table[self.strategy]242 trial = crosser(self.population[candidate],243 chooser(candidate) + differ(candidate))244 return trial245 def converged(self):246 return max(self.pop_values) - min(self.pop_values) <= self.eps247 def solve(self, newgens=100):248 """Run for newgens more generations.249 Return best parameter vector from the entire run.250 """251 for gen in range(self.generations+1, self.generations+newgens+1):252 for candidate in range(self.npop):253 trial = self.get_trial(candidate)254 ## apply boundary function255 if self.bound:256 trial = self.bound(candidate,trial)257 ## check if we have abortet that trial258 if len(trial) == 0:259 print( ".", end="")260 continue261 trial_value = self.func(trial, *self.args)262 if trial_value < self.pop_values[candidate]:263 self.population[candidate] = trial264 self.pop_values[candidate] = trial_value265 if trial_value < self.best_value:266 self.best_vector = trial267 self.best_value = trial_value268 self.best_val_history.append(self.best_value)269 self.best_vec_history.append(self.best_vector)270 if self.converged():271 break272 self.generations = gen...

Full Screen

Full Screen Github


Full Screen

...33 nice_bytes.append(' 0x')34 hex_seen = True35 nice_bytes.append('%02x' % b)36 return ''.join(nice_bytes)37 def pop_values(self, fmt):38 size = struct.calcsize(fmt)39 if len(self.buffer) < size:40 raise BufferUnderflowError(fmt, self.buffer)41 values = struct.unpack_from(fmt, self.buffer, 0)42 self.buffer = self.buffer[size:]43 return values44 def pop_int8(self):45 return self.pop_values('<b')[0]46 def pop_uint8(self):47 return self.pop_values('<B')[0]48 def pop_int16(self):49 return self.pop_values('<h')[0]50 def pop_uint16(self):51 return self.pop_values('<H')[0]52 def pop_int32(self):53 return self.pop_values('<i')[0]54 def pop_uint32(self):55 return self.pop_values('<I')[0]56 def pop_float32(self):57 return self.pop_values('<f')[0]58 def pop_float64(self):59 return self.pop_values('<d')[0]60 def pop_str16(self):61 l_name = []62 while 1:63 c = self.pop_uint16()64 if c == 0:65 break66 l_name.append(chr(c))67 return ''.join(l_name)68 def pop_str8(self):69 l_name = []70 while 1:71 c = self.pop_uint8()72 if c == 0:73 break...

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:


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

Run autotest 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?