Shortest Path Analysis Using Dijkstra’s Algorithm
shortest path
graph
dijkstra
- Shortest Path Analysis Using Dijkstra’s Algorithm
- Overview
- Methodology
- Technical explanation
- Output
- Interpreting the results
- Technical Considerations
- The Code
Overview
Finding the shortest route between two entities is a common problem in network analysis. In a graph, the shortest route does not always mean the route with the fewest connections, a route with more connections can have a lower total cost than a route with fewer connections. When relationships have different costs, the analysis must consider the weight of each connection.
Dijkstra’s Algorithm to identify the minimum-cost path between selected source and target nodes. It uses edge weights to determine the cost of moving from one node to another. Each relationship contains a cost property that represents the effort required to move between connected nodes. The algorithm evaluates these costs and identifies the route with the lowest accumulated value.
In graph analysis, nodes represent entities, while relationships represent connections between them. Each relationship can have a weight that represents distance, cost, time, capacity constraints, or another measurable factor.
Unlike an unweighted shortest-path algorithm, Dijkstra’s Algorithm considers the cost of each relationship. It evaluates possible routes and identifies the path with the lowest total cost from a source node to a target node.
For example, in a telecommunications infrastructure graph:
- Nodes can represent network devices, towers, switches, or service locations.
- Relationships can represent physical or logical network connections.
- Edge weights can represent connection distance, latency, or transmission cost.
The algorithm can then identify the lowest-cost route between two infrastructure nodes.
Methodology
Dijkstra’s Algorithm starts from a source node and evaluates the available paths to other nodes.
The process follows these steps:
- Graph projection: The analysis starts by creating a graph projection from the underlying graph data. Relevant node labels and relationship types are selected to represent the network structure. This step ensures that the algorithm evaluates the intended connections rather than unrelated relationships in the database.
- Dijkstra’s Algorithm step-by-step:
- Initialize the source node. Set its initial distance to zero. Set the distance of other nodes to infinity.
- Evaluate neighboring nodes. Calculate the cost of reaching each neighbor through the current node.
- Update the distances. Replace the previous distance when a lower-cost route is found.
- Select the next node. Process the unvisited node with the lowest known distance.
- Continue the search. Repeat the process until the required destination nodes have been reached or the algorithm has completed its search.
- Reconstruct the paths. Use the predecessor information to retrieve the sequence of nodes and relationships that form each shortest path.
- Output: The algorithm output provides the shortest-path result, but further processing is required to inspect each connection in detail.
- Cypher queries: it performs this additional processing. The
UNWINDclause expands the returned node sequence into individual records.MATCHretrieves the corresponding relationships, whileWHEREfilters the records to retain valid connections along the route. - Finalizing: The query also calculates the individual cost of each connection from the difference between consecutive cumulative costs. This produces a step-by-step representation of the route, from the source node to the destination.
Technical explanation
The total path cost is the sum of the weights of all relationships along the selected route.
$D(v)=\min_{u\in N(v)}\left[D(u)+w(u,v)\right]$
Where:
- $D(v)$: Minimum known cost from the source to node $v$.
- $N(v)$: Neighboring nodes of node $v$.
- $w(u,v)$: Weight of the relationship between nodes $u$ and $v$. Dijkstra’s Algorithm requires non-negative edge weights. It is not suitable for graphs that contain negative edge weights.
Output
Retrieve the shortest paths using Cypher
The algorithm output can be passed to a Cypher query for further inspection.
This stage uses UNWIND, MATCH, and WHERE to expand the returned node sequence and retrieve the corresponding nodes and relationships from the database.
The query can produce two levels of information:
- Path-level information: Source node, target node, and total path cost.
- Step-level information: Individual nodes, relationships, segment costs, and cumulative costs along the route.
The cumulative cost indicates how much of the total path cost has accumulated when the route reaches a particular node.
For example, consider a route with three connections:
| Route segment | Segment cost | Cumulative cost |
|---|---|---|
| A → B | 10 | 10 |
| B → C | 15 | 25 |
| C → D | 5 | 30 |
Interpreting the results
The final output contains the source node, target node, total route cost, individual connections, and cumulative cost at each step.
This structure makes it possible to inspect the complete route rather than relying only on the final shortest-path value. Each connection can be evaluated independently to identify which segments contribute most to the overall cost.
The resulting data can also support graph visualization. Nodes and relationships can be displayed in traversal order, with their corresponding costs attached to each connection.
This supports several types of analysis:
- Route optimization: Identify minimum-cost routes between selected network entities.
- Infrastructure assessment: Evaluate connection costs across telecommunications, utility, and IT infrastructure networks.
- Dependency tracing: Trace the connections between two entities and inspect the intermediate dependencies.
- Cost analysis: Identify expensive connections and measure their contribution to the total route cost.
- Network analysis: Compare alternative routes when relationship costs or network configurations change.
The results can also support network visualization. Each path can be displayed as a sequence of connected nodes, with relationship costs and cumulative values attached to each step.
Technical Considerations
- Weight definition: The relationship weight determines what the algorithm considers the shortest path. A distance property finds the route with the lowest distance. A latency property finds the route with the lowest accumulated latency, assuming the weights represent additive costs.
- Non-negative weights: Dijkstra’s Algorithm requires non-negative relationship weights. Check the weight property before running the algorithm.
- Direction and connectivity: The graph projection must reflect the actual direction of the relationships. A directed projection can produce different routes from an undirected projection. A target that is not reachable from the source will not produce a valid shortest-path result.
- Parallel relationships: Two nodes can have more than one relationship between them. A path reconstruction query must identify the relationship selected by the algorithm. Matching only the start and end nodes can return multiple relationships when parallel edges exist.
- Cost interpretation: The total cost represents the sum of relationship weights. It does not necessarily represent physical distance. The meaning and units of the weight must remain consistent throughout the analysis.
The Code
Assuming the Neo4j dataset is active and able to called by python library. By calling gds.shortpath_detection, we could calculate short-path using Dijkstra’s Algorithm and return the output that contains the source node, target node, total route cost, individual connections, and cumulative cost at each step..
Generate projection
target = "station"
relation = "track"
with driver.session(database=NEO4J_DATABASE) as session:
gds.project_graph(session, target, relation, GRAPH_NAME)
short-path
shortest_path, stations = gds.shortpath_detection([URI, NEO4J_DATABASE, USERNAME, PASSWORD], name='trains', node_name='station', relate_name='track', value_name='distance', first_last=["Birmingham New Street","Edinburgh"])
This function requires the following parameters:
- connector_params (
list): [URI, NEO4J_DATABASE, USERNAME, PASSWORD] - name (
string): name of graph projection - node_name (
string): name of nodes - relate_name (
string): name of relationships - value_name (
string): value of cost in relationship property - first_last (
list): list of the nodes, contains only 2 nodes for source and target node.
output
Shortest distance from Birmingham New Street to Edinburgh: 295.91
| sourceNode | targetNode | totalCost | nodeIds | costs | index | |
|---|---|---|---|---|---|---|
| 0 | 4576 | 4579 | 295.91 | [4576, 4355, 4349, 4293, 4373, 4286, 4390, 434… | [0.0, 3.91, 5.16, 7.12, 8.01, 9.39, 12.7, 22.3… | 0 |
| from_node_id | from_station | to_node_id | to_station | distance | cumulative_sum | |
|---|---|---|---|---|---|---|
| 0 | 4576 | Birmingham New Street | 4355 | Smethwick Galton Bridge | 3.91 | 3.91 |
| 1 | 4355 | Smethwick Galton Bridge | 4349 | Sandwell & Dudley | 1.25 | 5.16 |
| 2 | 4349 | Sandwell & Dudley | 4293 | Dudley Port | 1.96 | 7.12 |
| 3 | 4293 | Dudley Port | 4373 | Tipton | 0.89 | 8.01 |
| 4 | 4373 | Tipton | 4286 | Coseley | 1.38 | 9.39 |
| 5 | 4286 | Coseley | 4390 | Wolverhampton | 3.31 | 12.7 |
| 6 | 4390 | Wolverhampton | 4341 | Penkridge | 9.6 | 22.3 |
| 7 | 4341 | Penkridge | 5987 | Stafford | 5.71 | 28.01 |
| 8 | 5987 | Stafford | 5979 | Crewe | 24.26 | 52.27 |
| 9 | 5979 | Crewe | 4387 | Winsford | 7.54 | 59.81 |
| 10 | 4387 | Winsford | 4306 | Hartford (Cheshire) | 4.29 | 64.1 |
| 11 | 4306 | Hartford (Cheshire) | 4248 | Acton Bridge (Cheshire) | 2.67 | 66.77 |
| 12 | 4248 | Acton Bridge (Cheshire) | 5990 | Warrington Bank Quay | 9.65 | 76.42 |
| 13 | 5990 | Warrington Bank Quay | 5991 | Wigan North Western | 11.74 | 88.16 |
| 14 | 5991 | Wigan North Western | 4750 | Euxton Balshaw Lane | 8.36 | 96.52 |
| 15 | 4750 | Euxton Balshaw Lane | 4866 | Leyland | 2.75 | 99.27 |
| 16 | 4866 | Leyland | 5984 | Preston (Lancs) | 4.03 | 103.3 |
| 17 | 5984 | Preston (Lancs) | 5980 | Lancaster | 21.04 | 124.34 |
| 18 | 5980 | Lancaster | 5982 | Oxenholme Lake District | 19.09 | 143.43 |
| 19 | 5982 | Oxenholme Lake District | 5983 | Penrith (North Lakes) | 32.16 | 175.59 |
| 20 | 5983 | Penrith (North Lakes) | 5977 | Carlisle | 17.85 | 193.44 |
| 21 | 5977 | Carlisle | 5632 | Lockerbie | 25.83 | 219.27 |
| 22 | 5632 | Lockerbie | 5463 | Carstairs | 47.84 | 267.11 |
| 23 | 5463 | Carstairs | 5608 | Kirknewton | 17.75 | 284.86 |
| 24 | 5608 | Kirknewton | 5490 | Curriehill | 4.5 | 289.36 |
| 25 | 5490 | Curriehill | 5733 | Wester Hailes | 1.6 | 290.96 |
| 26 | 5733 | Wester Hailes | 5602 | Kingsknowe | 1.09 | 292.05 |
| 27 | 5602 | Kingsknowe | 5702 | Slateford | 0.88 | 292.93 |
| 28 | 5702 | Slateford | 5567 | Haymarket | 1.74 | 294.67 |
| 29 | 5567 | Haymarket | 4579 | Edinburgh | 1.24 | 295.91 |