{"cells":[{"cell_type":"markdown","source":["# Santa's shortest weighted path\n\n","## Introduction: Santa’s shortest weighted path\n\n","HO! HO! HO! Tonight it’s Christmas Eve and Santa Claus is riding his sleigh around the world. He loves delivering the best gifts\n","to every kid, making them happy. They are waiting for him since it gets dark. They stay by the fireplace or near the window,\n","looking up to the night sky trying to catch with their wide open eyes even the smallest sign of a flying reindeer. And one by one\n","each of them listens to a bell noise close to her house and a new gift for them appears suddenly beneath the Christmas\n","tree, as a magic has just being summoned. When Santa Claus is not in a hurry can even manage to knock at the door of their house,\n","meeting the excited kids face to face before giving them the present.\n","Santa Claus is now upon the skies of Rome. He is so cheerful since he has just delivered all the gifts in the town, heading to the next one.\n","But, wait! Nooo, he just realized that he has forgotten three children, Alessio, Daniela and Domenico! How can he fix this missing? Hurry up, Santa! Hurry up!\n","Let’s give them their present before they go to bed, fall asleep and it’s too late!!!\n","But how? Rack up your brain, Santa! Yeah, Eureka!!! He got it!!!\n","In less than no time he modeled the map of Rome as a graph: he thought that the nodes could be the junctions between two or more streets, while\n","the roads the edges connecting each intersection. The relationships can carry the time distance he needs to travel that street segment\n","from node to node as an attribute.\n","Store this model in a graph db as Neo4j, find the shortest weighted route to reach each child before she is going to sleep\n","and the success is guaranteed without a shadow of a doubt!\n","\n","![reindeers pulling santas sled or sleigh 0521 1009 1013 0121 SMU](https://www.christmas-clipart.com/free_christmas_clip_art_images/reindeers_pulling_santas_sled_or_sleigh_0521-1009-1013-0121_SMU.jpg)\n","\n"],"metadata":{}},{"cell_type":"markdown","source":["## Maps graph model\n\n","Representing a street map as a graph is a common use case scenario. This can be achieved in several ways. For example I can see three topologies.\n","You could model the street blocks as nodes and draw a relationship between adjacent blocks.\n","Or the vertexes could represent the ways and every pair of streets that lies across is a single edge.\n","A third model considers the road junctions as nodes. An edge is then created when two or more of them are directly connected by a segment\n","of a lane with no other intersection taking place. And so on.\n","All of these three examples are correct: you should just choose the one that best fits your purposes.\n","Tonight Santa is going to use the third representation.\n","There are two labels of nodes: **Kid** and **RoadJunction**. The former characterizes a kid waiting for the gift delivered by Santa, together with his name and the bedtime. For sake of simplicity the bedtime represents the number of minutes from the time Santa became fully aware of his missing and starts his new city traversal to when the child falls asleep.\n","The latter is the intersection between two or more streets, uniquely defined by its id.\n","A node can have both labels at the same time.\n","There is indeed only one type of relationship: **CONNECTED_TO**. It carries the attribute distance, that shows how much time Santa’s sleigh needs to pass through that street segment. Although it is a directed edge, it will be traversed both ways, assuming that the time to go from one side to another and vice versa is exactly the same.\n","It sketches the street map where Santa should find the fastest route. Each intersection is identified by an id and each street segment\n","has a distance value. The three kids are living in the road junctions whose ids are 1,2,3. Santa starts the traverse from node 0.\n"],"metadata":{}},{"cell_type":"markdown","source":["## Model setup in Neo4j\n\n","Let’s see how can you convert this use case scenario in a graph on Neo4j. There is a total of 22 RoadJunction nodes. Three of them represent the kids as well.\n","Their names are Alessio, Daniela and Domenico and their bedtimes are, respectively, 100, 50 and 30 minutes.\n","In order to execute Cypher queries, make sure that the IPython extension `icypher` is installed.\n","If not, run the following command to install it:\n"],"metadata":{}},{"cell_type":"code","execution_count":0,"metadata":{"slideshow":{"slide_type":"fragment"}},"outputs":[],"source":["pip install icypher"]},{"cell_type":"markdown","source":["Then, load the `icypher` extension:\n"],"metadata":{}},{"cell_type":"code","execution_count":0,"metadata":{"slideshow":{"slide_type":"fragment"}},"outputs":[],"source":["%load_ext icypher"]},{"cell_type":"markdown","source":["Now you’re ready to connect to your Neo4j database:\n"],"metadata":{}},{"cell_type":"code","execution_count":0,"metadata":{"slideshow":{"slide_type":"fragment"}},"outputs":[],"source":["%cypher http://user:passwd@localhost:7474/db/data"]},{"cell_type":"code","execution_count":0,"metadata":{"slideshow":{"slide_type":"fragment"}},"outputs":[],"source":["%%cypher\n","CREATE\n"," (a:Kid:RoadJunction {id: 1, name: 'Alessio', bedtime: 100}),\n"," (b:Kid:RoadJunction {id: 2, name: 'Daniela', bedtime: 50}),\n"," (c:Kid:RoadJunction {id: 3, name: 'Domenico', bedtime: 30}),\n"," (n0\t:RoadJunction\t{id:\t0\t}),\n"," (n4\t:RoadJunction\t{id:\t4\t}),\n"," (n5\t:RoadJunction\t{id:\t5\t}),\n"," (n6\t:RoadJunction\t{id:\t6\t}),\n"," (n7\t:RoadJunction\t{id:\t7\t}),\n"," (n8\t:RoadJunction\t{id:\t8\t}),\n"," (n9\t:RoadJunction\t{id:\t9\t}),\n"," (n10\t:RoadJunction\t{id:\t10\t}),\n"," (n11\t:RoadJunction\t{id:\t11\t}),\n"," (n12\t:RoadJunction\t{id:\t12\t}),\n"," (n13\t:RoadJunction\t{id:\t13\t}),\n"," (n14\t:RoadJunction\t{id:\t14\t}),\n"," (n15\t:RoadJunction\t{id:\t15\t}),\n"," (n16\t:RoadJunction\t{id:\t16\t}),\n"," (n17\t:RoadJunction\t{id:\t17\t}),\n"," (n18\t:RoadJunction\t{id:\t18\t}),\n"," (n19\t:RoadJunction\t{id:\t19\t}),\n"," (n20\t:RoadJunction\t{id:\t20\t}),\n"," (n21\t:RoadJunction\t{id:\t21\t}),\n"," (a)-[:CONNECTED_TO {distance : 4 }]->(n21),\n"," (a)-[:CONNECTED_TO {distance : 4 }]->(n7),\n"," (a)-[:CONNECTED_TO {distance : 4 }]->(n4),\n"," (b)-[:CONNECTED_TO {distance : 2 }]->(n10),\n"," (b)-[:CONNECTED_TO {distance : 8 }]->(n17),\n"," (b)-[:CONNECTED_TO {distance : 1 }]->(n11),\n"," (b)-[:CONNECTED_TO {distance : 4}]->(n12),\n"," (c)-[:CONNECTED_TO {distance : 2.5 }]->(n13),\n"," (c)-[:CONNECTED_TO {distance : 2 }]->(n15),\n"," (c)-[:CONNECTED_TO {distance : 6 }]->(n17),\n"," (c)-[:CONNECTED_TO {distance : 5 }]->(n19),\n"," (n16)-[:CONNECTED_TO {distance : 4 }]->(n21),\n"," (n16)-[:CONNECTED_TO {distance : 8 }]->(n14),\n"," (n4)-[:CONNECTED_TO {distance : 4 }]->(n14),\n"," (n0)-[:CONNECTED_TO {distance : 8 }]->(n21),\n"," (n0)-[:CONNECTED_TO {distance : 5.5 }]->(n7),\n"," (n0)-[:CONNECTED_TO {distance : 4 }]->(n8),\n"," (n7)-[:CONNECTED_TO {distance : 4 }]->(n6),\n"," (n7)-[:CONNECTED_TO {distance : 4 }]->(n8),\n"," (n9)-[:CONNECTED_TO {distance : 4 }]->(n8),\n"," (n9)-[:CONNECTED_TO {distance : 4 }]->(n6),\n"," (n9)-[:CONNECTED_TO {distance : 9 }]->(n10),\n"," (n5)-[:CONNECTED_TO {distance : 1 }]->(n6),\n"," (n5)-[:CONNECTED_TO {distance : 3 }]->(n4),\n"," (n1)-[:CONNECTED_TO {distance : 6 }]->(n12),\n"," (n14)-[:CONNECTED_TO {distance : 7.5 }]->(n20),\n"," (n13)-[:CONNECTED_TO {distance : 5 }]->(n20),\n"," (n13)-[:CONNECTED_TO {distance : 3 }]->(n15),\n"," (n12)-[:CONNECTED_TO {distance : 2 }]->(n13),\n"," (n12)-[:CONNECTED_TO {distance : 3.5 }]->(n11),\n"," (n15)-[:CONNECTED_TO {distance : 1.5 }]->(n11),\n"," (n20)-[:CONNECTED_TO {distance : 2.5 }]->(n19),\n"," (n18)-[:CONNECTED_TO {distance : 6 }]->(n19),\n"," (n18)-[:CONNECTED_TO {distance : 5 }]->(n17);"]},{"cell_type":"markdown","source":["To speed up the query when looking for a particular RoadJunction id, Santa decides\n","to create an index on that node attribute. In this little graph you cannot really appreciate it,\n","but in a bigger one it is fundamental.\n"],"metadata":{}},{"cell_type":"code","execution_count":0,"metadata":{"slideshow":{"slide_type":"fragment"}},"outputs":[],"source":["%%cypher\n","CREATE INDEX ON :RoadJunction(id)"]},{"cell_type":"markdown","source":["Here you can see the graph just modeled.\n"],"metadata":{}},{"cell_type":"code","execution_count":0,"metadata":{"slideshow":{"slide_type":"fragment"}},"outputs":[],"source":["%%cypher\n","MATCH (s)-[p]->(o) RETURN s,p,o;"]},{"cell_type":"markdown","source":["## Santa’s Algorithm\n\n","Santa is on RoadJunction {id:0} vertex when he realizes of his missing. This will be the starting\n","point of his route. He wants to look for the best path that meets the following requirements:\n","\n","- the gifts are delivered to each kid **before they fall asleep**\n","- the travel time to traverse the map from the starting point (node with id 0) to the last\nvisited kid must be **minimized**. Christmas Eve is not over yet, there are still plenty of children\nwaiting for their gifts in other towns! You don’t want them to miss their present, do you?\n","\n","At a first glance Santa Claus may think that using the already implemented *allShortestPaths* could be a cleaver idea.\n","However, this function doesn’t take into account the weight of each relationship, characterized by the distance property:\n","in fact, a shorter path, meant as the one with the least number of relationships, may have an higher total distance than a longer but lighter one.\n","Santa needs to develop a new query from scratch.\n","The Santa’s shortest weighted path algorithm is the following:\n"],"metadata":{}},{"cell_type":"code","execution_count":0,"metadata":{"slideshow":{"slide_type":"fragment"}},"outputs":[],"source":["MATCH (kid:Kid)\n","WITH count(kid) as numberOfKids\n","MATCH path = ((startingRoadJunction)-[:CONNECTED_TO*1..20]-(lastKid:Kid))\n","WHERE startingRoadJunction.id = 0 and size(filter(x in nodes(path) WHERE (x:Kid))) >= numberOfKids\n","WITH path, [x IN nodes(path) WHERE (x:Kid) | x] as kidsList, numberOfKids\n","UNWIND kidsList as kidInPath\n","WITH path, collect(distinct kidInPath) as kidsInPath, numberOfKids\n","WHERE size(kidsInPath) = numberOfKids\n","WITH path, REDUCE(dist = 0, rel in rels(path) | dist + rel.distance) AS pathLength, kidsInPath,\n"," [i in range(0,size(nodes(path))) where (nodes(path)[i]):Kid | i] as kidPositions, numberOfKids\n"," WHERE\n"," ALL (i in range (0,size(kidPositions)-1) WHERE\n"," reduce(dist = 0, rel in rels(path)[0..kidPositions[i]] | dist + rel.distance) < (kidsInPath[i]).bedtime)\n","RETURN path, pathLength\n","ORDER BY pathLength ASC\n","LIMIT 1"]},{"cell_type":"markdown","source":["Here the algorithm explanation line by line. Note that you may need to create the dataset in a your own Neo4j graph instance\n","to avoid `org.neo4j.kernel.guard.GuardOperationsCountException` exception that unfortunately may occur on the graphgist\n","platform.\n","**1,2)** Santa would firstly like to know how many kids he should deliver gifts.\n","The query is trivial and could be executed alone in this way\n"],"metadata":{}},{"cell_type":"code","execution_count":0,"metadata":{"slideshow":{"slide_type":"fragment"}},"outputs":[],"source":["%%cypher\n","MATCH (kid:Kid)\n","RETURN count(kid) as numberOfKids"]},{"cell_type":"markdown","source":["The result (3 in this case) is then passed to the other parts of the final query thanks\n","to the *WITH* clause (instead of *RETURN*).\n","**3)** You are looking for a subgraph that matches this pattern:\n","\n","- the node *lastKid* is a Kid\n","- there is at least 1 and a max of 20 hops to connect the nodes *startingRoadJunction* and *lastKid*. The type of this relationships is *CONNECTEDTO* . It is always a clever idea to set a lower and upper bound to the paths, especially if your hardware resources are limited and the graph is big. In this case 20 hops are enough for finding the route.\n","- the pattern is undirected, as long as the last node of the path is lastKid. Therefore the relationships are navigated both ways.\n","\n","Every path that matches this pattern is stored into the variable *path*.\n","**4)** In the *WHERE* condition the constraint that the first node of the path must have the id equal to 0 is set.\n","Furthermore\n"],"metadata":{}},{"cell_type":"code","execution_count":0,"metadata":{"slideshow":{"slide_type":"fragment"}},"outputs":[],"source":["size(filter(x in nodes(path) WHERE (x:Kid))) >= numberOfKids"]},{"cell_type":"markdown","source":["means that the number of the kids in the path must be equal or greater than the value of the variable numberOfKids, previously obtained.\n","This condition will help the search of the optimal solution, removing already from the further query steps and calculations\n","those paths that don’t include every kid for sure. The filter function iterates all the nodes of path, returning an array\n","comprising only those labeled by *Kid*.\n","**5)** The WITH clause permits to pass to the next algorithm steps the variable *path*, the numberOfKids variable\n","and an array containing all the Kid nodes found in the corresponding path (thanks to a filter-extract function).\n","**6,7)** A path may traverse a kid node more than once. The aim of those two lines is to unwind the kidsList array of each path and collecting it again\n","in order to remove the duplicates from it. Therefore the resulting collection is the set of kids contained in the path.\n","**8)** An extra where condition to apply on the kids sets. It removes from the result those path that don’t pass through all\n","the kids. The one you can find at line 4 is not enough to assure this requirement, due to the existence of the duplicates.\n","For instance a path with the kidsList [1,2,2] is excluding the kid with id 3, even if the size is actually three, and should be consequently pruned.\n","**9,10)** At this point the algorithm is making two important calculations, stored in the variables *pathLength* and *kidPositions*.\n","The former is the total time distance Santa needs to go from the start node to the end one. It is obtained thanks to the\n","*reduce* collection function.\n"],"metadata":{}},{"cell_type":"code","execution_count":0,"metadata":{"slideshow":{"slide_type":"fragment"}},"outputs":[],"source":["REDUCE(dist = 0, rel in rels(path) | dist + rel.distance)"]},{"cell_type":"markdown","source":["It iterates the relationships in the path, accumulating the total distance inside the dist variable, initialized to 0.\n","The latter, instead, leverages the collection function that combines extract and filter. It returns the array consisting of\n","the position of the kids among all the nodes of the path.\n","For example, let [1,4,3,4,6,2] be the array resulting from nodes(path) and 1,2,3 the kids. This function\n","will return [0,2,4], id est the indexes of the kids within the array.\n","The range function generates an array that goes from 0 to the total number of nodes in the path.\n"],"metadata":{}},{"cell_type":"code","execution_count":0,"metadata":{"slideshow":{"slide_type":"fragment"}},"outputs":[],"source":["[i in range(0,size(nodes(path))) where (nodes(path)[i]):Kid | i]"]},{"cell_type":"markdown","source":["Writing this Cypher snippet as an imperative programming pseudocode it would sounds like this:\n"],"metadata":{}},{"cell_type":"code","execution_count":0,"metadata":{"slideshow":{"slide_type":"fragment"}},"outputs":[],"source":["result = [];\n","for(int i = 0; i < nodes(path).length; i++){\n"," if(nodes(path)[i] is a kid)\n"," then result = result + i;\n","}\n","return result;"]},{"cell_type":"markdown","source":["**11,12,13)** This where condition exploits the *ALL* collection predicate: all the elements\n","must be true to the condition. It could be the trickiest step of all the algorithm.\n","Santa spent so much time thinking about it!\n"],"metadata":{}},{"cell_type":"code","execution_count":0,"metadata":{"slideshow":{"slide_type":"fragment"}},"outputs":[],"source":["ALL (i in range (0,size(kidPositions)-1) WHERE\n","reduce(dist = 0, rel in rels(path)[0..kidPositions[i]] | dist + rel.distance) < (kidsInPath[i]).bedtime)"]},{"cell_type":"markdown","source":["It iterates the array containing the kids position. At each step, it checks if the distance to reach the i-th Kid from the\n","beginning of the path is less than the bedtime of the i-th kid. If a path doesn’t meet this requirement, it will be\n","discarded by the query. The distance of each subpath is determined by a reduce function similar to the previous line. The\n","difference is that it is not considered all the path relationships collection but only its slice *0..i*\n","Writing this Cypher snippet as an imperative programming pseudocode it would sounds like this:\n"],"metadata":{}},{"cell_type":"code","execution_count":0,"metadata":{"slideshow":{"slide_type":"fragment"}},"outputs":[],"source":["result = true;\n","for(int i = 0; i < size(kidPositions); i++){\n"," distance = 0;\n"," for(int j = 0; j < kidPositions[i]; j++){\n"," distance += rels(path)[j];\n"," }\n"," if(distance >= kidsInPath[i].bedtime){\n"," result = false;\n"," }\n","}"]},{"cell_type":"markdown","source":["The constraint made by this ALL predicate condition is strong and Santa should take it into account while\n","selecting his route.\n","For instance let’s consider the following path whose nodes id are [0, 7, **1**, 4, 5, 6, 9, 10, **2**, 11, 15, **3**],\n","in bold the kids. Its distance amounts to 37 minutes and it reaches all the three kids during the graph traversal.\n","However the gift is being delivered to Domenico {id: 3, bedtime : 30} after has fallen asleep, not satisfying\n","all the problem requirements.\n","The best path returned by the algorithm is [0, 8, 9, 10, **2**, 11, 15, **3**, 19, 20, 14, 4, **1**]. Its total distance is 46.5,\n","greater than the previous path and requiring more connections; however the kids nodes are traversed in an order that\n","permits all the children to be fully awaken while receiving their Christmas presents. And you should note that Alessio, the kid closest to\n","the starting point, is actually the last one to meet Santa.\n"],"metadata":{}},{"cell_type":"markdown","source":["## Conclusion and future works\n\n","In this *GraphGist* a use case scenario for modeling a street map as a graph has been developed on Neo4j.\n","On top of it has been built in Cypher a **shortest weighted path search algorithm with constraints on nodes**; it\n","leverages most of the built-in collection functions (*extract*, *filter* and *reduce*), as well as *UNWIND*, *range* and *ALL* collection predicate.\n","The sample has been kept simple, in order to help the readers to understand better how the query works.\n","However the principles exposed here can be easily scaled to larger scenarios.\n","While testing it in bigger graphs, I realized that some tweaks may be useful for increasing the performances, especially when not having proper hardware resources.\n","For instance you may create both directions relationships between each couple of nodes, changing therefore the MATCH pattern\n","statement in (startingRoadJunction)-[:CONNECTED_TO*1..20]→(lastKid:Kid). From one hand, this will extend the physical size of the db;\n","from the other it may improve the overall performances while executing the query.\n","Using allShortestPath can definitely speed up the algorithm but it may\n","prune some optimal solutions, especially in case of a long but light path.\n","Moreover the hardcoded upper limit of 20 hops should be surely modified when traversing larger datasets.\n","In conclusion, even if the algorithm result is encouraging and Santa as well as the kids are happy thanks to it,\n","there is always room for enhancements, especially in a production environment where the performances play a key role.\n","I will leave you with two last code snippets to generate your random datasets and play with the query.\n","The nodes can be randomly created with the two following queries.\n"],"metadata":{}},{"cell_type":"code","execution_count":0,"metadata":{"slideshow":{"slide_type":"fragment"}},"outputs":[],"source":["WITH ['Alessio', 'Daniela', 'Domenico', 'Elsa', 'Antonella', 'Alessandro',\n"," 'Luciano', 'Susanna', 'Federica', 'Valerio', 'Fabio', 'Marta', 'Mario', 'Giustino'] as names\n","FOREACH (i IN range(0,100) | CREATE (kid:Kid:StreetNode {id: i, name:names[i % size(names)] + \" \" + i, bedtime:round(rand()*1000)}));\n","\n","FOREACH (i IN range(100,1000000) | CREATE (streetNode:StreetNode {id: i}));"]},{"cell_type":"markdown","source":["The edges, instead, with this one.\n","Note that in this query every RoadJunction will connect a maximum of four street\n","segments. This assumption it is very likely to happen in real maps as well.\n"],"metadata":{}},{"cell_type":"code","execution_count":0,"metadata":{"slideshow":{"slide_type":"fragment"}},"outputs":[],"source":["%%cypher\n","WITH range(0, 1000000) as streetNodeIds\n","unwind streetNodeIds as streetNodeId\n","with streetNodeId, extract(x in range(0, toInt(round(rand()*3))) | round(rand()*10000)) as coll\n","unwind coll as nearStreetNodeId\n","match (streetNode:StreetNode {id:streetNodeId}), (nearStreetNode:StreetNode {id: nearStreetNodeId})\n","where streetNodeId <> nearStreetNodeId\n","merge (streetNode)-[r:CONNECTED_TO {distance: round(rand()*100+1)}]-(nearStreetNode)\n","return streetNode, nearStreetNode"]},{"cell_type":"markdown","source":["Thank you for reading up to here! Hope you enjoyed it!\n","All the best,\n","Alessio and Santa Claus\n"],"metadata":{}}],"metadata":{"language_info":{"name":"python","version":"3.9.1"}},"nbformat":4,"nbformat_minor":4}