def run_ga(target, control, water_stress, year): print("Running Genetic Algorithm...") elegidos_control = ga.ga(target, control) print( f"Selected control: {len(elegidos_control)} wavelength(s)\n{elegidos_control}" ) rangos_control = ranges.rangos_clustering(target, elegidos_control, "control", year, "ga") print(f"Selected wavelength ranges (control set): {rangos_control}") print("") elegidos_water_stress = ga.ga(target, water_stress) print( f"Selected water stress: {len(elegidos_water_stress)} wavelength(s)\n{elegidos_water_stress}" ) rangos_water_stress = ranges.rangos_clustering(target, elegidos_water_stress, "ws", year, "ga") print( f"Selected wavelength ranges (water stress set): {rangos_water_stress}" ) control_long = data_preprocessing.wide_to_long(control.iloc[:, 1:]) graphics.ranges_graphics(target, control_long, rangos_control, "control", year, "ga") water_stress_long = data_preprocessing.wide_to_long(water_stress.iloc[:, 1:]) graphics.ranges_graphics(target, water_stress_long, rangos_water_stress, "ws", year, "ga") return
def main(): try: args = parseArguments() except: args = {"-h": True} if "-l" not in args: args["-l"] = False else: args["-l"] = True # handle argument if "-h" in args: printHelp() return if "-a" not in args: greedy(args) return if args["-a"] == "aco": aco(args) elif args["-a"] == "ga": ga(args) elif args["-a"] == "greedy": greedy(args) elif args["-a"] == "mst": mst(args) else: printHelp()
def update(name, dat, crash=None): payload = {} payload['an'] = __scriptname__ payload['av'] = __version__ payload['ec'] = name payload['ea'] = 'zelka' payload['ev'] = '1' payload['dl'] = urllib.quote_plus(dat.encode('utf-8')) ga().update(payload, crash)
def update(name, dat, crash=None): payload = {} payload['an'] = __scriptname__ payload['av'] = __version__ payload['ec'] = name payload['ea'] = dat payload['ev'] = '1' payload['dl'] = None ga().update(payload, crash)
def update(name, dat, crash=None): payload = {} payload["an"] = __scriptname__ payload["av"] = __version__ payload["ec"] = name payload["ea"] = "zelka" payload["ev"] = "1" payload["dl"] = urllib.quote_plus(dat.encode("utf-8")) ga().update(payload, crash)
def update(name, dat, crash=None): payload = {} payload['an'] = __scriptname__ payload['av'] = __version__ payload['ec'] = name payload['ea'] = 'tv_service' payload['ev'] = '1' payload['dl'] = urllib.quote_plus(dat.encode('utf-8')) ga('UA-79422131-11').update(payload, crash)
def update(name, dat, crash=None): payload = {} payload['an'] = __scriptname__ payload['av'] = __version__ payload['ec'] = name payload['ea'] = 'sony_ctrl' payload['ev'] = '1' payload['dl'] = urllib.parse.quote_plus(dat) ga().update(payload, crash)
def update(name, dat, crash=None): payload = {} payload['an'] = __scriptname__ payload['av'] = __version__ payload['ec'] = name payload['ea'] = 'zamunda' payload['ev'] = '1' payload['dl'] = urllib.quote_plus(dat.encode('utf-8')) ga().update(payload, crash)
def update(name, location, crash=None): p = {} p['an'] = addon.getAddonInfo('name') p['av'] = addon.getAddonInfo('version') p['ec'] = 'Addon actions' p['ea'] = name p['ev'] = '1' p['ul'] = xbmc.getLanguage() p['cd'] = location ga('UA-79422131-7').update(p, crash)
def update(self, name, location, crash=None): p = {} p['an'] = self.addon_name p['av'] = self.version p['ec'] = 'Addon actions' p['ea'] = name p['ev'] = '1' p['ul'] = xbmc.getLanguage() p['cd'] = location ga('UA-79422131-3').update(p, crash)
def update(name, act_ev, dat, crash=None): payload = {} payload['ec'] = name payload['ea'] = act_ev payload['ev'] = '1' payload['dl'] = urllib.quote_plus(dat.encode('utf-8')) if run_from_xbmc == True: payload['an'] = xbmcaddon.Addon().getAddonInfo('name') payload['av'] = xbmcaddon.Addon().getAddonInfo('version') ga().update(payload, crash) else: print payload
def runOpt(): # X2 = GAP X3 = OVERLAP # lb = [0.1, 0.05, 0.005,-0.03,0.5, 1.05,0.2] lb = [0.03, 0.1, 0.03, 0.1, 0.005, -0.03] ub = [0.20, 0.4, 0.20, 0.8, 0.030, 0.03] GA=ga.ga(fg.flap_geometry2,lb,ub,nCPU=1,displayFlag=1) GA.maxIter=5 GA=ga.ga(costFcn,lb,ub,0,8) GA.Nelite=4 GA.maxIter=1000 GA.maxLagIter=50 GA.populationSize=30 GA.solve()
def __update__(action, location, crash=None): try: from ga import ga p = {} p['an'] = this.getAddonInfo('name').decode('utf-8') p['av'] = this.getAddonInfo('version') p['ec'] = 'Addon actions' p['ea'] = action p['ev'] = '1' p['ul'] = xbmc.getLanguage() p['cd'] = location ga('UA-79422131-10').update(p, crash) except Exception, er: log(er)
def run_experiments(): for objective in objective_types: for num_decision in num_decisions: for num_objective in num_objectives: problem = objective(num_decision, num_objective) problem.find_min_max() for type in types: print objective.__name__ + ".%d.%d" % ( num_decision, num_objective) + "." + type.__name__, "= [", for repeat_ct in range(num_repeats): random.seed(1131 + repeat_ct * 2 - 1) print ga.ga(problem=problem, better=type), ",", print "]"
def update(action, location, crash=None): lu = settings.last_update day = time.strftime("%d") if lu == "" or lu != day: settings.last_update p = {} p['an'] = get_addon_name() p['av'] = get_addon_version() p['ec'] = 'Addon actions' p['ea'] = action p['ev'] = '1' p['ul'] = get_kodi_language() p['cd'] = location ga('UA-79422131-8').update(p, crash)
def update(name, location, crash=None): lu = settings.last_update d = time.strftime("%d") if lu != d: settings.last_update = d p = {} p['an'] = get_addon_name() p['av'] = get_addon_version() p['ec'] = 'Addon actions' p['ea'] = name p['ev'] = '1' p['ul'] = xbmc.getLanguage() p['cd'] = location import ga ga.ga('UA-79422131-12').update(p, crash)
def main(): # Load user parameters from file config = ConfigParser() config.read('params.ini') # Choose function function_name = config['PARAMS']['function_name'] if function_name == 'ackley': fun = fun1 elif function_name == 'griewank': fun = fun2 elif function_name == 'michalewicz': fun = fun3 else: raise Exception('Function not supported!') # Do the algorithm now = datetime.now() x = ga(fun=fun, num_of_population=int(config['PARAMS']['num_of_population']), dimension=int(config['PARAMS']['dimension']), num_of_iterations=int(config['PARAMS']['num_of_iterations']), lower_bound=float(config['PARAMS']['lower_bound']), upper_bound=float(config['PARAMS']['upper_bound']), param_crossing=float(config['PARAMS']['param_crossing']), param_mutation=float(config['PARAMS']['param_mutation']), num_elitism=int(config['PARAMS']['elitism'])) # Results print ('\n\nFunction results: \n') print ('x = {0}\nf(x) = {1}\n'.format(x, fun(x))) print ('Time: {0}'.format(datetime.now() - now))
def train(self): print('GA run for tuning hyperparameters of OBJ. function...') self.Theta, self.MinNegLnLik = ga(self.likelihood, self.nvars, self.LowerTheta, self.UpperTheta) print('GA run complete.') self.U, self.mu, self.SigmaSqr = self.likelihood(self.Theta)[1:]
def run_first_mlp_ga(): ''' GA with a fitness function for determining the optimum number of hidden neurons and what inputs should be activated or deactivated. Mutation rate determined by dividing 1 by the fitness function string length. ''' pl.ion() pl.show() x = ga.ga(84, 'fF.fitness_mlp1', 100, 50, 0.01, 4, True) x.runGA()
def objectives(self): model = dtlz(10, 2, 1) print "Calling GA with decs", self.decs calculated_objs = ga(model, self.base_min, self.base_max, self.basepop, self.decs[2], self.decs[3], self.decs[0], self.decs[1]) #args = (candidates, generation, mutation, crossover) #print "new objs", calculated_objs return calculated_objs
def objectives(self): model = dtlz(10, 2, 1) print "Calling GA with decs", self.decs calculated_objs = ga( model, self.base_min, self.base_max, self.basepop, self.decs[2], self.decs[3], self.decs[0], self.decs[1] ) #args = (candidates, generation, mutation, crossover) #print "new objs", calculated_objs return calculated_objs
def __update__(action, location, crash=None): try: lu = settings.last_update day = time.strftime("%d") if lu != day: settings.last_update = day from ga import ga p = {} p['an'] = this.getAddonInfo('name').decode('utf-8') p['av'] = this.getAddonInfo('version') p['ec'] = 'Addon actions' p['ea'] = action p['ev'] = '1' p['ul'] = xbmc.getLanguage() p['cd'] = location ga('UA-79422131-10').update(p, crash) except Exception, er: log(er)
def run_second_mlp_ga(): ''' GA with a fitness function for determining the optimum learning rate and number of iterations. Mutation rate determined by dividing 1 by the fitness function string length. ''' pl.ion() pl.show() x = ga.ga(25, 'fF.fitness_mlp2', 50, 50, 0.05, 4, True) x.runGA()
def __update__(action, location, crash=None): try: import time lu = settings.last_update day = time.strftime("%d") if lu != day: settings.last_update = day from ga import ga p = {} p['an'] = get_addon_name() p['av'] = get_addon_version() p['ec'] = 'Addon actions' p['ea'] = action p['ev'] = '1' p['ul'] = get_system_language() p['cd'] = location ga('UA-79422131-10').update(p, crash) except Exception, er: log(er)
def get_objectives(self, solution): self.init_hve_cache, hvol = ga(self.problem, pop_size=solution[3], gens=solution[4], select_type=solution[2], mutation_rate=solution[0], crossover_type=solution[1], init_hve=self.init_hve_cache) self.update_min_max(hvol) return hvol
def stage_11(): lb = array([0.05,0.001,0.001,0.001,-0.4 ,-0.4 ,-0.4]) ub = array([0.3 ,0.4 ,0.4 ,0.4 , 0.1, 0.1, 0.1]) design = Design() costFcn = design.objective GA = ga.ga(costFcn,lb,ub) GA.setCPU(1) GA.displayFlag = 1 GA.solve() print 'f=%.4f x1=%.4f x2=%.4f, Neval=%d' %(GA.fOpt,GA.xOpt[0],GA.xOpt[1],GA.funcCount)
def yplacement(drawing_object_dict, connection_list, inst_col_dict): """ Place the instanciations of the current module in the y-axis. At the minute, this is pure combinatorial. Will take ages for big ccts. """ global drawing_object_dict_ref global inst_col_dict_ref global connection_list_ref global drawing_object_name_list global possible_crossovers # Determine the number of objects to place so that we can set up the GA num_drawing_objects = len(drawing_object_dict) # Set up references to the drawing object dictionary drawing_object_dict_ref = drawing_object_dict inst_col_dict_ref = inst_col_dict connection_list_ref = connection_list # A sorted list of block names is needed so that we can assign genes # by position to y-axis settings of the blocks. drawing_object_name_list = drawing_object_dict.keys() drawing_object_name_list.sort() # Determine which nets can possible cross each other connection_point_coord_list = find_pin_coords(connection_list, drawing_object_dict, inst_col_dict) possible_crossovers = find_possible_crossovers( connection_list, connection_point_coord_list) # Configure the Genetic Algorithm placement_ga = ga.ga( fitness_function=layout_fitness_function, num_genes=num_drawing_objects, num_generations=20, population_size=120, num_crossovers=2, num_elite=20, num_parents=28, mutation_rate=0.01, max_range=16, mutation_max_deviation=2, go_low=True, ) # Run the GA, then choose the fittest member of the DGA population as # the final layout values print "-" * 80 best_layout = placement_ga.evolve() # return
def yplacement( drawing_object_dict, connection_list, inst_col_dict ): """ Place the instanciations of the current module in the y-axis. At the minute, this is pure combinatorial. Will take ages for big ccts. """ global drawing_object_dict_ref global inst_col_dict_ref global connection_list_ref global drawing_object_name_list global possible_crossovers # Determine the number of objects to place so that we can set up the GA num_drawing_objects = len( drawing_object_dict ) # Set up references to the drawing object dictionary drawing_object_dict_ref = drawing_object_dict inst_col_dict_ref = inst_col_dict connection_list_ref = connection_list # A sorted list of block names is needed so that we can assign genes # by position to y-axis settings of the blocks. drawing_object_name_list = drawing_object_dict.keys() drawing_object_name_list.sort() # Determine which nets can possible cross each other connection_point_coord_list = find_pin_coords(connection_list, drawing_object_dict, inst_col_dict) possible_crossovers = find_possible_crossovers(connection_list, connection_point_coord_list) # Configure the Genetic Algorithm placement_ga = ga.ga( fitness_function = layout_fitness_function, num_genes = num_drawing_objects, num_generations = 20, population_size = 120, num_crossovers = 2, num_elite = 20, num_parents = 28, mutation_rate = 0.01, max_range = 16, mutation_max_deviation = 2, go_low = True, ) # Run the GA, then choose the fittest member of the DGA population as # the final layout values print "-"*80 best_layout = placement_ga.evolve() # return
def Ok_command(self): self.initCitys() self.get_CityOrder() self.ga = ga(StartCity=self.CityOrder[0], gene=self.CityOrder, PCross=0.8, PMutation=0.02, LifeCount=100, GeneLength=len(self.CityOrder), MatchFun=self.matchFun()) n = 100 while n > 1: self.ga.next() distance = self.distance(self.ga.best.gene) n -= 1 self.ltt.insert(tk.INSERT, '最佳路径为:\n') for i in range(len(self.ga.best.gene) - 1): self.ltt.insert( tk.INSERT, self.citys[self.ga.best.gene[i]][0] + '-------->' + self.citys[self.ga.best.gene[i + 1]][0] + ' ' + str( geodesic( (self.citys[self.ga.best.gene[i]][2], self.citys[self.ga.best.gene[i]][1]), (self.citys[self.ga.best.gene[i + 1]][2], self.citys[self.ga.best.gene[i + 1]][1]))) + '\n') self.ltt.insert( tk.INSERT, self.citys[self.ga.best.gene[-1]][0] + '-------->' + self.citys[self.ga.best.gene[0]][0] + ' ' + str( geodesic((self.citys[self.ga.best.gene[-1]][2], self.citys[self.ga.best.gene[-1]][1]), (self.citys[self.ga.best.gene[0]][2], self.citys[self.ga.best.gene[0]][1]))) + '\n') self.ltt.insert(tk.INSERT, '路程共计为:\n' + str(self.distance(self.CityOrder))) self.line()
def __init__(self, population, function, inputs, hidden, outputs, display=True, mutation_rate=0.01, survival_rate=0.3, mutation_power=0.3, species=1, save_to_file=False, best_mode=False): self.population = population self.func = function self.fitness_sums = [] self.species = species self.best_mode = best_mode self.save_to_file = save_to_file if self.save_to_file and FileHandler.read('generation.pickle'): self.nets = FileHandler.read('generation.pickle') if (self.best_mode and FileHandler.read('best.pickle')): self.best = FileHandler.read('best.pickle') self.nets = [[self.best]] elif not self.save_to_file or not FileHandler.read( 'generation.pickle'): if best_mode: print("Could not find a file, acting ordirnally") self.nets = [[ ga(inputs, hidden, outputs, mutation_rate, mutation_power) for i in range(int(self.population / species)) ] for i in range(species)] self.best = None self.p = None self.survival_rate = survival_rate self.display = display
best_sol, best_cost, data = tb.tb( n, adj_mat, tb_size=20, # tabu solutions in tb_list max_tnm=100, # how many candidates picked in tournament selection mut_md= mut_md, # [get_sol, get delta], method of mutation, e.g. swap, 2-opt term_count=200 # terminate threshold if best_cost nor change ) elif method == 'ga': method_name = 'Genetic Algorithm' best_sol, best_cost, data = ga.ga( n, adj_mat, n_pop=200, r_cross=0.5, r_mut=0.8, selection_md='tnm', # 'rw' / 'tnm' / 'elt' max_tnm=3, term_count=200) elif method == 'sa': method_name = 'Simulated Annealing' best_sol, best_cost, data = sa.sa( n, adj_mat, tb_size=0, # tabu solutions in tb_list max_tnm=20, # how many candidates picked in tournament selection mut_md= mut_md, # [get_sol, get delta], method of mutation, e.g. swap, 2-opt term_count_1=25, # inner loop termination flag term_count_2=25, # outer loop termination flag
def step(self): for el in self.elevator: for key in el.timer: if el.timer[key] >= 0: el.timer[key] -= 1 # elevator ID counter el_id = 0 # loop through every elevator in self.elevator for el in self.elevator: el.setHeader() # loop through every key in el.timer dictionary for key in el.timer: # timer equal to 0 it means some action have to occur if el.timer[key] == 0: el.timer[key] = -1 # switch to find which is the key equal to 0 # if the key is 'moving' if key == 'moving': # then increment or decremtn the floor with regards to # the direction (up or down respectively) curr_floor = el.current_floor if el.destination_floor > el.current_floor: el.current_floor += 1 elif el.destination_floor < el.current_floor: el.current_floor -= 1 else: # if the direction is neither up nor down # then do nothing pass self.signals["setElevatorFloor"].emit( curr_floor, el.current_floor, el_id) # if there is one or more passenger in the elevator who need to get off # or if there are up or down calls at the current floor if len(el.passengersGettingOff()) > 0 or len( self.passengersGettingOn(el_id)) > 0: # then stop (that is decelerate, stop and open doors) el.moveToStop() else: # else continue moving upward or downward el.move() elif key == 'move_to_stop': # if there is one or more passenger in the elevator who needs to get off if len(el.passengersGettingOff()) > 0: el.unload() # else if there is one or more passenger who needs to get on elif len(self.passengersGettingOn(el_id)): el.load() elif key == 'stop_to_move': # azione di movimento el.move() elif key == 'loading': # p = self.floor_queue[el.current_floor].dequeue() # el.passenger.append(p) # el.timer['stop_to_move'] = H self.getOn(el_id) el.stopToMove() if self.assignment[el.current_floor] == el_id: self.assignment[el.current_floor] = -1 if self.assignment[int(el.current_floor + len(self.assignment) / 2) - 1] == el_id: self.assignment[int(el.current_floor + len(self.assignment) / 2) - 1] = -1 self.updateElevatorsDestinationFloor() elif key == 'unloading': # p = el.passenger.dequeue() # self.floor_queue[el.current_floor].enqueue(p) # el.timer['move_to_stop'] = L el.getOff() if len(self.passengersGettingOn(el_id)) > 0: el.load() self.updateElevatorsDestinationFloor() elif el.current_floor != el.destination_floor: el.stopToMove() else: raise KeyError( "Unknown elevator timer key in step function") el_id += 1 #Se abbiamo nuove chiamate: if self.new_calls: if DEBUG: print("GA will parse new calls") # Passive Time pt = SETTINGS["elevator"]["timing"]["loading"] + SETTINGS[ "elevator"]["timing"]["move_to_stop"] + SETTINGS["elevator"][ "timing"]["stop_to_move"] # Inter floor trip time it = SETTINGS["elevator"]["timing"]["moving"] # Hall call UP/DOWN hcu = [] hcd = [] call_flag = False for i in range(len(self.floor_queue)): queue = self.floor_queue[i] if i < len(self.floor_queue) - 1: hcu.append(0) if i > 0: hcd.append(0) for p in queue: call_flag = True if p.destination_floor > p.origin_floor: hcu[i] = 1 elif p.destination_floor < p.origin_floor: hcd[i - 1] = 1 else: raise Exception( "Passenger destination_floor == origin_floor") cf = [] cdf = [] for el in self.elevator: cf.append(el.current_floor) cdf.append(el.destination_floor) try: ''' print( "\n****************************************", "\nhcu=" + str(hcu), "\nhcd=" + str(hcd), "\ncf=" + str(cf), "\ncdf=" + str(cdf), "\n****************************************" ) input() ''' if call_flag: self.assignment = ga.ga(self.nf, self.nc, pt, it, list(hcu), list(hcd), cf, cdf).computeSolution() except Exception as e: print("GA error DEBUG", "hcu=" + str(list(hcu)), "hcd=" + str(list(hcd)), "cf=" + str(cf), "cdf=" + str(cdf)) raise e self.new_calls = False self.updateElevatorsDestinationFloor() for el_id in range(len(self.elevator)): el = self.elevator[el_id] if el.isIdle(): if el.destination_floor != el.current_floor: el.stopToMove() else: if len(self.passengersGettingOn(el_id)) > 0: el.load() else: for i in range(len(self.floor_queue)): queue = self.floor_queue[i] upgoings = 0 downgoings = 0 for p in queue: if p.destination_floor > p.origin_floor: upgoings += 1 else: downgoings += 1 if i == 0: up_assign = self.assignment[i] if up_assign == -1 and upgoings > 0: self.new_calls = True break elif 0 < i < len(self.floor_queue) - 1: down_assign = self.assignment[ i + int(len(self.assignment) / 2) - 1] if down_assign == -1 and downgoings > 0: self.new_calls = True break up_assign = self.assignment[i] if up_assign == -1 and upgoings > 0: self.new_calls = True break elif i == len(self.floor_queue) - 1: down_assign = self.assignment[ i + int(len(self.assignment) / 2) - 1] if down_assign == -1 and downgoings > 0: self.new_calls = True break
self.__t = m_start(self.__evt) if __name__ == '__main__': if __addon__.getSetting('firstrun') == 'true': __addon__.openSettings() __addon__.setSetting('firstrun', 'false') if __addon__.getSetting('dbg') == 'true': fname = 'dbg.png' else: fname = None payload = {} payload['an'] = __scriptname__ payload['av'] = __version__ payload['ec'] = 'led_start' payload['ea'] = 'led_start' payload['ev'] = '1' ga().update(payload, None) monitor = MyMonitor() while True: # Sleep/wait for abort for 1 seconds if monitor.waitForAbort(1): # Abort was requested while waiting. We should exit break del monitor
def next_infill(self): print('GA run for optimizing EI...') x, EI = ga(self.exp_imp, self.nvars, np.zeros((self.nvars, )), np.ones((self.nvars, ))) print('GA run complete.') return x, EI
# Code from Chapter 10 of Machine Learning: An Algorithmic Perspective (2nd Edition) # by Stephen Marsland (http://stephenmonika.net) # You are free to use, change, or redistribute the code in any way you wish for # non-commercial purposes, but please maintain the name of the original author. # This code comes with no warranty of any kind. # Stephen Marsland, 2008, 2014 # A runner for the Genetic Algorithm import ga import pylab as pl pl.ion() pl.show() plotfig = pl.figure() ga = ga.ga(30, "fF.fourpeaks", 301, 100, -1, "un", 4, True) ga.runGA(plotfig) pl.pause(0) # pl.show()
for MmutationProb in range(2): if MmutationProb == 0: mutationProb = -1.0 else: mutationProb = MmutationProb / 10.0 success = [] fail = [] for testI in range(20): ga1 = ga.ga( stringLength * (MstringLength + 1), fitnessFunction, nEpochs * (MnEpochs + 1), populationSize * (MpopulationSize + 1), mutationProb, crossover, nElite * (MnElite + 1), tournament) Fitness = ga1.runGA() dict = {} #dict["iteration"] = f = list(filter(lambda x: x > 100, Fitness)) localFail = list( filter(lambda x: x <= 100, Fitness)) success.extend(f) fail.extend(localFail) #print("\ni = ", i) #print("Fitness", Fitness)
params = [] sses_ga = [] for ite in range(nsim): ts = np.arange(-0, len(dates) - index_2020_10_13 - 0 - 1, dt) varbound = np.array([[0, 0.1], [0, 0.01], [4, 6], [1, 4]]) algorithm_param = {'max_num_iteration':niter,\ 'population_size': npop,\ 'mutation_probability':0.1,\ 'elit_ratio': 0.01,\ 'crossover_probability': 0.5,\ 'parents_portion': 0.3,\ 'crossover_type':'uniform',\ 'max_iteration_without_improv':None} model = ga(function=model_evaluation_param_est, dimension=4, variable_type='real', variable_boundaries=varbound, algorithm_parameters=algorithm_param) param_opt = model.run() param = model.output_dict['variable'] sses_ga.append(model.output_dict['function']) params.append(param) # @jit(nopython=True, parallel=True) # def main(nsim): # params = np.zeros((nsim,4),dtype=np.float64) # sses_ga=np.zeros(nsim,dtype=np.float64) # ts = np.arange(-0, len(dates)-index_2020_10_13-0-1, dt) # for ite in prange(nsim): # varbound=np.array([[0,0.1],[0,0.01],[4,6],[1,4]]) # algorithm_param = {'max_num_iteration':niter,\
# Code from Chapter 12 of Machine Learning: An Algorithmic Perspective # by Stephen Marsland (http://seat.massey.ac.nz/personal/s.r.marsland/MLBook.html) # You are free to use, change, or redistribute the code in any way you wish for # non-commercial purposes, but please maintain the name of the original author. # This code comes with no warranty of any kind. # Stephen Marsland, 2008 # A runner for the Genetic Algorithm import ga ga = ga.ga(20,'fF.knapsack',101,100,-1,'sp',4,True) ga.runGA()
import ga import numpy as np import pylab as pl popSize = 5 maxHiddenNodes= 32 # (43 plus one datapoints) stringLength = 45*maxHiddenNodes pop = np.random.rand(popSize, stringLength) pop = np.where(pop<0.5,1,1) pl.ion() pl.show() plotfig = pl.figure() ga = ga.ga(stringLength,'fF.myGA',1001,popSize,0.1,'none',0,False) ga.runGA(plotfig) pl.pause(0) pl.show()
# Code from Chapter 10 of Machine Learning: An Algorithmic Perspective (2nd Edition) # by Stephen Marsland (http://stephenmonika.net) # You are free to use, change, or redistribute the code in any way you wish for # non-commercial purposes, but please maintain the name of the original author. # This code comes with no warranty of any kind. # Stephen Marsland, 2008, 2014 # A runner for the Genetic Algorithm import pylab as pl import ga pl.ion() pl.show() plotfig = pl.figure() ga = ga.ga(30, 'fF.fourpeaks', 301, 100, -1, 'un', 4, True) ga.runGA(plotfig) pl.pause(0) # pl.show()
punishments += two_exams_at_once * STUDENT_TAKING_TWO_EXAMS_AT_ONCE punishments += exam_after_another * STUDENT_TAKING_EXAMS_ONE_AFTER_ANOTHER punishments += more_than_two_exams_at_one_day * STUDENT_TAKING_MORE_THAN_TWO_EXAMS_IN_ONE_DAY punishments += two_exams_at_one_day * STUDENT_TAKING_TWO_EXAMS_IN_ONE_DAY if inverse: return 1.0 / (1.0 + punishments), else: is_valid = two_exams_at_once == 0 return punishments, is_valid, { "two exams at once": two_exams_at_once, "exam after another": exam_after_another, "more than two exams at one day": more_than_two_exams_at_one_day, "two exams at one day": two_exams_at_one_day } # Launch this only if this script is launched directly (don't launch this if `from main import *` is invoked) if __name__ == '__main__': ga(pop_count=POPULATION_COUNT, generations_number=GENERATIONS_NUMBER, cx_prob=CROSSOVER_PROBABILITY, mut_prob=MUTATION_PROBABILITY, mut_change_exam_prob=MUTATION_CHANGE_EXAM_PROBABILITY, evaluate_func=evaluate, available_timeslots=available_timeslots, exams=exams, timeslot_to_day=timeslot_to_day, timeslot_to_dayslot=timeslot_to_dayslot, print_best=True)
import ga ## initialise the GA oga = ga.ga() oga.seedGA(2, 10, 8, 4) pops = oga.getPopulation() print(pops[0]["first_weights"].renderT()) print(pops[1]["first_weights"].renderT()) print(oga.mutatePopulation(pops, 1, 1)) pops = oga.getPopulation() print(pops[0]["first_weights"].renderT()) print(pops[1]["first_weights"].renderT())
from pso import PSO import ga from test_func import sphere as obj_func print('------------') print('starting PSO...') # my_pso = PSO(func=obj_func, pop=30, dim=5, max_iter=100) my_pso = PSO(func=obj_func, dim=3) fitness = my_pso.fit() print('best_x is ', my_pso.gbest_x) print('best_y is ', my_pso.gbest_y) my_pso.plot_history() print('-------------') print('starting GA...') # general_best,func_general_best=ga.ga(func=demo_func2, pop=50, iter_max=200, lb=[-1, -10, -5], ub=[2, 10, 2],precision=[1e-7, 1e-7, 1e-7],Pm=0.001) # print(general_best,func_general_best) general_best, func_general_best, FitV_history = ga.ga(func=obj_func, lb=[-1, -10, -5], ub=[2, 10, 2]) print('best_x:', general_best) print('best_y:', func_general_best) ga.plot_FitV(FitV_history)
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import ga, Matrix, Ann, copy, random ## initialise the GA oga = ga.ga() oga.seedGA(5, 20, 5, 4) for p in oga.getPopulation(): print(p["second_thresholds"]) print(p["second_thresholds"].renderT()) pop = oga.getPopulation() newPop = [] for n in range(5): newPop.append(copy.deepcopy(pop[0])) currVal = newPop[n]["second_thresholds"].getElem(1, 0) currVal += (0.1 - random.random()*0.2) newPop[n]["second_thresholds"].setElem(1, 0, currVal)
import numpy as np import ga as ga import time def costFcn(x,params): import numpy as np for i in range(10000): g=np.array([0,0]) f=100*(x[1]-x[0]**2)**2+(1-x[0])**2 g[0]=2*x[0]-x[1] g[1]=1-x[0] return (f,g) lb=np.array([-2.0,-5.0]) ub=np.array([3.0,5.0]) x=np.array([2.0,1.0]) f,g=costFcn(x,0.0) GA=ga.ga(costFcn,lb,ub) # denorm test XNorm=np.random.rand(100,2)#np.array([[0.5,0.4],[1.0,1.0],[0.0,0.0]]) X=GA._denorm(XNorm) time1=time.time() F,G=GA._systemEval(X) print "Single core time = ",time.time()-time1, "s" #print " input X values = ",X #print "output F values = ",F #print "output G values = ",G time2=time.time() F,G=GA._systemEval_pp(X) print "Multi core time = ",time.time()-time2, "s" #print " input X values = ",X