Search in sources :

Example 6 with BooleanEncodedValue

use of com.graphhopper.routing.ev.BooleanEncodedValue in project graphhopper by graphhopper.

the class CarFlagEncoderTest method testCombination.

@Test
public void testCombination() {
    ReaderWay way = new ReaderWay(123);
    way.setTag("highway", "cycleway");
    way.setTag("sac_scale", "hiking");
    assertEquals(EncodingManager.Access.CAN_SKIP, encoder.getAccess(way));
    assertNotEquals(EncodingManager.Access.CAN_SKIP, ((AbstractFlagEncoder) em.getEncoder("bike")).getAccess(way));
    IntsRef edgeFlags = em.handleWayTags(way, em.createRelationFlags());
    assertFalse(accessEnc.getBool(true, edgeFlags));
    assertFalse(accessEnc.getBool(false, edgeFlags));
    BooleanEncodedValue bikeAccessEnc = em.getEncoder("bike").getAccessEnc();
    assertTrue(bikeAccessEnc.getBool(true, edgeFlags));
    assertTrue(bikeAccessEnc.getBool(false, edgeFlags));
}
Also used : BooleanEncodedValue(com.graphhopper.routing.ev.BooleanEncodedValue) ReaderWay(com.graphhopper.reader.ReaderWay) IntsRef(com.graphhopper.storage.IntsRef) Test(org.junit.jupiter.api.Test)

Example 7 with BooleanEncodedValue

use of com.graphhopper.routing.ev.BooleanEncodedValue in project graphhopper by graphhopper.

the class EncodingManagerTest method testSharedEncodedValues.

@Test
public void testSharedEncodedValues() {
    EncodingManager manager = EncodingManager.create("car,foot,bike,motorcycle,mtb");
    for (FlagEncoder tmp : manager.fetchEdgeEncoders()) {
        AbstractFlagEncoder encoder = (AbstractFlagEncoder) tmp;
        BooleanEncodedValue accessEnc = encoder.getAccessEnc();
        BooleanEncodedValue roundaboutEnc = manager.getBooleanEncodedValue(Roundabout.KEY);
        ReaderWay way = new ReaderWay(1);
        way.setTag("highway", "primary");
        way.setTag("junction", "roundabout");
        IntsRef edgeFlags = manager.handleWayTags(way, manager.createRelationFlags());
        assertTrue(accessEnc.getBool(false, edgeFlags));
        if (!encoder.getName().equals("foot"))
            assertFalse(accessEnc.getBool(true, edgeFlags), encoder.getName());
        assertTrue(roundaboutEnc.getBool(false, edgeFlags), encoder.getName());
        way.clearTags();
        way.setTag("highway", "tertiary");
        way.setTag("junction", "circular");
        edgeFlags = manager.handleWayTags(way, manager.createRelationFlags());
        assertTrue(accessEnc.getBool(false, edgeFlags));
        if (!encoder.getName().equals("foot"))
            assertFalse(accessEnc.getBool(true, edgeFlags), encoder.getName());
        assertTrue(roundaboutEnc.getBool(false, edgeFlags), encoder.getName());
    }
}
Also used : BooleanEncodedValue(com.graphhopper.routing.ev.BooleanEncodedValue) ReaderWay(com.graphhopper.reader.ReaderWay) IntsRef(com.graphhopper.storage.IntsRef) Test(org.junit.jupiter.api.Test)

Example 8 with BooleanEncodedValue

use of com.graphhopper.routing.ev.BooleanEncodedValue in project graphhopper by graphhopper.

the class AbstractGraphStorageTester method test8AndMoreBytesForEdgeFlags.

@Test
public void test8AndMoreBytesForEdgeFlags() {
    List<FlagEncoder> list = new ArrayList<>();
    list.add(new CarFlagEncoder(29, 0.001, 0) {

        @Override
        public String getName() {
            return "car0";
        }
    });
    list.add(new CarFlagEncoder(29, 0.001, 0));
    EncodingManager manager = EncodingManager.create(list);
    graph = new GraphBuilder(manager).create();
    EdgeIteratorState edge = graph.edge(0, 1);
    IntsRef intsRef = manager.createEdgeFlags();
    intsRef.ints[0] = Integer.MAX_VALUE / 3;
    edge.setFlags(intsRef);
    // System.out.println(BitUtil.LITTLE.toBitString(Long.MAX_VALUE / 3) + "\n" + BitUtil.LITTLE.toBitString(edge.getFlags()));
    assertEquals(Integer.MAX_VALUE / 3, edge.getFlags().ints[0]);
    graph.close();
    graph = new GraphBuilder(manager).create();
    DecimalEncodedValue avSpeed0Enc = manager.getDecimalEncodedValue(getKey("car0", "average_speed"));
    BooleanEncodedValue access0Enc = manager.getBooleanEncodedValue(getKey("car0", "access"));
    DecimalEncodedValue avSpeed1Enc = manager.getDecimalEncodedValue(getKey("car", "average_speed"));
    BooleanEncodedValue access1Enc = manager.getBooleanEncodedValue(getKey("car", "access"));
    edge = graph.edge(0, 1);
    GHUtility.setSpeed(99.123, true, true, list.get(0), edge);
    assertEquals(99.123, edge.get(avSpeed0Enc), 1e-3);
    EdgeIteratorState edgeIter = GHUtility.getEdge(graph, 1, 0);
    assertEquals(99.123, edgeIter.get(avSpeed0Enc), 1e-3);
    assertTrue(edgeIter.get(access0Enc));
    assertTrue(edgeIter.getReverse(access0Enc));
    edge = graph.edge(2, 3);
    GHUtility.setSpeed(44.123, true, false, list.get(1), edge);
    assertEquals(44.123, edge.get(avSpeed1Enc), 1e-3);
    edgeIter = GHUtility.getEdge(graph, 3, 2);
    assertEquals(44.123, edgeIter.get(avSpeed1Enc), 1e-3);
    assertEquals(44.123, edgeIter.getReverse(avSpeed1Enc), 1e-3);
    assertFalse(edgeIter.get(access1Enc));
    assertTrue(edgeIter.getReverse(access1Enc));
    list.clear();
    list.add(new CarFlagEncoder(29, 0.001, 0) {

        @Override
        public String getName() {
            return "car0";
        }
    });
    list.add(new CarFlagEncoder(29, 0.001, 0));
    list.add(new CarFlagEncoder(30, 0.001, 0) {

        @Override
        public String getName() {
            return "car2";
        }
    });
    manager = EncodingManager.create(list);
    graph = new GraphBuilder(manager).create();
    edgeIter = graph.edge(0, 1).set(access0Enc, true, false);
    assertTrue(edgeIter.get(access0Enc));
    assertFalse(edgeIter.getReverse(access0Enc));
}
Also used : BooleanEncodedValue(com.graphhopper.routing.ev.BooleanEncodedValue) DecimalEncodedValue(com.graphhopper.routing.ev.DecimalEncodedValue) ArrayList(java.util.ArrayList) Test(org.junit.jupiter.api.Test)

Example 9 with BooleanEncodedValue

use of com.graphhopper.routing.ev.BooleanEncodedValue in project graphhopper by graphhopper.

the class Bike2WeightFlagEncoderTest method isGraphValid.

private boolean isGraphValid(Graph graph, FlagEncoder encoder) {
    EdgeExplorer explorer = graph.createEdgeExplorer();
    BooleanEncodedValue accessEnc = encoder.getAccessEnc();
    // iterator at node 0 considers the edge 0-1 to be undirected
    EdgeIterator iter0 = explorer.setBaseNode(0);
    iter0.next();
    boolean iter0flag = iter0.getBaseNode() == 0 && iter0.getAdjNode() == 1 && iter0.get(accessEnc) && iter0.getReverse(accessEnc);
    // iterator at node 1 considers the edge 1-0 to be directed
    EdgeIterator iter1 = explorer.setBaseNode(1);
    iter1.next();
    boolean iter1flag = iter1.getBaseNode() == 1 && iter1.getAdjNode() == 0 && iter1.get(accessEnc) && iter1.getReverse(accessEnc);
    return iter0flag && iter1flag;
}
Also used : BooleanEncodedValue(com.graphhopper.routing.ev.BooleanEncodedValue)

Example 10 with BooleanEncodedValue

use of com.graphhopper.routing.ev.BooleanEncodedValue in project graphhopper by graphhopper.

the class LandmarkStorage method createLandmarks.

/**
 * This method calculates the landmarks and initial weightings to & from them.
 */
public void createLandmarks() {
    if (isInitialized())
        throw new IllegalStateException("Initialize the landmark storage only once!");
    // fill 'from' and 'to' weights with maximum value
    long maxBytes = (long) graph.getNodes() * LM_ROW_LENGTH;
    this.landmarkWeightDA.create(2000);
    this.landmarkWeightDA.ensureCapacity(maxBytes);
    for (long pointer = 0; pointer < maxBytes; pointer += 2) {
        landmarkWeightDA.setShort(pointer, (short) SHORT_INFINITY);
    }
    int[] empty = new int[landmarks];
    Arrays.fill(empty, UNSET_SUBNETWORK);
    landmarkIDs.add(empty);
    byte[] subnetworks = new byte[graph.getNodes()];
    Arrays.fill(subnetworks, (byte) UNSET_SUBNETWORK);
    String snKey = Subnetwork.key(lmConfig.getName());
    // instead of using the subnetworkEnc from PrepareRoutingSubnetworks.
    if (!graph.getEncodingManager().hasEncodedValue(snKey))
        throw new IllegalArgumentException("EncodedValue '" + snKey + "' does not exist. For Landmarks this is " + "currently required (also used in PrepareRoutingSubnetworks). See #2256");
    // Exclude edges that we previously marked in PrepareRoutingSubnetworks to avoid problems like "connection not found".
    final BooleanEncodedValue edgeInSubnetworkEnc = graph.getEncodingManager().getBooleanEncodedValue(snKey);
    final IntHashSet blockedEdges;
    // landmarks for an area like Europe+Asia, which improves the query speed.
    if (areaIndex != null) {
        StopWatch sw = new StopWatch().start();
        blockedEdges = findBorderEdgeIds(areaIndex);
        if (logDetails)
            LOGGER.info("Made " + blockedEdges.size() + " edges inaccessible. Calculated country cut in " + sw.stop().getSeconds() + "s, " + Helper.getMemInfo());
    } else {
        blockedEdges = new IntHashSet();
    }
    EdgeFilter accessFilter = edge -> !edge.get(edgeInSubnetworkEnc) && !blockedEdges.contains(edge.getEdge());
    EdgeFilter tarjanFilter = edge -> accessFilter.accept(edge) && Double.isFinite(weighting.calcEdgeWeightWithAccess(edge, false));
    StopWatch sw = new StopWatch().start();
    ConnectedComponents graphComponents = TarjanSCC.findComponents(graph, tarjanFilter, true);
    if (logDetails)
        LOGGER.info("Calculated " + graphComponents.getComponents().size() + " subnetworks via tarjan in " + sw.stop().getSeconds() + "s, " + Helper.getMemInfo());
    String additionalInfo = "";
    // guess the factor
    if (factor <= 0) {
        // A 'factor' is necessary to store the weight in just a short value but without losing too much precision.
        // This factor is rather delicate to pick, we estimate it from an exploration with some "test landmarks",
        // see estimateMaxWeight. If we pick the distance too big for small areas this could lead to (slightly)
        // suboptimal routes as there will be too big rounding errors. But picking it too small is bad for performance
        // e.g. for Germany at least 1500km is very important otherwise speed is at least twice as slow e.g. for 1000km
        double maxWeight = estimateMaxWeight(graphComponents.getComponents(), accessFilter);
        setMaximumWeight(maxWeight);
        additionalInfo = ", maxWeight:" + maxWeight + " from quick estimation";
    }
    if (logDetails)
        LOGGER.info("init landmarks for subnetworks with node count greater than " + minimumNodes + " with factor:" + factor + additionalInfo);
    int nodes = 0;
    for (IntArrayList subnetworkIds : graphComponents.getComponents()) {
        nodes += subnetworkIds.size();
        if (subnetworkIds.size() < minimumNodes)
            continue;
        if (factor <= 0)
            throw new IllegalStateException("factor wasn't initialized " + factor + ", subnetworks:" + graphComponents.getComponents().size() + ", minimumNodes:" + minimumNodes + ", current size:" + subnetworkIds.size());
        int index = subnetworkIds.size() - 1;
        // ensure start node is reachable from both sides and no subnetwork is associated
        for (; index >= 0; index--) {
            int nextStartNode = subnetworkIds.get(index);
            if (subnetworks[nextStartNode] == UNSET_SUBNETWORK) {
                if (logDetails) {
                    GHPoint p = createPoint(graph, nextStartNode);
                    LOGGER.info("start node: " + nextStartNode + " (" + p + ") subnetwork " + index + ", subnetwork size: " + subnetworkIds.size() + ", " + Helper.getMemInfo() + ((areaIndex == null) ? "" : " area:" + areaIndex.query(p.lat, p.lon)));
                }
                if (createLandmarksForSubnetwork(nextStartNode, subnetworks, accessFilter))
                    break;
            }
        }
        if (index < 0)
            LOGGER.warn("next start node not found in big enough network of size " + subnetworkIds.size() + ", first element is " + subnetworkIds.get(0) + ", " + createPoint(graph, subnetworkIds.get(0)));
    }
    int subnetworkCount = landmarkIDs.size();
    // store all landmark node IDs and one int for the factor itself.
    this.landmarkWeightDA.ensureCapacity(maxBytes + /* landmark weights */
    subnetworkCount * landmarks);
    // calculate offset to point into landmark mapping
    long bytePos = maxBytes;
    for (int[] landmarks : landmarkIDs) {
        for (int lmNodeId : landmarks) {
            landmarkWeightDA.setInt(bytePos, lmNodeId);
            bytePos += 4L;
        }
    }
    landmarkWeightDA.setHeader(0 * 4, graph.getNodes());
    landmarkWeightDA.setHeader(1 * 4, landmarks);
    landmarkWeightDA.setHeader(2 * 4, subnetworkCount);
    if (factor * DOUBLE_MLTPL > Integer.MAX_VALUE)
        throw new UnsupportedOperationException("landmark weight factor cannot be bigger than Integer.MAX_VALUE " + factor * DOUBLE_MLTPL);
    landmarkWeightDA.setHeader(3 * 4, (int) Math.round(factor * DOUBLE_MLTPL));
    // serialize fast byte[] into DataAccess
    subnetworkStorage.create(graph.getNodes());
    for (int nodeId = 0; nodeId < subnetworks.length; nodeId++) {
        subnetworkStorage.setSubnetwork(nodeId, subnetworks[nodeId]);
    }
    if (logDetails)
        LOGGER.info("Finished landmark creation. Subnetwork node count sum " + nodes + " vs. nodes " + graph.getNodes());
    initialized = true;
}
Also used : java.util(java.util) LoggerFactory(org.slf4j.LoggerFactory) IntObjectPredicate(com.carrotsearch.hppc.predicates.IntObjectPredicate) Subnetwork(com.graphhopper.routing.ev.Subnetwork) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) GHUtility(com.graphhopper.util.GHUtility) SPTEntry(com.graphhopper.routing.SPTEntry) SubnetworkStorage(com.graphhopper.routing.subnetwork.SubnetworkStorage) StopWatch(com.graphhopper.util.StopWatch) ConnectedComponents(com.graphhopper.routing.subnetwork.TarjanSCC.ConnectedComponents) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IntArrayList(com.carrotsearch.hppc.IntArrayList) IntObjectProcedure(com.carrotsearch.hppc.procedures.IntObjectProcedure) ConnectionNotFoundException(com.graphhopper.util.exceptions.ConnectionNotFoundException) com.graphhopper.storage(com.graphhopper.storage) Logger(org.slf4j.Logger) EdgeIteratorState(com.graphhopper.util.EdgeIteratorState) Helper(com.graphhopper.util.Helper) IntHashSet(com.carrotsearch.hppc.IntHashSet) MapEntry(com.graphhopper.coll.MapEntry) BooleanEncodedValue(com.graphhopper.routing.ev.BooleanEncodedValue) DijkstraBidirectionRef(com.graphhopper.routing.DijkstraBidirectionRef) TarjanSCC(com.graphhopper.routing.subnetwork.TarjanSCC) IntObjectMap(com.carrotsearch.hppc.IntObjectMap) Weighting(com.graphhopper.routing.weighting.Weighting) GHPoint(com.graphhopper.util.shapes.GHPoint) ShortestWeighting(com.graphhopper.routing.weighting.ShortestWeighting) com.graphhopper.routing.util(com.graphhopper.routing.util) IntHashSet(com.carrotsearch.hppc.IntHashSet) GHPoint(com.graphhopper.util.shapes.GHPoint) StopWatch(com.graphhopper.util.StopWatch) BooleanEncodedValue(com.graphhopper.routing.ev.BooleanEncodedValue) ConnectedComponents(com.graphhopper.routing.subnetwork.TarjanSCC.ConnectedComponents) IntArrayList(com.carrotsearch.hppc.IntArrayList) GHPoint(com.graphhopper.util.shapes.GHPoint)

Aggregations

BooleanEncodedValue (com.graphhopper.routing.ev.BooleanEncodedValue)16 Test (org.junit.jupiter.api.Test)8 DecimalEncodedValue (com.graphhopper.routing.ev.DecimalEncodedValue)6 ArrayList (java.util.ArrayList)4 AllEdgesIterator (com.graphhopper.routing.util.AllEdgesIterator)3 Weighting (com.graphhopper.routing.weighting.Weighting)3 Snap (com.graphhopper.storage.index.Snap)3 GHPoint (com.graphhopper.util.shapes.GHPoint)3 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)3 IntArrayList (com.carrotsearch.hppc.IntArrayList)2 Profile (com.graphhopper.config.Profile)2 ReaderWay (com.graphhopper.reader.ReaderWay)2 Path (com.graphhopper.routing.Path)2 RoutingAlgorithm (com.graphhopper.routing.RoutingAlgorithm)2 Subnetwork (com.graphhopper.routing.ev.Subnetwork)2 QueryGraph (com.graphhopper.routing.querygraph.QueryGraph)2 IntsRef (com.graphhopper.storage.IntsRef)2 IntHashSet (com.carrotsearch.hppc.IntHashSet)1 IntObjectMap (com.carrotsearch.hppc.IntObjectMap)1 IntObjectPredicate (com.carrotsearch.hppc.predicates.IntObjectPredicate)1