def generate_population(toolbox: base.Toolbox, ccl_objects: dict, options: dict) -> List[gp.PrimitiveTree]: """Generate initial population""" pop = [] codes: Set[str] = set() pbar = tqdm.tqdm(total=options['population_size']) while len(pop) < options['population_size']: ind = toolbox.individual() if not check_symbol_counts(ind, options): continue try: sympy_expr = generate_sympy_expr(ind, ccl_objects) if sympy_expr.has(sympy.zoo, sympy.oo, sympy.nan, sympy.I): continue sympy_code = str(sympy_expr) except RuntimeError: continue if options['max_constant_allowed'] is not None and not check_max_constant(sympy_expr, options): continue if options['unique_population']: if sympy_code in codes: continue codes.add(sympy_code) ind.sympy_code = sympy_code pop.append(ind) pbar.update() pbar.close() return pop
# ## Evaluating Fitness # + def eval_knapsack(individual): weight = 0.0 value = 0.0 for package_id in individual: weight += packages[package_id]["weight"] value += packages[package_id]["value"] #if len(individual) > MAX_ITEM or weight > MAX_WEIGHT: # return 10000, 0 # Ensure overweighted bags are dominated return weight, value indv = toolbox.individual() indv_fitness = eval_knapsack(indv) print(f"The fitness (weight, monetary value) of knapsack {indv}\nis: \n{indv_fitness}") # - # ## Transformations # ### Crossover # # Here we use a different crossover from previous notebooks: # # `child1` gets that `parent1` and `parent2` overlap: `child1 = parent1 & parent2` #