Ejemplo n.º 1
0
  public GHResponse route(
      List<GHPoint> waypoints, List<Double> headings, boolean withInstructions) {
    if (waypoints.size() < 2) {
      throw new IllegalArgumentException("Number of waypoints must be greater or equal 2");
    }

    GHRequest request;
    if (headings != null) {
      request = new GHRequest(waypoints, headings);
      request.setVehicle(FlagEncoderFactory.CAR);
      request.setWeighting("fastest");
      if (!USE_CONTRACTION_HIERARCHIES) {
        request.getHints().put(Parameters.CH.DISABLE, true);
        request.getHints().put("routing.flexible_mode.force", true);
        request.getHints().put(Parameters.Routing.EDGE_BASED, true);
      } else {
        request
            .getHints()
            .put(
                Parameters.CH.FORCE_HEADING,
                true); // Allow headings for routes using CH, but may produce artifacts (see
        // https://github.com/graphhopper/graphhopper/pull/434#issuecomment-110275256)
      }
    } else {
      request = new GHRequest(waypoints);
    }
    request.setLocale(Locale.getDefault()).setAlgorithm(Parameters.Algorithms.DIJKSTRA_BI);
    if (!withInstructions) {
      request.getHints().put(Parameters.Routing.INSTRUCTIONS, false);
    }
    return gh.route(request);
  }
 public void suggest(File locationFile, int locationListSize, File outputFile, int hubSize) {
   // WARNING: this code is VERY DIRTY.
   // It's JUST good enough to generate the hubs for Belgium once (because we only need to
   // determine them once).
   // Further research to generate good hubs is needed.
   List<AirLocation> locationList = readAirLocationFile(locationFile);
   if (locationListSize > locationList.size()) {
     throw new IllegalArgumentException(
         "The locationListSize ("
             + locationListSize
             + ") is larger than the locationList size ("
             + locationList.size()
             + ").");
   }
   locationList = subselectLocationList(locationListSize, locationList);
   Map<Point, Point> fromPointMap = new LinkedHashMap<Point, Point>(locationListSize * 10);
   Map<Point, Point> toPointMap = new LinkedHashMap<Point, Point>(locationListSize * 10);
   int rowIndex = 0;
   double maxAirDistance = 0.0;
   for (AirLocation fromAirLocation : locationList) {
     for (AirLocation toAirLocation : locationList) {
       double airDistance = fromAirLocation.getAirDistanceDouble(toAirLocation);
       if (airDistance > maxAirDistance) {
         maxAirDistance = airDistance;
       }
     }
   }
   double airDistanceThreshold = maxAirDistance / 10.0;
   for (AirLocation fromAirLocation : locationList) {
     for (AirLocation toAirLocation : locationList) {
       double distance;
       if (fromAirLocation != toAirLocation) {
         GHRequest request =
             new GHRequest(
                     fromAirLocation.getLatitude(),
                     fromAirLocation.getLongitude(),
                     toAirLocation.getLatitude(),
                     toAirLocation.getLongitude())
                 .setVehicle("car");
         GHResponse response = graphHopper.route(request);
         if (response.hasErrors()) {
           throw new IllegalStateException(
               "GraphHopper gave " + response.getErrors().size() + " errors. First error chained.",
               response.getErrors().get(0));
         }
         // Distance should be in km, not meter
         distance = response.getDistance() / 1000.0;
         if (distance == 0.0) {
           throw new IllegalArgumentException(
               "The fromAirLocation ("
                   + fromAirLocation
                   + ") and toAirLocation ("
                   + toAirLocation
                   + ") are the same.");
         }
         PointList ghPointList = response.getPoints();
         PointPart previousFromPointPart = null;
         PointPart previousToPointPart = null;
         double previousLatitude = Double.NaN;
         double previousLongitude = Double.NaN;
         for (int i = 0; i < ghPointList.size(); i++) {
           double latitude = ghPointList.getLatitude(i);
           double longitude = ghPointList.getLongitude(i);
           if (latitude == previousLatitude && longitude == previousLongitude) {
             continue;
           }
           if (calcAirDistance(
                   latitude,
                   longitude,
                   fromAirLocation.getLatitude(),
                   fromAirLocation.getLongitude())
               < airDistanceThreshold) {
             Point fromPoint = new Point(latitude, longitude);
             Point oldFromPoint = fromPointMap.get(fromPoint);
             if (oldFromPoint == null) {
               // Initialize fromPoint instance
               fromPoint.pointPartMap = new LinkedHashMap<AirLocation, PointPart>();
               fromPointMap.put(fromPoint, fromPoint);
             } else {
               // Reuse existing fromPoint instance
               fromPoint = oldFromPoint;
             }
             PointPart fromPointPart = fromPoint.pointPartMap.get(fromAirLocation);
             if (fromPointPart == null) {
               fromPointPart = new PointPart(fromPoint, fromAirLocation);
               fromPoint.pointPartMap.put(fromAirLocation, fromPointPart);
               fromPointPart.previousPart = previousFromPointPart;
             }
             fromPointPart.count++;
             previousFromPointPart = fromPointPart;
           }
           if (calcAirDistance(
                   latitude, longitude, toAirLocation.getLatitude(), toAirLocation.getLongitude())
               < airDistanceThreshold) {
             Point toPoint = new Point(latitude, longitude);
             Point oldToPoint = toPointMap.get(toPoint);
             if (oldToPoint == null) {
               // Initialize toPoint instance
               toPoint.pointPartMap = new LinkedHashMap<AirLocation, PointPart>();
               toPointMap.put(toPoint, toPoint);
             } else {
               // Reuse existing toPoint instance
               toPoint = oldToPoint;
             }
             // Basically do the same as fromPointPart, but while traversing in the other direction
             PointPart toPointPart = toPoint.pointPartMap.get(toAirLocation);
             boolean newToPointPart = false;
             if (toPointPart == null) {
               toPointPart = new PointPart(toPoint, toAirLocation);
               toPoint.pointPartMap.put(toAirLocation, toPointPart);
               newToPointPart = true;
             }
             if (previousToPointPart != null) {
               previousToPointPart.previousPart = toPointPart;
             }
             toPointPart.count++;
             if (newToPointPart) {
               previousToPointPart = toPointPart;
             } else {
               previousToPointPart = null;
             }
           }
           previousLatitude = latitude;
           previousLongitude = longitude;
         }
       }
     }
     logger.debug("  Finished routes for rowIndex {}/{}", rowIndex, locationList.size());
     rowIndex++;
   }
   Set<Point> hubPointList = new LinkedHashSet<Point>(20);
   extractFromHubs(new ArrayList<Point>(fromPointMap.values()), hubPointList, (hubSize + 1) / 2);
   extractFromHubs(new ArrayList<Point>(toPointMap.values()), hubPointList, hubSize / 2);
   logger.info("Writing hubs...");
   BufferedWriter vrpWriter = null;
   try {
     vrpWriter =
         new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8"));
     vrpWriter.write("HUB_COORD_SECTION\n");
     int id = 0;
     for (Point point : hubPointList) {
       vrpWriter.write("" + id + " " + point.latitude + " " + point.longitude + " " + id + "\n");
       id++;
     }
     vrpWriter.write("\n\nGOOGLE MAPS\n");
     for (Point point : hubPointList) {
       vrpWriter.write("" + id + "\t0\t" + point.latitude + "," + point.longitude + "\n");
       id++;
     }
   } catch (IOException e) {
     throw new IllegalArgumentException(
         "Could not read the locationFile ("
             + locationFile.getName()
             + ") or write the vrpOutputFile ("
             + outputFile.getName()
             + ").",
         e);
   } finally {
     IOUtils.closeQuietly(vrpWriter);
   }
   // Throw in google docs spreadsheet and use add-on Mapping Sheets to visualize.
 }
Ejemplo n.º 3
0
  @Test
  public void testMonacoWithInstructions() {
    String osmFile = "files/monaco.osm.gz";
    String graphFile = "target/graph-monaco";
    String vehicle = "FOOT";
    String importVehicles = "FOOT";
    String weightCalcStr = "shortest";

    try {
      // make sure we are using fresh graphhopper files with correct vehicle
      Helper.removeDir(new File(graphFile));
      GraphHopper hopper =
          new GraphHopper()
              .setInMemory(true)
              .setOSMFile(osmFile)
              .disableCHShortcuts()
              .setGraphHopperLocation(graphFile)
              .setEncodingManager(new EncodingManager(importVehicles))
              .importOrLoad();

      Graph g = hopper.getGraph();
      GHResponse rsp =
          hopper.route(
              new GHRequest(43.727687, 7.418737, 43.74958, 7.436566)
                  .setAlgorithm("astar")
                  .setVehicle(vehicle)
                  .setWeighting(weightCalcStr));

      assertEquals(3437.6, rsp.getDistance(), .1);
      assertEquals(87, rsp.getPoints().getSize());

      InstructionList il = rsp.getInstructions();
      assertEquals(13, il.size());
      Translation tr = trMap.getWithFallBack(Locale.US);
      List<String> iList = il.createDescription(tr);
      // TODO roundabout fine tuning -> enter + leave roundabout (+ two rounabouts -> is it
      // necessary if we do not leave the street?)
      assertEquals("Continue onto Avenue des Guelfes", iList.get(0));
      assertEquals("Turn slight left onto Avenue des Papalins", iList.get(1));
      assertEquals("Turn sharp right onto Quai Jean-Charles Rey", iList.get(2));
      assertEquals("Turn left onto road", iList.get(3));
      assertEquals("Turn right onto Avenue Albert II", iList.get(4));

      List<Double> dists = il.createDistances();
      assertEquals(11, dists.get(0), 1);
      assertEquals(289, dists.get(1), 1);
      assertEquals(10, dists.get(2), 1);
      assertEquals(43, dists.get(3), 1);
      assertEquals(122, dists.get(4), 1);
      assertEquals(447, dists.get(5), 1);

      List<Long> times = il.createMillis();
      assertEquals(7, times.get(0) / 1000);
      assertEquals(207, times.get(1) / 1000);
      assertEquals(7, times.get(2) / 1000);
      assertEquals(30, times.get(3) / 1000);
      assertEquals(87, times.get(4) / 1000);
      assertEquals(321, times.get(5) / 1000);

      List<GPXEntry> list = rsp.getInstructions().createGPXList();
      assertEquals(123, list.size());
      final long lastEntryMillis = list.get(list.size() - 1).getMillis();
      final long totalResponseMillis = rsp.getMillis();
      assertEquals(totalResponseMillis, lastEntryMillis);

    } catch (Exception ex) {
      throw new RuntimeException("cannot handle osm file " + osmFile, ex);
    } finally {
      Helper.removeDir(new File(graphFile));
    }
  }