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 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)
class optimize_ga: 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 # Define on-the-fly analysis. # @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.ori_fmax) # self.logger.info(msg) # # def finalize(self, population, engine): # best_indv = population.best_indv(engine.fitness) # x = best_indv.solution # y = engine.ori_fmax # msg = 'Optimal solution: ({}, {})'.format(x, y) # self.logger.info(msg) def optimize(self): self.engine.run(ng=500) return self.population.best_indv(self.engine.fitness).solution
class ConsoleOutput(OnTheFlyAnalysis): master_only = True interval = 20 def register_step(self, generacija, population, gen_algo): best_indv = population.best_indv(gen_algo.fitness) msg = 'Generacija: {}, best fitness: {:.3f}'.format(generacija, gen_algo.fmax) gen_algo.logger.info(msg) for generacija in range(individual_template): trenutna_generacija = generacija if mpi.is_master: best_indv = population.best_indv(fitness) else: best_indv = None best_indv = mpi.bcast(best_indv) local_indvs = [] local_size = mpi.split_size(population.size // 2) for _ in range(local_size): roditelji = self.selection.select(population, fitness=fitness) djeca = crossover.cross(*roditelji) dijete= [mtation.mutation(dijete) for dijete in djeca] local_indvs.extend(djeca) indvs = mpi.merge_seq(local_indvs)