def selection(population, iteration, breakPoint=50, k=3): shape = population.individuals.shape[0] new_population = Population(None) new_population.individuals = np.empty(shape=shape, dtype=object) for i in range(shape): new_population.individuals[i] = roulette(population) if ( iteration < breakPoint) else tournament(population) return new_population
def crossover(population, crossover_ratio=0.70): shape = population.individuals.shape[0] newPopulation = Population(None) newPopulation.individuals = np.empty(shape=shape, dtype=object) for i in range(shape): newPopulation.individuals[i] = one_point_crossover( population.individuals[i], population.individuals[(i + 1) % (shape - 1)]) return newPopulation
def __init_window(self): init() self.__surface = display.set_mode(self.__screen_size) display.set_caption( 'Game of Life --- SPACE - Toggle evolution, R - reset generation') model = Population(PygameCellFactory(), self.__screen_size) self.__board_view = PygameBoard('Population', model, self.__surface) model.add_observer(self.__board_view) self.controller.model = model self.controller.view = self.__board_view while True: for e in event.get(): if e.type == QUIT: quit() exit() if e.type == KEYDOWN: if e.key == K_SPACE: model.toggle_evolution() if e.key == K_r: model.reset_population() self.controller.handle() self.__pyg_clock.tick(40) display.flip()
def main(): args_parser = build_args_parser() args = args_parser.parse_args() results_dir_path = args.output_path if not os.path.exists(results_dir_path): os.makedirs(results_dir_path) for function_type in [f.value for f in FunctionType]: function = build_function(function_type) best_fitness_history_by_topology_type = {} for topology_type in [t.value for t in TopologyType]: best_fitness_history = [] for i in range(args.num_simulations): start_time = time.time() population = Population(args.population_size, args.dimension, function.lower_limit, function.upper_limit, topology_type) if args.use_clerc: best_fitness = pso.optimize_with_clerc( function, population, args.num_iterations, args.cognitive_coeff, args.social_coeff) else: best_fitness = pso.optimize(function, population, args.num_iterations, args.initial_inertia_coeff, args.final_inertia_coeff, args.cognitive_coeff, args.social_coeff) elapsed_time = time.time() - start_time print(function_type + ", " + topology_type + ", simulação: " + str(i + 1) + ", fitness: " + str(round(best_fitness, 2)) + "(" + str(round(elapsed_time, 2)) + " s)") best_fitness_history.append(best_fitness) best_fitness_history_by_topology_type[ topology_type] = best_fitness_history plt.clf() plt.boxplot(list(best_fitness_history_by_topology_type.values()), labels=list(best_fitness_history_by_topology_type.keys())) plt.title(function_type) plt.savefig(os.path.join(results_dir_path, function_type + "_box_plot.png"), bbox_inches='tight')
def load_population(self, *, processes=1, period=1): self.population = Population.load(self.dataset, processes=processes, period=period)
def __init__(self, size, individualSize): self._size = size self._individualSize = individualSize self._initialPopulation = Population(size, individualSize) self._graph = [self._initialPopulation]
def evolvePopulation(self): newPopulation = self._graph[-1].iterationEA() new = Population(self._size, self._individualSize) new.setPopulation(newPopulation) self._graph.append(deepcopy(new))
from models.population import Population from models.pollution import Pollution from models.agriculture import Agriculture from const import _Const CONST = _Const() def get_list_for(results, const): res = {} for key, value in results.iteritems(): res[key] = value[const] return res start_year = 1900 year_step = 1 capital = Capital(CONST.START_YEAR) population = Population(CONST.START_YEAR) pollution = Pollution(CONST.START_YEAR) agriculture = Agriculture(CONST.START_YEAR) init_result = dict(capital.initial_result().items() + population.initial_result().items() + pollution.initial_result().items() + agriculture.initial_result().items()) results = [init_result] result_dict = {} population_list = {} year_list = f.drange(CONST.START_YEAR, CONST.START_YEAR+CONST.YEAR_RANGE+0.00001, CONST.YEAR_STEP_SIZE) for x in year_list: last_result = results[-1] result_dict[x] = last_result
if args.gpu == -1: supernet = torch.nn.DataParallel(supernet) # optimizer supernetOptimizer = optim.SGD(supernet.parameters(), lr=args.init_learning_rate, momentum=args.momentum, weight_decay=args.weight_decay) # scheduler scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( supernetOptimizer, args.warmup_epoch_first + decision_number * args.warmup_epoch_others) # define the population for search population = Population() logging.info('Population 0: %d', len(population.archList)) # begin search for geneOpIndex in range(decision_number): # The number of train epochs of the first decision is greator than that of the others. if geneOpIndex == 0: tmp_warmup_epoch = args.warmup_epoch_first else: tmp_warmup_epoch = args.warmup_epoch_others # If you have already trained the models after first warming up, you can reload it to avoid too much time consuming. if args.reload_model and os.path.exists( pretrainModelCheckPointPath) and geneOpIndex == 0: logging.info('==> Resuming from checkpoint: %s', os.path.abspath(pretrainModelCheckPointPath))