snake.cpp 39.9 KB
Newer Older
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1
#include <algorithm>
Valentin Platzgummer's avatar
Valentin Platzgummer committed
2 3 4 5
#include <iostream>

#include "snake.h"

Valentin Platzgummer's avatar
Valentin Platzgummer committed
6
#include <mapbox/geometry.hpp>
7
#include <mapbox/polylabel.hpp>
Valentin Platzgummer's avatar
Valentin Platzgummer committed
8 9 10

#include <boost/geometry.hpp>
#include <boost/geometry/geometries/adapted/boost_tuple.hpp>
11 12
#include <boost/geometry/geometries/box.hpp>
#include <boost/geometry/geometries/polygon.hpp>
Valentin Platzgummer's avatar
Valentin Platzgummer committed
13

Valentin Platzgummer's avatar
Valentin Platzgummer committed
14
#include "clipper/clipper.hpp"
15
#define CLIPPER_SCALE 1000000
Valentin Platzgummer's avatar
Valentin Platzgummer committed
16 17 18 19 20 21

#include "ortools/constraint_solver/routing.h"
#include "ortools/constraint_solver/routing_enums.pb.h"
#include "ortools/constraint_solver/routing_index_manager.h"
#include "ortools/constraint_solver/routing_parameters.h"

Valentin Platzgummer's avatar
Valentin Platzgummer committed
22 23
using namespace operations_research;

24
#ifndef NDEBUG
Valentin Platzgummer's avatar
Valentin Platzgummer committed
25
//#define SNAKE_SHOW_TIME
26 27
#endif

Valentin Platzgummer's avatar
Valentin Platzgummer committed
28 29 30
namespace bg = boost::geometry;
namespace trans = bg::strategy::transform;

Valentin Platzgummer's avatar
Valentin Platzgummer committed
31 32
BOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(bg::cs::cartesian)

Valentin Platzgummer's avatar
Valentin Platzgummer committed
33
namespace snake {
34
static const IntType stdScale = 1000000;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
35 36 37 38
//=========================================================================
// Geometry stuff.
//=========================================================================

39
void polygonCenter(const FPolygon &polygon, FPoint &center) {
40 41
  using namespace mapbox;
  if (polygon.outer().empty())
Valentin Platzgummer's avatar
Valentin Platzgummer committed
42
    return;
43 44 45 46 47
  geometry::polygon<double> p;
  geometry::linear_ring<double> lr1;
  for (size_t i = 0; i < polygon.outer().size(); ++i) {
    geometry::point<double> vertex(polygon.outer()[i].get<0>(),
                                   polygon.outer()[i].get<1>());
Valentin Platzgummer's avatar
Valentin Platzgummer committed
48
    lr1.push_back(vertex);
49 50 51
  }
  p.push_back(lr1);
  geometry::point<double> c = polylabel(p);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
52

53 54
  center.set<0>(c.x);
  center.set<1>(c.y);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
55 56
}

57
bool minimalBoundingBox(const FPolygon &polygon, BoundingBox &minBBox) {
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
  /*
  Find the minimum-area bounding box of a set of 2D points

  The input is a 2D convex hull, in an Nx2 numpy array of x-y co-ordinates.
  The first and last points points must be the same, making a closed polygon.
  This program finds the rotation angles of each edge of the convex polygon,
  then tests the area of a bounding box aligned with the unique angles in
  90 degrees of the 1st Quadrant.
  Returns the

  Tested with Python 2.6.5 on Ubuntu 10.04.4 (original version)
  Results verified using Matlab

  Copyright (c) 2013, David Butterworth, University of Queensland
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

      * Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
      * Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.
      * Neither the name of the Willow Garage, Inc. nor the names of its
        contributors may be used to endorse or promote products derived from
        this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  POSSIBILITY OF SUCH DAMAGE.
  */

Valentin Platzgummer's avatar
Valentin Platzgummer committed
99 100
  if (polygon.outer().empty() || polygon.outer().size() < 3)
    return false;
101
  FPolygon convex_hull;
102 103 104 105 106
  bg::convex_hull(polygon, convex_hull);

  // cout << "Convex hull: " << bg::wkt<BoostPolygon2D>(convex_hull) << endl;

  //# Compute edges (x2-x1,y2-y1)
107
  std::vector<FPoint> edges;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
108
  const auto &convex_hull_outer = convex_hull.outer();
109
  for (long i = 0; i < long(convex_hull_outer.size()) - 1; ++i) {
110 111
    FPoint p1 = convex_hull_outer.at(i);
    FPoint p2 = convex_hull_outer.at(i + 1);
112 113
    double edge_x = p2.get<0>() - p1.get<0>();
    double edge_y = p2.get<1>() - p1.get<1>();
114
    edges.push_back(FPoint{edge_x, edge_y});
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
  }

  //    cout << "Edges: ";
  //    for (auto e : edges)
  //        cout << e.get<0>() << " " << e.get<1>() << ",";
  //    cout << endl;

  // Calculate unique edge angles  atan2(y/x)
  double angle_scale = 1e3;
  std::set<long> angles_long;
  for (auto vertex : edges) {
    double angle = std::fmod(atan2(vertex.get<1>(), vertex.get<0>()), M_PI / 2);
    angle =
        angle < 0 ? angle + M_PI / 2 : angle; // want strictly positive answers
    angles_long.insert(long(round(angle * angle_scale)));
  }
  std::vector<double> edge_angles;
  for (auto a : angles_long)
    edge_angles.push_back(double(a) / angle_scale);

  //    cout << "Unique angles: ";
  //    for (auto e : edge_angles)
  //        cout << e*180/M_PI << ",";
  //    cout << endl;

  double min_area = std::numeric_limits<double>::infinity();
  // Test each angle to find bounding box with smallest area
  // print "Testing", len(edge_angles), "possible rotations for bounding box...
  // \n"
  for (double angle : edge_angles) {

    trans::rotate_transformer<bg::degree, double, 2, 2> rotate(angle * 180 /
                                                               M_PI);
148
    FPolygon hull_rotated;
149 150 151 152
    bg::transform(convex_hull, hull_rotated, rotate);
    // cout << "Convex hull rotated: " << bg::wkt<BoostPolygon2D>(hull_rotated)
    // << endl;

153
    bg::model::box<FPoint> box;
154 155 156 157 158
    bg::envelope(hull_rotated, box);
    //        cout << "Bounding box: " <<
    //        bg::wkt<bg::model::box<BoostPoint2D>>(box) << endl;

    //# print "Rotated hull points are \n", rot_points
159 160
    FPoint min_corner = box.min_corner();
    FPoint max_corner = box.max_corner();
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
    double min_x = min_corner.get<0>();
    double max_x = max_corner.get<0>();
    double min_y = min_corner.get<1>();
    double max_y = max_corner.get<1>();
    //        cout << "min_x: " << min_x << endl;
    //        cout << "max_x: " << max_x << endl;
    //        cout << "min_y: " << min_y << endl;
    //        cout << "max_y: " << max_y << endl;

    // Calculate height/width/area of this bounding rectangle
    double width = max_x - min_x;
    double height = max_y - min_y;
    double area = width * height;
    //        cout << "Width: " << width << endl;
    //        cout << "Height: " << height << endl;
    //        cout << "area: " << area << endl;
    //        cout << "angle: " << angle*180/M_PI << endl;

    // Store the smallest rect found first (a simple convex hull might have 2
    // answers with same area)
    if (area < min_area) {
      min_area = area;
      minBBox.angle = angle;
      minBBox.width = width;
      minBBox.height = height;

      minBBox.corners.clear();
188 189 190 191 192
      minBBox.corners.outer().push_back(FPoint{min_x, min_y});
      minBBox.corners.outer().push_back(FPoint{min_x, max_y});
      minBBox.corners.outer().push_back(FPoint{max_x, max_y});
      minBBox.corners.outer().push_back(FPoint{max_x, min_y});
      minBBox.corners.outer().push_back(FPoint{min_x, min_y});
193 194 195 196 197 198 199
    }
    // cout << endl << endl;
  }

  // Transform corners of minimal bounding box.
  trans::rotate_transformer<bg::degree, double, 2, 2> rotate(-minBBox.angle *
                                                             180 / M_PI);
200
  FPolygon rotated_polygon;
201 202
  bg::transform(minBBox.corners, rotated_polygon, rotate);
  minBBox.corners = rotated_polygon;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
203 204

  return true;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
205 206
}

207
void offsetPolygon(const FPolygon &polygon, FPolygon &polygonOffset,
208 209 210 211 212 213
                   double offset) {
  bg::strategy::buffer::distance_symmetric<double> distance_strategy(offset);
  bg::strategy::buffer::join_miter join_strategy(3);
  bg::strategy::buffer::end_flat end_strategy;
  bg::strategy::buffer::point_square point_strategy;
  bg::strategy::buffer::side_straight side_strategy;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
214

215
  bg::model::multi_polygon<FPolygon> result;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
216

217 218
  bg::buffer(polygon, result, distance_strategy, side_strategy, join_strategy,
             end_strategy, point_strategy);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
219

220 221
  if (result.size() > 0)
    polygonOffset = result[0];
Valentin Platzgummer's avatar
Valentin Platzgummer committed
222 223
}

224 225 226
void graphFromPolygon(const FPolygon &polygon, const FLineString &vertices,
                      Matrix<double> &graph) {
  size_t n = graph.n();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
227

228
  for (size_t i = 0; i < n; ++i) {
229
    FPoint v1 = vertices[i];
230
    for (size_t j = i + 1; j < n; ++j) {
231 232
      FPoint v2 = vertices[j];
      FLineString path{v1, v2};
Valentin Platzgummer's avatar
Valentin Platzgummer committed
233

234 235 236 237 238
      double distance = 0;
      if (!bg::within(path, polygon))
        distance = std::numeric_limits<double>::infinity();
      else
        distance = bg::length(path);
239 240
      graph(i, j) = distance;
      graph(j, i) = distance;
241 242
    }
  }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
243 244
}

245
bool toDistanceMatrix(Matrix<double> &graph) {
246
  size_t n = graph.n();
247

248 249 250
  auto distance = [&graph](size_t i, size_t j) -> double {
    return graph(i, j);
  };
251 252 253

  for (size_t i = 0; i < n; ++i) {
    for (size_t j = i + 1; j < n; ++j) {
254
      double d = graph(i, j);
255 256
      if (!std::isinf(d))
        continue;
257 258
      std::vector<size_t> path;
      if (!dijkstraAlgorithm(n, i, j, path, d, distance)) {
259 260
        return false;
      }
261 262 263 264 265
      //            cout << "(" << i << "," << j << ") d: " << d << endl;
      //            cout << "Path size: " << path.size() << endl;
      //            for (auto idx : path)
      //                cout << idx << " ";
      //            cout << endl;
266 267
      graph(i, j) = d;
      graph(j, i) = d;
268 269
    }
  }
270
  return true;
271
}
Valentin Platzgummer's avatar
Valentin Platzgummer committed
272

273 274 275
bool tiles(const FPolygon &area, Length tileHeight, Length tileWidth,
           Area minTileArea, std::vector<FPolygon> &tiles, BoundingBox &bbox,
           string &errorString) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
276 277
  if (area.outer().empty() || area.outer().size() < 4) {
    errorString = "Area has to few vertices.";
278
    return false;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
279
  }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
280

Valentin Platzgummer's avatar
Valentin Platzgummer committed
281 282
  if (tileWidth <= 0 * bu::si::meter || tileHeight <= 0 * bu::si::meter ||
      minTileArea < 0 * bu::si::meter * bu::si::meter) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
283
    std::stringstream ss;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
284 285
    ss << "Parameters tileWidth (" << tileWidth << "), tileHeight ("
       << tileHeight << "), minTileArea (" << minTileArea
Valentin Platzgummer's avatar
Valentin Platzgummer committed
286 287
       << ") must be positive.";
    errorString = ss.str();
288 289 290
    return false;
  }

Valentin Platzgummer's avatar
Valentin Platzgummer committed
291 292 293 294
  if (bbox.corners.outer().size() != 5) {
    bbox.corners.clear();
    minimalBoundingBox(area, bbox);
  }
295

Valentin Platzgummer's avatar
Valentin Platzgummer committed
296 297 298 299
  if (bbox.corners.outer().size() < 5)
    return false;
  double bboxWidth = bbox.width;
  double bboxHeight = bbox.height;
300
  FPoint origin = bbox.corners.outer()[0];
301 302 303 304

  // cout << "Origin: " << origin[0] << " " << origin[1] << endl;
  // Transform _mArea polygon to bounding box coordinate system.
  trans::rotate_transformer<boost::geometry::degree, double, 2, 2> rotate(
Valentin Platzgummer's avatar
Valentin Platzgummer committed
305
      bbox.angle * 180 / M_PI);
306 307
  trans::translate_transformer<double, 2, 2> translate(-origin.get<0>(),
                                                       -origin.get<1>());
308 309
  FPolygon translated_polygon;
  FPolygon rotated_polygon;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
310
  boost::geometry::transform(area, translated_polygon, translate);
311 312 313 314
  boost::geometry::transform(translated_polygon, rotated_polygon, rotate);
  bg::correct(rotated_polygon);
  // cout << bg::wkt<BoostPolygon2D>(rotated_polygon) << endl;

Valentin Platzgummer's avatar
Valentin Platzgummer committed
315 316
  size_t iMax = ceil(bboxWidth / tileWidth.value());
  size_t jMax = ceil(bboxHeight / tileHeight.value());
317 318 319

  if (iMax < 1 || jMax < 1) {
    std::stringstream ss;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
320
    ss << "Tile width (" << tileWidth << ") or tile height (" << tileHeight
Valentin Platzgummer's avatar
Valentin Platzgummer committed
321
       << ") to large for measurement area.";
322 323 324 325 326
    errorString = ss.str();
    return false;
  }

  trans::rotate_transformer<boost::geometry::degree, double, 2, 2> rotate_back(
Valentin Platzgummer's avatar
Valentin Platzgummer committed
327
      -bbox.angle * 180 / M_PI);
328 329 330
  trans::translate_transformer<double, 2, 2> translate_back(origin.get<0>(),
                                                            origin.get<1>());
  for (size_t i = 0; i < iMax; ++i) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
331 332
    double x_min = tileWidth.value() * i;
    double x_max = x_min + tileWidth.value();
333
    for (size_t j = 0; j < jMax; ++j) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
334 335
      double y_min = tileHeight.value() * j;
      double y_max = y_min + tileHeight.value();
336

337 338 339 340 341 342
      FPolygon tile_unclipped;
      tile_unclipped.outer().push_back(FPoint{x_min, y_min});
      tile_unclipped.outer().push_back(FPoint{x_min, y_max});
      tile_unclipped.outer().push_back(FPoint{x_max, y_max});
      tile_unclipped.outer().push_back(FPoint{x_max, y_min});
      tile_unclipped.outer().push_back(FPoint{x_min, y_min});
343

344
      std::deque<FPolygon> boost_tiles;
345 346 347 348
      if (!boost::geometry::intersection(tile_unclipped, rotated_polygon,
                                         boost_tiles))
        continue;

349
      for (FPolygon t : boost_tiles) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
350
        if (bg::area(t) > minTileArea.value()) {
351
          // Transform boost_tile to world coordinate system.
352 353
          FPolygon rotated_tile;
          FPolygon translated_tile;
354 355 356 357 358
          boost::geometry::transform(t, rotated_tile, rotate_back);
          boost::geometry::transform(rotated_tile, translated_tile,
                                     translate_back);

          // Store tile and calculate center point.
Valentin Platzgummer's avatar
Valentin Platzgummer committed
359
          tiles.push_back(translated_tile);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
360
        }
361
      }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
362
    }
363
  }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
364

Valentin Platzgummer's avatar
Valentin Platzgummer committed
365
  if (tiles.size() < 1) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
366
    std::stringstream ss;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
367
    ss << "No tiles calculated. Is the minTileArea (" << minTileArea
Valentin Platzgummer's avatar
Valentin Platzgummer committed
368 369
       << ") parameter large enough?";
    errorString = ss.str();
370 371
    return false;
  }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
372

373
  return true;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
374 375
}

376 377
bool joinedArea(const FPolygon &mArea, const FPolygon &sArea,
                const FPolygon &corridor, FPolygon &jArea,
Valentin Platzgummer's avatar
Valentin Platzgummer committed
378
                std::string &errorString) {
379
  // Measurement area and service area overlapping?
Valentin Platzgummer's avatar
Valentin Platzgummer committed
380 381
  bool overlapingSerMeas = bg::intersects(mArea, sArea) ? true : false;
  bool corridorValid = corridor.outer().size() > 0 ? true : false;
382 383 384 385 386

  // Check if corridor is connecting measurement area and service area.
  bool corridor_is_connection = false;
  if (corridorValid) {
    // Corridor overlaping with measurement area?
Valentin Platzgummer's avatar
Valentin Platzgummer committed
387
    if (bg::intersects(corridor, mArea)) {
388
      // Corridor overlaping with service area?
Valentin Platzgummer's avatar
Valentin Platzgummer committed
389
      if (bg::intersects(corridor, sArea)) {
390 391
        corridor_is_connection = true;
      }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
392
    }
393 394 395
  }

  // Are areas joinable?
396 397
  std::deque<FPolygon> sol;
  FPolygon partialArea = mArea;
398 399
  if (overlapingSerMeas) {
    if (corridor_is_connection) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
400
      bg::union_(partialArea, corridor, sol);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
401
    }
402
  } else if (corridor_is_connection) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
403
    bg::union_(partialArea, corridor, sol);
404
  } else {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
405
    std::stringstream ss;
406
    auto printPoint = [&ss](const FPoint &p) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
407 408 409 410
      ss << " (" << p.get<0>() << ", " << p.get<1>() << ")";
    };
    ss << "Areas are not overlapping." << std::endl;
    ss << "Measurement area:";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
411
    bg::for_each_point(mArea, printPoint);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
412 413
    ss << std::endl;
    ss << "Service area:";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
414
    bg::for_each_point(sArea, printPoint);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
415 416
    ss << std::endl;
    ss << "Corridor:";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
417
    bg::for_each_point(corridor, printPoint);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
418 419
    ss << std::endl;
    errorString = ss.str();
420 421 422 423 424 425 426 427 428
    return false;
  }

  if (sol.size() > 0) {
    partialArea = sol[0];
    sol.clear();
  }

  // Join areas.
Valentin Platzgummer's avatar
Valentin Platzgummer committed
429
  bg::union_(partialArea, sArea, sol);
430 431

  if (sol.size() > 0) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
432
    jArea = sol[0];
433
  } else {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
434
    std::stringstream ss;
435
    auto printPoint = [&ss](const FPoint &p) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
436 437 438 439 440 441 442 443 444 445 446 447 448
      ss << " (" << p.get<0>() << ", " << p.get<1>() << ")";
    };
    ss << "Areas not joinable." << std::endl;
    ss << "Measurement area:";
    bg::for_each_point(mArea, printPoint);
    ss << std::endl;
    ss << "Service area:";
    bg::for_each_point(sArea, printPoint);
    ss << std::endl;
    ss << "Corridor:";
    bg::for_each_point(corridor, printPoint);
    ss << std::endl;
    errorString = ss.str();
449 450 451 452
    return false;
  }

  return true;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
453 454
}

455
bool joinedArea(const std::vector<FPolygon *> &areas, FPolygon &joinedArea) {
456 457
  if (areas.size() < 1)
    return false;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
458
  joinedArea = *areas[0];
459 460 461 462
  std::deque<std::size_t> idxList;
  for (size_t i = 1; i < areas.size(); ++i)
    idxList.push_back(i);

463
  std::deque<FPolygon> sol;
464 465 466
  while (idxList.size() > 0) {
    bool success = false;
    for (auto it = idxList.begin(); it != idxList.end(); ++it) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
467
      bg::union_(joinedArea, *areas[*it], sol);
468 469 470 471 472 473 474
      if (sol.size() > 0) {
        joinedArea = sol[0];
        sol.clear();
        idxList.erase(it);
        success = true;
        break;
      }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
475
    }
476 477 478
    if (!success)
      return false;
  }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
479

480
  return true;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
481 482
}

483
BoundingBox::BoundingBox() : width(0), height(0), angle(0) {}
Valentin Platzgummer's avatar
Valentin Platzgummer committed
484

485 486 487 488 489
void BoundingBox::clear() {
  width = 0;
  height = 0;
  angle = 0;
  corners.clear();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
490 491
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
492
bool transectsFromScenario(Length distance, Length minLength, Angle angle,
493 494
                           const FPolygon &mArea,
                           const std::vector<FPolygon> &tiles,
Valentin Platzgummer's avatar
Valentin Platzgummer committed
495 496
                           const Progress &p, Transects &t,
                           string &errorString) {
497
  // Rotate measurement area by angle and calculate bounding box.
498
  FPolygon mAreaRotated;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
499
  trans::rotate_transformer<bg::degree, double, 2, 2> rotate(angle.value() *
500 501 502
                                                             180 / M_PI);
  bg::transform(mArea, mAreaRotated, rotate);

503
  FBox box;
504 505 506 507 508 509 510 511 512 513 514 515
  boost::geometry::envelope(mAreaRotated, box);
  double x0 = box.min_corner().get<0>();
  double y0 = box.min_corner().get<1>();
  double x1 = box.max_corner().get<0>();
  double y1 = box.max_corner().get<1>();

  // Generate transects and convert them to clipper path.
  size_t num_t = int(ceil((y1 - y0) / distance.value())); // number of transects
  vector<ClipperLib::Path> transectsClipper;
  transectsClipper.reserve(num_t);
  for (size_t i = 0; i < num_t; ++i) {
    // calculate transect
516 517 518
    FPoint v1{x0, y0 + i * distance.value()};
    FPoint v2{x1, y0 + i * distance.value()};
    FLineString transect;
519 520 521
    transect.push_back(v1);
    transect.push_back(v2);
    // transform back
522
    FLineString temp_transect;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
523 524
    trans::rotate_transformer<bg::degree, double, 2, 2> rotate_back(
        -angle.value() * 180 / M_PI);
525
    bg::transform(transect, temp_transect, rotate_back);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
526 527 528 529 530 531 532 533 534
    // to clipper
    ClipperLib::IntPoint c1{static_cast<ClipperLib::cInt>(
                                temp_transect[0].get<0>() * CLIPPER_SCALE),
                            static_cast<ClipperLib::cInt>(
                                temp_transect[0].get<1>() * CLIPPER_SCALE)};
    ClipperLib::IntPoint c2{static_cast<ClipperLib::cInt>(
                                temp_transect[1].get<0>() * CLIPPER_SCALE),
                            static_cast<ClipperLib::cInt>(
                                temp_transect[1].get<1>() * CLIPPER_SCALE)};
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
    ClipperLib::Path path{c1, c2};
    transectsClipper.push_back(path);
  }

  if (transectsClipper.size() == 0) {
    std::stringstream ss;
    ss << "Not able to generate transects. Parameter: distance = " << distance
       << std::endl;
    errorString = ss.str();
    return false;
  }

  // Convert measurement area to clipper path.
  ClipperLib::Path mAreaClipper;
  for (auto vertex : mArea.outer()) {
    mAreaClipper.push_back(ClipperLib::IntPoint{
        static_cast<ClipperLib::cInt>(vertex.get<0>() * CLIPPER_SCALE),
        static_cast<ClipperLib::cInt>(vertex.get<1>() * CLIPPER_SCALE)});
  }

  // Perform clipping.
  // Clip transects to measurement area.
  ClipperLib::Clipper clipper;
  clipper.AddPath(mAreaClipper, ClipperLib::ptClip, true);
  clipper.AddPaths(transectsClipper, ClipperLib::ptSubject, false);
  ClipperLib::PolyTree clippedTransecs;
  clipper.Execute(ClipperLib::ctIntersection, clippedTransecs,
                  ClipperLib::pftNonZero, ClipperLib::pftNonZero);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
563
  const auto *transects = &clippedTransecs;
564

Valentin Platzgummer's avatar
Valentin Platzgummer committed
565
  bool ignoreProgress = p.size() != tiles.size();
566 567 568 569 570
  ClipperLib::PolyTree clippedTransecs2;
  if (!ignoreProgress) {
    // Calculate processed tiles (_progress[i] == 100) and subtract them from
    // measurement area.
    size_t numTiles = p.size();
571
    vector<FPolygon> processedTiles;
572 573 574 575
    for (size_t i = 0; i < numTiles; ++i) {
      if (p[i] == 100) {
        processedTiles.push_back(tiles[i]);
      }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
576
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
577

578 579
    if (processedTiles.size() != numTiles) {
      vector<ClipperLib::Path> processedTilesClipper;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
580
      for (const auto &t : processedTiles) {
581
        ClipperLib::Path path;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
582
        for (const auto &vertex : t.outer()) {
583 584 585
          path.push_back(ClipperLib::IntPoint{
              static_cast<ClipperLib::cInt>(vertex.get<0>() * CLIPPER_SCALE),
              static_cast<ClipperLib::cInt>(vertex.get<1>() * CLIPPER_SCALE)});
Valentin Platzgummer's avatar
Valentin Platzgummer committed
586
        }
587 588 589 590 591
        processedTilesClipper.push_back(path);
      }

      // Subtract holes (tiles with measurement_progress == 100) from transects.
      clipper.Clear();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
592
      for (const auto &child : clippedTransecs.Childs) {
593
        clipper.AddPath(child->Contour, ClipperLib::ptSubject, false);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
594
      }
595 596 597
      clipper.AddPaths(processedTilesClipper, ClipperLib::ptClip, true);
      clipper.Execute(ClipperLib::ctDifference, clippedTransecs2,
                      ClipperLib::pftNonZero, ClipperLib::pftNonZero);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
598 599 600 601
      transects = &clippedTransecs2;
    } else {
      // All tiles processed (t.size() not changed).
      return true;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
602
    }
603 604 605
  }

  // Extract transects from  PolyTree and convert them to BoostLineString
Valentin Platzgummer's avatar
Valentin Platzgummer committed
606 607
  for (const auto &child : transects->Childs) {
    const auto &clipperTransect = child->Contour;
608 609 610 611
    FPoint v1{static_cast<double>(clipperTransect[0].X) / CLIPPER_SCALE,
              static_cast<double>(clipperTransect[0].Y) / CLIPPER_SCALE};
    FPoint v2{static_cast<double>(clipperTransect[1].X) / CLIPPER_SCALE,
              static_cast<double>(clipperTransect[1].Y) / CLIPPER_SCALE};
612

613
    FLineString transect{v1, v2};
Valentin Platzgummer's avatar
Valentin Platzgummer committed
614
    if (bg::length(transect) >= minLength.value()) {
615
      t.push_back(transect);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
616
    }
617 618 619 620 621 622 623 624 625 626
  }

  if (t.size() == 0) {
    std::stringstream ss;
    ss << "Not able to generate transects. Parameter: minLength = " << minLength
       << std::endl;
    errorString = ss.str();
    return false;
  }
  return true;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
627 628
}

629
bool route(const FPolygon &area, const Transects &transects,
630
           std::vector<Solution> &solutionVector, const RouteParameter &par) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
631

Valentin Platzgummer's avatar
Valentin Platzgummer committed
632
#ifdef SNAKE_SHOW_TIME
633
  auto start = std::chrono::high_resolution_clock::now();
634
#endif
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
  //================================================================
  // Create routing model.
  //================================================================
  // Use integer polygons to increase numerical robustness.
  // Convert area;
  IPolygon intArea;
  for (const auto &v : area.outer()) {
    auto p = float2Int(v);
    intArea.outer().push_back(p);
  }
  for (const auto &ring : area.inners()) {
    IRing intRing;
    for (const auto &v : ring) {
      auto p = float2Int(v);
      intRing.push_back(p);
    }
    intArea.inners().push_back(std::move(intRing));
  }

  // Helper classes.
  struct VirtualNode {
    VirtualNode(std::size_t f, std::size_t t) : fromIndex(f), toIndex(t) {}
    std::size_t fromIndex; // index for leaving node
    std::size_t toIndex;   // index for entering node
  };
  struct NodeToTransect {
    NodeToTransect(std::size_t i, bool r) : transectsIndex(i), reversed(r) {}
    std::size_t transectsIndex; // transects index
    bool reversed;              // transect reversed?
  };
  // Create vertex and node list
  std::vector<IPoint> vertices;
  std::vector<std::pair<std::size_t, std::size_t>> disjointNodes;
  std::vector<VirtualNode> nodeList;
  std::vector<NodeToTransect> nodeToTransectList;
  for (std::size_t i = 0; i < transects.size(); ++i) {
    const auto &t = transects[i];
    // Copy line edges only.
    if (t.size() == 1 || i == 0) {
      auto p = float2Int(t.back());
      vertices.push_back(p);
      nodeToTransectList.emplace_back(i, false);
      auto idx = vertices.size() - 1;
      nodeList.emplace_back(idx, idx);
    } else if (t.size() > 1) {
      auto p1 = float2Int(t.front());
      auto p2 = float2Int(t.back());
      vertices.push_back(p1);
      vertices.push_back(p2);
      nodeToTransectList.emplace_back(i, false);
      nodeToTransectList.emplace_back(i, true);
      auto fromIdx = vertices.size() - 1;
      auto toIdx = fromIdx - 1;
      nodeList.emplace_back(fromIdx, toIdx);
      nodeList.emplace_back(toIdx, fromIdx);
      disjointNodes.emplace_back(toIdx, fromIdx);
    } else { // transect empty
      std::cout << "ignoring empty transect with index " << i << std::endl;
    }
  }
#ifdef SNAKE_DEBUG
  // Print.
  std::cout << "nodeToTransectList:" << std::endl;
  std::cout << "node:transectIndex:reversed" << std::endl;
  std::size_t c = 0;
  for (const auto &n2t : nodeToTransectList) {
    std::cout << c++ << ":" << n2t.transectsIndex << ":" << n2t.reversed
              << std::endl;
  }
  std::cout << "nodeList:" << std::endl;
  std::cout << "node:fromIndex:toIndex" << std::endl;
  c = 0;
  for (const auto &n : nodeList) {
    std::cout << c++ << ":" << n.fromIndex << ":" << n.toIndex << std::endl;
  }
  std::cout << "disjoint nodes:" << std::endl;
  std::cout << "number:nodes" << std::endl;
  c = 0;
  for (const auto &d : disjointNodes) {
    std::cout << c++ << ":" << d.first << "," << d.second << std::endl;
  }
#endif

  // Add polygon vertices.
  for (auto &v : intArea.outer()) {
    vertices.push_back(v);
  }
  for (auto &ring : intArea.inners()) {
    for (auto &v : ring) {
      vertices.push_back(v);
    }
  }

  // Create connection graph (inf == no connection between vertices).
  // Note: graph is not symmetric.
  auto n = vertices.size();
  // Matrix must be double since integers don't have infinity and nan
  Matrix<double> connectionGraph(n, n);
  for (std::size_t i = 0; i < n; ++i) {
    auto &fromVertex = vertices[i];
    for (std::size_t j = 0; j < n; ++j) {
      auto &toVertex = vertices[j];
      ILineString line{fromVertex, toVertex};
      if (bg::covered_by(line, intArea)) {
        connectionGraph(i, j) = bg::length(line);
      } else {
        connectionGraph(i, j) = std::numeric_limits<double>::infinity();
      }
    }
  }
#ifdef SNAKE_DEBUG
  std::cout << "connection grah:" << std::endl;
  std::cout << connectionGraph << std::endl;
#endif

  // Create distance matrix.
  auto distLambda = [&connectionGraph](std::size_t i, std::size_t j) -> double {
    return connectionGraph(i, j);
  };
  auto nNodes = nodeList.size();
  Matrix<IntType> distanceMatrix(nNodes, nNodes);
  for (std::size_t i = 0; i < nNodes; ++i) {
    distanceMatrix(i, i) = 0;
    for (std::size_t j = i + 1; j < nNodes; ++j) {
      auto dist = connectionGraph(i, j);
      if (std::isinf(dist)) {
        std::vector<std::size_t> route;
        if (!dijkstraAlgorithm(n, i, j, route, dist, distLambda)) {
763 764 765 766 767 768 769 770 771 772 773
          std::stringstream ss;
          ss << "Distance matrix calculation failed. connection graph: "
             << connectionGraph << std::endl;
          ss << "area: " << bg::wkt(area) << std::endl;
          ss << "transects:" << std::endl;
          for (const auto &t : transects) {

            ss << bg::wkt(t) << std::endl;
          }

          par.errorString = ss.str();
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
          return false;
        }
        (void)route;
      }
      distanceMatrix(i, j) = dist;
      distanceMatrix(j, i) = dist;
    }
  }
#ifdef SNAKE_DEBUG
  std::cout << "distance matrix:" << std::endl;
  std::cout << distanceMatrix << std::endl;
#endif

  // Create (asymmetric) routing matrix.
  Matrix<IntType> routingMatrix(nNodes, nNodes);
  for (std::size_t i = 0; i < nNodes; ++i) {
    auto fromNode = nodeList[i];
    for (std::size_t j = 0; j < nNodes; ++j) {
      auto toNode = nodeList[j];
      routingMatrix(i, j) = distanceMatrix(fromNode.fromIndex, toNode.toIndex);
    }
  }
  // Insert max for disjoint nodes.
  for (const auto &d : disjointNodes) {
    auto i = d.first;
    auto j = d.second;
    routingMatrix(i, j) = std::numeric_limits<IntType>::max();
    routingMatrix(j, i) = std::numeric_limits<IntType>::max();
  }
#ifdef SNAKE_DEBUG
  std::cout << "routing matrix:" << std::endl;
  std::cout << routingMatrix << std::endl;
#endif

  // Create Routing Index Manager.
809 810 811 812 813 814 815
  auto minNumTransectsPerRun =
      std::max<std::size_t>(1, par.minNumTransectsPerRun);
  auto maxRuns = std::max<std::size_t>(
      1, std::floor(double(transects.size()) / minNumTransectsPerRun));
  auto numRuns = std::max<std::size_t>(1, par.numRuns);
  numRuns = std::min<std::size_t>(numRuns, maxRuns);

816
  RoutingIndexManager::NodeIndex depot(0);
817 818 819 820
  //  std::vector<RoutingIndexManager::NodeIndex> depots(numRuns, depot);
  //  RoutingIndexManager manager(nNodes, numRuns, depots, depots);
  RoutingIndexManager manager(nNodes, numRuns, depot);

821 822 823 824 825 826 827 828 829 830 831 832
  // Create Routing Model.
  RoutingModel routing(manager);
  // Create and register a transit callback.
  const int transitCallbackIndex = routing.RegisterTransitCallback(
      [&routingMatrix, &manager](int64 from_index, int64 to_index) -> int64 {
        // Convert from routing variable Index to distance matrix NodeIndex.
        auto from_node = manager.IndexToNode(from_index).value();
        auto to_node = manager.IndexToNode(to_index).value();
        return routingMatrix(from_node, to_node);
      });
  // Define cost of each arc.
  routing.SetArcCostEvaluatorOfAllVehicles(transitCallbackIndex);
833 834 835 836 837 838 839 840
  // Add distance dimension.
  if (numRuns > 1) {
    routing.AddDimension(transitCallbackIndex, 0, 300000000,
                         true, // start cumul to zero
                         "Distance");
    routing.GetMutableDimension("Distance")
        ->SetGlobalSpanCostCoefficient(100000000);
  }
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861

  // Define disjunctions.
#ifdef SNAKE_DEBUG
  std::cout << "disjunctions:" << std::endl;
#endif
  for (const auto &d : disjointNodes) {
    auto i = d.first;
    auto j = d.second;
#ifdef SNAKE_DEBUG
    std::cout << i << "," << j << std::endl;
#endif
    auto idx0 = manager.NodeToIndex(RoutingIndexManager::NodeIndex(i));
    auto idx1 = manager.NodeToIndex(RoutingIndexManager::NodeIndex(j));
    std::vector<int64> disj{idx0, idx1};
    routing.AddDisjunction(disj, -1 /*force cardinality*/, 1 /*cardinality*/);
  }

  // Set first solution heuristic.
  auto searchParameters = DefaultRoutingSearchParameters();
  searchParameters.set_first_solution_strategy(
      FirstSolutionStrategy::PATH_CHEAPEST_ARC);
862
  // Number of solutions.
863 864
  auto numSolutionsPerRun = std::max<std::size_t>(1, par.numSolutionsPerRun);
  searchParameters.set_number_of_solutions_to_collect(numSolutionsPerRun);
865 866
  // Set costume limit.
  auto *solver = routing.solver();
867
  auto *limit = solver->MakeCustomLimit(par.stop);
868
  routing.AddSearchMonitor(limit);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
869
#ifdef SNAKE_SHOW_TIME
870 871
  auto delta = std::chrono::duration_cast<std::chrono::milliseconds>(
      std::chrono::high_resolution_clock::now() - start);
872
  cout << "create routing model: " << delta.count() << " ms" << endl;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
873
#endif
874 875 876 877

  //================================================================
  // Solve model.
  //================================================================
Valentin Platzgummer's avatar
Valentin Platzgummer committed
878
#ifdef SNAKE_SHOW_TIME
879
  start = std::chrono::high_resolution_clock::now();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
880
#endif
881 882
  auto pSolutions = std::make_unique<std::vector<const Assignment *>>();
  (void)routing.SolveWithParameters(searchParameters, pSolutions.get());
883 884 885 886 887
#ifdef SNAKE_SHOW_TIME
  delta = std::chrono::duration_cast<std::chrono::milliseconds>(
      std::chrono::high_resolution_clock::now() - start);
  cout << "solve routing model: " << delta.count() << " ms" << endl;
#endif
888 889
  if (par.stop()) {
    par.errorString = "User terminated.";
890 891
    return false;
  }
892 893 894 895 896 897
  if (pSolutions->size() == 0) {
    std::stringstream ss;
    ss << "No solution found." << std::endl;
    par.errorString = ss.str();
    return false;
  }
898

899 900 901
  //================================================================
  // Construc route.
  //================================================================
902 903 904
#ifdef SNAKE_SHOW_TIME
  start = std::chrono::high_resolution_clock::now();
#endif
905 906 907 908 909 910 911 912 913 914 915 916 917
  long long counter = -1;
  // Note: route number 0 corresponds to the best route which is the last entry
  // of *pSolutions.
  for (auto solution = pSolutions->end() - 1; solution >= pSolutions->begin();
       --solution) {
    ++counter;
    if (!*solution || (*solution)->Size() <= 1) {
      std::stringstream ss;
      ss << par.errorString << "Solution " << counter << "invalid."
         << std::endl;
      par.errorString = ss.str();
      continue;
    }
918 919 920 921 922 923 924 925 926
    // Iterate over all routes.
    Solution routeVector;
    for (std::size_t vehicle = 0; vehicle < numRuns; ++vehicle) {
      if (!routing.IsVehicleUsed(**solution, vehicle))
        continue;

      // Create index list.
      auto index = routing.Start(vehicle);
      std::vector<size_t> route_idx;
927
      route_idx.push_back(manager.IndexToNode(index).value());
928 929 930 931
      while (!routing.IsEnd(index)) {
        index = (*solution)->Value(routing.NextVar(index));
        route_idx.push_back(manager.IndexToNode(index).value());
      }
932 933

#ifdef SNAKE_DEBUG
934 935 936 937 938 939 940 941
      // Print route.
      std::cout << "route " << counter
                << " route_idx.size() = " << route_idx.size() << std::endl;
      std::cout << "route: ";
      for (const auto &idx : route_idx) {
        std::cout << idx << ", ";
      }
      std::cout << std::endl;
942
#endif
943 944 945 946 947 948 949 950
      if (route_idx.size() < 2) {
        std::stringstream ss;
        ss << par.errorString
           << "Error while assembling route (solution = " << counter
           << ", run = " << vehicle << ")." << std::endl;
        par.errorString = ss.str();
        continue;
      }
951

952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
      // Assemble route.
      Route r;
      auto &path = r.path;
      auto &info = r.info;
      for (size_t i = 0; i < route_idx.size() - 1; ++i) {
        size_t nodeIndex0 = route_idx[i];
        size_t nodeIndex1 = route_idx[i + 1];
        const auto &n2t0 = nodeToTransectList[nodeIndex0];
        info.emplace_back(n2t0.transectsIndex, n2t0.reversed);
        // Copy transect to route.
        const auto &t = transects[n2t0.transectsIndex];
        if (n2t0.reversed) { // transect reversal needed?
          for (auto it = t.end() - 1; it > t.begin(); --it) {
            path.push_back(*it);
          }
        } else {
          for (auto it = t.begin(); it < t.end() - 1; ++it) {
            path.push_back(*it);
          }
971
        }
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989
        // Connect transects.
        std::vector<size_t> idxList;
        if (!shortestPathFromGraph(connectionGraph,
                                   nodeList[nodeIndex0].fromIndex,
                                   nodeList[nodeIndex1].toIndex, idxList)) {
          std::stringstream ss;
          ss << par.errorString
             << "Error while assembling route (solution = " << counter
             << ", run = " << vehicle << ")." << std::endl;
          par.errorString = ss.str();
          continue;
        }
        if (i != route_idx.size() - 2) {
          idxList.pop_back();
        }
        for (auto idx : idxList) {
          auto p = int2Float(vertices[idx]);
          path.push_back(p);
990
        }
991
      }
992 993 994 995 996
      // Append last transect info.
      const auto &n2t0 = nodeToTransectList.back();
      info.emplace_back(n2t0.transectsIndex, n2t0.reversed);

      if (path.size() < 2 || info.size() < 2) {
997
        std::stringstream ss;
998 999
        ss << par.errorString << "Route empty (solution = " << counter
           << ", run = " << vehicle << ")." << std::endl;
1000 1001 1002 1003
        par.errorString = ss.str();
        continue;
      }

1004 1005 1006 1007 1008
      routeVector.push_back(std::move(r));
    }
    if (routeVector.size() > 0) {
      solutionVector.push_back(std::move(routeVector));
    } else {
1009
      std::stringstream ss;
1010
      ss << par.errorString << "Solution " << counter << " empty." << std::endl;
1011
      par.errorString = ss.str();
1012 1013
    }
  }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1014
#ifdef SNAKE_SHOW_TIME
1015 1016
  delta = std::chrono::duration_cast<std::chrono::milliseconds>(
      std::chrono::high_resolution_clock::now() - start);
1017
  cout << "reconstruct route: " << delta.count() << " ms" << endl;
1018
#endif
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1019

1020
  if (solutionVector.size() > 0) {
1021 1022
    return true;
  } else {
1023
    return false;
1024
  }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1025 1026
}

1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
FPoint int2Float(const IPoint &ip) { return int2Float(ip, stdScale); }

FPoint int2Float(const IPoint &ip, IntType scale) {
  return FPoint{FloatType(ip.get<0>()) / scale, FloatType(ip.get<1>()) / scale};
}

IPoint float2Int(const FPoint &ip) { return float2Int(ip, stdScale); }

IPoint float2Int(const FPoint &ip, IntType scale) {
  return IPoint{IntType(std::llround(ip.get<0>() * scale)),
                IntType(std::llround(ip.get<1>() * scale))};
}

bool dijkstraAlgorithm(size_t numElements, size_t startIndex, size_t endIndex,
                       std::vector<size_t> &elementPath, double &length,
                       std::function<double(size_t, size_t)> distanceDij) {
  if (startIndex >= numElements || endIndex >= numElements) {
    length = std::numeric_limits<double>::infinity();
    return false;
  } else if (endIndex == startIndex) {
    length = 0;
    elementPath.push_back(startIndex);
    return true;
  }

  // Node struct
  // predecessorIndex is the index of the predecessor node
  // (nodeList[predecessorIndex]) distance is the distance between the node and
  // the start node node number is stored by the position in nodeList
  struct Node {
    std::size_t predecessorIndex = std::numeric_limits<std::size_t>::max();
    double distance = std::numeric_limits<double>::infinity();
  };

  // The list with all Nodes (elements)
  std::vector<Node> nodeList(numElements);
  // This list will be initalized with indices referring to the elements of
  // nodeList. Elements will be successively remove during the execution of the
  // Dijkstra Algorithm.
  std::vector<size_t> workingSet(numElements);

  // append elements to node list
  for (size_t i = 0; i < numElements; ++i)
    workingSet[i] = i;

  nodeList[startIndex].distance = 0;

  // Dijkstra Algorithm
  // https://de.wikipedia.org/wiki/Dijkstra-Algorithmus
  while (workingSet.size() > 0) {
    // serach Node with minimal distance
    auto minDist = std::numeric_limits<double>::infinity();
    std::size_t minDistIndex_WS =
        std::numeric_limits<std::size_t>::max(); // WS = workinSet
    for (size_t i = 0; i < workingSet.size(); ++i) {
      const auto nodeIndex = workingSet.at(i);
      const auto dist = nodeList.at(nodeIndex).distance;
      if (dist < minDist) {
        minDist = dist;
        minDistIndex_WS = i;
      }
    }
    if (minDistIndex_WS == std::numeric_limits<std::size_t>::max())
      return false;

    size_t indexU_NL = workingSet.at(minDistIndex_WS); // NL = nodeList
    workingSet.erase(workingSet.begin() + minDistIndex_WS);
    if (indexU_NL == endIndex) // shortest path found
      break;

    const auto distanceU = nodeList.at(indexU_NL).distance;
    // update distance
    for (size_t i = 0; i < workingSet.size(); ++i) {
      auto indexV_NL = workingSet[i]; // NL = nodeList
      Node *v = &nodeList[indexV_NL];
      auto dist = distanceDij(indexU_NL, indexV_NL);
      // is ther an alternative path which is shorter?
      auto alternative = distanceU + dist;
      if (alternative < v->distance) {
        v->distance = alternative;
        v->predecessorIndex = indexU_NL;
      }
    }
  }
  // end Djikstra Algorithm

  // reverse assemble path
  auto e = endIndex;
  length = nodeList[e].distance;
  while (true) {
    if (e == std::numeric_limits<std::size_t>::max()) {
      if (elementPath.size() > 0 &&
          elementPath[0] == startIndex) { // check if starting point was reached
        break;
      } else { // some error
        length = std::numeric_limits<double>::infinity();
        elementPath.clear();
        return false;
      }
    } else {
      elementPath.insert(elementPath.begin(), e);
      // Update Node
      e = nodeList[e].predecessorIndex;
    }
  }
  return true;
}

bool shortestPathFromGraph(const Matrix<double> &graph, const size_t startIndex,
                           const size_t endIndex,
                           std::vector<size_t> &pathIdx) {
  if (!std::isinf(graph(startIndex, endIndex))) {
    pathIdx.push_back(startIndex);
    pathIdx.push_back(endIndex);
  } else {
    auto distance = [&graph](size_t i, size_t j) -> double {
      return graph(i, j);
    };
    double d = 0;
    if (!dijkstraAlgorithm(graph.n(), startIndex, endIndex, pathIdx, d,
                           distance)) {
      return false;
    }
  }
  return true;
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1154
} // namespace snake
1155

1156
bool boost::geometry::model::operator==(snake::FPoint &p1, snake::FPoint &p2) {
1157 1158 1159
  return (p1.get<0>() == p2.get<0>()) && (p1.get<1>() == p2.get<1>());
}

1160 1161 1162 1163 1164 1165 1166 1167
bool boost::geometry::model::operator!=(snake::FPoint &p1, snake::FPoint &p2) {
  return !(p1 == p2);
}

bool boost::geometry::model::operator==(snake::IPoint &p1, snake::IPoint &p2) {
  return (p1.get<0>() == p2.get<0>()) && (p1.get<1>() == p2.get<1>());
}
bool boost::geometry::model::operator!=(snake::IPoint &p1, snake::IPoint &p2) {
1168 1169
  return !(p1 == p2);
}