Utils#
Utility functions for the Distance Closure package
- distanceclosure.utils.prox2dist(p)[source]#
Transforms a non-negative
[0,1]
proximity to distance in the[0,inf]
interval:\[d = \frac{1}{p} - 1\]See also
- distanceclosure.utils.dist2prox(d)[source]#
Transforms a non-negative integer distance
d
to a proximity/similarity value in the[0,1]
interval:\[p = \frac{1}{(d+1)}\]It accepts both dense and sparse matrices.
- Parameters
D (matrix) – Distance matrix
- Returns
P – Proximity matrix
- Return type
matrix
See also
- distanceclosure.utils.dict2matrix(d)[source]#
Tranforms a 2D dictionary into a numpy. Usefull when converting Dijkstra results.
- Parameters
(dict) (d) –
- Returns
m
- Return type
Numpy matrix
Warning
If your nodes are identified by names instead of numbers, make sure to keep a mapping.
Examples
>>> d = {0: {0: 0, 1: 1, 2:3}, 1: {0: 1, 1: 0, 2:2}, 2: {0: 3, 1:2, 2:0}} >>> dict2matrix(d) [[ 0 1 3] [ 1 0 2] [ 3 2 0]]
Note
Uses pandas to accomplish this in a one liner.
See also
- distanceclosure.utils.matrix2dict(m)[source]#
Tranforms a Numpy matrix into a 2D dictionary. Usefull when comparing dense metric and Dijkstra results.
- Parameters
(matrix) (m) –
- Returns
d (dict)
- Return type
2D dictionary
Examples
>>> m = [[0, 1, 3], [1, 0, 2], [3, 2, 0]] >>> matrix2dict(m) {0: {0: 0, 1: 1, 2:3}, 1: {0: 1, 1: 0, 2:2}, 2: {0: 3, 1:2, 2:0}}
Note
Uses pandas to accomplish this in a one liner.
See also
- distanceclosure.utils.dict2sparse(d)[source]#
Tranforms a 2D dictionary into a Scipy sparse matrix.
- Parameters
d (dict) – 2D dictionary
- Returns
m – CRS Sparse Matrix
- Return type
CSR matrix
Examples
>>> d = {0: {0: 0, 1: 1, 2:3}, 1: {0: 1, 1: 0, 2:2}, 2: {0: 3, 1:2, 2:0}} >>> dict2sparse(d) (0, 1) 1 (0, 2) 3 (1, 0) 1 (1, 2) 2 (2, 0) 3 (2, 1) 2
Note
Uses pandas to convert dict into dataframe and then feeds it to the csr_matrix.
See also
- distanceclosure.utils.from_networkx_to_dijkstra_format(D, weight='weight')[source]#
Converts a
NetworkX.Graph
object to input variables to be used bycython.dijkstra
.- Parameters
D (NetworkX:Graph) – The Distance graph.
weight (string) – The edge property to use as distance weight.
- Returns
nodes (list) – List of all nodes converted to sequential numbers.
edges (list) – List of all edges.
neighbors (dict) – Dictionary containing the neighborhood of every node in a fast access format.
dict_int_nodes (dict) – The mapping between original node names and the numeric node names.
Examples
>>> G = nx.path(5) >>> nx.set_edge_attributes(G, name='distance', values=1) >>> nodes, edges, neighbors, dict_int_nodes = from_networkx_to_dijkstra_format(G, weight='distance')