def test_cross(self): ''' Make sure individuals can be crossed correctly. ''' father = BinaryIndividual(ranges=[(0, 1)]).init(solution=[0.398]) mother = BinaryIndividual(ranges=[(0, 1)]).init(solution=[0.298]) crossover = UniformCrossover(pc=1.0, pe=0.5) child1, child2 = crossover.cross(father, mother)
def test_clone(self): ''' Make sure individual can be cloned correctly. ''' indv = BinaryIndividual(ranges=[(0, 1)], eps=0.001).init(solution=[0.398]) indv_clone = indv.clone() self.assertListEqual(indv.chromsome, indv_clone.chromsome) self.assertAlmostEqual(indv.solution[0], indv_clone.solution[0], places=2) self.assertEqual(indv.ranges, indv_clone.ranges) self.assertEqual(indv.eps, indv_clone.eps)
def tain_svm(): indv_template = BinaryIndividual(ranges=[(-8, 8), (-8, 8), (-8, 8)], eps=[0.001, 0.001, 0.001]) population = Population(indv_template=indv_template, size=1000) population.init() # Initialize population with individuals. # In[ ]: selection = RouletteWheelSelection() crossover = UniformCrossover(pc=0.8, pe=0.5) # mutation = FlipBitMutation(pm=0.1) mutation = FlipBitBigMutation(pm=0.1, pbm=0.55, alpha=0.6) engine = GAEngine(population=population, selection=selection, crossover=crossover, mutation=mutation, analysis=[ConsoleOutput, FitnessStore]) ############################################################# indv = engine.population.best_indv(engine.fitness).variants c, e, g = indv.variants[1], indv.variants[2], indv.variants[-1] clf = svm.svR(C=c, epsilon=e, gamma=g, kernel='rbf') data_x, data_y = preprocess_pca() clf.fit(data_x, data_y) predictval = clf.predict(data_x) reaval = data_y print(predictval) # In[ ]: engine.run(ng=100)
def ga(df, start, end, _positionList, ranges=[(20,100),(0.01, 1),(0.01, 1),(0.01, 1),(1, 5)], eps=0.01): indv_template = BinaryIndividual(ranges=ranges, eps=eps) population = Population(indv_template=indv_template, size=100) population.init() # Initialize population with individuals. # Use built-in operators here. selection = RouletteWheelSelection() crossover = UniformCrossover(pc=0.8, pe=0.5) mutation = FlipBitMutation(pm=0.3) engine = GAEngine(population=population, selection=selection, crossover=crossover, mutation=mutation, analysis=[FitnessStore]) @engine.fitness_register def fitness(indv): n, upper, lower, adds, cutoff = indv.solution df['KAMA'] = talib.KAMA(df.close, int(n)) df['VAR'] = talib.VAR(df.close-df.KAMA.shift(1) - df.close.shift(1)+df.KAMA.shift(2),10) profitsList, buypriceList, sellpriceList, fits,positionList = profitsCal(df, start, end, _positionList, upper=upper, lower=lower, adds = adds, cutoff=cutoff) return float(fits) @engine.analysis_register class ConsoleOutput(OnTheFlyAnalysis): master_only = True interval = 1 def register_step(self, g, population, engine): best_indv = population.best_indv(engine.fitness) msg = 'Generation: {}, best fitness: {:.3f}'.format(g, engine.fmax) print(best_indv.solution) engine.logger.info(msg) engine.run(ng=30) return population.best_indv(engine.fitness).solution, _positionList
def setUp(self): self.maxDiff = True self.indv_template = BinaryIndividual(ranges=[(0, 1)]) def fitness(indv): x, = indv.solution return x**3 - 60*x**2 + 900*x + 100 self.fitness = fitness
def test_run(self): ''' Make sure GA engine can run correctly. ''' indv_template = BinaryIndividual(ranges=[(0, 10)], eps=0.001) population = Population(indv_template=indv_template, size=50).init() # Create genetic operators. selection = RouletteWheelSelection() crossover = UniformCrossover(pc=0.8, pe=0.5) mutation = FlipBitMutation(pm=0.1) # Create genetic algorithm engine. engine = GAEngine(population=population, selection=selection, crossover=crossover, mutation=mutation) @engine.fitness_register @engine.dynamic_linear_scaling() def fitness(indv): x, = indv.solution return x + 10 * sin(5 * x) + 7 * cos(4 * x) engine.run(50)
def test_selection(self): indv = BinaryIndividual(ranges=[(0, 30)]) p = Population(indv) p.init() selection = TournamentSelection() father, mother = selection.select(p, fitness=self.fitness) self.assertTrue(isinstance(father, BinaryIndividual)) self.assertTrue(isinstance(mother, BinaryIndividual))
def test_mutate_binary_indv(self): ''' Make sure the individual can be mutated correctly. ''' indv = BinaryIndividual(ranges=[(0, 1)]).init(solution=[0.398]) mutation = FlipBitMutation(pm=1.0) chromsome_before = [0, 1, 1, 0, 0, 1, 0, 1, 1] chromsome_after = [1, 0, 0, 1, 1, 0, 1, 0, 0] self.assertListEqual(indv.chromsome, chromsome_before) mutation.mutate(indv, engine=None) self.assertListEqual(indv.chromsome, chromsome_after)
def doga(units, ploads, hload, size=50, ng=5, pc=0.8, pe=0.5, pm=0.1): # 计算不同典型日下,最小运行成本均值 def calcost(indv): # 输入改造方案 for chpunit, rtype in zip(chpunits, indv): chpunit.rtype = rtype meancost = 0 # ploads为字典,key:典型日出现的概率,value:[典型日负荷曲线,风电出力极限曲线1,...,风电出力极限曲线n] for p in ploads.keys(): x = ProSimu() x.pload = ploads[p][0] x.hload = hload wn = 0 for wpunit in wpunits: wn += 1 wpunit.maxwp = ploads[p][wn] x.units = units meancost += x.getoptvalue()*p return meancost ranges = list() wpunits = list() chpunits = list() for unit in units: if unit.ptype == 0: # Wind Power Unit wpunits += [unit] elif unit.ptype == 2: # CHP Unit-1 ranges += [(0, 4)] chpunits += [unit] elif unit.ptype == 3: # CHP Unit-2 ranges += [(0, 3)] chpunits += [unit] template = BinaryIndividual(ranges, eps=1) population = Population(indv_template=template, size=size).init() selection = TournamentSelection() crossover = UniformCrossover(pc=pc, pe=pe) mutation = FlipBitMutation(pm=pm) engine = GAEngine(population=population, selection=selection, crossover=crossover, mutation=mutation, analysis=[ConsoleOutput, FitnessStore]) @engine.fitness_register @engine.minimize def fitness(indv): # print(type(float(calcost(indv.solution)))) return float(calcost(indv.solution)) engine.run(ng=ng) bestindv = population.best_indv(engine.fitness).solution for unitt, rtype in zip(chpunits, bestindv): unitt.rtype = rtype result = calcost(bestindv) print('Best individual:', bestindv) print('Optimal result:', result)
def test_selection(self): indv = BinaryIndividual(ranges=[(0, 30)]) p = Population(indv) p.init() selection = RouletteWheelSelection() father, mother = selection.select(p, fitness=self.fitness) self.assertTrue(isinstance(father, BinaryIndividual)) self.assertTrue(isinstance(mother, BinaryIndividual)) self.assertNotEqual(father.chromsome, mother.chromsome)
def __init__(self, objfunc, var_bounds, individual_size, max_iter, max_or_min, **kwargs): super().__init__(objfunc) self.max_iter = max_iter # 定义个体 / 种群 self.individual = BinaryIndividual(ranges=var_bounds, eps=0.001) self.population = Population(indv_template=self.individual, size=individual_size).init() # Create genetic operators. # selection = RouletteWheelSelection() selection = TournamentSelection() crossover = UniformCrossover(pc=0.8, pe=0.5) mutation = FlipBitBigMutation(pm=0.1, pbm=0.55, alpha=0.6) self.engine = GAEngine(population=self.population, selection=selection, crossover=crossover, mutation=mutation, analysis=[FitnessStore]) @self.engine.fitness_register def fitness(indv): """ 适应度函数: 注意这里默认为优化得到最小值 :param indv: :return: """ x = indv.solution if max_or_min == 'max': return objfunc(x, **kwargs) else: return -objfunc(x, **kwargs) @self.engine.analysis_register class ConsoleOutputAnalysis(OnTheFlyAnalysis): interval = 1 master_only = True def register_step(self, g, population, engine): best_indv = population.best_indv(engine.fitness) msg = 'Generation: {}, best fitness: {:.3f}'.format( g, engine.fitness(best_indv)) # self.logger.info(msg) def finalize(self, population, engine): best_indv = population.best_indv(engine.fitness) x = best_indv.solution y = engine.fitness(best_indv) msg = 'Optimal solution: ({}, {})'.format(x, y)
def test_binary_encoding(self): ''' Make sure individual can decode and encode binary gene correctly. ''' indv = BinaryIndividual(ranges=[(0, 1)], eps=0.001) indv.init(solution=[0.398]) # Test binary chromsome. ref_chromsome = [0, 1, 1, 0, 0, 1, 0, 1, 1] self.assertListEqual(indv.chromsome, ref_chromsome) # Test decode. self.assertListEqual(indv.decode(), [0.396484375]) indv = BinaryIndividual(ranges=[(0, 1), (-1, 1)], eps=0.001) indv.init(solution=[0.398, 0.66]) # Test binary chromsome. ref_chromsome = [ 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1 ] self.assertListEqual(indv.chromsome, ref_chromsome) # Test decode. self.assertListEqual(indv.decode(), [0.396484375, 0.658203125])
def __init__(self ,k ,total_implied_variance ,slice_before ,slice_after ,tau): self.k =k self.total_implied_variance =total_implied_variance self.slice_before =slice_before self.slice_after = slice_after self.tau = tau # Define population. indv_template = BinaryIndividual(ranges=[(1e-5, 20),(1e-5, 20),(1e-5, 20)], eps=0.001) self.population = Population(indv_template=indv_template, size=30).init() # Create genetic operators. selection = TournamentSelection() crossover = UniformCrossover(pc=0.8, pe=0.5) mutation = FlipBitMutation(pm=0.1) # Create genetic algorithm engine. self.engine = GAEngine(population=self.population, selection=selection, crossover=crossover, mutation=mutation, analysis=[FitnessStore]) # Define fitness function. @self.engine.fitness_register @self.engine.minimize def fitness(indv): a, b, m, rho, sigma = indv.solution model_total_implied_variance=svi_raw(self.k,np.array([a, b, m, rho, sigma]),self.tau) value = norm(self.total_implied_variance - model_total_implied_variance,ord=2) # if bool(len(self.slice_before)) and np.array(model_total_implied_variance < self.slice_before).any(): # value +=(np.count_nonzero(~np.array(model_total_implied_variance < self.slice_before))*100) # # value = 1e6 # # if bool(len(self.slice_after)) and np.array(model_total_implied_variance > self.slice_after).any(): # value += float(np.count_nonzero(~np.array(model_total_implied_variance > self.slice_after)) * 100) # # value = 1e6 # if np.isnan(value): # value = 1e6 value = float(value) return value
def test_init(self): ''' Make sure the individual can be initialized correctly. ''' indv = BinaryIndividual(ranges=[(0, 1)], eps=0.001) # Check chromsome initialization. indv.init(chromsome=[0, 1, 1, 0, 0, 0, 1, 1, 1, 0]) self.assertListEqual([0, 1, 1, 0, 0, 0, 1, 1, 1, 0], indv.chromsome) self.assertListEqual(indv.solution, [0.388671875]) # Check solution initialization. indv.init(solution=[0.398]) self.assertListEqual(indv.solution, [0.398]) self.assertListEqual(indv.chromsome, [0, 1, 1, 0, 0, 1, 0, 1, 1])
def test_mutate(self): ''' Make sure the individual can be mutated correctly. ''' indv_template = BinaryIndividual(ranges=[(0, 10)], eps=0.001) population = Population(indv_template=indv_template, size=50).init() # Create genetic operators. selection = RouletteWheelSelection() crossover = UniformCrossover(pc=0.8, pe=0.5) mutation = FlipBitBigMutation(pm=0.03, pbm=0.2, alpha=0.6) # Create genetic algorithm engine. engine = GAEngine(population=population, selection=selection, crossover=crossover, mutation=mutation) @engine.fitness_register def fitness(indv): x, = indv.solution return x + 10 * sin(5 * x) + 7 * cos(4 * x) mutation.mutate(indv_template, engine)
(math.pow(x, 2) + math.pow(y, 2))))) b = -math.exp(0.5 * (math.cos(2 * math.pi * x) + math.cos(2 * math.pi * y))) c = math.exp(1) d = 20 result = a + b + c + d global best if best < abs(result): best = abs(result) print('The best outcome reward till now is {}'.format(best)) count += 1 return result search_domain = (-5, 5) indv_template = BinaryIndividual(ranges=[search_domain, search_domain], eps=0.001) # Define population population = Population(indv_template=indv_template, size=50).init() # Create genetic operators. #selection = RouletteWheelSelection() selection = TournamentSelection() crossover = UniformCrossover(pc=0.8, pe=0.5) mutation = FlipBitBigMutation(pm=0.1, pbm=0.55, alpha=0.6) # Create genetic algorithm engine. # Here we pass all built-in analysis to engine constructor. engine = GAEngine(population=population, selection=selection, crossover=crossover, mutation=mutation,
import os import sys from gaft import GAEngine from gaft.components import BinaryIndividual, Population from gaft.operators import RouletteWheelSelection, UniformCrossover, FlipBitMutation from gaft.plugin_interfaces.analysis import OnTheFlyAnalysis from gaft.analysis import FitnessStore from multiprocessing import Value sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')) from track_eval.test_net import * tracker_num = Value('i', 0) if __name__ == '__main__': arg_set.logger_handler.removeHandler(arg_set.logfile_handler) indv_template = BinaryIndividual(ranges=[(1.0000001, 1.25), (0.9, 1.0), (0.15, 0.7), (0.05, 0.7)], eps=0.0001) population = Population(indv_template=indv_template, size=50) population.init() selection = RouletteWheelSelection() crossover = UniformCrossover(pc=0.8, pe=0.5) mutation = FlipBitMutation(pm=0.1) engine = GAEngine(population=population, selection=selection, crossover=crossover, mutation=mutation, analysis=[FitnessStore]) # @engine.analysis_register # class ConsoleOutput(OnTheFlyAnalysis): # master_only = True
from gaft.operators import TournamentSelection from gaft.operators import UniformCrossover from gaft.operators import FlipBitBigMutation # Built-in best fitness analysis. from gaft.analysis.fitness_store import FitnessStore from gaft.analysis.console_output import ConsoleOutput # Analysis plugin base class. from gaft.plugin_interfaces.analysis import OnTheFlyAnalysis data = scipy.io.loadmat('./burgers_shock.mat') max_train_iter = 2 # Define population. indv_template = BinaryIndividual(ranges=[(2, 50), (2, 20)], eps=0.001) population = Population(indv_template=indv_template, size=18).init() # Create genetic operators. #selection = RouletteWheelSelection() selection = TournamentSelection() crossover = UniformCrossover(pc=0.8, pe=0.5) mutation = FlipBitBigMutation(pm=0.1, pbm=0.55, alpha=0.6) # Create genetic algorithm engine. # Here we pass all built-in analysis to engine constructor. engine = GAEngine(population=population, selection=selection, crossover=crossover, mutation=mutation, analysis=[FitnessStore])
from gaft import GAEngine from gaft.components import BinaryIndividual from gaft.components import Population from gaft.operators import TournamentSelection from gaft.operators import UniformCrossover from gaft.operators import FlipBitBigMutation # Built-in best fitness analysis. from gaft.analysis.fitness_store import FitnessStore from gaft.analysis.console_output import ConsoleOutput # Analysis plugin base class. from gaft.plugin_interfaces.analysis import OnTheFlyAnalysis # Define population. indv_template = BinaryIndividual(ranges=[(1, 200), (2, 3)], eps=0.001) population = Population(indv_template=indv_template, size=18).init() # Create genetic operators. # selection = RouletteWheelSelection() selection = TournamentSelection() crossover = UniformCrossover(pc=0.8, pe=0.5) mutation = FlipBitBigMutation(pm=0.1, pbm=0.55, alpha=0.6) # Create genetic algorithm engine. # Here we pass all built-in analysis to engine constructor. engine = GAEngine(population=population, selection=selection, crossover=crossover, mutation=mutation,
from gaft import GAEngine from gaft.components import BinaryIndividual from gaft.components import Population from gaft.operators import TournamentSelection from gaft.operators import UniformCrossover from gaft.operators import FlipBitMutation from gaft.plugin_interfaces.analysis import OnTheFlyAnalysis matplotlib.use('tkagg') # lab: 7 variant start, end, eps = 0, 10, 0.001 indv_template = BinaryIndividual(ranges=[(start, end)], eps=eps) population = Population(indv_template=indv_template, size=10).init() selection = TournamentSelection() crossover = UniformCrossover(pc=1.0, pe=0.5) mutation = FlipBitMutation(pm=0.1) engine = GAEngine(population=population, selection=selection, crossover=crossover, mutation=mutation, analysis=[]) def npfunc(): t = np.arange(start, end, eps)
n_nines = [] for s in scores: precisao = str(s).split('.')[1] noves = re.search(r'(^9*)', precisao) n_nines.append(len(noves[0])) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(geracoes, n_nines) plt.show() if __name__ == "__main__": individuo = BinaryIndividual(ranges=[(-100, 100), (-100, 100)], eps=0.000001) populacao = Population(indv_template=individuo, size=100) populacao.init() selecao = TournamentSelection() crossover = UniformCrossover(pc=0.65, pe=0.65) mutacao = FlipBitMutation(pm=0.008) engine = GAEngine(population=populacao, selection=selecao, crossover=crossover, mutation=mutacao, analysis=[FitnessStore, ConsoleOutput]) @engine.fitness_register def aptidao(ind):
def test_multi_precisions(self): ''' Make sure we can construct individual using different decrete precisions. ''' indv = BinaryIndividual(ranges=[(0, 1), (0, 10)], eps=[0.01, 1.0]).init(solution=[0.3, 0.5]) self.assertNotEqual(indv.precisions[0], indv.precisions[1])
def func2(t, a=1.3, b=1.9, c=1.1, d=-1.5): return (a * t + b) * math.cos(c * math.pi * t + d) ''' @engine.fitness_register @engine.minimize def fitness(indv): x, = indv.solution return x + 10*sin(5*x) + 7*cos(4*x) ''' if __name__ == '__main__': # Create individual (use binary encoding) indv = BinaryIndividual(ranges=[(0, 10)], eps=0.001) # Create a population with 50 individuals population = Population(indv_template=indv, size=50).init() # Create genetic operators: selection, crossover, mutation # 1. Tournament selection selection = TournamentSelection() # 2. Uniform crossover # pc is the probabililty of crossover operation # pe is the exchange probabiltiy for each possible gene bit in chromsome crossover = UniformCrossover(pc=0.8, pe=0.5) # 3. Flip bit mutation # pm is the probability of mutation mutation = FlipBitMutation(pm=0.1) # Create an engine to run engine1 = GAEngine(population=population, selection=selection,
PBM = PM * 5 # alpha: intensive factor (0.5, 1) ALPHA = 0.6 # Run # ng: Evolution iteration steps (generations number) NG = 150 # Built-in best fitness analysis. from gaft.analysis.fitness_store import FitnessStore from gaft.analysis.console_output import ConsoleOutput # Define population. indv_template = BinaryIndividual(ranges=[XB, YB], eps=EPS) population = Population(indv_template=indv_template, size=POPULATION_SIZE).init() # Create genetic operators. selection = SELECTION crossover = UniformCrossover(pc=PC, pe=PE) mutation = FlipBitBigMutation(pm=PM, pbm=PBM, alpha=ALPHA) # Create genetic algorithm engine. # Here we pass all built-in analysis to engine constructor. engine = GAEngine(population=population, selection=selection, crossover=crossover, mutation=mutation, analysis=[ConsoleOutput, FitnessStore])
from gaft.components import Population from gaft.operators import * from gaft.analysis.fitness_store import FitnessStore from gaft.analysis.console_output import ConsoleOutput from gaft.plugin_interfaces.analysis import OnTheFlyAnalysis import os from math import sin, cos, pi, exp import numpy as np # Define Generation generation = 50 # Define Population and the Constraints population_size = 10 indv_template = BinaryIndividual(ranges=[(-3, 12.1), (4.1, 5.8)], eps=0.001) population = Population(indv_template=indv_template, size=population_size).init() # Define Genetic Operators ## Selection : RouletteWheelSelection, TournamentSelection, LinearRankingSelection, ExpotentialRankingSelection #selection = RouletteWheelSelection() selection = TournamentSelection() ## Crossover ### pc : probability of crossover(usually between 0.25 - 1.0) ### pe : gene exchange probability crossover = UniformCrossover(pc=0.8, pe=0.5) ## Mutate ### pm : The probability of mutation (usually between 0.001 ~ 0.1)
from gaft import GAEngine from gaft.components import BinaryIndividual from gaft.components import DecimalIndividual from gaft.components import Population from gaft.operators import RouletteWheelSelection from gaft.operators import TournamentSelection from gaft.operators import UniformCrossover from gaft.operators import FlipBitBigMutation from gaft.operators import FlipBitMutation # Built-in best fitness analysis. from gaft.analysis.fitness_store import FitnessStore from gaft.analysis.console_output import ConsoleOutput import time # Define population. indv_template = BinaryIndividual(ranges=[(1,1000),(0,1)], eps=0.01) #indv_template = DecimalIndividual(ranges=[(1, 1000),(0.0,0.5)], eps=0.001) population = Population(indv_template=indv_template, size=80).init() # Create genetic operators. selection = RouletteWheelSelection() #selection = TournamentSelection() crossover = UniformCrossover(pc=0.8, pe=0.5) mutation = FlipBitBigMutation(pm=0.1, pbm=0.55, alpha=0.6) #mutation = FlipBitMutation(pm=0.1) # Create genetic algorithm engine. # Here we pass all built-in analysis to engine constructor. engine = GAEngine(population=population, selection=selection, crossover=crossover, mutation=mutation, analysis=[ConsoleOutput, FitnessStore])
from math import sin, cos, pi from gaft import GAEngine from gaft.components import BinaryIndividual from gaft.components import Population from gaft.operators import TournamentSelection from gaft.operators import UniformCrossover from gaft.operators import FlipBitBigMutation # Built-in best fitness analysis. from gaft.analysis.fitness_store import FitnessStore from gaft.analysis.console_output import ConsoleOutput # Define population. indv_template = BinaryIndividual(ranges=[(-2, 2), (-2, 2)], eps=0.001) population = Population(indv_template=indv_template, size=50).init() # Create genetic operators. #selection = RouletteWheelSelection() selection = TournamentSelection() crossover = UniformCrossover(pc=0.8, pe=0.5) mutation = FlipBitBigMutation(pm=0.1, pbm=0.55, alpha=0.6) # Create genetic algorithm engine. # Here we pass all built-in analysis to engine constructor. engine = GAEngine(population=population, selection=selection, crossover=crossover, mutation=mutation, analysis=[ConsoleOutput, FitnessStore])
from gaft import GAEngine from gaft.components import BinaryIndividual from gaft.components import Population from gaft.operators import TournamentSelection from gaft.operators import UniformCrossover from gaft.operators import FlipBitBigMutation from gaft.plugin_interfaces.analysis import OnTheFlyAnalysis matplotlib.use('tkagg') x1_range = (-2, 2) x2_range = (-2, 2) eps = 0.001 indv_template = BinaryIndividual(ranges=[x1_range, x2_range], eps=eps) population = Population(indv_template=indv_template, size=10).init() selection = TournamentSelection() crossover = UniformCrossover(pc=1, pe=0.5) mutation = FlipBitBigMutation(pm=0.1, pbm=0.55, alpha=0.6) engine = GAEngine(population=population, selection=selection, crossover=crossover, mutation=mutation, analysis=[]) ax = plt.axes(projection='3d')
from gaft import GAEngine from gaft.components import BinaryIndividual from gaft.components import Population from gaft.operators import TournamentSelection from gaft.operators import UniformCrossover from gaft.operators import FlipBitMutation # Analysis plugin base class. from gaft.plugin_interfaces.analysis import OnTheFlyAnalysis # Built-in best fitness analysis. from gaft.analysis.fitness_store import FitnessStore # Define population. # 先对你所指定的初始种群进行编码 indv_template = BinaryIndividual(ranges=[(0, 10)], eps=0.001) ''' :param ranges: value ranges for all entries in solution. :type ranges: list of range tuples. e.g. [(0, 1), (-1, 1)] :param eps: decrete precisions for binary encoding, default is 0.001. :type eps: float or float list with the same length with ranges. ''' population = Population(indv_template=indv_template, size=30).init() # Create genetic operators. selection = TournamentSelection() crossover = UniformCrossover(pc=0.8, pe=0.5) ''' Crossover operator with uniform crossover algorithm, see https://en.wikipedia.org/wiki/Crossover_(genetic_algorithm)
pv = find(bus[:, 9] == 2) myfun_lower_bound = 0 myfun_upper_bound = 1 bounds = np.zeros([len(pv), 2]) bounds[:, 0] = myfun_lower_bound bounds[:, 1] = myfun_upper_bound bounds = bounds.tolist() generations = 15 population_size = 20 # --------------------------------------------------------------------------------------------------- # Define population. indv_template = BinaryIndividual(ranges=bounds, eps=0.001) population = Population(indv_template=indv_template, size=population_size).init() # Create genetic operators. #selection = RouletteWheelSelection() selection = TournamentSelection() crossover = UniformCrossover(pc=0.8, pe=0.5) mutation = FlipBitBigMutation(pm=0.1, pbm=0.55, alpha=0.6) # Create genetic algorithm engine. # Here we pass all built-in analysis to engine constructor. engine = GAEngine(population=population, selection=selection, crossover=crossover, mutation=mutation) # ===================================================================================================