Esempio n. 1
0
def find_pulses(
    cptm: ContinousPulseTransitionsMaker = ContinousPulseTransitionsMaker(
        30, (5, 10), 20, 0.3
    ),
    generations: int = DEFAULT_GENERATIONS,
    population_size: int = DEFAULT_POPULATION_SIZE,
    seed: int = DEFAULT_SEED,
) -> typing.Tuple[float, ...]:
    udp = pg.problem(cptm)
    algorithm = pg.algorithm(pg.gaco(gen=generations, seed=seed))
    # algorithm.set_verbosity(1)
    algorithm.set_verbosity(0)
    population = pg.population(udp, population_size)
    resulting_population = algorithm.evolve(population)

    best_x = resulting_population.champion_x
    best_fitness = resulting_population.champion_f

    pulses = cptm._convert_x_to_pulses(best_x)

    is_valid = best_fitness[1] <= 0 and best_fitness[2] <= 0
    if is_valid:
        print("Found valid solution.")
    else:
        msg = "WARNING: FOUND INVALID SOLUTION!"
        if best_fitness[1] > 0:
            msg += " Solution is too small."
        else:
            msg += " Solution is too big."
        print(msg)

    return pulses
def applyACO(**kwargs):

    try:

        prob = pg.problem(pg.rosenbrock(dim=kwargs.get('dim')))
        pop = pg.population(prob, size=kwargs.get('tamPopulation'), seed=23)
        algo = pg.algorithm(
            pg.gaco(kwargs.get('iters'), kwargs.get('kernel'), 1.0, 1e9, 0.0,
                    1, 7, 100000, 100000, 0.0, False, 23))
        algo.set_verbosity(1)
        pop = algo.evolve(pop)

        uda = algo.extract(pg.gaco)
        return uda.get_log()

    except:
        raise
Esempio n. 3
0
def main(argv):
    help_message = 'test.py <inputfile> <outputfile>'
    if len(argv) < 2:
        print(help_message)
        sys.exit(2)
    else:
        inputfile = argv[0]
        outputfile = argv[1]

    print("Reading data from " + inputfile)
    # Setting up the user defined problem in pygmo
    prob = pg.problem(TestOptimizer(inputfile))
    solution_size = 10000
    # Start with an initial set of 100 sets
    pop = pg.population(prob, size=solution_size)
    # Set the algorithm to non-dominated sorting GA
    algo = pg.algorithm(pg.gaco(gen=40))
    # Optimize
    pop = algo.evolve(pop)

    # This returns a set of optimal vectors and corresponding fitness values
    fits, vectors = pop.get_f(), pop.get_x()

    for i in range(len(vectors)):
        print("solution " + str(i))
        total = 0
        for j in range(len(vectors[i])):
            total += int(vectors[i][j])
        print("Total tests = " + str(total))

    print("Writing output to " + outputfile)
    jsonfile = pygeoj.load(filepath=inputfile)
    num_districts = len(jsonfile)
    counter = 0
    for feature in jsonfile:
        for sol in range(solution_size):
            feature.properties["sol" + str(sol)] = str(
                int(vectors[sol][counter]))
        counter += 1
    # Save output
    jsonfile.save(outputfile)

    print(vectors)
Esempio n. 4
0
def find_best_cengkoks(generations: int = 10, population_size: int = 40):
    def _get_best_of_multi_objective_population(pop):
        sorted_pop = pg.sort_population_mo(points=pop.get_f())
        x = pop.get_x()[sorted_pop[0]]
        x = tuple(int(x) for x in x)
        fitness = pop.get_f()[sorted_pop[0]]
        fitness = tuple(float(n) for n in fitness)
        return x, fitness

    for vanitas_rhythm, vanitas_melody_part in zip(
            rhythms.RHYTHMS,
            vanitas_melody_parts.VANITAS_MELODY_PARTS.items()):
        start_time, vanitas_melody = vanitas_melody_part

        bcf = BestCengkokFinder(vanitas_melody, vanitas_rhythm)
        problem = pg.problem(bcf)

        algorithm = pg.algorithm(pg.gaco(gen=generations))
        algorithm.set_verbosity(1)

        population = pg.population(problem, population_size)
        resulting_population = algorithm.evolve(population)

        best_x = resulting_population.champion_x
        best_fitness = resulting_population.champion_f

        # best_x, best_fitness = _get_best_of_multi_objective_population(
        #     resulting_population
        # )
        result = bcf._convert_nested_sequential_event_to_sequential_event(
            bcf._convert_x_to_nested_sequential_event(best_x))

        print(best_fitness)
        print("")

        with open(
                "{}/{}_{}.pickle".format(PICKLE_PATH, start_time.numerator,
                                         start_time.denominator),
                "wb",
        ) as f:
            pickle.dump((start_time, result), f)
import numpy as np
import pygmo as pg

from matplotlib import pyplot as plt

import constants as cte

from optim_class import Coverage, initiate

# def optimise():
sim_time, sun_pos, targets = initiate(cte.target_coors, cte.sun_pos0, cte.omega_earth, cte.omega_moon, cte.dt, cte.synodic_period)

coverage = Coverage(sim_time, sun_pos, targets, cte.r_m, cte.mu_m, cte.dt, cte.min_elev, cte.max_sat_range, cte.ecc, cte.aop, cte.tar_battery_cap, cte.tar_charge_power, cte.tar_max_sps_power, cte.sat_las_power, cte.tar_hib_power, cte.sat_point_acc, cte.tar_r_rec, cte.sat_n_las, cte.sat_n_geom, cte.tar_n_rec, cte.sat_wavelength, cte.sat_r_trans)

prob = pg.problem(coverage)
algo_class = pg.gaco(gen=10)
# algo_class.set_bfe(pg.bfe())
algo = pg.algorithm(algo_class)

pop = pg.population(prob, 100)

algo.set_verbosity(1)
pop = algo.evolve(pop)

print(pop.champion_x, pop.champion_f)
# return pop.champion_x, pop.champion_f
Esempio n. 6
0
    # Each job is a list of multiple tasks: (machine_id, processing_time)
    jobs_data = [
        [(0, 3), (1, 2), (2, 2)],  # Job0
        [(0, 2), (2, 1), (1, 4)],  # Job1
        [(1, 4), (2, 3)]  # Job2
    ]

    # Flatten the jobs data by index by encoding the job_id into the tuple
    # the *task syntax will unpack a tuple
    jobs_list = [(i, *task) for i in range(len(jobs_data))
                 for task in jobs_data[i]]

    # Create the problem
    prob = pg.problem(jobshop_function(jobs=jobs_list, max_schedule_time=12))
    print(prob)

    # Optimise
    population_size = 1000
    iterations = 100
    pop = pg.population(prob, size=population_size, seed=123)
    algo = pg.algorithm(pg.gaco(gen=iterations, ker=population_size, seed=123))
    algo.set_verbosity(1000)

    tic = time.perf_counter()
    pop = algo.evolve(pop)
    tock = time.perf_counter()

    print(
        f'solution: {pop.champion_x}, fitness value: {pop.champion_f} ({tock-tic:.3f} seconds)'
    )
Esempio n. 7
0
    def __call__(self, function):

        scanner_options = {
            'sade':
            dict(gen=self.gen,
                 variant=self.variant,
                 variant_adptv=self.variant_adptv,
                 ftol=self.ftol,
                 xtol=self.xtol,
                 memory=self.memory,
                 seed=self.seed),
            'gaco':
            dict(gen=self.gen,
                 ker=self.ker,
                 q=self.q,
                 oracle=self.oracle,
                 acc=self.acc,
                 threshold=self.threshold,
                 n_gen_mark=self.n_gen_mark,
                 impstop=self.impstop,
                 evalstop=self.evalstop,
                 focus=self.focus,
                 memory=self.memory,
                 seed=self.seed),
            'maco':
            dict(gen=self.gen,
                 ker=self.ker,
                 q=self.q,
                 threshold=self.threshold,
                 n_gen_mark=self.n_gen_mark,
                 evalstop=self.evalstop,
                 focus=self.focus,
                 memory=self.memory,
                 seed=self.seed),
            'gwo':
            dict(gen=self.gen, seed=self.seed),
            'bee_colony':
            dict(gen=self.gen, limit=self.limit, seed=self.seed),
            'de':
            dict(gen=self.gen,
                 F=self.F,
                 CR=self.CR,
                 variant=self.variant,
                 ftol=self.ftol,
                 xtol=self.xtol,
                 seed=self.seed),
            'sea':
            dict(gen=self.gen, seed=self.seed),
            'sga':
            dict(gen=self.gen,
                 cr=self.cr,
                 eta_c=self.eta_c,
                 m=self.m,
                 param_m=self.param_m,
                 param_s=self.param_s,
                 crossover=self.crossover,
                 mutation=self.mutation,
                 selection=self.selection,
                 seed=self.seed),
            'de1220':
            dict(gen=self.gen,
                 allowed_variants=self.allowed_variants,
                 variant_adptv=self.variant_adptv,
                 ftol=self.ftol,
                 xtol=self.xtol,
                 memory=self.memory,
                 seed=self.seed),
            'cmaes':
            dict(gen=self.gen,
                 cc=self.cc,
                 cs=self.cs,
                 c1=self.c1,
                 cmu=self.cmu,
                 sigma0=self.sigma0,
                 ftol=self.ftol,
                 xtol=self.xtol,
                 memory=self.memory,
                 force_bounds=self.force_bounds,
                 seed=self.seed),
            'moead':
            dict(gen=self.gen,
                 weight_generation=self.weight_generation,
                 decomposition=self.decomposition,
                 neighbours=self.neighbours,
                 CR=self.CR,
                 F=self.F,
                 eta_m=self.eta_m,
                 realb=self.realb,
                 limit=self.limit,
                 preserve_diversity=self.preserve_diversity,
                 seed=self.seed),
            'compass_search':
            dict(max_fevals=self.max_fevals,
                 start_range=self.start_range,
                 stop_range=self.stop_range,
                 reduction_coeff=self.reduction_coeff),
            'simulated_annealing':
            dict(Ts=self.Ts,
                 Tf=self.Tf,
                 n_T_adj=self.n_T_adj,
                 n_range_adj=self.n_range_adj,
                 bin_size=self.bin_size,
                 start_range=self.start_range,
                 seed=self.seed),
            'pso':
            dict(gen=self.gen,
                 omega=self.omega,
                 eta1=self.eta1,
                 eta2=self.eta2,
                 max_vel=self.max_vel,
                 variant=self.variant,
                 neighb_type=self.neighb_type,
                 neighb_param=self.neighb_param,
                 memory=self.memory,
                 seed=self.seed),
            'pso_gen':
            dict(gen=self.gen,
                 omega=self.omega,
                 eta1=self.eta1,
                 eta2=self.eta2,
                 max_vel=self.max_vel,
                 variant=self.variant,
                 neighb_type=self.neighb_type,
                 neighb_param=self.neighb_param,
                 memory=self.memory,
                 seed=self.seed),
            'nsga2':
            dict(gen=self.gen,
                 cr=self.cr,
                 eta_c=self.eta_c,
                 m=self.m,
                 eta_m=self.eta_m,
                 seed=self.seed),
            'nspso':
            dict(gen=self.gen,
                 omega=self.omega,
                 c1=self.c1,
                 c2=self.c2,
                 chi=self.chi,
                 v_coeff=self.v_coeff,
                 leader_selection_range=self.leader_selection_range,
                 diversity_mechanism=self.diversity_mechanism,
                 memory=self.memory,
                 seed=self.seed),
            'mbh':
            dict(algo=self.algo,
                 stop=self.stop,
                 perturb=self.perturb,
                 seed=self.seed),
            'cstrs_self_adaptive':
            dict(iters=self.iters, algo=self.algo, seed=self.seed),
            'ihs':
            dict(gen=self.gen,
                 phmcr=self.phmcr,
                 ppar_min=self.ppar_min,
                 ppar_max=self.ppar_max,
                 bw_min=self.bw_min,
                 bw_max=self.bw_max,
                 seed=self.seed),
            'xnes':
            dict(gen=self.gen,
                 eta_mu=self.eta_mu,
                 eta_sigma=self.eta_sigma,
                 eta_b=self.eta_b,
                 sigma0=self.sigma0,
                 ftol=self.ftol,
                 xtol=self.xtol,
                 memory=self.memory,
                 force_bounds=self.force_bounds,
                 seed=self.seed)
        }

        if self.log_data:
            xl = []
            yl = []

        log_data = self.log_data

        #
        class interf_function:
            def __init__(self, dim):
                self.dim = dim

            def fitness(self, x):
                x = np.expand_dims(x, axis=0)
                y = function(x)
                # x = x[0]
                y = y.tolist()
                if log_data:
                    xl.append(x)
                    yl.append(y)
                # print (x, y[0])
                return y[0]

            if function.is_differentiable():

                def gradient(self, x):
                    x = np.expand_dims(x, axis=0)
                    g = function(x)
                    g = g.tolist()
                    return g[0]

            def get_bounds(self):
                lb = []
                ub = []
                bounds = function.get_ranges()
                # warning
                # check for infinities
                for i in range(len(bounds)):
                    lb.append(bounds[i, 0])
                    ub.append(bounds[i, 1])
                r = (np.array(lb), np.array(ub))
                return r

        # I need to call pygmo functions directly
        prob = pg.problem(interf_function(function))

        # print (prob.get_thread_safety())

        if self.scanner == "sade":
            # I need a dictionary with algorithms and options
            algo = pg.algorithm(pg.sade(**scanner_options[self.scanner]))
        elif self.scanner == "gaco":
            algo = pg.algorithm(pg.gaco(**scanner_options[self.scanner]))
        # elif self.scanner == "maco": # is not implemented though in webpage
        #                               looks it is
        # algo = pg.algorithm(pg.maco(**scanner_options[self.scanner]))
        elif self.scanner == "gwo":
            algo = pg.algorithm(pg.gwo(**scanner_options[self.scanner]))
        elif self.scanner == "bee_colony":
            algo = pg.algorithm(pg.bee_colony(**scanner_options[self.scanner]))
        elif self.scanner == "de":
            algo = pg.algorithm(pg.de(**scanner_options[self.scanner]))
        elif self.scanner == "sea":
            algo = pg.algorithm(pg.sea(**scanner_options[self.scanner]))
        elif self.scanner == "sga":
            algo = pg.algorithm(pg.sga(**scanner_options[self.scanner]))
        elif self.scanner == "de1220":
            algo = pg.algorithm(pg.de1220(**scanner_options[self.scanner]))
        elif self.scanner == "cmaes":
            algo = pg.algorithm(pg.cmaes(**scanner_options[self.scanner]))
        # elif self.scanner == "moead": #multiobjective algorithm
        #  algo = pg.algorithm(pg.moead(**scanner_options[self.scanner]))
        elif self.scanner == "compass_search":
            algo = pg.algorithm(
                pg.compass_search(**scanner_options[self.scanner]))
        elif self.scanner == 'simulated_annealing':
            algo = pg.algorithm(
                pg.simulated_annealing(**scanner_options[self.scanner]))
        elif self.scanner == 'pso':
            algo = pg.algorithm(pg.pso(**scanner_options[self.scanner]))
        elif self.scanner == 'pso_gen':
            algo = pg.algorithm(pg.pso_gen(**scanner_options[self.scanner]))
        # elif self.scanner == 'nsga2': #multiobjective algorithm
        #  algo = pg.algorithm(pg.nsga2(**scanner_options[self.scanner]))
        # elif self.scanner == 'nspso': is not implemented though in webpage
        #                               looks it is
        #  algo = pg.algorithm(pg.nspso(**scanner_options[self.scanner]))
        elif self.scanner == 'mbh':
            if scanner_options[self.scanner]['algo'] == 'de':
                algo = pg.algorithm(
                    pg.mbh(pg.algorithm(pg.de(**scanner_options['de']))))
        # elif self.scanner == 'ihs': #does not work
        #  algo = pg.algorithm(ihs(**scanner_options[self.scanner]))
        # elif self.scanner == 'xnes': #does not work
        #  algo = pg.algorithm(xnes(**scanner_options[self.scanner]))
        # uda = algo.extract(xnes)
        else:
            print(
                'The ' + self.scanner + ' algorithm is not implemented. The '
                'list of algorithms available is', algorithms)
            sys.exit()

        # add verbosing flag
        if self.verbose > 1:
            algo.set_verbosity(self.verbose)

        pop = pg.population(prob, self.size)

        if self.verbose > 9:
            print('prob', prob)

        opt = algo.evolve(pop)

        if self.verbose > 9:
            print('algo', algo)

        # best_x = np.expand_dims(opt.champion_x, axis=0)
        # best_fitness = np.expand_dims(opt.get_f()[opt.best_idx()], axis=0)
        best_x = np.expand_dims(opt.champion_x, axis=0)
        best_fitness = np.expand_dims(opt.champion_f, axis=0)

        if self.verbose > 0:
            print('best fit:', best_x, best_fitness)

        if self.log_data:
            x = np.squeeze(xl, axis=(1, ))
            y = np.squeeze(yl, axis=(2, ))

        if self.log_data:
            return (x, y)
        else:
            return (best_x, best_fitness)
Esempio n. 8
0
from matplotlib import pyplot as plt

import constants as cte

from optim_class import Coverage, initiate

sim_time, sun_pos, targets = initiate()

# 1 - Instantiate a pygmo problem constructing it from a UDP
# (user defined problem).
coverage = Coverage(sim_time, sun_pos, targets)

prob = pg.problem(coverage)

# 2 - Instantiate a pagmo algorithm
algo = pg.algorithm(pg.gaco(gen=100))

# 3 - Instantiate an archipelago with 16 islands having each 20 individuals
archi = pg.archipelago(1, algo=algo, prob=prob, pop_size=7)

# 4 - Run the evolution in parallel on the 16 separate islands 10 times.
archi.evolve(1)

# 5 - Wait for the evolutions to be finished
archi.wait()

# 6 - Print the fitness of the best solution in each island
res = None
fit = 100
for isl in archi:
    if fit < isl.get_population().champion_f: