Example #1
0
    def gen_pop(seed, algos, pop_size):

        prob = pg.problem(sfunc_inst)

        if nlopt and not seed:
            algo = pg.algorithm(pg.nlopt(solver="cobyla"))
            print('[swarms:]'.ljust(15, ' ') + 'On seed ' + str(seed) +
                  ' creating ' + algo.get_name())
            algo.extract(pg.nlopt).maxeval = nlopt
        elif nlopt and seed == 1:
            algo = pg.algorithm(pg.nlopt(solver="neldermead"))
            print('[swarms:]'.ljust(15, ' ') + 'On seed ' + str(seed) +
                  ' creating ' + algo.get_name())
            algo.extract(pg.nlopt).maxeval = nlopt
        else:
            random.seed(seed)
            algo = random.sample(algos, 1)[0]
            print('[swarms:]'.ljust(15, ' ') + 'On seed ' + str(seed) +
                  ' creating ' + algo.get_name())
            algo.set_seed(seed)

        pop = pg.population(prob, size=pop_size, seed=seed)
        ser_pop = dump_pop(pop)
        ser_algo = cpickle.dumps(algo)

        return ser_algo, ser_pop
Example #2
0
    def run(self, converge_info=False, pop_info=False):
        """
        Run the optimisation process using PSO algorithm.
        :param converge_info: optional run the optimisation with convergence information
        :param converge_info: optional run the optimisation with population information
        :return:
        """
        print("Start the optimisation process...")

        if pop_info != False:
            uda = pg.pso(gen=1)
            algo = pg.algorithm(uda)
            algo.set_verbosity(1)
            pop = pg.population(self.problem, self.pop_size)
            self.pop_history = [pop]
            for i in range(int(pop_info)):
                pop = algo.evolve(pop)
                self.pop_history.append(pop)
            self.log = algo.extract(type(uda)).get_log()
            self.pop = pop
        elif converge_info == True:
            uda = pg.pso(gen=self.generation)
            algo = pg.algorithm(uda)
            algo.set_verbosity(1)
            pop = pg.population(self.problem, self.pop_size)
            self.log = algo.extract(type(uda)).get_log()
            self.pop = pop
        else:
            uda = pg.pso(gen=self.generation)
            algo = pg.algorithm(uda)
            pop = pg.population(self.problem, self.pop_size)
            pop = algo.evolve(pop)
        self.champion = pop.champion_x
        return pop.champion_f, pop.champion_x
Example #3
0
    def optimize(self, population, steps, seed=None):
        algorithm_constructor = available_algorithms[self.algorithm_name][0]
        if 'nlopt' in self.algorithm_name: # nlopt algorithms called differently.
            _algorithm = algorithm_constructor()
            _algorithm.maxeval = steps
            self._algorithm = pygmo.algorithm(_algorithm)
        else:
            self._algorithm = pygmo.algorithm(algorithm_constructor(gen=steps, seed=seed, **self.algorithm_kwargs))
        logger.info('(algorithm) using %s algorithm with steps: %d seed: %d' % (self.algorithm_name, steps, seed))

        results = self._algorithm.evolve(population)
        self._internal_problem.finalize()
        return results
Example #4
0
def _create_algorithm(algo_name, algo_options, origin):
    """Create a pygmo algorithm.

    Todo:
        - Pass the algo options through

    """
    if origin == "nlopt":
        algo = pg.algorithm(pg.nlopt(solver=algo_name))
    elif origin == "pygmo":
        pygmo_uda = getattr(pg, algo_name)
        algo = pg.algorithm(pygmo_uda())

    return algo
Example #5
0
def _create_algorithm(algo_name, algo_options, origin):
    """Create a pygmo algorithm."""
    if origin == "nlopt":
        algo = pg.algorithm(pg.nlopt(solver=algo_name))
        for option, val in algo_options.items():
            setattr(algo.extract(pg.nlopt), option, val)
    elif origin == "pygmo":
        pygmo_uda = getattr(pg, algo_name)
        algo_options = algo_options.copy()
        if "popsize" in algo_options:
            del algo_options["popsize"]
        algo = pg.algorithm(pygmo_uda(**algo_options))

    return algo
Example #6
0
def run_island(island):
    import pygmo as pg
    from multiprocessing import cpu_count
    from pymemcache.client.base import Client
    mc_client = Client((island.mc_host, island.mc_port))
    #udp = island.problem_factory()

    algorithm = pg.algorithm(pg.de())
    #problem = pg.problem(udp)
    problem = island.problem_factory()
    # TODO: configure pop size
    i = pg.island(algo=algorithm, prob=problem, size=20)

    mc_client.set(island.domain_qualifier('island', str(island.id), 'status'),
                  'Running', 10000)
    mc_client.set(island.domain_qualifier('island', str(island.id), 'n_cores'),
                  str(cpu_count()), 10000)
    #print('Starting island {} with {} cpus'.format(str(i.id), str(cpu_count())))

    i.evolve()
    i.wait()

    import socket
    hostname = socket.gethostname()
    ip = [
        l for l in ([
            ip for ip in socket.gethostbyname_ex(socket.gethostname())[2]
            if not ip.startswith("127.")
        ][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close())
                 for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]
                 ][0][1]]) if l
    ][0][0]
    return (ip, hostname, i.get_population().problem.get_fevals())
Example #7
0
 def run(self):
     algo = pg.algorithm(pg.pso(gen=self.generation))
     pop = pg.population(self.problem, self.pop_size)
     print("Start optimisation process...")
     pop = algo.evolve(pop)
     self.champion = pop.champion_x
     return pop.champion_f, pop.champion_x
    def solve(self, otol=1e-5, zguess=None, seperate=False):

        if seperate:
            self.segments = self.pool.map(lambda seg: seg.solve(),
                                          self.segments)
            #[seg.solve() for seg in self.segments]

        else:
            # set optimisation params
            self.otol = otol

            # instantiate optimisation problem
            prob = pg.problem(self)

            # instantiate algorithm
            algo = pg.ipopt()
            algo.set_numeric_option("tol", self.otol)
            algo = pg.algorithm(algo)
            algo.set_verbosity(1)

            # instantiate and evolve population
            if zguess is None:
                pop = pg.population(prob, 1)
            else:
                pop = pg.population(prob, 0)
                pop.push_back(zguess)
            pop = algo.evolve(pop)

            # extract soltution
            self.zopt = pop.champion_x
            self.fitness(self.zopt)

        # combine records
        self.process_records()
Example #9
0
def run_benchmark(cp, x_train, y_train, funset):
    ib, params, bounds = define_cgp_system(
        cp.getint('CGPPARAMS', 'n_nodes'),
        x_train.shape[1] if len(x_train.shape) > 1 else 1,
        y_train.shape[1] if len(y_train.shape) > 1 else 1, funset,
        cp.getint('CGPPARAMS', 'max_back'))
    cf = cost_function(x_train, y_train, params, bounds)
    prob = pg.problem(cf)

    algo = pg.algorithm(
        pg.simulated_annealing(Ts=cp.getfloat('OPTIMPARAMS', 'Ts'),
                               Tf=cp.getfloat('OPTIMPARAMS', 'Tf'),
                               n_T_adj=cp.getint('OPTIMPARAMS', 'n_T_adj'),
                               n_range_adj=cp.getint('OPTIMPARAMS',
                                                     'n_range_adj'),
                               bin_size=cp.getint('OPTIMPARAMS', 'bin_size'),
                               start_range=cp.getfloat('OPTIMPARAMS',
                                                       'start_range')))

    algo.set_verbosity(100)
    pop = pg.population(prob, 1)
    pop = algo.evolve(pop)
    uda = algo.extract(pg.simulated_annealing)

    return [x[2] for x in uda.get_log()]
Example #10
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
Example #11
0
 def runTest(self):
     from dcgpy import symbolic_regression, generate_koza_quintic, kernel_set_double, gd4cgp
     import pygmo as pg
     import pickle
     X, Y = generate_koza_quintic()
     # Interface for the UDPs
     udp = symbolic_regression(points=X,
                               labels=Y,
                               rows=1,
                               cols=20,
                               levels_back=21,
                               arity=2,
                               kernels=kernel_set_double(
                                   ["sum", "diff", "mul", "pdiv"])(),
                               n_eph=2,
                               multi_objective=False,
                               parallel_batches=0)
     prob = pg.problem(udp)
     pop = pg.population(prob, 10)
     # Interface for the UDAs
     uda = gd4cgp(max_iter=10, lr=0.1, lr_min=1e-6)
     algo = pg.algorithm(uda)
     algo.set_verbosity(0)
     # Testing some evolutions
     pop = algo.evolve(pop)
     # In parallel
     archi = pg.archipelago(prob=prob, algo=algo, n=16, pop_size=4)
     archi.evolve()
     archi.wait_check()
     # Pickling.
     self.assertTrue(repr(algo) == repr(pickle.loads(pickle.dumps(algo))))
Example #12
0
def run_example4():
    import pygmo as pg
    from pykep.examples import add_gradient, algo_factory

    N = 20

    # problem
    udp = add_gradient(mga_lt_earth_mars_sundmann(nseg=N), with_grad=False)
    prob = pg.problem(udp)
    prob.c_tol = [1e-5] * prob.get_nc()

    # algorithm
    uda = algo_factory("snopt7", False)
    uda2 = pg.mbh(uda, 5, 0.05)
    algo = pg.algorithm(uda2)
    algo.set_verbosity(1)

    # 3 - Population
    pop = pg.population(prob, 1)

    # 4 - Solve the problem (evolve)
    print("Running Monotonic Basin Hopping ....")
    pop = algo.evolve(pop)

    print("Is the solution found a feasible trajectory? " +
          str(prob.feasibility_x(pop.champion_x)))
    udp.udp_inner.plot(pop.champion_x)
Example #13
0
def optimize(results, dir):
    pg.mp_bfe.init_pool(50)
    prob = pg.problem(MotGunOptimizationProblem(dir))
    bfe = pg.bfe(pg.mp_bfe())
    nsga2 = pg.nsga2()
    nsga2.set_bfe(bfe)
    algo = pg.algorithm(nsga2)
    pop = pg.population(prob=prob, size=256, b=bfe)
    iteration = 1
    while True:
        print(f"\033[31mITERATION: {iteration}\033[m")
        plt.title(f'Iteration {iteration}')
        plt.xlabel('Emittance (nm)')
        plt.ylabel('Charge (fC)')
        pg.plot_non_dominated_fronts(pop.get_f())
        plt.savefig(results / f'{iteration}.png', dpi=300)
        plt.clf()
        assert len(pop.get_x()) == len(pop.get_f())
        with open(results / f'iteration_{iteration}.txt', 'w+') as f:
            f.write(
                '[Mot Z Offset (mm), Phase (deg)] -> [Emittance 4D sqrt (nm), Charge (fC)]\n'
            )
            for i in range(len(pop.get_x())):
                f.write('{} -> {}\n'.format(pop.get_x()[i], pop.get_f()[i]))
        pop = algo.evolve(pop)
        iteration += 1
    def run(self):

        self.algo = pg.algorithm(
            pg.pso(gen=self.param['gen'],
                   eta1=self.param['eta1'],
                   eta2=self.param['eta2']))
        self.algo.set_verbosity(1)

        for i in range(self.param['sessions']):

            print("\n" + str(i + 1) + " out of " +
                  str(self.param['sessions']) + " started. \n")

            self.algo.set_seed(randint(0, 1000))

            self.pop = pg.population(self.problem,
                                     size=self.param['pop_size'],
                                     seed=randint(0, 1000))
            self.pop = self.algo.evolve(self.pop)

            self.process_results()
            self.save_results()

            print(self.pop)
            print("\n" + str(i + 1) + " out of " +
                  str(self.param['sessions']) + " saved.")
Example #15
0
def run_example3():
    import pygmo as pg
    from pykep.examples import add_gradient, algo_factory

    # problem
    udp = add_gradient(mga_lt_EVMe(), with_grad=False)
    prob = pg.problem(udp)
    prob.c_tol = [1e-5] * prob.get_nc()

    # algorithm
    uda = algo_factory("snopt7", False)
    uda2 = pg.mbh(uda, 5, 0.05)
    algo = pg.algorithm(uda2)
    algo.set_verbosity(1)

    # 3 - Population
    pop = pg.population(prob, 1)

    # 4 - Solve the problem (evolve)
    print("Running Monotonic Basin Hopping ....")
    pop = algo.evolve(pop)

    print("Is the solution found a feasible trajectory? " +
          str(prob.feasibility_x(pop.champion_x)))
    udp.udp_inner.plot(pop.champion_x)
Example #16
0
def run_benchmark_coevolution(cp, x_train, y_train, funset):
    ib, params, bounds = define_cgp_system(
        cp.getint('CGPPARAMS', 'n_nodes'),
        x_train.shape[1] if len(x_train.shape) > 1 else 1,
        y_train.shape[1] if len(y_train.shape) > 1 else 1, funset,
        cp.getint('CGPPARAMS', 'max_back'))

    # setup the coevolution elements
    ts = TrainersSet(ib, 16, fitness_function, x_train, y_train)
    predictors = GaPredictors(x_train, y_train, 10, 24)
    predictors.evaluate_fitness(ts)
    x_reduced, y_reduced = predictors.best_predictors_data()

    GENS_STEP = 50

    cf = cost_function(x_reduced, y_reduced, params, bounds)
    prob = pg.problem(cf)
    algo = pg.algorithm(
        pg.pso(gen=GENS_STEP,
               omega=cp.getfloat('OPTIMPARAMS', 'omega'),
               eta1=cp.getfloat('OPTIMPARAMS', 'eta1'),
               eta2=cp.getfloat('OPTIMPARAMS', 'eta2'),
               memory=True))
    algo.set_verbosity(1)
    pop = pg.population(prob, cp.getint('DEFAULT', 'population_size'))
    n_gens = GENS_STEP

    while n_gens < 500:

        pop = algo.evolve(pop)

        # calculate exact fitness of champion and
        # add it to the trainers set
        champion = NPIndividual(pop.champion_x, cf.bounds, cf.params)
        try:
            champion.fitness = fitness_function(champion, x_train, y_train)
            ts.add_trainer(champion)
        except ValueError:
            print('unsuccessful adding of champion')

        # update random population
        ts.update_random_population()

        predictors.predictors_evolution_step(ts)
        print('changing the subset, best predictor: ',
              predictors.best_predictor.fitness)

        x_reduced, y_reduced = predictors.best_predictors_data()
        pop.problem.extract(object).X = x_reduced
        pop.problem.extract(object).Y = y_reduced
        n_gens += GENS_STEP

    uda = algo.extract(pg.pso)

    champion = NPIndividual(pop.champion_x, cf.bounds, cf.params)
    champion.fitness = fitness_function(champion, x_train, y_train)

    fitnesses = [x[2] for x in uda.get_log()]
    fitnesses.append(champion.fitness)
    return fitnesses
Example #17
0
def _create_algorithm(algo_name, algo_options, origin):
    """Create a pygmo algorithm.

    Todo:
        - Pass the algo options through

    """
    if origin == "nlopt":
        algo = pg.algorithm(pg.nlopt(solver=algo_name))
        for option, val in algo_options.items():
            setattr(algo.extract(pg.nlopt), option, val)
    elif origin == "pygmo":
        pygmo_uda = getattr(pg, algo_name)
        algo = pg.algorithm(pygmo_uda(**algo_options))

    return algo
Example #18
0
def run(dataset_train, dataset_test, cols, gen):
    ss = dcgpy.kernel_set_double([
        "sum", "diff", "mul", "pdiv", "sin", "cos", "tanh", "log", "exp",
        "psqrt"
    ])

    Xtrain, ytrain = dataset_train[:, :-1], dataset_train[:, -1]
    Xtest, ytest = dataset_test[:, :-1], dataset_test[:, -1]

    udp = dcgpy.symbolic_regression(points=Xtrain,
                                    labels=ytrain[:, np.newaxis],
                                    kernels=ss(),
                                    rows=1,
                                    cols=cols,
                                    levels_back=21,
                                    arity=2,
                                    n_eph=3,
                                    multi_objective=False,
                                    parallel_batches=0)

    uda = dcgpy.es4cgp(gen=gen)  #, mut_n = 1)

    algo = pg.algorithm(uda)
    pop = pg.population(udp, 4)
    pop = algo.evolve(pop)

    return RMSE(udp.predict(Xtrain, pop.champion_x),
                ytrain), RMSE(udp.predict(Xtest, pop.champion_x), ytest)
Example #19
0
def main():

    # instantiate dynamics
    dyn = Dynamics()

    # instantiate leg
    leg = Leg(dyn, alpha=0, bound=True)

    # set boudaries
    t0 = 0
    s0 = np.array([1000, 1000, *np.random.randn(4)], dtype=float)
    l0 = np.random.randn(len(s0))
    tf = 1000
    sf = np.zeros(len(s0))
    leg.set(t0, s0, l0, tf, sf)

    # define problem
    udp = Problem(leg, atol=1e-8, rtol=1e-8)
    prob = pg.problem(udp)

    # instantiate algorithm
    uda = pg7.snopt7(True, "/usr/lib/libsnopt7_c.so")
    uda.set_integer_option("Major iterations limit", 4000)
    uda.set_integer_option("Iterations limit", 40000)
    uda.set_numeric_option("Major optimality tolerance", 1e-2)
    uda.set_numeric_option("Major feasibility tolerance", 1e-4)
    algo = pg.algorithm(uda)

    # instantiate population with one chromosome
    pop = pg.population(prob, 1)
    #pop = pg.population(prob, 0)
    #pop.push_back([1000, *l0])

    # optimise
    pop = algo.evolve(pop)
Example #20
0
def test2():
    mma = pg.algorithm(pg.nlopt("mma"))
    p_toy = pg.problem(toy_problem_2())
    archi = pg.archipelago(n=6, algo=mma, prob=p_toy, pop_size=1)
    archi.evolve()
    archi.wait_check()
    print("end of test2")
Example #21
0
    def _fit_impl(self, objective, parameters):
        ndim = len(parameters.infos())
        minimums = ndim * [-np.inf]
        maximums = ndim * [+np.inf]
        initials = np.empty((ndim, self._size))
        #   for i, pinfo in enumerate(parameters.infos().values()):
        for i, name in enumerate(parameters.names()):
            pinfo = parameters.infos()[name]
            minimum = pinfo.minimum()
            maximum = pinfo.maximum()
            value = pinfo.initial_value()
            scale = pinfo.initial_scale()
            has_init = pinfo.has_initial()
            init_min = value - 0.5 * scale if has_init else minimum
            init_max = value + 0.5 * scale if has_init else maximum
            init_min = max(init_min, minimum)
            init_max = min(init_max, maximum)
            initials[i, :] = random.uniform(init_min, init_max, self._size)
            minimums[i] = minimum
            maximums[i] = maximum

    #   print(parameters.names())
    #exit()
        prb = pg.problem(Problem(objective, parameters, minimums, maximums))
        alg = pg.algorithm(self._setup_algorithm(parameters))
        alg.set_verbosity(self._verbosity)
        pop = pg.population(prb, size=self._size, seed=self._seed)
        for i in range(self._size):
            pop.set_x(i, initials[:, i])
        pop = alg.evolve(pop)
        solution = dict(mode=pop.champion_x)
        result = make_fitter_result(objective, parameters, solutions=solution)
        return result
def solver(dimension, lower_bound, upper_bound, optim, bias, popsize):
    global algo
    global pop
    global niter
    global log
    global curve
    prob = pg.problem(
        rastrigin_prob(dimension, lower_bound, upper_bound, optim, bias))
    algo = pg.algorithm(
        pg.sga(gen=2000,
               cr=0.9,
               eta_c=2.0,
               m=0.02,
               param_m=1.0,
               param_s=2,
               crossover='binomial',
               mutation='gaussian',
               selection='truncated'))
    algo.set_verbosity(1)
    pop = pg.population(prob, popsize)
    pop = algo.evolve(pop)
    log = algo.extract(pg.sga).get_log()
    curve = [x[2] for x in log]
    niter = log[-1][0]
    return prob, algo, pop, log, niter, curve
Example #23
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 = 8
    # 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.nsga2(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()

    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(vectors[sol][counter])}
        counter += 1
    # Save output
    jsonfile.save(outputfile)
def genetic_algorithm(explr_p):
    prob = pg.problem(GeneticAlgoProblem())
    #sade = pg.sade(gen=1, ftol=1e-20, xtol=1e-20)
    population_size = 5

    if obj_fcn == 'griewank' or dim_x == 3:
        total_evals = 500
    elif obj_fcn == 'shekel' and dim_x == 20:
        total_evals = 5000
    else:
        total_evals = 1000
    generations = total_evals / population_size
    optimizer = pg.cmaes(gen=generations, ftol=1e-20, xtol=1e-20)
    algo = pg.algorithm(optimizer)
    algo.set_verbosity(1)
    pop = pg.population(prob, size=population_size)
    pop = algo.evolve(pop)
    print pop.champion_f
    champion_x = pop.champion_x
    uda = algo.extract(pg.cmaes)
    log = np.array(uda.get_log())
    n_fcn_evals = log[:, 1]
    pop_best_at_generation = -log[:, 2]
    evaled_x = None
    evaled_y = pop_best_at_generation

    max_y = [pop_best_at_generation[0]]
    for y in pop_best_at_generation[1:]:
        if y > max_y[-1]:
            max_y.append(y)
        else:
            max_y.append(max_y[-1])

    return evaled_x, evaled_y, max_y, 0
Example #25
0
def nsga2(ppn):
    print('*** NSGA-II ALGORITHM ***')

    # INSTANCIATE A PYGMO PROBLEM CONSTRUCTING IT FROM A UDP
    inittime = perf_counter()
    prob = pg.problem(PPNOProblem(ppn))
    generations = trials = nochanges = 0
    best_f = best_x = None

    # INSTANCIATE THE PYGMO ALGORITM NSGA-II
    algo = pg.algorithm(pg.nsga2(gen=GENERATIONS_PER_TRIAL))

    # INSTANCIATE A POPULATION
    pop = pg.population(prob, size=POPULATION_SIZE)
    while True:

        # RUN THE EVOLUION
        pop = algo.evolve(pop)
        trials += 1
        generations += GENERATIONS_PER_TRIAL

        # EXTRACT RESULTS AND SEARCH THE BEST
        fits, vectors = pop.get_f(), pop.get_x()
        new_f = new_x = None
        for fit, vector in zip(fits, vectors):

            # VALID SOLUTION
            if fit[1] <= 0:
                if isinstance(new_f, type(None)):
                    new_f = fit
                    new_x = vector
                elif new_f[0] > fit[0]:
                    new_f = fit
                    new_x = vector
        if not isinstance(new_f, type(None)):
            if isinstance(best_f, type(None)):
                best_f = new_f
                best_x = new_x
            else:
                if best_f[0] > new_f[0]:
                    best_f = new_f
                    best_x = new_x
                    nochanges = 0
                else:
                    nochanges += 1
        if not isinstance(best_f, type(None)):
            print('Generations: %i ' % (generations), end='')
            print('Cost: %.2f Pressure deficit: %0.3f ' %
                  (best_f[0], best_f[1]))
        if (perf_counter() - inittime) >= MAX_TIME:
            print('Maximum evolution time was reached.')
            break
        elif trials >= MAX_TRIALS:
            print('Maximum number of trials was reached.')
            break
        elif nochanges >= MAX_NO_CHANGES:
            print('Objective function value was repeated %i times.' %
                  (nochanges))
            break
    return (best_f, best_x)
Example #26
0
    def solve(self, otol=1e-5):

        # set optimisation params
        self.otol = otol

        # instantiate optimisation problem
        prob = pg.problem(self)

        # instantiate algorithm
        algo = pg.ipopt()
        algo.set_numeric_option("tol", self.otol)
        algo = pg.algorithm(algo)
        algo.set_verbosity(1)

        # instantiate and evolve population
        pop = pg.population(prob, 1)
        pop = algo.evolve(pop)

        # extract soltution
        self.zopt = pop.champion_x
        self.fitness(self.zopt)

        # process records
        self.process_records()

        return self
Example #27
0
def get_equilibrium(nn_controller, random_seed=0, mass=0.38905):
    class controller_equilibrium:
        def __init__(self, nn_controller):
            self.nn_controller = nn_controller

        def fitness(self, state):
            g0 = 9.81
            return [
                np.linalg.norm(
                    self.nn_controller.compute_control(state) -
                    np.array([g0 * mass, 0]))
            ]

        def get_bounds(self):
            return ([-1, 0, -1, 0, 0], [1, 0, 1, 0, 0])

    # optimisation parameters
    # increase if necessary to ensure convergence
    n_generations = 700
    n_individuals = 100

    prob = pygmo.problem(controller_equilibrium(nn_controller))
    algo = pygmo.algorithm(
        pygmo.de(gen=n_generations, tol=0, ftol=0, seed=random_seed))

    pop = pygmo.population(prob, size=n_individuals, seed=random_seed)
    pop.push_back([0, 0, 0, 0, 0])
    algo.set_verbosity(100)
    pop = algo.evolve(pop)

    return pop.champion_x
def sade(problem, population_size, params):
    '''
    Execute the Pygmo SADE algorithm on an
    optimisation problem with the population size
    and parameters specified. The SADE possible
    set of parameters are:
    * variant: mutation variant:
            1  -> best/1/exp            10 -> rand/2/bin
            2  -> rand/1/exp            11 -> rand/3/exp
            3  -> rand-to-best/1/exp    12 -> rand/3/bin
            4  -> best/2/exp            13 -> best/3/exp
            5  -> rand/2/exp            14 -> best/3/bin
            6  -> best/1/bin            15 -> rand-to-current/2/exp
            7  -> rand/1/bin            16 -> rand-to-current/2/bin
            8  -> rand-to-best/1/bin    17 -> rand-to-best-and-current/2/exp
            9  -> best/2/bin            18 -> rand-to-best-and-current/2/bin
    * variant_adptv: scale factor F and crossover rate CR
        adaptation scheme to be used
    * ftol: stopping criteria on the function tolerance
    * xtol: stopping criteria on the step tolerance

    Parameters
    ----------
    - problem: the problem to optimise. It must comply
        to the Pygmo requirements, i.e. being an
        instance of an UDP class
    - population_size: The size of the population
    - params: dictionnary of parameters for the
        SADE algorithm

    Return
    ------
    - log: the logs of the execution of the
        optimisation problem with the population size
    - duration: the total duration of the resolution
        of the  problem
    '''
    # Extract algorithm parameters
    nb_generation = params["nb_generation"]
    variant = params["variant"]
    variant_adptv = params["variant_adptv"]
    ftol = params["ftol"]
    xtol = params["xtol"]

    algo = pg.algorithm(
        pg.sade(gen=nb_generation,
                variant=variant,
                variant_adptv=variant_adptv,
                ftol=ftol,
                xtol=xtol))
    algo.set_verbosity(1)
    solution = pg.population(problem, size=population_size, b=None)
    startt = datetime.now()
    solution = algo.evolve(solution)
    duration = (datetime.now() - startt)
    uda = algo.extract(pg.sade)
    log = uda.get_log()

    return (log, duration, solution.champion_f, solution.champion_x)
Example #29
0
def optimize_pagmo():
    solo_mgar = solo_mgar_udp([7000, 8000])
    for i in range(6000):
        prob = pg.problem(solo_mgar)
        pop = pg.population(prob=prob, size=32)
        alg = pg.algorithm(pg.sade(memory=True, gen=1))
        pop = alg.evolve(pop)
        print(i, pop.champion_f, solo_mgar.fitness(pop.champion_x))
Example #30
0
def method_a():
    algo = pg.algorithm(uda=pg.nlopt('auglag'))
    algo.extract(pg.nlopt).local_optimizer = pg.nlopt('var2')
    algo.set_verbosity(
        200)  # in this case this correspond to logs each 200 objevals
    pop = pg.population(prob=UdpConstrained(), size=1)
    pop.problem.c_tol = [1E-6] * 6
    pop = algo.evolve(pop)
Example #31
0
def method_b():
    algo = pg.algorithm(uda=pg.mbh(pg.nlopt("slsqp"), stop=20, perturb=.2))
    print(algo)
    algo.set_verbosity(
        1)  # in this case this correspond to logs each 1 call to slsqp
    pop = pg.population(prob=UdpConstrained(), size=1)
    pop.problem.c_tol = [1E-6] * 6
    pop = algo.evolve(pop)
def user_defined_problem():
    prob = pg.problem(sphere_function(3))
    print(prob)

    algo = pg.algorithm(pg.bee_colony(gen = 200, limit = 20))
    pop = pg.population(prob, 10)
    pop = algo.evolve(pop)
    print(pop.champion_f)
    print(pop)
Example #33
0
def test_pagmo(joint_likelihood_bn090217206_nai):

    pagmo = GlobalMinimization("PAGMO")
    minuit = LocalMinimization("minuit")

    algo = pygmo.algorithm(pygmo.bee_colony(gen=100))

    pagmo.setup(islands=4, population_size=20, evolution_cycles=1, second_minimization=minuit, algorithm=algo)

    do_analysis(joint_likelihood_bn090217206_nai, pagmo)
Example #34
0
def algo_factory(name, original_screen_output=True):
    if name is "slsqp":
        uda = pg.nlopt('slsqp')
        uda.xtol_rel = 1e-5
        uda.ftol_rel = 0
        algo = pg.algorithm(uda)
        algo.set_verbosity(1)
        return algo
    elif name is "ipopt":
        if original_screen_output:
            pl = 5
        else:
            pl = 0
        uda = pg.ipopt()
        uda.set_integer_option("print_level", pl)
        uda.set_integer_option("acceptable_iter", 4)
        uda.set_integer_option("max_iter", 150)

        uda.set_numeric_option("tol", 1e-8)
        uda.set_numeric_option("dual_inf_tol", 1e-8)
        uda.set_numeric_option("constr_viol_tol", 1e-8)
        uda.set_numeric_option("compl_inf_tol", 1e-8)

        uda.set_numeric_option("acceptable_tol", 1e-3)
        uda.set_numeric_option("acceptable_dual_inf_tol", 1e-2)
        uda.set_numeric_option("acceptable_constr_viol_tol", 1e-6)
        uda.set_numeric_option("acceptable_compl_inf_tol", 1e-6)

        algo = pg.algorithm(uda)
        return algo
    elif name is "snopt7":
        import pygmo_plugins_nonfree as pg7
        uda = pg7.snopt7(original_screen_output,
                         "/usr/local/lib/libsnopt7_c.so")
        uda.set_integer_option("Major iterations limit", 2000)
        uda.set_integer_option("Iterations limit", 200000)
        uda.set_numeric_option("Major optimality tolerance", 1e-2)
        uda.set_numeric_option("Major feasibility tolerance", 1e-9)

        algo = pg.algorithm(uda)
        return algo
def quick_start_demo():
    # 1 - Instantiate a pygmo problem constructing it from a UDP
    # (user defined problem).
    prob = pg.problem(pg.schwefel(30))

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

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

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

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

    # 6 - Print the fitness of the best solution in each island
    res = [isl.get_population().champion_f for isl in archi]
    print(res)
Example #36
0
    udp = mga(seq=seq,
              t0=[-1000., 0.],
              tof=[[30, 400], [100, 470], [30, 400], [400, 2000], [1000, 6000]],
              vinf=3.,
              tof_encoding='direct',
              orbit_insertion=True,
              e_target=0.98,
              rp_target=108950000)

    udp = mga(seq=seq,
              t0=[-1000., 0.],
              tof=7000.,
              vinf=3.,
              tof_encoding='eta',
              orbit_insertion=True,
              e_target=0.98,
              rp_target=108950000)

    #udp = mga(seq=seq, t0=[-1000., 0.], tof=[[130,200], [430,470], [30, 70], [900, 1200], [4000, 5000]], vinf=0., alpha_encoding=False)
    prob = pg.problem(udp)
    uda = pg.cmaes(1500, force_bounds=True, sigma0=0.5, ftol=1e-4)
    #uda = pg.sade(4500)
    algo = pg.algorithm(uda)
    algo.set_verbosity(10)
    res = list()
    # for i in range(100):
    pop = pg.population(prob, 100)
    pop = algo.evolve(pop)
    res.append(pop.champion_f)