{"cells":[{"cell_type":"markdown","source":["# Information Flow Through a Network\n\n","## Introduction\n\n","Modern financial markets operate very quickly due to algorithmic trading.\n","Essentially, computers execute trades automatically based on information inputs and clever algorithms. All of this occurs very rapidly.\n","The computers are so good at executing trades quickly, in fact, that the speed at which information moves from one city to another is actually a limiting factor.\n","For example, if an announcement that impacts the financial markets is made in Washington, DC, traders in New York, NY will probably \"hear\" about it before those in, say, Seattle, WA.\n","Since information can travel no faster than the speed of light (in reality it travels much more slowly because of various processing that must be done along the way) we can compute a lower bound on the time it will take a particular piece of information released in one city to arrive in other cities.\n","As you might expect, this problem involves flow through a network, and is therefore fairly simple to model in Neo4j (or any graph database, really).\n"],"metadata":{}},{"cell_type":"markdown","source":["## Data Model\n\n","Our data model consists of a set of cities, each with a latitude and longitude, which we will use to compute distances (we could have entered the distances as data, but it was more fun to use Neo4j for this task, and in a more generalized case you might want the nodes to be able to move).\n","Each city is linked to one or more other cities by `:BACKBONE_TO` relationships.\n","This indicates that the two cities involved in the relationship have an Internet backbone running between them.\n","For this example, we mostly made up the backbones, although the backbones running to Tokyo are accurate given actual undersea cable topology.\n","\n","![Information network data model](https://ik.imagekit.io/ggp/a01425e1-7a39-4206-a857-17950ec386bf_3FJQ-ulHA)\n","\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 (chc:City { name: \"Chicago\", lat: 41.833, lon: -87.617 }), (sea:City { name: \"Seattle\", lat: 47.617, lon: -122.334 }),\n","(sfo:City { name: \"San Francisco\", lat: 37.783, lon: -122.433 }), (tok:City { name: \"Tokyo\", lat: 35.667, lon: 139.75 }),\n","(chc)-[:BACKBONE_TO]->(sea), (sea)-[:BACKBONE_TO]->(sfo), (sea)-[:BACKBONE_TO]->(tok), (sfo)-[:BACKBONE_TO]->(tok)"]},{"cell_type":"markdown","source":["## Distance Computation\n\n","Before we can establish a lower bound on the time it takes information to flow between cities, we must determine the distance between cities that are linked by an Internet backbone.\n","We assume that the cables connecting cities lie on [great circles](https://en.wikipedia.org/wiki/Great-circle_distance), in other words, that each cable lies on the shortest possible line between cities.\n"],"metadata":{}},{"cell_type":"code","execution_count":0,"metadata":{"slideshow":{"slide_type":"fragment"}},"outputs":[],"source":["%%cypher\n","// Find the great circle distance from Tokyo to Seattle\n","MATCH (c1:City { name: \"Tokyo\" })\n","MATCH (c2:City { name: \"Seattle\" })\n","RETURN 2 * 6371 * asin(sqrt(haversin(radians(c1.lat - c2.lat)) + cos(radians(c1.lat)) * cos(radians(c2.lat)) * haversin(radians(c1.lon - c2.lon)))) AS Distance"]},{"cell_type":"markdown","source":["In our case we would like to record the distances between cities that are connected with an Internet backbone.\n","We can store this data on the `:BACKBONE_TO` edges.\n","Note that we don’t have to worry about double-computing because we have specified a relationship direction, so each distance will only be computed once.\n","If we left out the direction, each distance would be computed twice, although the end result would be exactly the same.\n"],"metadata":{}},{"cell_type":"code","execution_count":0,"metadata":{"slideshow":{"slide_type":"fragment"}},"outputs":[],"source":["%%cypher\n","// Add distance to backbone edges\n","MATCH (c1:City)-[r:BACKBONE_TO]->(c2:City)\n","WITH 2 * 6371 * asin(sqrt(haversin(radians(c1.lat - c2.lat))+ cos(radians(c1.lat))* cos(radians(c2.lat))* haversin(radians(c1.lon - c2.lon)))) AS dist, r, c1, c2\n","SET r.dist = dist\n","RETURN c1.name, c2.name, r.dist"]},{"cell_type":"markdown","source":["## Mapping Information Flow\n\n","Our next step is to find candidate paths from one city to another.\n","Once we have these paths, we can compute the minimum amount of time it would take a piece of information to move along each path, and find the shortest route between them.\n","First, we can find all unique, simple (no repeated cities) from one city to another.\n","Here is example for Tokyo and Chicago:\n"],"metadata":{}},{"cell_type":"code","execution_count":0,"metadata":{"slideshow":{"slide_type":"fragment"}},"outputs":[],"source":["%%cypher\n","// Find all unique, simple paths from one city to another\n","MATCH p=(:City { name: \"Tokyo\" })-[:BACKBONE_TO*]-(:City { name: \"Chicago\" })\n","WHERE all(c IN nodes(p) WHERE 1=size([m IN nodes(p) WHERE m=c]))\n","RETURN DISTINCT [ n IN nodes(p) | n.name] AS Path, length(p) AS Length"]},{"cell_type":"markdown","source":["Next, we would like to find the shortest path, in terms of distance:\n"],"metadata":{}},{"cell_type":"code","execution_count":0,"metadata":{"slideshow":{"slide_type":"fragment"}},"outputs":[],"source":["%%cypher\n","// Find the shortest distance path from one city to another\n","MATCH p=(:City { name: \"Tokyo\" })-[:BACKBONE_TO*]-(:City { name: \"Chicago\" })\n","WHERE all(c IN nodes(p) WHERE 1=size([m IN nodes(p) WHERE m=c]))\n","WITH reduce(s = 0, hop IN relationships(p) | s + hop.dist) AS distance, p\n","ORDER BY distance LIMIT 1\n","RETURN DISTINCT [n IN nodes(p) | n.name] AS Path, length(p) AS Length, distance AS Distance"]},{"cell_type":"markdown","source":["The next step is to change distance into an amount of time.\n","We will assume that information travels between cities at the speed of light.\n","As mentioned earlier this is not strictly true, but since we are looking for a lower bound on the time it takes information to move from one city to another, using the fastest possible speed for the information flow itself makes sense.\n","As an aside, we could make this model more complicated, and perhaps more accurate, by taking into account the processing time each each junction point along the way.\n","When information arrives at a particular node in the network it must be routed to the next node along its path, this takes some non-zero amount of time.\n","Therefore, we might actually want to minimize the distance information has to travel, subject to the constraint that each \"hop\" has a cost.\n","In this case, we would tend to prefer less complicated paths, even if they are slightly longer.\n","We can compute the number of milliseconds it should take information to travel between cities using the query below.\n","Note that we simply divide the distance by 300 to get milliseconds, since light travels at 300,000 kilometers per second.\n"],"metadata":{}},{"cell_type":"code","execution_count":0,"metadata":{"slideshow":{"slide_type":"fragment"}},"outputs":[],"source":["%%cypher\n","// Find the shortest distance path from one city to another\n","MATCH p=(:City { name: \"Tokyo\" })-[:BACKBONE_TO*]-(:City { name: \"Chicago\" })\n","WHERE all(c IN nodes(p) WHERE 1=size([m IN nodes(p) WHERE m=c]))\n","WITH reduce(s = 0, hop IN relationships(p) | s + hop.dist) AS distance, p\n","ORDER BY distance LIMIT 1\n","RETURN DISTINCT [n IN nodes(p) | n.name] AS Path, length(p) AS Length, distance AS Distance"]},{"cell_type":"markdown","source":["We can then generalize this query to compute the time it would take information to travel between any pair of cities.\n"],"metadata":{}},{"cell_type":"code","execution_count":0,"metadata":{"slideshow":{"slide_type":"fragment"}},"outputs":[],"source":["%%cypher\n","// Compute the minimum travel time between all pairs of cities\n","MATCH p=(c1:City)-[:BACKBONE_TO*]-(c2:City)\n","WHERE c1.name <> c2.name and all(c IN nodes(p) WHERE 1=size([m IN nodes(p) WHERE m=c]))\n","WITH reduce(s = 0, hop IN relationships(p) | s + hop.dist) AS distance, p, c1, c2\n","ORDER BY distance\n","RETURN c1.name AS `Start City`, c2.name AS `End City`, collect(distance / 300)[0] AS ms\n","ORDER BY c2.name"]},{"cell_type":"markdown","source":["## About\n\n","Create by George Lesica ([@glesica](https://twitter.com/glesica)) and William Lyon ([@lyonwj](https://twitter.com/lyonwj)).\n"],"metadata":{}}],"metadata":{"language_info":{"name":"python","version":"3.9.1"}},"nbformat":4,"nbformat_minor":4}