-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathedge_select.py
More file actions
273 lines (237 loc) · 10.2 KB
/
edge_select.py
File metadata and controls
273 lines (237 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
from __future__ import annotations
from typing import Any, Callable, Dict, List, Optional, Set, Tuple
from ngraph.lib.graph import StrictMultiDiGraph, NodeID, EdgeID, AttrDict
from ngraph.lib.algorithms.base import Cost, MIN_CAP, EdgeSelect
def edge_select_fabric(
edge_select: EdgeSelect,
select_value: Optional[Any] = None,
edge_select_func: Optional[
Callable[
[
StrictMultiDiGraph,
NodeID,
NodeID,
Dict[EdgeID, AttrDict],
Optional[Set[EdgeID]],
Optional[Set[NodeID]],
],
Tuple[Cost, List[EdgeID]],
]
] = None,
excluded_edges: Optional[Set[EdgeID]] = None,
excluded_nodes: Optional[Set[NodeID]] = None,
cost_attr: str = "cost",
capacity_attr: str = "capacity",
flow_attr: str = "flow",
) -> Callable[
[
StrictMultiDiGraph,
NodeID,
NodeID,
Dict[EdgeID, AttrDict],
Optional[Set[EdgeID]],
Optional[Set[NodeID]],
],
Tuple[Cost, List[EdgeID]],
]:
"""
Creates (fabricates) a function that selects edges between two nodes according
to a given EdgeSelect strategy (or a user-defined function).
Args:
edge_select: An EdgeSelect enum specifying the selection strategy.
select_value: An optional numeric threshold or scaling factor for capacity checks.
edge_select_func: A user-supplied function if edge_select=USER_DEFINED.
excluded_edges: A set of edges to ignore entirely.
excluded_nodes: A set of nodes to skip.
cost_attr: The edge attribute name representing cost/metric.
capacity_attr: The edge attribute name representing capacity.
flow_attr: The edge attribute name representing current flow.
Returns:
A function with signature:
(graph, src_node, dst_node, edges_dict, excluded_edges, excluded_nodes) ->
(selected_cost, [list_of_edge_ids])
where `selected_cost` is the numeric cost used by the path-finding algorithm
(e.g. Dijkstra), and `[list_of_edge_ids]` is the set (or subset) of edges chosen.
"""
# --------------------------------------------------------------------------
# Internal selection routines (closed over the above arguments).
# Each of these returns (cost, [edge_ids]) indicating which edges are chosen.
# --------------------------------------------------------------------------
def get_all_min_cost_edges(
graph: StrictMultiDiGraph,
src_node: NodeID,
dst_node: NodeID,
edges_map: Dict[EdgeID, AttrDict],
ignored_edges: Optional[Set[EdgeID]] = None,
ignored_nodes: Optional[Set[NodeID]] = None,
) -> Tuple[Cost, List[EdgeID]]:
"""Return all edges with the minimal cost among those available."""
if ignored_nodes and dst_node in ignored_nodes:
return float("inf"), []
edge_list: List[EdgeID] = []
min_cost = float("inf")
for edge_id, attr in edges_map.items():
if ignored_edges and edge_id in ignored_edges:
continue
cost_val = attr[cost_attr]
if cost_val < min_cost:
min_cost = cost_val
edge_list = [edge_id]
elif abs(cost_val - min_cost) < 1e-12:
# If cost_val == min_cost
edge_list.append(edge_id)
return min_cost, edge_list
def get_single_min_cost_edge(
graph: StrictMultiDiGraph,
src_node: NodeID,
dst_node: NodeID,
edges_map: Dict[EdgeID, AttrDict],
ignored_edges: Optional[Set[EdgeID]] = None,
ignored_nodes: Optional[Set[NodeID]] = None,
) -> Tuple[Cost, List[EdgeID]]:
"""Return exactly one edge: the single lowest-cost edge."""
if ignored_nodes and dst_node in ignored_nodes:
return float("inf"), []
chosen_edge: List[EdgeID] = []
min_cost = float("inf")
for edge_id, attr in edges_map.items():
if ignored_edges and edge_id in ignored_edges:
continue
cost_val = attr[cost_attr]
if cost_val < min_cost:
min_cost = cost_val
chosen_edge = [edge_id]
return min_cost, chosen_edge
def get_all_edges_with_cap_remaining(
graph: StrictMultiDiGraph,
src_node: NodeID,
dst_node: NodeID,
edges_map: Dict[EdgeID, AttrDict],
ignored_edges: Optional[Set[EdgeID]] = None,
ignored_nodes: Optional[Set[NodeID]] = None,
) -> Tuple[Cost, List[EdgeID]]:
"""
Return all edges that have remaining capacity >= min_cap, ignoring
their cost except for reporting the minimal one found.
"""
if ignored_nodes and dst_node in ignored_nodes:
return float("inf"), []
edge_list: List[EdgeID] = []
min_cost = float("inf")
min_cap = select_value if select_value is not None else MIN_CAP
for edge_id, attr in edges_map.items():
if ignored_edges and edge_id in ignored_edges:
continue
if (attr[capacity_attr] - attr[flow_attr]) >= min_cap:
cost_val = attr[cost_attr]
min_cost = min(min_cost, cost_val)
edge_list.append(edge_id)
return min_cost, edge_list
def get_all_min_cost_edges_with_cap_remaining(
graph: StrictMultiDiGraph,
src_node: NodeID,
dst_node: NodeID,
edges_map: Dict[EdgeID, AttrDict],
ignored_edges: Optional[Set[EdgeID]] = None,
ignored_nodes: Optional[Set[NodeID]] = None,
) -> Tuple[Cost, List[EdgeID]]:
"""
Return all edges that have remaining capacity >= min_cap,
among those with the minimum cost.
"""
if ignored_nodes and dst_node in ignored_nodes:
return float("inf"), []
edge_list: List[EdgeID] = []
min_cost = float("inf")
min_cap = select_value if select_value is not None else MIN_CAP
for edge_id, attr in edges_map.items():
if ignored_edges and edge_id in ignored_edges:
continue
available_cap = attr[capacity_attr] - attr[flow_attr]
if available_cap >= min_cap:
cost_val = attr[cost_attr]
if cost_val < min_cost:
min_cost = cost_val
edge_list = [edge_id]
elif abs(cost_val - min_cost) < 1e-12:
edge_list.append(edge_id)
return min_cost, edge_list
def get_single_min_cost_edge_with_cap_remaining(
graph: StrictMultiDiGraph,
src_node: NodeID,
dst_node: NodeID,
edges_map: Dict[EdgeID, AttrDict],
ignored_edges: Optional[Set[EdgeID]] = None,
ignored_nodes: Optional[Set[NodeID]] = None,
) -> Tuple[Cost, List[EdgeID]]:
"""
Return exactly one edge with the minimal cost among those with
remaining capacity >= min_cap.
"""
if ignored_nodes and dst_node in ignored_nodes:
return float("inf"), []
chosen_edge: List[EdgeID] = []
min_cost = float("inf")
min_cap = select_value if select_value is not None else MIN_CAP
for edge_id, attr in edges_map.items():
if ignored_edges and edge_id in ignored_edges:
continue
if (attr[capacity_attr] - attr[flow_attr]) >= min_cap:
cost_val = attr[cost_attr]
if cost_val < min_cost:
min_cost = cost_val
chosen_edge = [edge_id]
return min_cost, chosen_edge
def get_single_min_cost_edge_with_cap_remaining_load_factored(
graph: StrictMultiDiGraph,
src_node: NodeID,
dst_node: NodeID,
edges_map: Dict[EdgeID, AttrDict],
ignored_edges: Optional[Set[EdgeID]] = None,
ignored_nodes: Optional[Set[NodeID]] = None,
) -> Tuple[Cost, List[EdgeID]]:
"""
Return exactly one edge, factoring both 'cost_attr' and load level
into a combined cost:
combined_cost = (cost * 100) + round((flow / capacity) * 10)
Only edges with remaining capacity >= min_cap are considered.
"""
if ignored_nodes and dst_node in ignored_nodes:
return float("inf"), []
chosen_edge: List[EdgeID] = []
min_cost_factor = float("inf")
min_cap = select_value if select_value is not None else MIN_CAP
for edge_id, attr in edges_map.items():
if ignored_edges and edge_id in ignored_edges:
continue
remaining_cap = attr[capacity_attr] - attr[flow_attr]
if remaining_cap >= min_cap:
load_factor = round((attr[flow_attr] / attr[capacity_attr]) * 10)
cost_val = attr[cost_attr] * 100 + load_factor
if cost_val < min_cost_factor:
min_cost_factor = cost_val
chosen_edge = [edge_id]
return float(min_cost_factor), chosen_edge
# --------------------------------------------------------------------------
# Fabric: map the EdgeSelect enum to the appropriate inner function.
# --------------------------------------------------------------------------
if edge_select == EdgeSelect.ALL_MIN_COST:
return get_all_min_cost_edges
elif edge_select == EdgeSelect.SINGLE_MIN_COST:
return get_single_min_cost_edge
elif edge_select == EdgeSelect.ALL_MIN_COST_WITH_CAP_REMAINING:
return get_all_min_cost_edges_with_cap_remaining
elif edge_select == EdgeSelect.ALL_ANY_COST_WITH_CAP_REMAINING:
return get_all_edges_with_cap_remaining
elif edge_select == EdgeSelect.SINGLE_MIN_COST_WITH_CAP_REMAINING:
return get_single_min_cost_edge_with_cap_remaining
elif edge_select == EdgeSelect.SINGLE_MIN_COST_WITH_CAP_REMAINING_LOAD_FACTORED:
return get_single_min_cost_edge_with_cap_remaining_load_factored
elif edge_select == EdgeSelect.USER_DEFINED:
if edge_select_func is None:
raise ValueError(
"edge_select=USER_DEFINED requires 'edge_select_func' to be provided."
)
return edge_select_func
else:
raise ValueError(f"Unknown edge_select value {edge_select}")