コード例 #1
0
    def costWithNode(self,customer,index):
        cost = 0.0
        load = self._totalDemand + customer.get_demand()
        duration = self._totalDuration + customer.get_duration()
        length = len(self._tour)

        if length == 0: #lista vazia:
            cost = 2 * dist.euclidianDistance(self._depot.get_x_coord(),self._depot.get_y_coord(),customer.get_x_coord(),customer.get_y_coord())
            load = customer.get_demand()
            duration = customer.get_duration()
        #verificar se ele ligará ao depósito
        elif index == 0:
            cost = self._cost - dist.euclidianDistance(self._depot.get_x_coord(),self._depot.get_y_coord(),self._tour[0].get_x_coord(),self._tour[0].get_y_coord()) + \
            dist.euclidianDistance(self._depot.get_x_coord(),self._depot.get_y_coord(),customer.get_x_coord(),customer.get_y_coord()) + \
            dist.euclidianDistance(customer.get_x_coord(),customer.get_y_coord(),self._tour[0].get_x_coord(),self._tour[0].get_y_coord())
        elif index == length:
            cost = self._cost - dist.euclidianDistance(self._depot.get_x_coord(),self._depot.get_y_coord(),self._tour[length-1].get_x_coord(),self._tour[length-1].get_y_coord()) + \
            dist.euclidianDistance(self._tour[length-1].get_x_coord(),self._tour[length-1].get_y_coord(),customer.get_x_coord(),customer.get_y_coord()) + \
            dist.euclidianDistance(self._depot.get_x_coord(),self._depot.get_y_coord(),customer.get_x_coord(),customer.get_y_coord())

        #está entre dois clientes
        else:
             cost = self._cost - dist.euclidianDistance(self._tour[index-1].get_x_coord(),self._tour[index-1].get_y_coord(),self._tour[index].get_x_coord(),self._tour[index].get_y_coord()) + \
             dist.euclidianDistance(self._tour[index-1].get_x_coord(),self._tour[index-1].get_y_coord(),customer.get_x_coord(),customer.get_y_coord()) + \
             dist.euclidianDistance(customer.get_x_coord(),customer.get_y_coord(),self._tour[index].get_x_coord(),self._tour[index].get_y_coord())

        #verificar se há penalizações
        costTotal = cost
        if load > self._depot.get_loadVehicle():
            costTotal += 1000 * (load - self._depot.get_loadVehicle())
        if duration > self._depot.get_durationRoute():
            costTotal += 1000 * (duration - self._depot.get_durationRoute())

        return [costTotal,cost,load,duration]
コード例 #2
0
def main():
    np.random.seed(7890)
    # recebendo instâncias
    r = ReadingDatas("dat/p01")
    r.readFile()
    # adicionando clientes
    Customers.addCustomers(r)
    # for cst in Customers.get_customersList().values():
    # print(cst)

    # adicionando depósitos
    Depots.addDepots(r)
    # print("\n\n\n\")
    # for dpt in Depots.get_depotsList().values():
    # print(dpt)

    # cálculo das distâncias
    Distances.euclidianDistanceAll(Customers.get_customersList(),
                                   Depots.get_depotsList())

    # for cst in Customers.get_customersList():
    #     print(cst)
    #     print(Customers.get_customersList()[cst].get_depotsDistances())
    # print("\n\n\n")
    # for cst in Customers.get_customersList():
    #     print(cst)
    #     print(Customers.get_customersList()[cst].get_neighborsDistances())

    ga = GA()
    ga.GA()
コード例 #3
0
    def calculeCost(self):
        cost = 0.0
        demand = 0.0
        duration = 0.0
        length = len(self._tour)

        #custo do depósito ao primeiro cliente
        customer = self._tour[0]
        cost += dist.euclidianDistance(customer.get_x_coord(),customer.get_y_coord(),self._depot.get_x_coord(),self._depot.get_y_coord())
        demand += customer.get_demand()
        duration += customer.get_duration()
        #custo do último cliente ao depósito
        customer = self._tour[length-1]
        cost += dist.euclidianDistance(customer.get_x_coord(),customer.get_y_coord(),self._depot.get_x_coord(),self._depot.get_y_coord())
        demand += customer.get_demand()
        duration += customer.get_duration()
        #custo dos clientes intermediários
        for i in range(length):

            if i+1 < length:
                customer = self._tour[i]
                nextCustomer = self._tour[i+1]
                cost += dist.euclidianDistance(customer.get_x_coord(),customer.get_y_coord(),nextCustomer.get_x_coord(),nextCustomer.get_y_coord())
            if i>0 and i<length-1:
                demand += customer.get_demand()
                duration += customer.get_duration()

        self._totalDemand = demand
        self._totalDuration = duration
        self._cost = cost
        self.updatePenalty()
コード例 #4
0
    def splitRoute(self, path, depot):
        n = len(path)
        # print("path")
        # print(path)
        # print(depot)
        vehicleCapacity = depot.get_loadVehicle()  # máximo carregamento
        durationRoute = depot.get_durationRoute()  # máxima duração
        v = []  # custo do menor caminho do depósito até o ponto.
        predecessor = []  # predecessores de cada idCsts neste caminho
        predecessor.append(-1)  # depósito não tem precedente
        v.append(0.0)
        # print("n = {}".format(len(path)))

        for i in range(n):
            v.append(SplitAlgorithms._infinite)
            # pior hipótese - número de rotas = número clientes
            predecessor.append(0)

        for i in range(1, n + 1):
            load = 0.0
            cost = 0.0
            j = i
            while (j <= n) and (load < vehicleCapacity) and (
                    cost < 2 * durationRoute):
                customer = path[j - 1]
                load += customer.get_demand()
                if i == j:
                    # custo de ida e volta
                    cost = 2 * dist.euclidianDistance(
                        customer.get_x_coord(), customer.get_y_coord(),
                        depot.get_x_coord(),
                        depot.get_y_coord()) + customer.get_service()
                else:
                    previewCustomer = path[j - 2]
                    cost = cost - dist.euclidianDistance(
                        previewCustomer.get_x_coord(),
                        previewCustomer.get_y_coord(), depot.get_x_coord(),
                        depot.get_y_coord()) + dist.euclidianDistance(
                            previewCustomer.get_x_coord(),
                            previewCustomer.get_y_coord(),
                            customer.get_x_coord(), customer.get_y_coord()
                        ) + customer.get_service() + dist.euclidianDistance(
                            customer.get_x_coord(), customer.get_y_coord(),
                            depot.get_x_coord(), depot.get_y_coord())

                if (load <= vehicleCapacity) and (cost <= 2 * durationRoute):
                    if (v[i - 1] + cost) < v[j]:
                        v[j] = v[i - 1] + cost
                        predecessor[j] = i - 1
                j += 1
                # print("cost: {} load: {}".format(cost, load))
                # print("pred: {}".format(predecessor))
                # print("v: {}".format(v))

        # print("\n")
        # print(predecessor)
        return predecessor
コード例 #5
0
    def test_shouldHaveFrontDistanceSensorWhenEnabledInSettings(self):
        # given
        self.settings.hasFrontDistanceSensor.return_value = True

        # when
        self.distances = Distances(self.settings)

        # then
        self.assertIsNotNone(self.distances.distance_sensor_front)
        self.settings.getFrontDistanceSensorAddress.assert_called_once()
コード例 #6
0
    def test_shouldNotHaveFrontDistanceSensorWhenDisabledInSettings(self):
        # given
        self.settings.hasFrontDistanceSensor.return_value = False

        # when
        self.distances = Distances(self.settings)

        # then
        self.assertIsNone(self.distances.distance_sensor_front)
        self.settings.getFrontDistanceSensorAddress.assert_not_called()
コード例 #7
0
ファイル: route.py プロジェクト: glouigi/Projeto-MDVRP
    def costWithoutNode(self, indexCst):
        cost = 0.0
        load = self._totalDemand - self._tour[indexCst].get_demand()
        service = self._totalService - self._tour[indexCst].get_service()
        length = len(self._tour)

        if length == 1:  #só tem esse cliente
            return [0, 0, 0, 0]
        #verificar se ele liga ao depósito
        elif indexCst == 0:
            cost = self._cost - dist.euclidianDistance(self._depot.get_x_coord(),self._depot.get_y_coord(),self._tour[indexCst].get_x_coord(),self._tour[indexCst].get_y_coord()) + \
            dist.euclidianDistance(self._depot.get_x_coord(),self._depot.get_y_coord(),self._tour[1].get_x_coord(),self._tour[1].get_y_coord()) - \
            dist.euclidianDistance(self._tour[indexCst].get_x_coord(),self._tour[indexCst].get_y_coord(),self._tour[1].get_x_coord(),self._tour[1].get_y_coord())

        elif indexCst == length - 1:
            cost = self._cost - dist.euclidianDistance(self._depot.get_x_coord(),self._depot.get_y_coord(),self._tour[indexCst].get_x_coord(),self._tour[indexCst].get_y_coord()) + \
            dist.euclidianDistance(self._depot.get_x_coord(),self._depot.get_y_coord(),self._tour[length-2].get_x_coord(),self._tour[length-2].get_y_coord()) - \
            dist.euclidianDistance(self._tour[indexCst].get_x_coord(),self._tour[indexCst].get_y_coord(),self._tour[length-2].get_x_coord(),self._tour[length-2].get_y_coord())
        #está entre dois clientes
        else:
            cost = self._cost - dist.euclidianDistance(self._tour[indexCst-1].get_x_coord(),self._tour[indexCst-1].get_y_coord(),self._tour[indexCst].get_x_coord(),self._tour[indexCst].get_y_coord()) - \
            dist.euclidianDistance(self._tour[indexCst].get_x_coord(),self._tour[indexCst].get_y_coord(),self._tour[indexCst+1].get_x_coord(),self._tour[indexCst+1].get_y_coord()) + \
            dist.euclidianDistance(self._tour[indexCst-1].get_x_coord(),self._tour[indexCst-1].get_y_coord(),self._tour[indexCst+1].get_x_coord(),self._tour[indexCst+1].get_y_coord())

        #verificar se há penalizações
        costTotal = cost
        if load > self._depot.get_loadVehicle():
            costTotal += 1000 * (load - self._depot.get_loadVehicle())
        if cost + service > self._depot.get_durationRoute():
            costTotal += 1000 * abs(service - self._depot.get_durationRoute())

        return [costTotal, cost, load, service]
コード例 #8
0
    def test_shouldReadDistanceSensorSettingsFromSettings(self):
        # given

        # when
        self.distances = Distances(self.settings)

        # then
        self.settings.getRightDistanceSensorAddress.assert_called_once()
        self.settings.getLeftDistanceSensorAddress.assert_called_once()
        self.assertIsNotNone(self.distances.distance_sensor_right)
        self.assertIsNotNone(self.distances.distance_sensor_left)
コード例 #9
0
    def propagatek(i, j, k, listCst, sumDistance, potential, depot):
        distDeptNextI = dist.euclidianDistance(
            listCst[i].get_x_coord(), listCst[i].get_y_coord(),
            depot.get_x_coord(),
            depot.get_y_coord())  # distancia de i+1 até o depósito
        distDeptJ = dist.euclidianDistance(
            listCst[j - 1].get_x_coord(), listCst[j - 1].get_y_coord(),
            depot.get_x_coord(),
            depot.get_y_coord())  # distancia de j até o depósito

        return potential[k][i] + sumDistance[j] - sumDistance[
            i + 1] + distDeptNextI + distDeptJ
コード例 #10
0
    def dominates(i, j, listCst, sumDistance, potential, sumLoad, depot):
        distDeptNextJ = dist.euclidianDistance(listCst[j].get_x_coord(),
                                               listCst[j].get_y_coord(),
                                               depot.get_x_coord(),
                                               depot.get_y_coord())
        distDeptNextI = dist.euclidianDistance(listCst[i].get_x_coord(),
                                               listCst[i].get_y_coord(),
                                               depot.get_x_coord(),
                                               depot.get_y_coord())

        return sumLoad[i] == sumLoad[j] and (potential[j] + distDeptNextJ) > (
            potential[i] + distDeptNextI + sumDistance[j + 1] -
            sumDistance[i + 1] - 0.0001)
コード例 #11
0
    def dominatesRightk(i, j, k, listCst, sumDistance, potential, depot):
        distDeptNextJ = dist.euclidianDistance(listCst[j].get_x_coord(),
                                               listCst[j].get_y_coord(),
                                               depot.get_x_coord(),
                                               depot.get_y_coord())
        distDeptNextI = dist.euclidianDistance(listCst[i].get_x_coord(),
                                               listCst[i].get_y_coord(),
                                               depot.get_x_coord(),
                                               depot.get_y_coord())

        return (potential[k][j] + distDeptNextJ) < (
            potential[k][i] + distDeptNextI + sumDistance[j + 1] -
            sumDistance[i + 1] + 0.0001)
コード例 #12
0
    def distances(self):
        distances = Distances(self)
        frontier = [self]

        while len(frontier) > 0:
            new_frontier = []

            for cell in frontier:
                for link in cell.get_links():
                    if not link in distances.cells:
                        distances.cells[link] = distances.cells[cell] + 1
                        new_frontier.append(link)

            frontier = new_frontier
        return distances
コード例 #13
0
    def distances(self):
        distances = Distances(self)
        frontier = [self]

        while len(frontier) is not 0:
            new_frontier = []
            for cell in frontier:
                for linked in cell.links():
                    if linked in distances.keys():
                        continue
                    distances[linked] = distances[cell] + 1
                    new_frontier.append(linked)
            frontier = new_frontier

        return distances
コード例 #14
0
    def splitRoute(path, depot):
        n = len(path)
        vehicleCapacity = depot.get_loadVehicle()
        durationRoute = depot.get_durationRoute()
        v = []  # custo do menor caminho do depósito até o ponto.
        predecessor = []  # predecessores de cada idCsts neste caminho
        predecessor.append(-1)  # depósito não tem precedente
        v.append(0.0)
        for i in range(n):
            v.append(SplitAlgorithms._infinite)
            predecessor.append("")

        for i in range(1, n + 1):
            load = 0.0
            cost = 0.0
            j = i
            duration = 0
            while (j <= n) and (load <= vehicleCapacity) and (duration <=
                                                              durationRoute):
                customer = path[j - 1]
                load += customer.get_demand()
                if i == j:
                    # custo de ida e volta
                    duration += customer.get_duration()
                    cost = 2 * dist.euclidianDistance(
                        customer.get_x_coord(), customer.get_y_coord(),
                        depot.get_x_coord(),
                        depot.get_y_coord()) + customer.get_duration()
                else:
                    duration += customer.get_duration()
                    previewCustomer = path[j - 2]
                    cost = cost - dist.euclidianDistance(
                        previewCustomer.get_x_coord(),
                        previewCustomer.get_y_coord(), depot.get_x_coord(),
                        depot.get_y_coord()) + dist.euclidianDistance(
                            previewCustomer.get_x_coord(),
                            previewCustomer.get_y_coord(),
                            customer.get_x_coord(), customer.get_y_coord()
                        ) + customer.get_duration() + dist.euclidianDistance(
                            customer.get_x_coord(), customer.get_y_coord(),
                            depot.get_x_coord(), depot.get_y_coord())

                if (load <= vehicleCapacity) and (duration <= durationRoute):
                    if (v[i - 1] + cost) < v[j]:
                        v[j] = v[i - 1] + cost
                        predecessor[j] = i - 1
                    j += 1
        return predecessor
コード例 #15
0
    def test_shouldReturnCorrectDistanceValuesWhenFrontSensorDisabled(self):
        # given
        self.settings.hasFrontDistanceSensor.return_value = False
        self.distances = Distances(self.settings)
        self.distances.distance_sensor_right = MagicMock()
        self.distances.distance_sensor_left = MagicMock()
        self.distances.distance_sensor_right.value.return_value = 111
        self.distances.distance_sensor_left.value.return_value = 222

        # when
        actual_distances = self.distances.getDistances()

        # then
        self.assertEqual(11, actual_distances.get('right'))
        self.assertEqual(22, actual_distances.get('left'))
        self.assertFalse('front' in actual_distances)
コード例 #16
0
    def test_shouldReturnCorrectDistanceValues(self):
        # given
        self.distances = Distances(self.settings)
        self.distances.distance_sensor_right = MagicMock()
        self.distances.distance_sensor_left = MagicMock()
        self.distances.distance_sensor_front = MagicMock()
        self.distances.distance_sensor_right.value.return_value = 111
        self.distances.distance_sensor_left.value.return_value = 222
        self.distances.distance_sensor_front.value.return_value = 333

        # when
        actual_distances = self.distances.getDistances()

        # then
        self.assertEqual(11, actual_distances.get('right'))
        self.assertEqual(22, actual_distances.get('left'))
        self.assertEqual(33, actual_distances.get('front'))
コード例 #17
0
def main(SEED, POP, DESC, PROB_MUT, PROB_LS_POP, PROB_LS, PROB_LSB, PROB_LSBP,
         GEN_ILS, GEN_ILSA, DATFILE, INSTANCE):

    # redefinindo variáveis conforme Package Irace
    # config.FRAC_MAX_DISTRIBUTION = FRAC
    config.SIZE_POP = POP
    config.SIZE_DESC = DESC
    config.PROB_MUTATION = PROB_MUT
    config.PROB_LS_POP = PROB_LS_POP
    config.PROB_LS = PROB_LS
    config.PROB_LS_BEST = PROB_LSB
    config.PROB_LS_BEST_P = PROB_LSBP
    config.GEN_ILS = GEN_ILS
    config.GEN_ILSA = GEN_ILSA

    seed = SEED

    timeIni = time.time()

    # exit(0)

    # recebendo instâncias
    r = ReadingDatas(INSTANCE)
    r.readFile()
    # adicionando clientes
    Customers.addCustomers(r)

    # adicionando depósitos
    Depots.addDepots(r)

    # cálculo das distâncias
    Distances.euclidianDistanceAll(Customers.get_customersList(),
                                   Depots.get_depotsList())

    ga = GA()
    best = ga.GA(seed)
    cost = best.get_cost()
    timeEnd = (time.time() - timeIni) / 60.0

    logging.debug("Melhor indivíduo: %s" % best)
    logging.debug("tempo total: " + str(timeEnd) + " minutos.")
    logging.debug("------------fim algoritmo genético-----------")

    with open(DATFILE, 'w') as f:
        f.write(str(cost))
コード例 #18
0
ファイル: run.py プロジェクト: Emekaborisama/distance_finder
def run(from_file,
        to_file,
        from_colname,
        to_colname,
        db_name,
        metric,
        threshold):
    client = Distances(db_name)

    from_df = get_from_adresser(from_file)
    to_df = get_to_addresser(to_file)

    client.import_data_from_df(from_df, from_column=from_colname)
    client.import_data_from_df(to_df, to_column=to_colname)
    output_df = client.output_distances()

    merged_data = merge_dfs(from_df, to_df, output_df)
    min_distance = calculate_min_distance(merged_data)
    over_threshold = min_distance[min_distance[metric] <= threshold]
    under_threshold = min_distance[min_distance[metric] > threshold]

    writer = pd.ExcelWriter(f'results_max_{metric}_{threshold}.xlsx')

    over_threshold.to_excel(writer, sheet_name=f'Over {threshold}', index=False)
    under_threshold.to_excel(writer, sheet_name=f'Under {threshold}', index=False)

    writer.save()
コード例 #19
0
 def get_all_angular_distances(self, max_distance=None):
     stars = self.stars
     distances = Distances()
     for i, star in enumerate(stars):
         other_stars = stars[i + 1:]
         for other_star in other_stars:
             distances.add_distance(star, other_star, max_distance)
     distances.sort()
     return distances
コード例 #20
0
    def __init__(self, acceptable_delay):
        self.buffer = dict()
        self.distances = Distances()

        # acceptable delay is in seconds
        self.acceptable_delay = acceptable_delay

        self.buffer_counter = 0
        self.trips_out_counter = 0
        self.extra_trips_combined = 0

        self.unmodified_durations = 0
        self.modified_durations = 0

        self.requests_assigned = {}
コード例 #21
0
ファイル: route.py プロジェクト: glouigi/Projeto-MDVRP
    def calculeCost(self):
        cost = 0.0
        demand = 0.0
        service = 0.0
        length = len(self._tour)

        #custo do depósito ao primeiro cliente
        customer = self._tour[0]
        cost += dist.euclidianDistance(customer.get_x_coord(),
                                       customer.get_y_coord(),
                                       self._depot.get_x_coord(),
                                       self._depot.get_y_coord())

        #custo do último cliente ao depósito
        customer = self._tour[length - 1]
        cost += dist.euclidianDistance(customer.get_x_coord(),
                                       customer.get_y_coord(),
                                       self._depot.get_x_coord(),
                                       self._depot.get_y_coord())

        #custo dos clientes intermediários
        for i in range(length):
            customer = self._tour[i]
            demand += customer.get_demand()
            service += customer.get_service()
            if i + 1 < length:
                nextCustomer = self._tour[i + 1]
                cost += dist.euclidianDistance(customer.get_x_coord(),
                                               customer.get_y_coord(),
                                               nextCustomer.get_x_coord(),
                                               nextCustomer.get_y_coord())

        self._totalDemand = demand
        self._totalService = service
        self._cost = cost
        self.updatePenalty()
コード例 #22
0
ファイル: cell.py プロジェクト: mmcclimon/codebooks
    def distances(self):
        distances = Distances(self)
        frontier = [self]

        while len(frontier) > 0:
            new_frontier = []

            for cell in frontier:
                for linked in cell.links:
                    if linked not in distances:
                        distances[linked] = distances[cell] + 1
                        new_frontier.append(linked)

            frontier = new_frontier

        return distances
コード例 #23
0
  def distances(self):
    weights = Distances(self)
    pending = [ self ]

    while pending:
      cell = sorted(pending, key=lambda c: weights[c])[0]
      pending.remove(cell)

      for neighbor in cell.links:
        total_weight = weights[cell] + neighbor.weight

        if not weights[neighbor] or total_weight < weights[neighbor]:
          pending.append(neighbor)
          weights[neighbor] = total_weight

    return weights
コード例 #24
0
ファイル: cell.py プロジェクト: mjgpy3/mfp-python3-examples
    def distances(self):
        distances = Distances(self)
        frontier = [self]

        while frontier:
            new_frontier = []

            for cell in frontier:
                for linked in cell.links:
                    if distances[linked] != None:
                        continue

                    distances[linked] = distances[cell] + 1
                    new_frontier.append(linked)

            frontier = new_frontier

        return distances
コード例 #25
0
    def get_matrix_loss(self, q, d, m, distance="dot", loss="mse", symmetric=False):
        query_part = self.call_query(q)
        if not symmetric:
            doc_part = self.call_doc(d)
        else:
            doc_part = (
                query_part
                if (d is None) or (d is q) else
                self.call_query(d)
            )
    
        if isinstance(distance, str):
            dist = Distances(distance)(query_part, doc_part)
        elif hasattr(distance, "__call__"):
            if symmetric:
                assert query_part is doc_part # debug
            dist = distance(query_part, doc_part)
        else:
            raise RuntimeError("suspicious distance")

        if loss == "mse":
            delta = (m - dist)
            loss = tf.reduce_mean(delta ** 2)
        elif loss == "distortion":
            loss = metrics.distortion_loss(dist=dist, m=m)
        elif loss == "softmax":
            loss = metrics.softmax_proba_loss(dist, r=m)
        elif loss == "softmax_1/dist":
            loss = metrics.softmax_proba_inverted_dist_loss(dist, r=m)
        elif loss == "1/dist":
            loss = metrics.proba_inverted_dist_loss(dist, r=m)
        elif loss is None:
            return dist
        elif hasattr(metrics, loss + "_loss"):
            loss = getattr(metrics, loss + "_loss")(dist, m=m)
        else:
            raise NotImplementedError("Unknown loss")
        
        return loss
コード例 #26
0
def main():
    parser = argparse.ArgumentParser(description='Cluster data using Nearest'
                                     ' Neighbor algorithm.')
    parser.add_argument('--datafile',
                        dest='data_file',
                        type=str,
                        required=True,
                        help='absolute or relative path to data file')
    parser.add_argument('--datainfofile',
                        dest='data_info_file',
                        type=str,
                        required=True,
                        help='absolute or relative path to data info file')
    parser.add_argument('--threshold',
                        dest='threshold',
                        type=float,
                        required=True,
                        help='threshold to be used by the algorithm'
                        ' (should be value between 0..1)')
    parser.add_argument('--outputfile',
                        dest='output_file',
                        type=str,
                        help='absolute or relative path to file where'
                        ' results should be written (if not'
                        ' specified results are printed in stdout)')
    args = parser.parse_args()

    data, data_info = prepare_data(args.data_file, args.data_info_file)
    distances = Distances(data, data_info).get_distances()
    clusters = NearestNeighbor(data, distances, args.threshold).get_clusters()

    printed_clusters = pretty_print_clusters(clusters)
    if args.output_file:
        with open(args.output_file, 'w') as f:
            f.write(printed_clusters)
            f.close()
    else:
        print printed_clusters
コード例 #27
0
    def M10(self, solution):
        solution1 = copy.deepcopy(solution)
        depots = dpts.get_depotsList()
        #escolha da rota
        routes = solution1.get_routes()
        idRoute = np.random.randint(len(routes))
        route = copy.deepcopy(routes[idRoute])
        length = len(route.get_tour())  # comprimento da rota
        oldDepot = route.get_depot()
        costWithoutRoute = solution1.get_cost() - route.get_totalCost()
        penalty = route.get_totalCost() - route.get_costWithoutPenalty()
        extraPenalty = 0
        # print(penalty)
        cont = 0

        bestRoute = copy.deepcopy(route)
        # print("tamanho de rotas")
        # print(len(routes))
        # print("route")
        # print(route)
        if length > 0:
            route1 = copy.deepcopy(route)
            #rotação da rota
            for i in range(length):
                #rotacionar
                # print(route1)
                aux = route1.get_tour()[0]
                # print(aux)
                cost = route1.costWithoutNode(0)
                route1.removeCustomer(aux)
                route1.set_cost(cost[1], cost[2], cost[3])
                cost = route1.costWithNode(aux, length - 1)
                route1.addCustomer(aux)
                route1.set_cost(cost[1], cost[2], cost[3])
                # print(route1)
                # print("-----")
                # verificar se rota gerada é melhor (considerando mesmo depósito)
                if bestRoute.get_totalCost() > route1.get_totalCost():
                    extraPenalty = 0
                    bestRoute = copy.deepcopy(route1)
                    cont = 1
                # verificar transferência da rota em outro depósito
                for dpt in depots.values():
                    if str(dpt) != str(oldDepot):
                        # verificar rota para o novo depósito
                        tour = route1.get_tour()
                        # tirar o custo associado ao depósito
                        cost1 = route1.get_totalCost() - dist.euclidianDistance(tour[0].get_x_coord(),
                                tour[0].get_y_coord(), oldDepot.get_x_coord(), oldDepot.get_y_coord()) - \
                                dist.euclidianDistance(tour[length-1].get_x_coord(),
                                tour[length-1].get_y_coord(), oldDepot.get_x_coord(), oldDepot.get_y_coord())

                        # computar custo com o novo depósito
                        newCost = cost1 + dist.euclidianDistance(tour[0].get_x_coord(),
                            tour[0].get_y_coord(), dpt.get_x_coord(), dpt.get_y_coord()) + \
                            dist.euclidianDistance(tour[length-1].get_x_coord(),
                            tour[length-1].get_y_coord(), dpt.get_x_coord(), dpt.get_y_coord())

                        if bestRoute.get_totalCost() > newCost:
                            # verifica número de veículos utilizados pelo depósito
                            nVehicles = 0
                            for r in solution1.get_routes():
                                if r.get_depot() == dpt:
                                    nVehicles += 1
                            if nVehicles < dpt.get_numberVehicles():
                                if (costWithoutRoute + newCost
                                    ) < solution1.get_cost():  # é melhor
                                    extraPenalty = 0
                                    bestRoute = copy.deepcopy(route1)
                                    bestRoute.set_depot(dpt)
                                    newCost1 = newCost - penalty
                                    bestRoute.set_cost(
                                        newCost1, bestRoute.get_totalDemand(),
                                        bestRoute.get_totalService())

                                    cont = 1
                            # else:
                            #     if (costWithoutRoute + newCost + 1000) < solution1.get_cost(): # ainda é melhor
                            #         extraPenalty = 1000 #penalização por rota a mais
                            #         bestRoute.set_depot(dpt)
                            #         newCost1 = newCost - penalty
                            #         bestRoute.set_cost(newCost1, bestRoute.get_totalDemand(),
                            #             bestRoute.get_totalService())
                            #         cont = 1

            if cont == 1:
                # print(penalty)
                # # print(bestRoute.get_totalCost())
                # print(route)
                # # print("best")
                # print(bestRoute)
                solution1.setRoute(bestRoute, idRoute)
                solution1.formGiantTour()
                solution1.calculateCost(extraPenalty)
                return solution1

        return solution
コード例 #28
0
    def getSteeringPIDDerivativeGain(self):
        return 0.0008

    def getSteeringPIDIntegralTermLimit(self):
        return -1.0


if __name__ == "__main__":
    log_message_queue_listener.start()
    logging.info('Loading')
    ev3.Sound.beep().wait()
    ev3.Sound.beep().wait()
    settings = Settings()
    bumpers = Bumpers(settings.getFrontBumperAddress()) if (settings.hasFrontBumper()) else None
    steering = Steering(
        settings.getSteeringMotorAddress(),
        settings.getSteeringMotorSpeedFactor(),
        settings.getSteeringSpeed(),
        settings.getSteeringMaxRange(),
        settings.getSteeringMotorPositionFactor(),
        settings.getDoCenterSteeringWhenInitializing()
    )
    folkracer = Folkracer(steering, Engine(settings), Distances(settings), bumpers, Buttons(), settings, None, None, LightsAndSounds())
    folkracer.start()
    folkracer.join()
    logging.info('Shutting down.')
    log_message_queue_listener.stop()
    ev3.Sound.beep().wait()
    ev3.Sound.beep().wait()
コード例 #29
0
def distance():
    os.environ['API_KEY'] = 'AIzaasdf'
    return Distances('sqlite:///:memory:')
コード例 #30
0
ファイル: distances_test.py プロジェクト: ekinoguz/hiding
  def testEuclidean(self):
    r1 = {'value1':5}
    r2 = {'value2':5}    
    distanceCalculator = Distances()
    distanceCalculator.set_type(Distances.EUCLIDEAN)
    distance = distanceCalculator.calculate(r1, r2)
    self.assertEqual(50, distance)

    r1 = {'value1':5}
    r2 = {'value1':5}
    distanceCalculator = Distances()
    distanceCalculator.set_type(Distances.EUCLIDEAN)
    distance = distanceCalculator.calculate(r1, r2)
    self.assertEqual(0, distance)

    r1 = {'value1':5}
    r2 = {'value1':3}
    distanceCalculator = Distances()
    distanceCalculator.set_type(Distances.EUCLIDEAN)
    distance = distanceCalculator.calculate(r1, r2)
    self.assertEqual(4, distance)

    r1 = {'value1':1, 'value2':2, 'value3':3}
    r2 = {'value1':5, 'value2':6, 'value3':5}
    distanceCalculator = Distances()
    distanceCalculator.set_type(Distances.EUCLIDEAN)
    distance = distanceCalculator.calculate(r1, r2)
    self.assertEqual(36, distance)
コード例 #31
0
ファイル: distances_test.py プロジェクト: ekinoguz/hiding
  def testChiSquare(self):
    r1 = {'value1':5}
    r2 = {'value1':5}
    distanceCalculator = Distances()
    distanceCalculator.set_type(Distances.CHI_SQUARE)
    distance = distanceCalculator.calculate(r1, r2)
    self.assertEqual(0, distance)

    r1 = {'value1':5}
    r2 = {'value2':5}
    distanceCalculator = Distances()
    distanceCalculator.set_type(Distances.CHI_SQUARE)
    distance = distanceCalculator.calculate(r1, r2)
    self.assertEqual(10, distance)

    r1 = {'value1':5}
    r2 = {'value1':3}
    distanceCalculator = Distances()
    distanceCalculator.set_type(Distances.CHI_SQUARE)
    distance = distanceCalculator.calculate(r1, r2)
    self.assertEqual(0.5, distance)

    r1 = {'value2':2, 'value3':3}
    r2 = {'value2':6, 'value3':5}
    distanceCalculator = Distances()
    distanceCalculator.set_type(Distances.CHI_SQUARE)
    distance = distanceCalculator.calculate(r1, r2)
    self.assertEqual(2.5, distance)

    r1 = {'value1':1, 'value2':2, 'value3':3}
    r2 = {'value2':6, 'value3':5, 'value4':2}
    distanceCalculator = Distances()
    distanceCalculator.set_type(Distances.CHI_SQUARE)
    distance = distanceCalculator.calculate(r1, r2)
    self.assertEqual(5.5, distance)
コード例 #32
0
    def splitLinearBounded(solution):
        solution1 = copy.deepcopy(solution)
        solution2 = copy.deepcopy(solution)
        depotsList = dpts.get_depotsList()
        customers = solution1.get_giantTour()
        depots = solution1.get_depots()
        for dpt in depotsList:
            listCst = []
            depot = depotsList[dpt]
            for j in range(len(customers)):
                if dpt == str(depots[j].get_id()):
                    listCst.append(customers[j])

            sumDistance = [0.0 for x in range(len(listCst) + 1)]
            sumLoad = [0.0 for x in range(len(listCst) + 1)]
            sumDistance[0] = 0  # distancia do depósito
            # distância do depósito ao primeiro nó
            sumDistance[1] = dist.euclidianDistance(listCst[0].get_x_coord(),
                                                    listCst[0].get_y_coord(),
                                                    depot.get_x_coord(),
                                                    depot.get_y_coord())

            sumLoad[0] = 0
            sumLoad[1] = customers[0].get_demand()
            # inicializar com o somatório distancia de i-1 a i e a demanda de i-1 a i
            for i in range(2, len(listCst) + 1):
                sumDistance[i] = sumDistance[i - 1] + dist.euclidianDistance(
                    listCst[i - 2].get_x_coord(), listCst[i - 2].get_y_coord(),
                    listCst[i - 1].get_x_coord(), listCst[i - 1].get_y_coord())
                sumLoad[i] = sumLoad[i - 1] + listCst[i - 1].get_demand()

            potential = []
            pred = []

            for k in range(depot.get_numberVehicles() + 1):
                potential.append([1.e30 for x in range(len(listCst) + 1)])
                pred.append([-1 for x in range(len(listCst) + 1)])

            potential[0][0] = 0

            for k in range(depot.get_numberVehicles()):
                queue = [k]
                i = k + 1
                while (i <= len(listCst)) and (len(queue) > 0):
                    # o primeiro da fila será o melhor predecessor de i
                    potential[k + 1][i] = SplitAlgorithms.propagatek(
                        queue[0], i, k, listCst, sumDistance, potential,
                        depot)  # calcula custo de i a j
                    pred[k + 1][i] = queue[0]

                    # se i não é dominado pelo último da pilha
                    if i < len(listCst):
                        if not (SplitAlgorithms.dominatesk(
                                queue[len(queue) - 1], i, k, listCst,
                                sumDistance, potential, sumLoad, depot)):
                            # então i será inserido, precisando remover quem ele domina
                            while len(
                                    queue
                            ) > 0 and SplitAlgorithms.dominatesRightk(
                                    queue[len(queue) - 1], i, k, listCst,
                                    sumDistance, potential, depot):
                                del queue[len(queue) - 1]
                            queue.append(i)

                        # Verifica se a frente consegue chegar ao próximo nó, caso contrário ele desaparecerá.
                        while len(queue) > 0 and (
                                sumLoad[i + 1] - sumLoad[queue[0]]) > (
                                    depot.get_loadVehicle() + 0.0001):
                            del queue[0]

                    i += 1

            if potential[depot.get_numberVehicles()][len(listCst)] > 1.e29:
                # print("ERRO: nenhuma solução de divisão foi propagada até o último nó")
                del solution1
                return SplitAlgorithms.mountRoutes(solution2)

            else:
                # achando o número ótimo de rotas
                minCost = 1.e30
                nRoutes = 0
                for k in range(1, depot.get_numberVehicles() + 1):
                    if potential[k][len(listCst)] < minCost:
                        minCost = potential[k][len(listCst)]
                        # print("minCost "+str(minCost))
                        nRoutes = k

                cour = len(listCst)
                for i in range(nRoutes - 1, -1, -1):
                    route = Route(depot)
                    j = pred[i + 1][cour]
                    for k in range(j + 1, cour + 1):
                        route.addCustomer(listCst[k - 1])
                    cour = j
                    # calcular custo da rota formada
                    route.startValues()
                    route.calculeCost()
                    solution1.addRoutes(route)

        solution1.formGiantTour()
        solution1.calculateCost()
        # print(solution)
        return solution1