Exemplo n.º 1
0
def main():
    """Run a classification test run on iris dataset"""
    evaluator = IrisFlowerEvaluator()

    nn_hyperparams = {
        'layers': (4, 6, 3),
        'activation_functions': (sigmoid, sigmoid),
    }
    generator = IndividualGenerator(NNIndividual, nn_hyperparams)

    reporters = [BestIndividualReporter()]
    selector = RouletteWheelSelector()
    crossover = NNPointCrossover(generator, 3)
    mutation = NNNormalMutation(stddev=0.03)

    population_size = 100
    max_iterations = 0
    target_fitness = 148

    alg = GeneticAlgorithm(reporters,
                           evaluator,
                           selector,
                           crossover,
                           mutation,
                           population_size,
                           generator,
                           max_iterations,
                           target_fitness=target_fitness)

    alg.run()
def initGhostAlgorithm(ghost, player, algorithm):
    if algorithm == 'A*':
        ghost.setAlgorithm(AStar(ghost, player))

    # elif algorithm == 'DFS':
    #     ghost.setAlgorithm(Dfs(ghost, player))

    elif algorithm == 'GeneticAlgorithm':
        ghost.setAlgorithm(GeneticAlgorithm(ghost, player))

    elif algorithm == 'Frightened':
        ghost.setAlgorithm(Frightened(ghost))
Exemplo n.º 3
0
 def fn_factory(exec_code):
     return GeneticAlgorithm(defs.fn_goal, defs.fn_neighbor_ga, defs.fn_init_state_ga(exec_code), qtt_iter=defs.QTT_ITERATION_GA, is_min=defs.IS_MINIMIZATION)
Exemplo n.º 4
0
                               fitness_function="Overall_Sum_add_Potential")

# 2. Random Search
rs = RandomSearch(problem_instance, random_state)
rs.initialize()
rs.search(n_iterations=100, report=True)

# 3. Hill Climbing interpretation
hc = HillClimbing(problem_instance, random_state)
hc.initialize()
hc.search(n_iterations=200, report=True)

# 4. Genetic Algorithm Standard
ga = GeneticAlgorithm(problem_instance, random_state,
                      population_size=50,
                      selection_method="tournament",
                      crossover_method="one-point", crossover_rate=0.5,
                      mutation_method="position-flip", mutation_rate=0.5,
                      tournament_size=4)
ga.initialize()
ga.search(n_iterations=200, report=True)



print("_"*45)
print("Results of Random Search")
print("Cost of current Best Squad: %.2f Mil. Eur"% (rs.best_solution.value))
print("Mean Score of Current best Squad: %.1f" %(rs.best_solution.overall))
print("Average Age of Current best Squad: %.1f" %(rs.best_solution.age))
print("Average Potential of Current best Squad: %.1f" %(rs.best_solution.potential))
print()
show_squad(rs.best_solution.representation)
Exemplo n.º 5
0
    # - optimization of ANN's weights is a COP
    #++++++++++++++++++++++++++
    ann_op_i = ANNOP(search_space=(-2, 2, n_weights), fitness_function=ann_i.stimulate,
                     minimization=False, validation_threshold=validation_threshold)

    #++++++++++++++++++++++++++
    # THE SEARCH
    # restrictions:
    # - 5000 offsprings/run max*
    # - 50 offsprings/generation max*
    # - use at least 5 runs for your benchmarks
    # * including reproduction
    #++++++++++++++++++++++++++
    ga1 = GeneticAlgorithm2(ann_op_i, random_state, ps, uls.parametrized_tournament_selection(pressure),
                          uls.one_point_crossover, p_c, uls.parametrized_ball_mutation(radius), 0.2)
    ga2 = GeneticAlgorithm(ann_op_i, random_state, ps, uls.parametrized_tournament_selection(pressure),
                           uls.two_point_crossover, p_c, uls.parametrized_ball_mutation(radius), 0.1)
    sa1 = SimulatedAnnealing(ann_op_i, random_state, ps, uls.parametrized_ball_mutation(radius), control, update_rate)
    search_algorithms = [ga1, ga2]

    # initialize search algorithms
    [algorithm.initialize() for algorithm in search_algorithms]

    # execute search
    [algorithm.search(n_iterations=n_gen, report=False) for algorithm in search_algorithms]

#++++++++++++++++++++++++++
# TEST
# - test algorithms on unseen data
#++++++++++++++++++++++++++
for algorithm in search_algorithms:
    ann_i._set_weights(algorithm.best_solution.representation)
Exemplo n.º 6
0
def argparser():
    parser = argparse.ArgumentParser(description='Chips and Circuits')

    parser.add_argument('--netlist',
                        default=1,
                        type=int,
                        choices=[1, 2, 3, 4, 5, 6],
                        help='choose the netlist.')

    parser.add_argument('--algorithm',
                        choices=[
                            "astar", "genetic", "hillclimbing", "randomwalk",
                            "hillclimbing_solution"
                        ],
                        help='the algorithm that is used.')

    parser.add_argument('--astar-complete',
                        default=1,
                        type=int,
                        choices=[0, 1],
                        help='Whether to find a complete solution')

    parser.add_argument('--genetic-poolSize',
                        default=500,
                        type=int,
                        help='The pool size for genetic algorithm')

    parser.add_argument('--genetic-parentSize',
                        default=25,
                        type=int,
                        help='The parent size(pair) for genetic algorithm')

    parser.add_argument('--genetic-generationSize',
                        default=30,
                        type=int,
                        help='The generation size for genetic algorithm')

    parser.add_argument('--steps',
                        default=50,
                        type=int,
                        help='The steps for hill climber')
    parser.add_argument(
        '--amount',
        default=3,
        type=int,
        help='The amount of wires changed in a transformation for hill climber'
    )
    parser.add_argument('--retry',
                        default=3,
                        type=int,
                        help='The allowed max retry in a step in hill climber')
    parser.add_argument(
        '--savechip',
        default=False,
        type=bool,
        choices=[0, 1],
        help='Save the best chip in json file after hill climbing')
    parser.add_argument('--showchip',
                        default=False,
                        type=bool,
                        choices=[0, 1],
                        help='Show the best chip after hill climbing')
    parser.add_argument('--result',
                        default=True,
                        type=bool,
                        choices=[0, 1],
                        help='Show the hill climbing process')
    parser.add_argument('--savechip_name',
                        default="hillclimbing_bestchip.json",
                        type=str,
                        help='The name of the chip json file')
    parser.add_argument('--showchip_name',
                        default="hillclimbing_bestchip",
                        type=str,
                        help='The name of the chip plot')
    parser.add_argument('--result_name',
                        default="hillclimbing_result",
                        type=str,
                        help='The name of the plot of hill climbing process')

    args = parser.parse_args()

    if args.algorithm != 'astar' and args.astar_complete != True:
        parser.error(
            '--astar-complete can only be set when --algorithm=astar.')

    if args.algorithm != "genetic" and args.genetic_poolSize != 500:
        parser.error(
            '--genetic-poolSize can only be set when --algorithm=genetic.')

    if args.algorithm != 'genetic' and args.genetic_parentSize != 25:
        parser.error(
            '--genetic-parentSize can only be set when --algorithm=genetic.')

    if args.algorithm != 'genetic' and args.genetic_generationSize != 30:
        parser.error(
            '--genetic-generationSize can only be set when --algorithm=genetic.'
        )

    env = Environment(args.netlist)
    steps = args.steps
    amount = args.amount
    retry = args.retry
    savechip = args.savechip
    showchip = args.showchip
    result = args.result
    savechip_name = args.savechip_name
    showchip_name = args.showchip_name
    result_name = args.result_name

    algos = {
        "astar":
        AstarSpfa(env).run,
        "genetic":
        GeneticAlgorithm(env).run,
        "hillclimbing":
        HillClimber(env,
                    steps=steps,
                    amount=amount,
                    retry=retry,
                    save_chip=savechip,
                    show_chip=showchip,
                    show_lineplot=result,
                    chip_filename=savechip_name,
                    chip_plotname=showchip_name,
                    lineplot_filename=result_name).hillclimbing,
        "randomwalk":
        HillClimber(env,
                    steps=steps,
                    amount=amount,
                    retry=retry,
                    save_chip=savechip,
                    show_chip=showchip,
                    show_lineplot=result,
                    chip_filename=savechip_name,
                    chip_plotname=showchip_name,
                    lineplot_filename=result_name).randomwalk,
        "hillclimbing_solution":
        HillClimber(env,
                    steps=steps,
                    amount=amount,
                    retry=retry,
                    save_chip=savechip,
                    show_chip=showchip,
                    show_lineplot=result,
                    chip_filename=savechip_name,
                    chip_plotname=showchip_name,
                    lineplot_filename=result_name).hillclimbing_solution,
    }

    if args.algorithm == "astar":
        algos[args.algorithm](args.astar_complete)
    elif args.algorithm == "genetic":
        algos[args.algorithm](args.genetic_poolSize, args.genetic_parentSize,
                              args.genetic_generationSize)
    elif args.algorithm == "hillclimbing" or \
            args.algorithm == "randomwalk" or \
            args.algorithm == "hillclimbing_solution":
        algos[args.algorithm]()
    else:
        parser.print_help()
Exemplo n.º 7
0
def main(_):
    # Load command input options
    options, remainder = create_parser().parse_args()

    num_meta_datasets = 20
    num_generations = 5
    population_size = 30
    num_children = 5
    best_sample = 8
    lucky_few = 4
    chance_of_mutation = 5
    fraction_to_mutate = 5

    hparams_linear = tf.contrib.training.HParams(name='LinearFullPosterior',
                                                 num_steps=20,
                                                 actions_dim=98,
                                                 positive_reward=10,
                                                 negative_reward=-1,
                                                 a0=6.0,
                                                 b0=6.0,
                                                 lambda_prior=0.1,
                                                 intercept=True,
                                                 remove_actions=False)

    raw_data = pd.read_pickle(options.input)
    raw_data = preprocess(raw_data)
    raw_data = remove_outlier_vals(raw_data)

    meta_data = []
    for _ in range(num_meta_datasets):
        actions, rewards = retrieve_synthetic_data(data=raw_data,
                                                   input_path=None,
                                                   fst_type_filter=True,
                                                   fst_latlng_param=0.5,
                                                   fst_utility_filter=None,
                                                   fst_feature_param=None,
                                                   fst_category_filter=None,
                                                   fst_price_param=None,
                                                   fst_area_param=None,
                                                   snd_type_filter=True,
                                                   snd_latlng_param=1,
                                                   snd_utility_filter=True,
                                                   snd_feature_param=0.5,
                                                   snd_category_filter=True,
                                                   snd_price_param=0.6,
                                                   snd_area_param=0.7,
                                                   max_selected=6000,
                                                   min_positive=10,
                                                   max_positive=1000,
                                                   verbose=False)

        normalized_actions = normalize(actions)
        data = BanditDataset(normalized_actions, rewards)
        meta_data.append(data)

    start_time = time.time()
    ga = GeneticAlgorithm(sampling=LinearFullPosteriorSampling,
                          hparams=hparams_linear,
                          meta_data=meta_data,
                          population_size=population_size,
                          num_children=num_children,
                          best_sample=best_sample,
                          lucky_few=lucky_few,
                          chance_of_mutation=chance_of_mutation,
                          fraction_to_mutate=fraction_to_mutate)
    ga.run(num_generations=num_generations)

    best = ga.get_best_individual_from_population()
    print('Finished. Best fitness score:', best[0])
    print('Elapsed time: ',
          datetime.timedelta(seconds=(time.time() - start_time)))

    best_path = os.path.join(
        LOG_PATH,
        datetime.datetime.now().strftime('%y%m%d%H%M%S%f') + '.pkl')
    with open(best_path, 'wb') as f:
        pickle.dump(best, f)

    return 0
Exemplo n.º 8
0
#++++++++++++++++++++++++++
# THE OPTIMIZATION
# restrictions:
# - 5000 f.e./run
# - 50 f.e./generation
# - use at least 5 runs for benchmarks
#++++++++++++++++++++++++++
n_gen = 384
ps = 50
p_c = 1
p_m = .5
radius = .015
pressure = .6

ga1 = GeneticAlgorithm(ann_op_i, random_state, ps, uls.parametrize_roulette_wheel_w_pressure(pressure),
                          uls.geometric_semantic_crossover, p_c, uls.parametrized_gaussian_member_mutation(radius)
                                                                                        , p_m, pressure)

ga2 = GeneticAlgorithm(ann_op_i, random_state, ps, uls.parametrize_roulette_wheel_w_pressure(pressure),
                          uls.uniform_points_crossover, p_c, uls.parametrized_gaussian_member_mutation(radius)
                                                                                         , p_m, pressure)

ga3 = GeneticAlgorithm(ann_op_i, random_state, ps, uls.parametrize_roulette_wheel_w_pressure(pressure),
                          uls.two_point_crossover, p_c, uls.parametrized_gaussian_member_mutation(radius)
                                                                                        , p_m, pressure)

ga4 = GeneticAlgorithm(ann_op_i, random_state, ps, uls.parametrize_roulette_wheel_pressure(pressure),
                          uls.media_crossover_point, p_c, uls.parametrized_gaussian_member_mutation(radius)
                                                                                        , p_m, pressure)

def main():

    idw = arcpy.env.workspace + "\\Idw_Projected_30"
    noise_map = arcpy.env.workspace + "\\Transportation_Noise"
    line_for_initialization = arcpy.env.workspace + "\\example_route"
    geofences_restricted_airspace = arcpy.env.workspace + "\\Restricted_Airspace"
    geofence_point_boundary = arcpy.env.workspace + "\\Restricted_Airspace_Point_Boundary"
    output_new_line = r'threedline'
    #set up flight constraints
    # legal constraints parameters
    maximum_speed_legal = 27.7777777778  # in m/s. 100 in km/h
    # air taxi specific parameters

    #for Lilium Jet flight characteristics: aircraft = "Lilium". for Ehang aircraft ="EHANG"
    aircraft = "Lilium"
    type_aircraft, weight_aircraft, wing_area, CD_from_drag_polar, maximum_speed_air_taxi, acceleration_speed, acceleration_energy, deceleration_speed, deceleration_energy, minimal_cruise_energy, take_off_and_landing_energy, hover_energy, noise_pressure_acceleration, noise_pressure_deceleration, noise_at_cruise, noise_at_hover = init.aircraft_specs(
        aircraft)

    # flight comfort constraint
    maximum_angular_speed = 1  # (in radian/second)
    #environmental depending settings
    air_density = 1.225  #(in kg/m³) standard air pressure
    speed_of_sound = 343  # in m/s, at 20 Degrees Celsius
    gravity = 9.81  # in m/s²

    flight_constraints = flight_Constraints(
        type_aircraft, weight_aircraft, wing_area, CD_from_drag_polar,
        maximum_speed_legal, maximum_speed_air_taxi, acceleration_speed,
        acceleration_energy, deceleration_speed, deceleration_energy,
        minimal_cruise_energy, take_off_and_landing_energy, hover_energy,
        noise_pressure_acceleration, noise_pressure_deceleration,
        noise_at_cruise, noise_at_hover, maximum_angular_speed, air_density,
        speed_of_sound, gravity)

    #if feature classes from previous runs shall not be deleted, uncomment
    #uls.delete_old_objects_from_gdb("threed")

    # setup problem
    hypercube = [(-5, 5), (-5, 5)]
    rs = uls.get_random_state(1)
    problem_instance = ThreeDSpace(
        search_space=hypercube,
        fitness_function=uls.multi_objective_NSGA_fitness_evaluation(),
        IDW=idw,
        noisemap=noise_map,
        x_y_limits=900,
        z_sigma=5,
        work_space=env.workspace,
        random_state=rs,
        init_network=line_for_initialization,
        sample_point_distance="400 Meters",
        restricted_airspace=geofences_restricted_airspace,
        flight_constraints=flight_constraints,
        geofence_point_boundary=geofence_point_boundary)
    #evalluate least cost path
    # from solutions import solution
    # import utils
    #
    # linefc = "least_cost_path_3d"
    # pointfc = "least_cost_path_3d_p"
    # zpointfc = "least_cost_path_3d_p_z"
    # #utils.lineToPoints(linefc, pointfc, 10)
    # #utils.extractValuesRaster(pointfc, idw, zpointfc)
    #
    # repr = utils.point3d_fc_to_np_array(zpointfc, additional_fields = None)
    #
    # least_cost_path_solution = solution.Solution(repr)
    # least_cost_path_solution.PointFCName = pointfc
    # least_cost_path_solution.LineFCName = linefc
    # problem_instance.evaluate(least_cost_path_solution)

    # setup Genetic Algorithm
    p_c = 0.9
    p_m = 0.5
    n_iterations = 25
    population_size = 16
    n_crossover_points = 4
    selection_pressure = 0.4
    #params mutation
    percentage_disturbed_chromosomes = 0.2
    max_disturbance_distance = 200
    percentage_inserted_and_deleted_chromosomes = 0.25
    mutation_group_size = 3

    for seed in range(1):
        # setup random state
        random_state = uls.get_random_state(seed)
        # execute Genetic Algorithm
        ga1 = GeneticAlgorithm(
            problem_instance=problem_instance,
            random_state=random_state,
            population_size=population_size,
            selection=uls.nsga_parametrized_tournament_selection(
                selection_pressure),
            crossover=uls.n_point_crossover(n_crossover_points),
            p_c=p_c,
            mutation=uls.parametrized_point_mutation(
                percentage_disturbed_chromosomes=
                percentage_disturbed_chromosomes,
                max_disturbance_distance=max_disturbance_distance,
                percentage_inserted_and_deleted_chromosomes=
                percentage_inserted_and_deleted_chromosomes,
                group_size=mutation_group_size),
            p_m=p_m,
            aimed_point_amount_factor=2)
        ga1.initialize()
        #setting up the logging
        t = strftime("%Y-%m-%d_%H_%M_%S", gmtime())
        lgr = logging.getLogger(t)
        lgr.setLevel(logging.DEBUG)  # log all escalated at and above DEBUG
        # add a file handler
        fh = logging.FileHandler(r'baseline_routing/log_files/' + t +
                                 '_new.csv')
        fh.setLevel(logging.DEBUG)
        frmt = logging.Formatter(
            '%(asctime)s,%(name)s,%(levelname)s,%(message)s')
        fh.setFormatter(frmt)
        lgr.addHandler(fh)
        log_event = [
            "rs",
            id(seed), __name__, "population_size", population_size,
            "x_y_limits", problem_instance.x_y_limits, "z_sigma",
            problem_instance.z_sigma, "sample_point_distance",
            problem_instance.sample_point_distance, "selection_pressure",
            selection_pressure, "pc", p_c, "pm", p_m, "aimed_point_factor",
            ga1.aimed_point_amount_factor, "n_crossover", n_crossover_points,
            "mutation_max_disturbance_distance", max_disturbance_distance,
            "mutation_group_size", mutation_group_size,
            "percentage_inserted_and_deleted",
            percentage_inserted_and_deleted_chromosomes,
            "percentage_disturbed", percentage_disturbed_chromosomes
        ]
        lgr.info(','.join(list(map(str, log_event))))
        ga1.search(n_iterations=n_iterations,
                   lgr=lgr,
                   report=True,
                   log=True,
                   dplot=None)
Exemplo n.º 10
0
#++++++++++++++++++++++++++
# THE OPTIMIZATION
# restrictions:
# - 5000 f.e./run
# - 50 f.e./generation
# - use at least 5 runs for benchmarks
#++++++++++++++++++++++++++
n_gen = 100
ps = 50
p_c = .5
p_m = .9
radius = .2
pressure = .2
ga = GeneticAlgorithm(ann_op_i, random_state, ps,
                      uls.parametrized_tournament_selection(pressure),
                      uls.two_point_crossover, p_c,
                      uls.parametrized_ball_mutation(radius), p_m)
ga.initialize()
ga.search(n_gen, True, True)

ga.best_solution.print_()
print("Training fitness of the best solution: %.2f" % ga.best_solution.fitness)
print("Validation fitness of the best solution: %.2f" %
      ga.best_solution.validation_fitness)

#sa = SimulatedAnnealing(ann_op_i, random_state, ps, uls.parametrized_ball_mutation(radius), 2, .9)
#sa.initialize()
#sa.search(n_gen, False, True)

#sa.best_solution.print_()
#print("Training fitness of the best solution: %.2f" % sa.best_solution.fitness)
Exemplo n.º 11
0
"""TODO comment and properly document
"""
from problems.titanic import Titanic
from algorithms.genetic_algorithm import GeneticAlgorithm

# TODO: get from input, with defaults
hyperparameters = {
    'generations': 200,
    'population_size': 100,
    'breeding_rate': 0.2,
    'crossover_rate': 0.96,
    'mutation_rate': 0.08,
    'mutation_range': 0.1,
}

if __name__ == '__main__':
    # TODO: handle inputs

    t = Titanic()
    g = GeneticAlgorithm(hyperparameters, t)

    while not g.terminate():
        g.next_generation(debug=True)

    g.print_best()