how to add float typed weights to an retworkx digraph
Without knowing what in_node_indices
, out_node_indices
and weights_matrix
contain in the code snippets it's hard to provide an exact working example for your use case. But, I can take a guess based on the error message. I think the issue you're hitting here is likely because you're trying to use the values in in_node_indices
and out_node_indices
as retworkx indices but there isn't a 1:1 mapping necessarily. The retworkx index for a node is assigned when the node is added and is the returned value. So if you do something like graph.add_node(3)
, the return from that will not necessarily be 3
it will be the node index assigned to that instance of 3
when it's added as a node in the graph. If you ran graph.add_nodes_from([3, 3])
you'd get two different indices returned. This is different from networkx which treats the data payloads as a lookup key in the graph (so graph.add_node(3)
adds a node 3
to the graph which you look up by 3
, but then you can only have a single node with the payload 3
). You can refer to the documentation on retworkx for networkx users for more details here: https://qiskit.org/documentation/retworkx/networkx.html
So when you call add_nodes_from()
you need to map the value at a position in the input array to the returned index from the method at the same position to identify that node in the graph. I think if you do something like:
import retworkx as rx
graph = rx.PyDiGraph(multigraph=False)
unique_indices = np.unique([in_node_indices, out_node_indices])
rx_indices = graph.add_nodes_from(unique_indices)
index_map = dict(zip(unique_indices, rx_indices))
in_out_weight_triplets = np.concatenate((in_node_indices, out_node_indices,
np.abs(weights_matrix)), axis=1)
graph.add_nodes_from([(index_map[in], index_map[out], weight) for in, out, weight in in_out_weight_triplets])
I haven't tested the above snippet (so there might be typos or other issues with it) because I don't know what the contents of in_node_indices
, out_node_indices
, and weight_matrix
are. But it should give you an a better idea of what I described above.
That being said I do wonder if weight_matrix
is an adjacency matrix, if it is then it's probably easier to just do:
import retworkx
graph = retworkx.PyDiGraph.from_adjacency_matrix(weight_matrix)
this is also typically faster (assuming you already have the matrix) because it uses the numpy C api and avoids the type conversion going between python and rust and all the pre-processing steps.
There was also an issue opened similar to this in the retworkx issue tracker recently: https://github.com/Qiskit/retworkx/issues/546. My response there contains more details on the internals of retworkx.