コード例 #1
0
ファイル: _ex5.py プロジェクト: darioizzo/pykep
def run_example5():
    import pygmo as pg
    from pykep import epoch
    from pykep.planet import jpl_lp
    from pykep.trajopt import mga_1dsm

    # We define an Earth-Venus-Earth problem (single-objective)
    seq = [jpl_lp('earth'), jpl_lp('venus'), jpl_lp('earth')]
    udp = mga_1dsm(
        seq=seq,
        t0=[epoch(5844), epoch(6209)],
        tof=[0.7 * 365.25, 3 * 365.25],
        vinf=[0.5, 2.5],
        add_vinf_dep=False,
        add_vinf_arr=True,
        multi_objective=False
    )

    pg.problem(udp)
    # We solve it!!
    uda = pg.sade(gen=100)
    archi = pg.archipelago(algo=uda, prob=udp, n=8, pop_size=20)
    print(
        "Running a Self-Adaptive Differential Evolution Algorithm .... on 8 parallel islands")
    archi.evolve(10)
    archi.wait()
    sols = archi.get_champions_f()
    idx = sols.index(min(sols))
    print("Done!! Solutions found are: ", archi.get_champions_f())
    udp.pretty(archi.get_champions_x()[idx])
    udp.plot(archi.get_champions_x()[idx])
コード例 #2
0
def goto_mars():
    # We define an Earth-Mars problem (single-objective)
    seq = [jpl_lp('earth'), jpl_lp('mars')]
    udp = mga_1dsm(seq=seq,
                   t0=[epoch(18 * 365.25 + 1),
                       epoch(25 * 365.25 + 1)],
                   tof=[0.7 * 365.25, 7 * 365.25],
                   vinf=[0.5, 5],
                   add_vinf_dep=False,
                   add_vinf_arr=True,
                   multi_objective=False)

    pg.problem(udp)
    # We solve it!!
    uda = pg.sade(gen=200)
    archi = pg.archipelago(algo=uda, prob=udp, n=8, pop_size=30)
    print(
        "Running a Self-Adaptive Differential Evolution Algorithm .... on 8 parallel islands"
    )
    archi.evolve(10)
    archi.wait()
    sols = archi.get_champions_f()
    idx = sols.index(min(sols))
    print("Done!! Solutions found are: ", archi.get_champions_f())
    print(f"\nThe best solution with Dv = {min(sols)[0]}:\n")
    udp.pretty(archi.get_champions_x()[idx])
    udp.plot(archi.get_champions_x()[idx], savepath="plot.png")
コード例 #3
0
def run_example5():
    import pygmo as pg
    from pykep import epoch
    from pykep.planet import jpl_lp
    from pykep.trajopt import mga_1dsm

    # We define an Earth-Venus-Earth problem (single-objective)
    seq = [jpl_lp('earth'), jpl_lp('venus'), jpl_lp('earth')]
    udp = mga_1dsm(seq=seq,
                   t0=[epoch(5844), epoch(6209)],
                   tof=[0.7 * 365.25, 3 * 365.25],
                   vinf=[0.5, 2.5],
                   add_vinf_dep=False,
                   add_vinf_arr=True,
                   multi_objective=False)

    pg.problem(udp)
    # We solve it!!
    uda = pg.sade(gen=100)
    archi = pg.archipelago(algo=uda, prob=udp, n=8, pop_size=20)
    print(
        "Running a Self-Adaptive Differential Evolution Algorithm .... on 8 parallel islands"
    )
    archi.evolve(10)
    archi.wait()
    sols = archi.get_champions_f()
    idx = sols.index(min(sols))
    print("Done!! Solutions found are: ", archi.get_champions_f())
    udp.pretty(archi.get_champions_x()[idx])
    udp.plot(archi.get_champions_x()[idx])
コード例 #4
0
ファイル: optimization.py プロジェクト: fossabot/D3HRE
    def __init__(self, Task, config={}):

        self.config = config
        self.Task = Task
        self.set_parameters()
        if config != {}:
            self.problem = pg.problem(
                Mixed_objective_optimization_function(Task, self.config))
        else:
            self.problem = pg.problem(
                Mixed_objective_optimization_function(Task))

        self.rea_sim = simulation.Reactive_simulation(self.Task,
                                                      config=self.config)
コード例 #5
0
    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()
コード例 #6
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()]
コード例 #7
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
コード例 #8
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))))
コード例 #9
0
def _test_archipelago(algo, problem, num=10000, stop_val=-1E99, log=logger()):
    udp = pygmo_udp(problem.fun, problem.bounds)
    prob = pg.problem(udp)
    best_y = math.inf
    best_x = None
    t0 = time.perf_counter()

    for _ in range(num):
        archi = pg.archipelago(n=mp.cpu_count(),
                               algo=algo,
                               prob=prob,
                               pop_size=64)
        archi.evolve()
        archi.wait()
        ys = archi.get_champions_f()
        if not ys is None and len(ys) > 0:
            sort = np.argsort([y[0] for y in ys])
            y = ys[sort[0]][0]
            if y < best_y:
                best_y = y
                best_x = archi.get_champions_x()[sort[0]]
                message = '{0} {1} {2} {3!s}'.format(problem.name, dtime(t0),
                                                     best_y, list(best_x))
                log.info(message)
                if best_y < stop_val:
                    break
    return OptimizeResult(x=best_x, fun=best_y, success=True)
コード例 #10
0
def evaluate_vectors_in_csv(csvpath, codec_arg, rate_control_arg):
    print("Evaluating vectors of: " + codec_arg + " " + rate_control_arg)

    cfg.mog_alg = "eval-from-csv"
    cfg.epoch = 0
    cfg.NO_GENERATIONS = 0
    cfg.load_params_from_json(codec_arg, rate_control_arg)
    opt_prob = pyg.problem(sweetspot_problem())
    pop = pyg.population(prob=opt_prob)

    param_sets = []
    with open(csvpath) as csv_file:
        csv_data = csv.reader(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
        for row in csv_data:
            x = row[0]
            x = x.replace('\n', '').replace('[', '').replace(']', '').replace("'", "").replace('"', "")
            x = re.sub('\s+', ',', x.strip())
            x = x.split(",")
            x = [elem for elem in x if elem != ""]
            param_sets.append(x)
    param_sets = np.asfarray(param_sets,float)

    cfg.POP_SIZE = len(param_sets)

    # Evaluate decision vectors
    for i in trange(len(param_sets)):
        pset = param_sets[i]
        pop.push_back(pset)
コード例 #11
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
コード例 #12
0
ファイル: evolution.py プロジェクト: olavosamp/CPC881_MCIN
    def __init__(self, func_id, pop_size=100, dim=10, max_iters=100):
        self.dim = dim
        self.pop_size = pop_size
        self.xMin = -100  # Search space limits
        self.xMax = 100  #
        self.maxIters = max_iters

        self.func_id = func_id
        self.fitnessEvals = 0

        # Original parameters
        self.c1 = 2.0
        self.c2 = 2.0
        self.w = 1.0
        self.wdamp = 1.0

        # Yarpiz default
        # self.c1    = 1.4962
        # self.c2    = 1.4962
        # self.w     = 0.7298
        # self.wdamp = 1.0

        self.problem = pg.problem(
            pg.cec2014(prob_id=self.func_id, dim=self.dim))

        self.psoProblem = {
            'CostFunction': self.get_fitness,
            'nVar': self.dim,
            'xMin': self.
            xMin,  # Alternatively you can use a "numpy array" with nVar elements, instead of scalar
            'xMax': self.
            xMax,  # Alternatively you can use a "numpy array" with nVar elements, instead of scalar
        }
コード例 #13
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")
コード例 #14
0
ファイル: fitter.py プロジェクト: bek0s/gbkfit
    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
コード例 #16
0
def get_solution(func_id=1, dim=10, input_data_filepath=None):
    '''
        func_list: Function id, between 1 and 31.
        dim      : Problem dimensionality

        Returns a solution corresponding the global optima of the function given
        by func_id.
    '''
    import pygmo as pg
    from glob import glob

    # solution = dict()
    if func_id < 23:
        prob = pg.problem(pg.cec2014(prob_id=func_id, dim=dim))
        filepath = dirs.input if input_data_filepath is None else input_data_filepath
        shift_data = np.loadtxt(filepath +
                                "/shift_data_{}.txt".format(func_id))

        # solution[func_id] = prob.fitness(shift_data[:dim])[0]
        solution = prob.fitness(shift_data[:dim])[0]

    if func_id >= 23:
        raise NotImplementedError(
            "f_{:2d} not yet implemented".format(func_id))
        return None
    return solution
コード例 #17
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
コード例 #18
0
def _create_problem(func, bounds, gradient_, dim, batch_evaluator, n_cores):
    class Problem:
        def fitness(self, x):
            return [func(x)]

        def get_bounds(self):
            return bounds

        def gradient(self, dv):
            return gradient_(dv)

        def batch_fitness(self, dvs):
            dv_list = dvs.reshape(-1, dim)
            eval_list = batch_evaluator(
                func=func,
                arguments=dv_list,
                n_cores=n_cores,
                # Error handling is done on a higher level
                error_handling="raise",
            )
            evals = np.array(eval_list)
            return evals

    problem = pg.problem(Problem())
    return problem
コード例 #19
0
ファイル: optimize.py プロジェクト: wanghaopku/dftfit
    def __init__(self, potential, training,
                 dbm=None, db_write_interval=10,                      # database
                 algorithm='pygmo.de', algorithm_kwargs=None,         # algorithm
                 features=None, weights=None, problem_kwargs=None,    # problem
                 run_id=None):

        self.algorithm_name = algorithm
        if self.algorithm_name not in available_algorithms:
            raise ValueError(f'algorithm {self.algorithm_name} not available')

        _problem_kwargs = {
            'potential': potential,
            'training': training,
            'dbm': dbm, 'db_write_interval': db_write_interval,
            'features': features, 'weights': weights,
            'run_id': run_id,
            **problem_kwargs
        }
        if available_algorithms[self.algorithm_name][1] == 'S':
            internal_problem = DFTFITSingleProblem(**_problem_kwargs)
        else:
            internal_problem = DFTFITMultiProblem(**_problem_kwargs)
        self._internal_problem = internal_problem
        self._problem = pygmo.problem(internal_problem)
        self.algorithm_kwargs = algorithm_kwargs or {}
コード例 #20
0
ファイル: test.py プロジェクト: bluescarni/dcgp
 def runTest(self):
     from dcgpy import symbolic_regression, generate_koza_quintic, kernel_set_double
     import pygmo as pg
     X, Y = generate_koza_quintic()
     udp = symbolic_regression(points=X,
                               labels=Y,
                               rows=1,
                               cols=20,
                               levels_back=21,
                               arity=2,
                               kernels=kernel_set_double(["sum", "diff"])(),
                               n_eph=2,
                               multi_objective=False,
                               parallel_batches=0)
     prob = pg.problem(udp)
     pop = pg.population(prob, 10)
     udp.pretty(pop.champion_x)
     udp.prettier(pop.champion_x)
     # Unconstrained
     self.assertEqual(prob.get_nc(), 0)
     self.assertEqual(prob.get_nic(), 0)
     # Single objective
     self.assertEqual(prob.get_nobj(), 1)
     # Dimensions
     self.assertEqual(prob.get_nix(), 20 * (2 + 1) + 1)
     self.assertEqual(prob.get_nx(), 2 + prob.get_nix())
     # Has gradient and hessians
     self.assertEqual(prob.has_gradient(), True)
     self.assertEqual(prob.has_hessians(), True)
コード例 #21
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)
コード例 #22
0
ファイル: evolution.py プロジェクト: olavosamp/CPC881_MCIN
    def __init__(self, dim=2, func_id=1, pop_size=20):
        self.dim = dim  # Problem dimensionality
        self.xMin = -100  # Search space limits
        self.xMax = 100  #
        self.pop_size = pop_size  # Population size
        self.func_id = func_id
        self.fitnessEvals = 0  # Initial fitness evaluations

        # Algorithm parameters
        self.minSigma = 0.0001
        self.tau1 = 4 * 1 / (np.sqrt(2 * self.pop_size))
        self.tau2 = 4 * 1 / (np.sqrt(2 * np.sqrt(self.pop_size)))
        self.mutateProb = 1.0
        self.numTourneyPlays = 10

        # Fitness Function definition
        if self.func_id < 23:
            self.problem = pg.problem(
                pg.cec2014(prob_id=self.func_id, dim=self.dim))
        else:
            raise ValueError("f_{:2d} not yet implemented".format(
                self.func_id))
            return -1

        # Initialize population DataFrame and compute initial Fitness
        self.init_states()
コード例 #23
0
ファイル: pygmo_rocketry.py プロジェクト: gandalfsaxe/letomes
def pygmo_es():
    ARCHIPELAGO = True
    iterations = 10

    uda = salimans_nes(iter=iterations)  # user defined algorithm
    udp = saddle_space()  # user defined problem
    prob = pg.problem(udp)  # Beautiful white snow

    if ARCHIPELAGO:
        archi = pg.archipelago(algo=uda, prob=prob, n=1, pop_size=4)
        archi.evolve()
        #         print(archi) # prints description of islands contained in archipelago
        #         archi.wait()
        sols = archi.get_champions_f()
        idx = sols.index(min(sols))
        sols_x = archi.get_champions_x()
        sol = sols[idx], sols_x[idx]
    else:
        pop = pg.population(prob=prob, size=4)
        pop.set_x(0,
                  [-2.277654673852600, 0.047996554429844, 3.810000000000000])
        pop.set_x(1,
                  [-0.138042744751570, -0.144259374836607, 3.127288444444444])
        pop.set_x(2,
                  [-2.086814820119193, -0.000122173047640, 3.111181716545691])
        uda.evolve(pop)
        sol = (pop.champion_f, pop.champion_x)

    print("Done! best solution is:")
    print(sol)
    return sol
コード例 #24
0
ファイル: evolution.py プロジェクト: olavosamp/CPC881_MCIN
    def __init__(self, func_id, pop_size=100, dim=10, max_iters=100):
        self.dim = dim
        self.pop_size = pop_size
        self.xMin = -100  # Search space limits
        self.xMax = 100  #
        self.vMin = self.xMin / 2  # Velocity limits
        self.vMax = self.xMax / 2  #

        self.func_id = func_id
        self.fitnessEvals = 0

        # # Debug
        # self.c1    = 1.0
        # self.c2    = 1.0
        # self.w     = 1.0
        # self.wdamp = 1.0

        # GOPSO default
        self.c1 = 1.49618
        self.c2 = 1.49618
        self.w = 0.72984
        self.wdamp = 1.0

        self.problem = pg.problem(
            pg.cec2014(prob_id=self.func_id, dim=self.dim))

        self.init_states()
コード例 #25
0
ファイル: _ex4.py プロジェクト: darioizzo/pykep
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)
コード例 #26
0
def check_good_solution(x):
    solo_mgar = solo_mgar_udp([7000, 8000])
    prob = pg.problem(solo_mgar)
    print(str(prob.fitness(x)))
    solo_mgar.pretty(x)
    solo_mgar.plot(x)
    solo_mgar.plot_distance_and_flybys(x)
コード例 #27
0
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
コード例 #28
0
ファイル: gaoptimizer.py プロジェクト: andresgciamtez/ppno
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)
コード例 #29
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
コード例 #30
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)
コード例 #31
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)
コード例 #32
0
def optimize():
    fprob = single_objective(pg.problem(udp))
    print('interferometer optimization')

    # Python Differential Evolution implementation, uses ask/tell for parallel function evaluation.
    ret = de.minimize(fprob.fun,
                      bounds=fprob.bounds,
                      workers=16,
                      popsize=32,
                      max_evaluations=50000)

    # Python CMAES implementation, uses ask/tell for parallel function evaluation.
    #ret = cmaes.minimize(fprob.fun, bounds=fprob.bounds, workers=16, popsize=32, max_evaluations=50000)

    # Parallel retry using DE
    #ret = retry.minimize(fprob.fun, bounds=fprob.bounds, optimizer=De_cpp(20000, popsize=32), workers=16, num_retries=64)

    # Parallel retry using Bite
    # ret = retry.minimize(fprob.fun, bounds=fprob.bounds, optimizer=Bite_cpp(20000, M=1), workers=16, num_retries=64)

    # Parallel retry using CMA-ES
    #ret = retry.minimize(udp.fitness, bounds=bounds, optimizer=Cma_cpp(20000, popsize=32), workers=16, num_retries=64)

    # Smart retry using DE
    #ret = advretry.minimize(fprob.fun, bounds=fprob.bounds, optimizer=De_cpp(1500, popsize=32), workers=16)

    # Smart retry using CMA-ES
    #ret = advretry.minimize(fprob.fun, bounds=fprob.bounds, optimizer=Cma_cpp(1500, popsize=32), workers=16)

    # Smart retry using DE->CMA sequence
    #ret = advretry.minimize(fprob.fun, bounds=fprob.bounds, optimizer=de_cma(1500, popsize=32), workers=16)

    print("best result is " + str(ret.fun) + ' x = ' +
          ", ".join(str(x) for x in ret.x))
コード例 #33
0
ファイル: _ex11.py プロジェクト: darioizzo/pykep
def run_example11(n_seg=30):
    """
    This example demonstrates the use of the class lt_margo developed for the internal ESA CDF study on the 
    interplanetary mission named MARGO. The class was used to produce the preliminary traget selection
    for the mission resulting in 88 selected possible targets 
    (http://www.esa.int/spaceinimages/Images/2017/11/Deep-space_CubeSat)
    (http://www.esa.int/gsp/ACT/mad/projects/lt_to_NEA.html)
    """
    import pykep as pk
    import pygmo as pg
    import numpy as np
    from matplotlib import pyplot as plt
    from pykep.examples import add_gradient, algo_factory

    # 0 - Target asteroid from MPCORB
    mpcorbline = "K14Y00D 24.3   0.15 K1794 105.44160   34.12337  117.64264    1.73560  0.0865962  0.88781021   1.0721510  2 MPO369254   104   1  194 days 0.24 M-v 3Eh MPCALB     2803          2014 YD            20150618"

    # 1 - Algorithm
    algo = algo_factory("snopt7")

    # 2 - Problem
    udp = add_gradient(pk.trajopt.lt_margo(
        target=pk.planet.mpcorb(mpcorbline),
        n_seg=n_seg,
        grid_type="uniform",
        t0=[pk.epoch(8000), pk.epoch(9000)],
        tof=[200, 365.25 * 3],
        m0=20.0,
        Tmax=0.0017,
        Isp=3000.0,
        earth_gravity=False,
        sep=True,
        start="earth"),
        with_grad=False
    )
    prob = pg.problem(udp)
    prob.c_tol = [1e-5] * prob.get_nc()

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

    # 4 - Solve the problem (evolve)
    pop = algo.evolve(pop)

    # 5 - Inspect the solution
    print("Feasible?:", prob.feasibility_x(pop.champion_x))

    # 6 - plot trajectory
    axis = udp.udp_inner.plot_traj(pop.champion_x, plot_segments=True)
    plt.title("The trajectory in the heliocentric frame")

    # 7 - plot control
    udp.udp_inner.plot_dists_thrust(pop.champion_x)

    # 8 - pretty
    udp.udp_inner.pretty(pop.champion_x)

    plt.ion()
    plt.show()
コード例 #34
0
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)
コード例 #35
0
ファイル: _ex8.py プロジェクト: darioizzo/pykep
def run_example8(nseg=40):
    """
    This example demonstrates the direct method (sims-flanagan) on a planet to planet scenario.
    """
    import pykep as pk
    import pygmo as pg
    import numpy as np
    from matplotlib import pyplot as plt
    from pykep.examples import add_gradient, algo_factory

    # 1 - Algorithm
    algo = algo_factory("snopt7")

    # 2 - Problem
    udp = add_gradient(pk.trajopt.direct_pl2pl(
        p0="earth",
        pf="mars",
        mass=1000,
        thrust=0.1,
        isp=3000,
        vinf_arr=1e-6,
        vinf_dep=3.5,
        hf=False,
        nseg=nseg,
        t0=[1100, 1400],
        tof=[200, 750]),
        with_grad=False
    )

    prob = pg.problem(udp)
    prob.c_tol = [1e-5] * prob.get_nc()

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

    # 4 - Solve the problem (evolve)
    pop = algo.evolve(pop)

    # 5 - Inspect the solution
    if prob.feasibility_x(pop.champion_x):
        print("Optimal Found!!")
    else:
        print("No solution found, try again :)")

    udp.udp_inner.pretty(pop.champion_x)

    axis = udp.udp_inner.plot_traj(pop.champion_x)
    plt.title("The trajectory in the heliocentric frame")
    axis = udp.udp_inner.plot_control(pop.champion_x)
    plt.title("The control profile (throttle)")

    plt.ion()
    plt.show()
コード例 #36
0
ファイル: _ex6.py プロジェクト: darioizzo/pykep
def run_example6(n_seg=5):
    """
    This example demonstrates the optimization of a multiple randezvous mission (low-thrust).
    Such a mission (including more asteroids) is also called asteroid hopping

    The spacecraft performances, as well as the three asteroids visited, are taken from the GTOC7 problem description.
    """
    import pygmo as pg
    from pykep.trajopt import mr_lt_nep
    from pykep.planet import gtoc7
    from pykep.examples import add_gradient, algo_factory
    from matplotlib import pyplot as plt

    # If you have no access to snopt7, try slsqp (multiple starts may be
    # necessary)
    algo = algo_factory("snopt7")

    udp = add_gradient(
        mr_lt_nep(
            t0=[9600., 9700.],
            seq=[gtoc7(5318), gtoc7(14254), gtoc7(7422), gtoc7(5028)],
            n_seg=n_seg,
            mass=[800., 2000.],
            leg_tof=[100., 365.25],
            rest=[30., 365.25],
            Tmax=0.3,
            Isp=3000.,
            traj_tof=365.25 * 3.,
            objective='mass',
            c_tol=1e-05
        ),
        with_grad=False)

    prob = pg.problem(udp)
    prob.c_tol = [1e-5] * prob.get_nc()

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

    solution = pop.champion_x
    if prob.feasibility_x(solution):
        print("FEASIBILE!!!")
        ax = udp.udp_inner.plot(solution)
    else:
        print("INFEASIBLE :(")
        ax = None

    plt.ion()
    plt.show()
コード例 #37
0
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)
コード例 #38
0
ファイル: _ex7.py プロジェクト: darioizzo/pykep
def run_example7(solver="snopt7"):
    """
    This example demonstrates the indirect method (cartesian) on a orbit to orbit scenario.
    The orbits are those of Earth and Mars.
    """
    import pykep as pk
    import pygmo as pg
    import numpy as np
    from matplotlib import pyplot as plt
    from pykep.examples import add_gradient, algo_factory

    # Some pre-computed solutions (obtaining spending some iterations and
    # restarts from random initial guesses)
    z_mass_optimal = [397.88267909228767, 2.0719343674552215, 2.7313941033119407, 11.882803539732214, 10.567639551625298,
                      0.50803671389927796, -11.056641527923768, 12.176151455434058, 4.1269457596809245, 3.4434953247725324]
    z_quadratic_control = [381.32031472240106, 1.0102363292172423, 1.8134352964367946, 19.522442569527868, -
                           6.7894353762521105, -3.3749783899165928, 7.0438655057343054, 19.923912672512174, 0.93896446800741751, 3.5483645070393743]
    z_quadratic_control2 = [459.51623108767666, -1.616057488705803, 0.33049652475302532, -17.735981532357027, -
                            3.2374905349904912, 2.2249621531880934, 2.9550456430212937, -20.226761256676323, -2.9684113654904061, 3.1471248891703905]
    z_quadratic_control3 = [519.45371103815569, 0.39617485433378341, 2.7008977766929818, 7.9136210333255468, -
                            11.03747486077437, -3.0776988186969136, 9.1796869310249747, 6.5013311040515687, -0.2054349910826633, 3.0084671211666865]
    # A random initial solution
    z_random = np.hstack(
        [[np.random.uniform(100, 700)], 2 * np.random.randn(9)])

    # We use an initial guess within 10% of a known optima, you can experiment what happens
    # with a different choice
    z = z_quadratic_control + z_quadratic_control * np.random.randn(10) * 0.1
    #z = z_random

    # 1 - Algorithm
    algo = algo_factory(solver)

    # 2 - Problem. We define a minimum quadratic control problem (alpha=0) with free time
    # (hamiltonian will be forced to be 0). We provide the option for estimating the gradient numerically for
    # algorithms that require it.
    udp = add_gradient(pk.trajopt.indirect_or2or(
        elem0=[149598261129.93335, 0.016711230601231957,
               2.640492490927786e-07, 3.141592653589793, 4.938194050401601, 0],
        elemf=[227943822376.03537, 0.09339409892101332,
               0.032283207367640024, 0.8649771996521327, 5.000312830124232, 0],
        mass=1000,
        thrust=0.3,
        isp=2500,
        atol=1e-12,
        rtol=1e-12,
        tof=[100, 700],
        freetime=True,
        alpha=0,
        bound=True,
        mu=pk.MU_SUN),
        with_grad=False)

    prob = pg.problem(udp)
    prob.c_tol = [1e-7] * 10

    # 3 - Population (i.e. initial guess)
    pop = pg.population(prob)
    pop.push_back(z)

    # 4 - Solve the problem (evolve)
    pop = algo.evolve(pop)

    # 5 - Inspect the solution
    if prob.feasibility_x(pop.champion_x):
        print("Optimal Found!!")
        # We call the fitness to set the leg
        udp.udp_inner.fitness(pop.champion_x)
        arr = udp.udp_inner.leg.get_states(1e-12, 1e-12)
        print("Final mass is: ", arr[-1, 7])
    else:
        print("No solution found, try again :)")
    # plot trajectory
    axis = udp.udp_inner.plot_traj(
        pop.champion_x, quiver=True, mark="k", length=1)
    plt.title("The trajectory in the heliocentric frame")

    # plot control
    udp.udp_inner.plot_control(pop.champion_x)
    plt.title("The control profile (throttle)")
    plt.ion()
    plt.show()

    # Show the trajectory data
    udp.udp_inner.pretty(pop.champion_x)
コード例 #39
0
ファイル: _ex_utilities.py プロジェクト: darioizzo/pykep
 def __init__(self, udp, with_grad=False):
     self.udp_inner = udp
     self.prob = pg.problem(udp)
     self.with_grad = with_grad
コード例 #40
0
ファイル: _ex10.py プロジェクト: darioizzo/pykep
def run_example10():
    """
    This example demonstrates the indirect method (cartesian) on a point to point fixed time scenario.
    The boundary conditions are taken from a run of the indirect method.
    """
    import pykep as pk
    import pygmo as pg
    import numpy as np
    from matplotlib import pyplot as plt
    from pykep.examples import add_gradient, algo_factory

    # 1 - Algorithm
    algo = algo_factory("snopt7")

    # 2 - Problem
    udp = add_gradient(pk.trajopt.indirect_pt2pt(
        x0=[44914296854.488266, -145307873786.94177, 1194292.6437741749,
            31252.149474878544, 9873.214642584162, -317.08718075574404, 1000],
        xf=[-30143999066.728119, -218155987244.44385, -3829753551.2279921,
            24917.707565772216, -1235.74045124602, -638.05209482866155, 905.47894037275546],
        thrust=0.1,
        isp=3000,
        mu=pk.MU_SUN,
        tof=[616.77087591237546, 616.77087591237546],
        freetime=False,
        alpha=0,    # quadratic control
        bound=True),
        with_grad=False
    )
    prob = pg.problem(udp)
    prob.c_tol = [1e-5] * prob.get_nc()

    # 3 - Population
    pop = pg.population(prob)
    z = np.hstack(([np.random.uniform(udp.udp_inner.tof[0],
                                      udp.udp_inner.tof[1])], 10 * np.random.randn(7)))
    pop.push_back(z)

    # 4 - Solve the problem (evolve)
    pop = algo.evolve(pop)

    # 5 - Continue the solution to mass optimal
    homotopy_path = [0.5, 0.75, 0.9, 1]
    for alpha in homotopy_path:
        z = pop.champion_x
        print("alpha: ", alpha)
        udp = add_gradient(pk.trajopt.indirect_pt2pt(
            x0=[44914296854.488266, -145307873786.94177, 1194292.6437741749,
                31252.149474878544, 9873.214642584162, -317.08718075574404, 1000],
            xf=[-30143999066.728119, -218155987244.44385, -3829753551.2279921,
                24917.707565772216, -1235.74045124602, -638.05209482866155, 905.47894037275546],
            thrust=0.1,
            isp=3000,
            mu=pk.MU_SUN,
            tof=[616.77087591237546, 616.77087591237546],
            freetime=False,
            alpha=alpha,    # quadratic control
            bound=True),
            with_grad=False
        )
        prob = pg.problem(udp)
        prob.c_tol = [1e-5] * prob.get_nc()

        # 7 - Solve it
        pop = pg.population(prob)
        pop.push_back(z)
        pop = algo.evolve(pop)

    # 8 - Inspect the solution
    print("Feasible?:", prob.feasibility_x(pop.champion_x))

    # plot trajectory
    axis = udp.udp_inner.plot_traj(pop.champion_x, quiver=True, mark="k")
    plt.title("The trajectory in the heliocentric frame")

    # plot control
    udp.udp_inner.plot_control(pop.champion_x)
    plt.title("The control profile (throttle)")

    plt.ion()
    plt.show()

    udp.udp_inner.pretty(pop.champion_x)

    print("\nDecision vector: ", list(pop.champion_x))
コード例 #41
0
ファイル: _ex9.py プロジェクト: darioizzo/pykep
def run_example9():
    """
    This example demonstrates the indirect method (cartesian) on a point to planet variable time scenario.
    The starting conditions are taken from a run of the indirect method.
    """
    import pykep as pk
    import pygmo as pg
    import numpy as np
    from matplotlib import pyplot as plt
    from pykep.examples import add_gradient, algo_factory

    # 1 - Algorithm
    algo = algo_factory("snopt7")

    # 2 - Problem
    udp = add_gradient(pk.trajopt.indirect_pt2pl(
        x0=[44459220055.461708, -145448367557.6174, 1195278.0377499966,
            31208.214734303529, 9931.5012318647168, -437.07278242521573, 1000],
        t0=1285.6637861007277,
        pf="mars",
        thrust=0.1,
        isp=3000,
        mu=pk.MU_SUN,
        tof=[600, 720],
        alpha=0,    # quadratic control
        bound=True),
        with_grad=False
    )
    prob = pg.problem(udp)
    prob.c_tol = [1e-5] * prob.get_nc()

    # 3 - Population
    pop = pg.population(prob)
    z = np.hstack(([np.random.uniform(udp.udp_inner.tof[0],
                                      udp.udp_inner.tof[1])], 10 * np.random.randn(7)))
    pop.push_back(z)

    # 4 - Solve the problem (evolve)
    pop = algo.evolve(pop)

    homotopy_path = [0.2, 0.4, 0.6, 0.8, 0.9, 0.98, 0.99, 0.995, 1]
    for alpha in homotopy_path:
        z = pop.champion_x
        print("alpha is: ", alpha)
        udp = add_gradient(pk.trajopt.indirect_pt2pl(
            x0=[44459220055.461708, -145448367557.6174, 1195278.0377499966,
                31208.214734303529, 9931.5012318647168, -437.07278242521573, 1000],
            t0=1285.6637861007277,
            pf="mars",
            thrust=0.1,
            isp=3000,
            mu=pk.MU_SUN,
            tof=[600, 720],
            alpha=alpha,    # quadratic control
            bound=True),
            with_grad=False
        )
        prob = pg.problem(udp)
        prob.c_tol = [1e-5] * prob.get_nc()

        # 7 - Solve it
        pop = pg.population(prob)
        pop.push_back(z)
        pop = algo.evolve(pop)

    # 8 - Inspect the solution
    print("Feasible?:", prob.feasibility_x(pop.champion_x))

    # plot trajectory
    axis = udp.udp_inner.plot_traj(pop.champion_x, quiver=True, mark='k')
    plt.title("The trajectory in the heliocentric frame")

    # plot control
    udp.udp_inner.plot_control(pop.champion_x)
    plt.title("The control profile (throttle)")

    plt.ion()
    plt.show()

    udp.udp_inner.pretty(pop.champion_x)

    print("\nDecision vector: ", list(pop.champion_x))
コード例 #42
0
ファイル: _mga.py プロジェクト: darioizzo/pykep
    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)