Search code examples
graphnetworkx

Shortest distance with complex number in network x


I have a graph, where the edge weights are complex numbers. I am trying to get the weighted shortest path length but I got an error.
Does networkx support complex weights?

Here is a sample code:

import networkx as nx
G = nx.Graph()
G.add_nodes_from([1, 2, 3, 4, 5])

G.add_edge(1, 2, weight=complex(1, 2))
G.add_edge(1, 3, weight=complex(3, 4))
G.add_edge(2, 4, weight=complex(5, 6))
G.add_edge(3, 4, weight=complex(7, 8))
G.add_edge(4, 5, weight=complex(9, 10))

shortest_path = nx.shortest_path_length(G, 1, 5, weight='weight')

I got this error:

TypeError: '<' not supported between instances of 'complex' and 'complex'


Solution

  • Assuming you would take the absolute value of the complex numbers as edge weights, you can input a function for the weight argument to compute the shortest path this way:

    def abs_weight(v, w, edge_data):
        return abs(edge_data['weight'])
    
    shortest_path = nx.shortest_path(G, 1, 5, weight=abs_weight)
    

    From here, you can compute the "complex path length" of the path like this:

    def complex_path_length(G, source, target, path):
        edges = zip(path, path[1:]) #First element source node, second element target
        return sum(G.edges[u, v]['weight'] for u, v in edges)
    
    complex_path_length(G, 1, 5, shortest_path)
    

    If the assumption is wrong (e.g., you only want to take the real part of the complex numbers while computing the shortest path), you can define a similar metric to convert the weights into real numbers.
    If you do not need the complex path length, just the absolute value one (or something real valued), you can use the shortest_path_length function in one row.