Returns a dictionary indexed by node id1's, in which each value is a dictionary of connected node id2's linking to the edge weight. If directed=True, edges go from id1 to id2, but not the other way. If stochastic=True, all the weights for the neighbors of a given node sum to
(graph, directed=False, reversed=False, stochastic=False, heuristic=None)
| 751 | #--- GRAPH THEORY ---------------------------------------------------------------------------------- |
| 752 | |
| 753 | def adjacency(graph, directed=False, reversed=False, stochastic=False, heuristic=None): |
| 754 | """ Returns a dictionary indexed by node id1's, |
| 755 | in which each value is a dictionary of connected node id2's linking to the edge weight. |
| 756 | If directed=True, edges go from id1 to id2, but not the other way. |
| 757 | If stochastic=True, all the weights for the neighbors of a given node sum to 1. |
| 758 | A heuristic function can be given that takes two node id's and returns |
| 759 | an additional cost for movement between the two nodes. |
| 760 | """ |
| 761 | # Caching a heuristic from a method won't work. |
| 762 | # Bound method objects are transient, |
| 763 | # i.e., id(object.method) returns a new value each time. |
| 764 | if graph._adjacency is not None and \ |
| 765 | graph._adjacency[1:] == (directed, reversed, stochastic, heuristic and heuristic.func_code): |
| 766 | return graph._adjacency[0] |
| 767 | map = {} |
| 768 | for n in graph.nodes: |
| 769 | map[n.id] = {} |
| 770 | for e in graph.edges: |
| 771 | id1, id2 = not reversed and (e.node1.id, e.node2.id) or (e.node2.id, e.node1.id) |
| 772 | map[id1][id2] = 1.0 - 0.5 * e.weight |
| 773 | if heuristic: |
| 774 | map[id1][id2] += heuristic(id1, id2) |
| 775 | if not directed: |
| 776 | map[id2][id1] = map[id1][id2] |
| 777 | if stochastic: |
| 778 | for id1 in map: |
| 779 | n = sum(map[id1].values()) |
| 780 | for id2 in map[id1]: |
| 781 | map[id1][id2] /= n |
| 782 | # Cache the adjacency map: this makes dijkstra_shortest_path() 2x faster in repeated use. |
| 783 | graph._adjacency = (map, directed, reversed, stochastic, heuristic and heuristic.func_code) |
| 784 | return map |
| 785 | |
| 786 | def dijkstra_shortest_path(graph, id1, id2, heuristic=None, directed=False): |
| 787 | """ Dijkstra algorithm for finding the shortest path between two nodes. |
no test coverage detected
searching dependent graphs…