Skip to content

Distance matrix support (WIP) - #705

Closed
IsNull wants to merge 24 commits into
graphhopper:masterfrom
ElderByte:distance-matrix-support
Closed

IsNull wants to merge 24 commits into
graphhopper:masterfrom
ElderByte:distance-matrix-support

Conversation

@IsNull

@IsNull IsNull commented Apr 21, 2016 •

Copy link
Copy Markdown

This pull request implements a basic API for distance matrix queries as discussed in #131. As such, I want to review the proposed API before refining it and adding tests.

Please have a look and tell me if the proposed API goes into the right direction. I'd like to avoid putting too much work into something you don't consider for merge. You find the primary code under the package /matrix in the core project.

Edit

  • Added some unit tests
  • Adapted to refactorings

@IsNull

IsNull commented Apr 25, 2016

Copy link
Copy Markdown
Author

The DijkstraOneToManyalgorithm returns zero for some distances when the cache is used. I am not sure if I have stumbled over a Bug or if I just used it wrong. Current usage is simply as follows:

        DistanceMatrix matrix = new DistanceMatrix();

        DijkstraOneToMany algorithm = (DijkstraOneToMany)routingFactory.createAlgo(graph, underlyingAlgo);


        for (int origin : origins) {

            algorithm.clear(); // Clear cache on different start node
            DistanceMatrix.DistanceRow row = matrix.addRow(origin);

            for (int destination : destinations) {
                Path path = algorithm.calcPath(origin, destination);
                row.addDestination(destination, path.getDistance(), path.getTime());
            }
        }

I.e. the algorithm is reused with cache for all destinations of a single origin. For each new origin, clear() is called since the documentation states that its necessary to clear the cache for different start nodes.

The code works if DijkstraOneToMany is created as new instance for each usage, but this obviously is not the idea.

@karussell

karussell commented Apr 25, 2016 •

Copy link
Copy Markdown
Member

If you feel if that is a bug I need a simple unit test showing it. Also keep in mind that DijkstraOneToMany is not thread safe, so for our use case you would need the same approach as the other algorithms (destroy queue etc on every request) or you need manage it in ThreadLocal (more efficient but more RAM usage and more complex). Furthermore DijkstraOneToMany won't work for CH (at least not now), so I would recommend a simple but new dijkstra class similar to the others and thread safe.

@IsNull

IsNull commented Apr 25, 2016 •

Copy link
Copy Markdown
Author

I can not follow you completely where you see a multithreading issue. For each user request a new MatrixAlgorithm instance is being created, the only thing shared between Threads would be the MatrixAlgorithmFactory which is thread safe since it does not use any class fields and just returns new instances.

Furthermore DijkstraOneToMany won't work for CH (at least not now), so I would recommend a simple but new dijkstra class similar to the others and thread safe.

Ok that is a problem, because using the DijkstraOneToMany would make it impossible to use the CH optimisations.

Before I am able to implement a custom Dijkstra, I need to fully understand the threading issues. Could you please explain in Detail how the algorithm is not thread-safe, if for each usage a new instance is created?

Thanks for your time :)

PS:

If you feel if that is a bug I need a simple unit test showing it.

I will in a separate pull request, I just removed it from here so my pull request does not fail on Travis.

@karussell

Copy link
Copy Markdown
Member

Could you please explain in Detail how the algorithm is not thread-safe, if for each usage
a new instance is created?

Then there is no problem, but if you look into the data structures then you'll see that recreating per request is very expensive in contrast to the very cheap recreation for the normal algorithms.

@IsNull

IsNull commented Apr 25, 2016 •

Copy link
Copy Markdown
Author

Understood. As for the matrix API itself, this seems to be less of an issue. Usually, the matrix api will be used with few requests, but each request is very expensive. So a single initialisation per request is not too big of an issue IMHO.

Anyway, the DijkstraOneToMany implementation is now working using the workaround described in #707 , at least the very basic unit tests confirm this.

@karussell

Copy link
Copy Markdown
Member

So a single initialisation per request is not too big of an issue IMHO.

That would be the wrong approach. Please keep in mind that creating such a data structure is really very expensive and does not make sense to be recreated for every request, instead just see the other algorithms how this is handled. Also the Matrix API can be used for one-to-10 or just 10-to-10 requests not only for heavy weight stuff.

@IsNull

IsNull commented Apr 25, 2016

Copy link
Copy Markdown
Author

Yea I actually prefer clean solutions as well. I just have not fully grasped all the design decisions in the code. For example, there are many checkAlreadyRun(); in your algorithms, so by design these algorithms can only be used once. So I assumed that an algorithm usually only runs once.

I guess we are not talking about the same initialisation?

Now the DijkstraOneToMany is a different story, as it can repeatedly be used and does actually prepare memory for all nodes

        parents = new int[graph.getNodes()];
        Arrays.fill(parents, EMPTY_PARENT);

        edgeIds = new int[graph.getNodes()];
        Arrays.fill(edgeIds, EdgeIterator.NO_EDGE);

        weights = new double[graph.getNodes()];

        Arrays.fill(weights, Double.MAX_VALUE);

Are these the complex data structures you are referring to? Just ensuring we are on the same page.

The more I think about it, it would probably make sense to move the cache part out in a shared, Thread-safe component. The cache obviously has to support different start nodes, otherwise its likely that the cache does not help much. This cache can probably be generalised and does not necessary have to be for a specific algorithm. Its probably similar to the CH, just not calculated up front but something like a cache for already calculated path partials / shortcuts etc. Maybe I just reinvent something or this approach is otherwise unfeasible... Any thoughts on this?

Before inventing a new cache/data-structure & algorithm, I will do also a bit research on existing algorithms & data-structures which are better suited for repeated queries.

@karussell

karussell commented Apr 25, 2016 •

Copy link
Copy Markdown
Member

Are these the complex data structures you are referring to? Just ensuring we are on the same page.

Yes. Although with 'complex' I mean more 'expensive' :)

The cache obviously has to support different start nodes

Ah, yes. Virtual nodes are another problem which you would need to solve when trying to reuse stuff.

Before inventing a new cache/data-structure & algorithm

I wouldn't go this more complex way as the first trial. Just put enough tests that later on one can refactor simple to more complex solutions with the same results.

@IsNull

IsNull commented Apr 25, 2016 •

Copy link
Copy Markdown
Author

Thanks for the clarification.

I wouldn't go this more complex way as the first trial. Just put enough tests that later on one can refactor simple to more complex solutions with the same results.

Yep that was the idea in the first place. I almost got carried away :) So I'd say for a first version, I will leave the DijkstraOneToMany as it is now, but it should only be used for large matrices. Im not going to hack in any thread-local stuff since this would lead to memory leaks - for every thread which accesses the matrix api, a new DijkstraOneToMany would be in memory. So this needs quite some thought and I think we need to design this from ground up.

I will add some more tests and do some clean up. If you are going to merge the refactoring I will adopt the code as necessary.

@IsNull

IsNull commented Apr 26, 2016

Copy link
Copy Markdown
Author

I am reiterating about the matrix API and performance thoughts:

  • The CH's should be used since they give a massive performance boost
  • The CH already acts as a global cache for routing algorithms
  • We do not really need to expand the full path - only the time/distance is interesting for further optimisations

So if in shortcuts of your CH implementation the the distance/time is stored, its getting very fast since the full path does not need to get expanded.

@karussell

Copy link
Copy Markdown
Member

The Matrix should work for both cases (with and without CH). But I would just start with the simple interface via the double for loop and then improve from there.

@IsNull

IsNull commented May 6, 2016

Copy link
Copy Markdown
Author

@karussell Yes, lets keep this pull request simple in terms of the provided matrix algorithms.

There are two open points which we probably should address before a merge can be considered:

  • The creation/handling of the AlgorithmOptions is not optimal and also has some code redundancies with GrahpHopper.java Could you have a look at this - to solve this we probably have to refactor some portions out of the GrahpHopper.java class.
  • The GHRequest/GHResponse are also similar to the GHMatrixRequest/GHMatrixResonse. Would it make sense to refactore this to a common GHRequest/GHResponse base, which then probably also gets used in the new code from the point above?

queryGraph.lookup(merged);

List<Integer> originNodes = mapToNodes(originQNodes);
List<Integer> destinationNodes = mapToNodes(destinationQNodes);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need this conversion step?

@karussell karussell May 11, 2016 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, okay. You are separating the low level API from the higher one and just require the algorithm to know 'nodes', no need for QueryResults. Maybe the 'lookupNodes' method already directly returns nodes?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well I need the QueryResults due to the necessary queryGraph.lookup(merged); to properly initialise the queryGraph.

But since this code is almost 1:1 identical to the GraphHopper default route Graph initialisation, I really think this should be refactored in a shared Graph-Preparation class.

@IsNull

IsNull commented Jun 10, 2016

Copy link
Copy Markdown
Author

I have merged your refactoring and adapted my code so it works with it.

Keep in mind that we later want an improved version of this where we potentially have hundreds of points and need a possibility to implement the GHMatrixResponse very memory efficient e.g. in raw arrays like times[][]; distances[][] instead of "row objects"

Sounds reasonable, I will refactor the distance matrix response to use an array based data structure.

@IsNull

IsNull commented Jun 14, 2016

Copy link
Copy Markdown
Author

I've refactored the matrix data structures to 2d arrays for maximum performance and minimal memory consumption. I've also collapsed the internal used DistanceMatrix class and the external visible GHMatrixResponse, which now uses the DistanceMatrix as property.

It is optimised so it can be directly turned into JSON by Jackson or a similar mapper. (Well thats not important for you since you apparently do this stuff manually in your web service anyway.)

@IsNull

IsNull commented Jun 14, 2016

Copy link
Copy Markdown
Author

The GHMatrixResponse currently only holds the calculated matrix. We can later add more information such as completion state, runtime duration etc. if required.

Anyway, please have a look and tell me what needs more work in order to consider merging this PR.

* @param destIndex The destination index
* @return THe cell of the origin-destination
*/
public DistanceMatrixCell getCell(int originIndex, int destIndex){

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

here I would avoid creating an object, even if it is on-demand and even if the JVM is fast with these things :)

I would instead create three methods like getDistance(int, int), see similar work I've done very recently to improve the memory usage of the directions api matrix client

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok np, I'll refactor it.

@karussell

karussell commented Jun 14, 2016 •

Copy link
Copy Markdown
Member

Thanks for the work!

It is optimised so it can be directly turned into JSON by Jackson or a similar mapper

This is indeed nice and I should have done similar with the normal routing objects too.

For really big matrices (>1000²) it can be beneficial if you stream the results directly into the JSON, of course no requirement for the first shot but we should keep this in mind and make it possible at some point.

Two questions: is the web integration already here? And as it is using normal routing, is it working&tested for CH and non-CH?

@IsNull

IsNull commented Jun 14, 2016

Copy link
Copy Markdown
Author

To your last two questions:

I did not do any tests related CH / non-CH yet. I'm even not quite sure how such a test should look like? I assumed since I just reuse normal routing this will work out of the box since the normal routing is already tested properly?

As a side note: The project where I want to use this is currently in "pre production", meaning that I'm still evaluating stuff and not working primarily on it. This is why you see this infrequent progress :). Anyway, as soon that we get startet on it we will use the distance matrix api for real world scenarios and have some production grade tests on top of it. The performance of it will also be evaluated then.

To the web integration: Honestly, I am not sure if im going to do this. We will internally create a new web service based on spring boot which just uses the graphhopper core. (Writing a solid rest api takes very few lines with spring boot) On top of that, spring boot delivers a lot of integrations for free, which we need for our Microservice architecture: Health/Metrics, Netflix component integration such as Eureka and Feign and probably also some authentication. Some additional features such as configuring/uploading an osm file and a general UI for configuration will also be required.

We probably make this project open source, but since it will be mission critical it has to be under our full control.

@karussell

Copy link
Copy Markdown
Member

I assumed since I just reuse normal routing this will work out of the box since the normal routing is already tested properly?

Yes, still important to assert what should work, probably not now but very certainly later on.

Honestly, I am not sure if im going to do this

It is important to have and define some structure like the matrix java API defines the structure, also without a web component it wouldn't be useful for half of the GraphHopper users I fear. Furthermore the Matrix API json structure is even a lot easier than the routing api

@IsNull

IsNull commented Jun 14, 2016 •

Copy link
Copy Markdown
Author

Yes, still important to assert what should work, probably not now but very certainly later on.

Agreed. I will certainly do some manual testing soon when integrating graphhopper. If you help me with improved unit tests which test both CH and non-CH I'm happy to work on this as well.

It is important to have and define some structure like the matrix java API defines the structure, also without a web component it wouldn't be useful for half of the GraphHopper users I fear. Furthermore the Matrix API json structure is even a lot easier than the routing api

Well a matrix request could potentially be a quite long running operation, putting the system under stress. The way I'm going to implement this is by designing an async API which returns immediately after a matrix request with a job-id, which can be polled later on. Also, the number of concurrent running matrix requests should be limited (maybe 2-3). There needs to be a queuing system which gets async handled, and this goes hand in hand with the async rest api.

So implementing this just quick and dirty might pose some stability threads.

The thing is, implementing very basic support would be 4 lines of code if there would be a framework in place. Spending time manually parsing a request etc. just seems a waste of time to me - just compare the below code which probably is enough for a rest API in Spring (or alternatives like Jersey):

@RestController
@RequestMapping("/api/matrix")
public class MatrixResource {
    @Autowired
    private MatrixService matrixService;

    @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<GHMatrixResponse> matrix(@RequestBody GHMatrixRequest request) {
        return new ResponseEntity<>(matrixService.matrix(request), HttpStatus.OK);
    }
}

Anyway, matrix api support in the core is a feature on its own. If someone needs the matrix api in the web project, by all means, he can contribute to this project as well :)

I hope you can understand my point.

@karussell

Copy link
Copy Markdown
Member

So implementing this just quick and dirty might pose some stability threads.

For sure, but eg. serializing json is a subproblem and I would want the simple version of this all in the web module if we have matrix calculation in the core

Spending time manually parsing a request etc. just seems a waste of time to me

I agree. But those frameworks come to a cost: the learning curve and there are many to choose from, e.g. we use dropwizard internally. And so I would for now provide simple GET requests for the matrix ("reference implementation"). We can add simple tests and if one day we move to a simpler framework like dropwizard or spring boot those tests should still work.

If someone needs the matrix api in the web project, by all means, he can contribute to this project as well :)

I have to disagree. I want to make most of the features available and how should we advertise that matrix is now included but no one except Java devs can use it? There are features which have no explicit UI like the round trip feature, although one can still make it work using some parameters. But there is no feature (or very few) which are not accessible from the web module. Trust me: having this in the web module from the beginning is very important.

@karussell

Copy link
Copy Markdown
Member

Regarding framework: I think convenience is really important especially if you have many REST endpoints, but we don't have that and for us performance is more important. For me this is one of the reasons to stay a bit more low level. See here. (Probably more important for simple a-to-b routing than it is for matrix requests).

@alewaros

Copy link
Copy Markdown

Is the matrix support still on the roadmap? I could contribute if help is needed.

@kalexmills

Copy link
Copy Markdown

Ditto to alewaros' comment. Looking to gain this support for my own graphhopper instance.

@TimPigden

Copy link
Copy Markdown

Hi, we're very interested in using a one-to-many. but it looks like this has faded away over the issue of web support. Is someone able to comment?

@karussell

Copy link
Copy Markdown
Member

@karussell karussell closed this Jul 25, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants