Exemplo n.º 1
0
 def fit(self, kernel=None, n_restarts_optimizer=4):
     start = current_milli_time()
     if kernel is None: kernel = self.kernel
     # self.model = GaussianProcessRegressor(kernel=RationalQuadratic(length_scale_bounds=(0.08, 100)) + WhiteKernel(noise_level_bounds=(1e-5, 1e-2)), n_restarts_optimizer=10)
     self.model = GaussianProcessRegressor(
         kernel=kernel,
         n_restarts_optimizer=n_restarts_optimizer,
         copy_X_train=True,
         random_state=self.seed)
     self.model.fit(self.first_xys + self.fixed_xys,
                    self.first_zs + probe(self.f, self.fixed_xys))
     self.model_time += current_milli_time() - start
Exemplo n.º 2
0
    def calculate_tour(self):
        """ps. Keep the old tour if it's still within the budget and the number of cities remains compatible with the tour length."""
        start = current_milli_time()
        xys = [self.depot] + self.fixed_xys + self.xys
        n = len(self.tour)
        tmptour = self.tour + [0]
        self.cost, self.feasible = n, True
        for i in list(range(n)):
            a, b = xys[tmptour[i]]
            c, d = xys[tmptour[i + 1]]
            self.cost += dist(a, b, c, d)

        if self.budget - self.cost >= 1:
            self.possibly_no_more_room_left = False
        if self.cost > self.budget or self.tour == [] or n != len(xys):
            self.tour, self.feasible, self.cost, self.possibly_no_more_room_left = plan_tour(
                [self.depot] + self.fixed_xys + self.xys, self.budget, True,
                self.fixed_tour)

        self.tour_time += current_milli_time() - start
Exemplo n.º 3
0
 def select_kernel(self):
     start = current_milli_time()
     self.kernel = kernel_selector(
         self.first_xys + self.fixed_xys,
         self.first_zs + probe(self.f, self.fixed_xys))
     self.model_time += current_milli_time() - start
Exemplo n.º 4
0
 def predict(self, xys):
     start = current_milli_time()
     preds = self.model.predict(xys, return_std=False)
     self.pred_time += current_milli_time() - start
     return preds
Exemplo n.º 5
0
 def predict_stds(self, xys):
     start = current_milli_time()
     _, stds = self.model.predict(xys, return_std=True)
     self.pred_time += current_milli_time() - start
     return stds
Exemplo n.º 6
0
trip = Trip(f, depot, first_xys, first_zs, budget, plotter)
print('# selecting kernel...')
trip.select_kernel()  # TOD
print('# fitting...')
trip.fit()

# Main loop. Report stddev and error...: first iteration -> ...using only known points; (conta == 0)
#                                        second iteration -> ...after orienteering; (conta == 1)
#                                        third iteration -> ...after first distortion; (conta == 2)
#                                        next iterations -> ...after probing [only for online mode] and next distortions; (conta > 2)
conta, acctime = 0, 0
trip_var = sum(trip.stds_simulated(TSxy))
if argv[1] == 'plotvar': trip.plotvar = True
while acctime < time_limit * 3600000:
    trip.tour_time, trip.model_time, trip.pred_time = 0, 0, 0
    start = current_milli_time()

    if conta > 0: trip.add_while_possible(trip.add_maxvar_point(TSxy))
    if conta == 1:
        trip_var = sum(trip.stds_simulated(TSxy))
    elif conta > 1:
        if online and conta > 2: trip.probe_next()
        if len(trip.xys) > 0:
            if alg == '1c':
                trip_var = custom_distortion(trip, TSxy, nb, random_distortion)
            if alg == 'sw':
                trip_var = swarm_distortion(
                    trip, TSxy, time_limit * 3600000 - acctime -
                    (current_milli_time() - start))
            if alg == 'ga': trip_var = ga_distortion(trip, TSxy)
            if alg == 'a4':
Exemplo n.º 7
0
 def py_outf(it, leader, fx, x):
     """Function called at every iteration. It is for logging purposes, but also to stop when a criterion is matched."""
     elapsed = current_milli_time() - start
     # print(available_time - elapsed )
     return available_time - elapsed  # negative number = stop
Exemplo n.º 8
0
def swarm_distortion(trip,
                     testset_xy,
                     available_time,
                     maxf=4000,
                     maxit=4000,
                     size=100):
    """Optimize points in trip via PSO, evaluating over a test set. The available time is almost never respected."""
    def py_outf(it, leader, fx, x):
        """Function called at every iteration. It is for logging purposes, but also to stop when a criterion is matched."""
        elapsed = current_milli_time() - start
        # print(available_time - elapsed )
        return available_time - elapsed  # negative number = stop

    def py_objf(xs):
        """Function called at every iteration. It is for swarm fitness evaluation."""
        def var(x):
            """Evaluates fitness of a given particle of the swarm."""
            xys = tuplefy(
                x
            )  # Ps.: According to my tests with oldtrip.count(), trip methods don't need to be thread-safe here.
            v, _ = trip.fitness(xys, testset_xy)
            return v

        return [var(x) for x in xs]

    # Initial PSO settings.
    start = current_milli_time()
    x0 = flat(trip.xys)
    variabs = len(x0)
    problem = {
        'Variables': variabs,
        'objf': py_objf,
        'lb': zeros(variabs),
        'ub': ones(variabs),
        'x0': x0
    }
    # , 'A': [[-1.0 / sqrt(3), 1], [-1.0, sqrt(3)], [1.0, sqrt(3)]], 'b': [0, 0, 6] # <- Defaults
    options = {
        'maxf': maxf,
        'maxit': maxit,
        'social': 0.5,
        'cognitial': 0.5,
        'fweight': 0.4,
        'iweight': 0.9,
        'size': size,
        'iprint': 10,
        'tol': 1E-5,
        'ddelta': 0.5,
        'idelta': 2.0,
        'outputfcn': py_outf,
        'vectorized': 1
    }

    # PSO running.
    result = pswarm(problem, options)

    # PSO results.
    if result['ret'] == 0:  # zero means successful
        new_xys = tuplefy(result['x'])
        trip.xys = new_xys.copy()
    return result['f']