r/javascript • • Sep 21 '17

I made a very fast path finding library. What do you think?

https://github.com/anvaka/ngraph.path
353 Upvotes

70 comments sorted by

34

u/anvaka Sep 21 '17

And here is the interactive demo to play with: https://anvaka.github.io/ngraph.path.demo/

If you are curious how it's made - I documented my process here https://github.com/anvaka/ngraph.path.demo

8

u/nothingduploading Sep 21 '17

Does the demo take into account one-way streets?

16

u/anvaka Sep 21 '17

The demo doesn't, but the library does

1

u/Amadox Sep 27 '17

if I see that right, either all streets are considered bidirectional, or none are? ofc we could just go for none, and then make reverse addLinks for every bidrectional streets, but wouldn't it be nicer if we could specify direction for each addLink individually?

15

u/maffoobristol Sep 21 '17

It's definitely fast, and I love your write up, but it doesn't seem massively accurate, at least in the demo.

This definitely doesn't seem like the shortest route! https://imgur.com/a/hNAEI

Also it seems it wants you to swim a bit!

5

u/anvaka Sep 21 '17

Interesting! Can you share the url? It should have start/end points in it.

5

u/maffoobristol Sep 21 '17

7

u/anvaka Sep 21 '17

This is what I see. Seem to be correct. Does it look different for you?

8

u/maffoobristol Sep 21 '17

My coordinates seem to render differently for me. I'm on iOS, and when I pan or zoom, the markers and routes don't move with it, if that helps at all? May be more an issue with the map than the integration

14

u/anvaka Sep 21 '17

This is very helpful. I think the bug is somewhere around WebGL/SVG layer (not in the pathfinder).

I remember it was easy to break older versions of Safari with SVG. What version of the iOS/Safari are you using?

PS: I don't want to waste to much of your time, but if you know how to debug safari looking into console logs might be helpful too!

7

u/Prison__Mike_ Sep 21 '17

FWIW I can't reproduce this on PC Chrome nor Android

-1

u/R0b0d0nut Sep 22 '17

2

u/anvaka Sep 22 '17

Interesting!

This is what Google Maps suggest: https://www.google.com/maps/dir/52.4288552,4.872062/52.4099466,4.890144/@52.4131114,4.8921518,14.41z/data=!4m2!4m1!3e0

They have straighter lines. Very likely they consider speed limits (I don't), and optimize for other subtle things which make route slightly longer but more pleasant (like reducing number of turns).

What do you think?

1

u/R0b0d0nut Sep 22 '17

Yes. The googs definitely consider things like number of turns, direction of turns (left turns take more time at unregulated intersections ) , traffic.

I want to say that what you’ve done is super fucking cool. I’m a geography and gis guy so this stuff floats my boat.

The detail as to what you did is really great. My money is on someone like mapbox “borrowing” it.

1

u/imguralbumbot Sep 21 '17

Hi, I'm a bot for linking direct images of albums with only 1 image

https://i.imgur.com/WP6VNvc.png

Source | Why? | Creator | ignoreme | deletthis

5

u/mflux Sep 21 '17

I really enjoyed the write up. Thank you!

I haven't checked but what is your license for the library?

8

u/anvaka Sep 21 '17

Thanks! It's under MIT license

8

u/E_R_E_R_I Sep 21 '17 edited Sep 21 '17

Good Lord how is it so fast?

I've opened it on my phone and it calculates routes across the city in 10ms. Some years ago, I wanted to create a Tower Defense game using javascript and HTML5, but I ended up giving up because one of my requirements was that I wanted to have dynamic terrain, and the AI of each enemy should recalculate the route evrytime the map was altered. I also wanted freeform movement, no tile system.

I implemented Dijkstra in a very simple raycasting technique (each vertex on the scenarios 2D polygons were represented by a node) and it was pretty bad performance wise. I had some dozens of enemies at once on the screen.

Granted, I was a novice and my implementation might've been bad, but I even managed to optimize it a bit treating chunks of enemies next to each other as one. In the end, 60 enemies recalculating their routes would take about three seconds each time.

The node count was pretty similar to these routes I just tried here. This suggests I could maybe get them all to recalculate routes in under a second which is pretty acceptable.

I'm very impressed, I'll look into it later. Congrats :P

EDIT: Corrected a dumb calculation mistake

7

u/ivosaurus Sep 21 '17 edited Sep 21 '17

Dijkstra's algorithm is accurate, but it's not very fast at all. You can notice simply in the demo it's taking about 3 times as long as A*. You would be extremely hard pressed to find any professional game using dijkstra for path finding over A*, where search time had any meaning in performance.

3

u/E_R_E_R_I Sep 21 '17

This is interesting. Is A* less accurate?

9

u/munificent Sep 21 '17

No, provided the world you are pathfinding in obeys certain pretty normal physical rules (i.e. no wormholes or places where there is a straight line isn't the shortest path), A* will find the shortest path.

Dijkstra's is nice when you want to find the shortest path to a given node from all other nodes. But if you're trying to find a single path between two points, A* (or one of the more advanced ones like jump-point search) is usually what you want.

2

u/E_R_E_R_I Sep 22 '17

Thx mate :P

0

u/rcfox Sep 22 '17

No, provided the world you are pathfinding in obeys certain pretty normal physical rules (i.e. no wormholes or places where there is a straight line isn't the shortest path), A* will find the shortest path.

A* doesn't care about the layout of your graph. It's almost exactly the same algorithm as Dijkstra, with the difference being an added heuristic to help check better paths first. It's up to you provide a permissible heuristic for estimating path costs.

Dijkstra's is nice when you want to find the shortest path to a given node from all other nodes.

You've got that backwards. Dijkstra's algorithm solves the single-source shortest path problem. (Not all graphs have bidirectional edges.)

3

u/spankalee Sep 22 '17 edited Sep 22 '17

A* doesn't care about the layout of your graph. It's almost exactly the same algorithm as Dijkstra, with the difference being an added heuristic to help check better paths first. It's up to you provide a permissible heuristic for estimating path costs.

A* cares that you can provide an admissible heuristic, which can just be Euclidean distance with normal physics. Wormholes would cause Euclidean distance to over-estimate the cost of the solution, making it non-admissible.

Edit:

You've got that backwards.

SSSP and SDSP are the same, just reverse the edges.

1

u/rcfox Sep 22 '17

So don't use such a simple heuristic in that case? If you have wormholes, label those edges as such and treat them differently.

2

u/munificent Sep 22 '17

It's up to you provide a permissible heuristic for estimating path costs.

That's what I meant by "normal physical rules". I didn't want to use A* jargon. If your world is weird, you may not be able to devise a good admissible heuristic in which case A* may not return the true shortest path.

You've got that backwards. Dijkstra's algorithm solves the single-source shortest path problem. (Not all graphs have bidirectional edges.)

Oops, you're correct. It gives you the shortest path from a given node to all other nodes.

2

u/nmarshall23 Sep 21 '17

Could we have a demo that gives weight to major vs minor roads. In the demo that would be thick vs thin.

Overall looks like a great library. Thanks for you work.

2

u/JanitorMaster Sep 22 '17

My, that demo is sexy.

4

u/d36williams Sep 21 '17

This was fun to review. I think your code in ngraph.path is the most interesting part

1

u/anvaka Sep 21 '17

Thank you :)! I'm glad you liked it

2

u/Swadqq Sep 21 '17

I love it! I'm running into a little trouble in places though. What's going on here? https://anvaka.github.io/ngraph.path.demo/#?graph=amsterdam-roads&fromId=11092&toId=33214

https://imgur.com/a/nkUPK

3

u/anvaka Sep 21 '17 edited Sep 21 '17

Thanks! I believe this is just the data. Two roads intersecting on a map do not alway mean you can make a turn. For example, one could be a bridge over the other. I think I found your path on Google Maps as well: https://www.google.com/maps/dir/52.3626229,4.9628647/52.366142,4.9451907/@52.3703753,4.9519916,14.96z/data=!4m2!4m1!3e0 - looks very similar.

1

u/Swadqq Sep 21 '17

Ooh, that's exciting!

1

u/imguralbumbot Sep 21 '17

Hi, I'm a bot for linking direct images of albums with only 1 image

https://i.imgur.com/OWarJi6.png

Source | Why? | Creator | ignoreme | deletthis

2

u/vidro3 Sep 22 '17

I'm kind of dumbstruck.

So, how is this so fast? Can you differentiate your approach from others that are commonly used?

What is NBA*, some version of A*?

4

u/anvaka Sep 22 '17

I documented it here: https://github.com/anvaka/ngraph.path#why-is-it-fast but maybe GitHub's hash links are not working well on mobile. The section is called Why is it fast?

TL;DR: Used optimized heap data structure, used GC friendly object pool, and yes NBA* is a bi-directional A* with smart and fast exit criteria.

2

u/vidro3 Sep 22 '17

thanks for the link - i had just read your .demo page not the actual library write up.

so much to learn ...

1

u/anvaka Sep 22 '17

You are very welcome!

2

u/vidro3 Sep 22 '17

also, all my searches for NBA* algorithm bring back results about basketball.

is this a known algorithm or did you just create something new?

1

u/anvaka Sep 22 '17

The algorithm is known, but probably less than it deserves to be known. I think you pointed out the reason why it's not very well-known (bsketball).

It was created by Wim Pijls and Henk Post in 2009. Here is a paper describing it: https://repub.eur.nl/pub/16100/ei2009-10.pdf

2

u/xwnatnai Sep 22 '17

Amazing work!

1

u/anvaka Sep 22 '17

Thank you :)!

3

u/winteriver Sep 21 '17

Awesome man. I love it.

1

u/anvaka Sep 21 '17

Thanks!

1

u/rcfox Sep 21 '17

In your demo, you have one fixed point and one that gets swept around. (I say "fixed point" because you can only interact with one at a time.)

In that case, might it be better to run Dijkstra once over the whole graph to find the shortest paths from the "fixed point" to everywhere else?

1

u/anvaka Sep 21 '17

I say "fixed point" because you can only interact with one at a time.

You can interact with both of them at the same time on touch device :).

Might it be better to run Dijkstra once over the whole graph to find the shortest paths from the "fixed point" to everywhere else?

That's a very good idea if your source point is always fixed! Unfortunately precomputing and storing all possible paths for all points (when source point is not fixed) is very expensive for large graphs.

There are methods which allow you to precompute paths only for small subset of "landmarks". They require solid amount of time for pre-processing, but after that they seem to be blazingly fast: https://www.microsoft.com/en-us/research/publication/better-landmarks-within-reach/

1

u/Desmulator Sep 21 '17

You dont need to store each path. Just for each node it's previous node. Now you generate the path in reverse.

2

u/anvaka Sep 21 '17

Sure! That works if you run single source shortest path.

I was talking about all source shortest paths. If we have two shortest paths:

A -> B -> C
E -> B -> D

What should we store as parent for B? In one case it should be A, while in other it will be E... Unless I'm missing something, this would still require you O(n^2) storage, where n is number of nodes.

4

u/Desmulator Sep 21 '17

You are completely right.

1

u/Spanholz Sep 22 '17

Could you add a little copyright notice for OpenStreetMap in one of the corners of your demo? The more people know about the project the better the map data will be. :)

2

u/anvaka Sep 22 '17

I'll see what I can do. By the way, the link to OSM is already available if you click Aboutbutton, also description of the project has more information about where data comes from (the NYC graph comes from a different place).

1

u/epmatsw Sep 22 '17

Re: the lazy A*, there's a good solution for that problem in this paper: https://nofile.io/f/HTG6Y0gGMak/Bi+Directional+A+Star.pdf. The termination condition is basically step 5 on page 131.

Basically, you know that the shortest path is through a node that you've already explored. Because you've calculated the shortest distance from the start and from the goal for each of those nodes already, you can just iterate through them looking for the node with the lowest sum of those two, and then build the result path back outward from that optimal middle.

1

u/anvaka Sep 22 '17

Thanks for the link!

1

u/spankalee Sep 22 '17

"A* greedy" converged the fastest, however, as name implies the found path is not necessary globally optimal.

This is an odd claim. A* should always be optimal with an admissible heuristic.

1

u/anvaka Sep 22 '17

You are totally right. If you run your search in one direction - you are guaranteed to find the shortest path.

A* greedy is my "failed" attempt at bi-directional A* search, where we perform searches from both ends. When two searches meet - I stop the process. Problem with that, is the meeting point is not necessary on the globally optimal solution.

NBA* is also bi-directional path finder, but unlike my initial attempt, it always ends with the shortest path.

1

u/nullality Sep 21 '17

The demo gif had B point starting in my neighborhood lol that was weird but cool. This project rocks, awesome docs.

1

u/anvaka Sep 22 '17

Thank you :)! I love Seattle.

2

u/[deleted] Sep 21 '17

Very cool... good job.

2

u/livrem Sep 22 '17

My guess is that the comparison is unfair to Dijkstra's. Everyone is always unfair to Dijkstra's.

The way you use Dijkstra's (and I find that to be a much more common problem to need solving) is you run it once for a source node and then it will give you all the shortest paths to all other nodes. Then when you want the shortest path to some other node you only need to follow the pointers already saved, which will be much faster than running Astar for every node.

Since this test page shows Dijkstra's being much slower, my guess is that it runs once for every time a new destination node is selected?

In practice I find I need Dijkstra's a lot, almost never Astar, because there is very often a single node and you need to find many shortest paths from it, so just a single run of Dijkstra's will do that, instead of having to run some Astar over and over for every other node you need.

1

u/maffoobristol Sep 21 '17

I'll have a look into it further. But I was actually running it in Reddit's app (which I think is safari) and mobile chrome and both had the same issue!

1

u/akujinhikari Sep 22 '17

Chrome on iPhone runs on Safari, so that would make sense.

1

u/TotesMessenger Sep 22 '17

I'm a bot, bleep, bloop. Someone has linked to this thread from another place on reddit:

If you follow any of the above links, please respect the rules of reddit and don't vote in the other threads. (Info / ^Contact)

1

u/ckohler4692 Sep 22 '17

I notice the "A" and "B" can only be followed by the end or start nodes of each road segment. I worked on routing using postgresql and qgis to make drive-time isochrones and came upon the same problem. This brought on another effort because going through and unsplitting road segments in the network allowed higher accuracy for in real-time positions(for example addresses instead of road segments would be use). I did this technique only for cases where road segments were significantly large. To manually do this for entire city's network I imagine would be close to hell.

This is where I would go next in order to improve the accuracy of your project.

1

u/[deleted] Sep 21 '17

I'm lacking the time write now to have a close look at it but my first impression is very positive. Good job!

0

u/[deleted] Sep 21 '17

[deleted]

18

u/E_R_E_R_I Sep 21 '17 edited Sep 21 '17

The map is a giant graph. Every intersection is a node, that contains information such as distance to neighbor nodes (the length of the street) and other stuff.

EDIT: Formatting

23

u/anvaka Sep 21 '17 edited Sep 21 '17

Yes!

I also did a write up on how I made it all here: https://github.com/anvaka/ngraph.path.demo#ngraphpath-demo

It has references to OpenStreetMap API - play with it and see the response. Everything on the map is a graph's node. Some nodes are connected by ways. way can be anything - a road, a river, even a building outline is a "way".

Intersections of two roads are nodes (even when a road bends - it means there is a node between two straight parts of a road).

Both ways and nodes have attributes. node has information about its geographic location (lon/lat), while way may have attribute describing its name (if it's a street), its speed limit, how many lanes it has and so on.

It's a very rich data set! I don't take into account neither directionality of roads nor speed limits - that would add significant amount of data (+20% in download size for the smallest graph of Amsterdam), which would impact demo's start up time.

Said that, it's totally possible to add weights to the shortest path computation. Right now i'm considering a "distance" between two points as euclidian distance. But if we have speed limits, we could translate distance to travel time, and the algorithm would try to minimize that.

If we are using Dijkstra, then we'd be done with this simple transformation. However for A* search, we would also have to make sure that our estimated distance between two points is always smaller than it actually is (otherwise the algorithm will not give the shortest path). One trivial way to update this heuristic would be to think that each road has the lowest possible speed limit.

8

u/mrMalloc Sep 21 '17

When i was at the uni ~ 15y ago I remember a lecture about searching and my professor said something about using A* to make sure it’s a reachable destination. Then applying dijktstras to find a good enough path fast enough.

Put you can’t prove it’s the best route. ;) You can just prove it’s one of the better ones.

Otherwise it’s NP complete

Looks like a good library tho.

0

u/[deleted] Sep 21 '17

[deleted]

7

u/E_R_E_R_I Sep 21 '17 edited Sep 21 '17

It is kinda crazy, but you already guessed one way of making the job easier.

Yes, there are nodes at each point where two or more streets meet, that is actually how we store map data. We don't store it in SVG of course, but it is a graph. Everytime you open Google Maps, it reads the graph and builds the svg code to visually represent the section you are seeing.

It's an insurmountable amount of data and goes to show how big of an achievement Google Maps is. Think about it, even if we didn't do that, we'd still have to store the information for each street's names, speed limits and allowed traffic directions, it isn't like having nodes (which essentially is just a way of storing the data of where a street starts and where it ends) is the biggest hurdle.

Of course, this wasn't built all by hand. There are algorithms that can look at a traditional map (a picture, essentially) and "guess" were the nodes should be, plus read the street names. Those algorithms are becoming better and better with machine learning, but they existed before the AI craze. However, running those algorithms everytime you want to trace a path would be impractical, so they are run once, and the result is stored in the form of a graph. It might seem crazy at first, but if you think about it, everything that can be processed can be stored.

These nodal maps like Google's trade the need for constant processing power for the need for storage, since it's much cheaper to have some dozens of petabytes stored than it is to have a hundreds of supercomputers working non stop, which generates more heat, brings higher energy costs and so on.

That said, there's still a huge amount of human touch in Google Maps and similar solutions. As far as I know, every data that goes into it is eventually revised by human beings. At least that's how it was until some years ago, don't know about now.

EDIT: Grammar

0

u/[deleted] Sep 21 '17

[deleted]

2

u/Gravyd3ath Sep 22 '17

I do this for a living it gets super boring.

0

u/[deleted] Sep 21 '17

[deleted]

1

u/anvaka Sep 21 '17

You are correct.

I wouldn't expect it impacts performance too much. Compared to everything else what it does inside, this is probably going to be negligible. I ran this code under profiler a few times - most of the slowness comes from algorithm itself. Simple things like checking if node belongs to closed set were highlighted by profiler as "hot"...