Repository navigation
Expand file tree
/
Copy pathdispatch.py
More file actions
321 lines (274 loc) · 11.7 KB
/
Copy pathdispatch.py
File metadata and controls
321 lines (274 loc) · 11.7 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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
from stn import STN, loadSTNfromJSONfile
from util import STNtoDCSTN, PriorityQueue
from dc_stn import DC_STN
from relax import relaxSearch
import empirical
import random
import json
# For faster checking in safely_scheduled
import simulation as sim
##
# \file dispatch.py
# \brief Hosts method to dispatch STNUs that were modified by the
# old dynamic checking algorithm
# \note More detailed explanation about the dispatch algorithm can be found in:
# https://pdfs.semanticscholar.org/0313/af826f45d090a63fd5d787c92321666115c8.pd
ZERO_ID = 0
##
# \fn simulate_and_save(file_names, size, out_name)
# \brief Keep track of dispatch results on networks
def simulate_and_save(file_names: list, size: int, out_name: str):
rates = {}
# Loop through files and record the dispatch success rates and
# approximated probabilities
for name in file_names:
success_rate = simulate_file(name, size)
rates[name] = success_rate
# Save the results
with open(out_name, 'w') as out_json:
out_json.dump(rates)
print("Results saved to", out_name)
##
# \fn simulate_file(file_name, size)
# \brief Record dispatch result for single file
def simulate_file(file_name, size, verbose=False, gauss=False, relaxed=False) -> float:
network = loadSTNfromJSONfile(file_name)
result = simulation(network, size, verbose, gauss, relaxed)
if verbose:
print(f"{file_name} worked {100*result}% of the time.")
return result
##
# \fn simulation(network, size)
def simulation(network: STN, size: int, verbose=False, gauss=False, relaxed=False) -> float:
# Collect useful data from the original network
contingent_pairs = network.contingentEdges.keys()
contingents = {src: sink for (src, sink) in contingent_pairs}
uncontrollables = set(contingents.values())
if relaxed:
dispatching_network, count, cycles, weights = relaxSearch(getMinLossBounds(network.copy(), 2))
if dispatching_network == None:
dispatching_network = network
else:
dispatching_network = network
total_victories = 0
dc_network = STNtoDCSTN(dispatching_network)
dc_network.addVertex(ZERO_ID)
controllability = dc_network.is_DC()
if verbose:
print("Finished checking DC...")
# Detect if the network has an inconsistency in a fixed edge
verts = dc_network.verts.keys()
for vert in verts:
if (vert, vert) in dc_network.edges:
if verbose:
print("Checking", vert)
edge = dc_network.edges[vert, vert][0]
if edge.weight < 0:
dc_network.edges[(vert, vert)].remove(edge)
dc_network.verts[vert].outgoing_normal.remove(edge)
dc_network.verts[vert].incoming_normal.remove(edge)
del dc_network.normal_edges[(vert, vert)]
# Run the simulation
for j in range(size):
realization = generate_realization(network, gauss)
copy = dc_network.copy()
result = dispatch(dispatching_network, copy, realization, contingents,
uncontrollables, verbose)
if verbose:
print("Completed a simulation.")
if result:
total_victories += 1
goodie = float(total_victories / size)
if verbose:
print(f"Worked {100*goodie}% of the time.")
return goodie
##
# \fn getMinLossBounds(network, numSig)
# \brief Create copy of network with bounds related to spread
def getMinLossBounds(network: STN, numSig):
for nodes, edge in network.edges.items():
if edge.type == 'pstc' and edge.dtype == 'gaussian':
sigma = edge.sigma
mu = edge.mu
edge.Cij = mu + numSig * sigma
edge.Cji = -(mu - numSig * sigma)
return network
##
# \fn dispatch(network, dc_network, realization, contingent_map,
# uncontrollable_events, verbose)
# \brief Run an early-first scheduling algorithm on a network
#
# @param network The original STNU we are scheduling on
# @param dc_network The modified STNU with inferred constraints
# @param realization An assignment of values for contingent edges
# @param contingent_map A dictionary for contingent edges
# @param uncontrollable_events A collection of uncontrollables
# @param verbose Prints extra statements when set to True
#
# @post A flag which is True precisely when dispatch is succeeds
def dispatch(network: STN,
dc_network: DC_STN,
realization: dict,
contingent_map: dict,
uncontrollable_events,
verbose=False) -> bool:
# Dispatch the modified network and assume we have a zero reference point
enabled = {ZERO_ID}
not_executed = set(dc_network.verts.keys())
executed = set()
current_time = 0.0
schedule = {}
time_windows = {event: [0, float('inf')] for event in not_executed}
current_event = ZERO_ID
if verbose:
print("Beginning dispatch...")
while len(not_executed) > 0:
# Find next event to execute
min_time = float('inf')
if verbose:
print("\n\nNetwork looks like: ")
print(dc_network)
print("Current time windows: ", time_windows)
print("Currently enabled: ", enabled)
print("Already executed: ", executed)
print("Still needs to be executed: ", not_executed)
# Pick an event to schedule
for event in enabled:
if verbose:
print("checking enabled event", event)
lower_bound = time_windows[event][0]
if event in uncontrollable_events:
if lower_bound < min_time:
min_time = lower_bound
current_event = event
else:
# Check that the wait constraints on the event are satisfied
waits = dc_network.verts[event].outgoing_upper
lower_bound = time_windows[event][0]
for edge in waits:
if edge.parent != event:
if (edge.parent not in executed):
if edge.j not in executed:
continue
lower_bound = max(lower_bound,
schedule[edge.j] - edge.weight)
if lower_bound < min_time:
min_time = lower_bound
current_event = event
is_uncontrollable = current_event in uncontrollable_events
if verbose:
if is_uncontrollable:
print("This event is uncontrollable!")
current_time = min_time
schedule[current_event] = current_time
if verbose:
print('event', current_event,'is scheduled at', current_time)
# If the executed event was a contingent source
if current_event in contingent_map:
uncontrollable = contingent_map[current_event]
delay = realization[uncontrollable]
set_time = current_time + delay
enabled.add(uncontrollable)
time_windows[uncontrollable] = [set_time, set_time]
if is_uncontrollable:
# Remove waits
original_edges = list(dc_network.upper_case_edges.items())
for nodes, edge in original_edges:
if edge.parent == current_event:
if (current_event != edge.i) and (current_event != edge.j):
# Modifying the network
dc_network.remove_upper_edge(edge.i, edge.j)
if current_event in not_executed:
not_executed.remove(current_event)
else:
return False
if current_event in enabled:
enabled.remove(current_event)
executed.add(current_event)
# Propagate the constraints
for nodes, edge in dc_network.normal_edges.items():
if edge.i == current_event:
new_upper_bound = edge.weight + current_time
if new_upper_bound < time_windows[edge.j][1]:
time_windows[edge.j][1] = new_upper_bound
if edge.j == current_event:
new_lower_bound = current_time - edge.weight
if new_lower_bound > time_windows[edge.i][0]:
time_windows[edge.i][0] = new_lower_bound
# Add newly enabled events
for event in not_executed:
if verbose:
print("***")
print("Checking event", event)
if (event not in enabled) and (event not in uncontrollable_events):
ready = True
outgoing_reqs = dc_network.verts[event].outgoing_normal
# Check required constraints
for edge in outgoing_reqs:
# For required
if edge.weight < 0:
if edge.j not in executed:
if verbose:
print(event, "was not enabled because of",
edge)
ready = False
break
elif edge.weight == 0:
if (edge.j, edge.i) in dc_network.edges:
if dc_network.edges[(edge.j, edge.i)][0].weight != 0:
if edge.j not in executed:
ready = False
break
else:
if edge.j not in executed:
ready = False
break
# Check wait constraints
outgoing_upper = dc_network.verts[event].outgoing_upper
for edge in outgoing_upper:
if edge.weight < 0:
label_wait = (edge.parent not in executed)
main_wait = (edge.j not in executed)
if label_wait and main_wait:
ready = False
if verbose:
print(event, "was not enabled because of",
edge)
break
if ready:
if verbose:
print("Looks like we enabled", event)
enabled.add(event)
# The realization should be preserved for src, sink in contingent_map
if verbose:
print("\n\nFinal schedule is: ")
print(schedule)
print("Network is: ")
print(network)
good = empirical.scheduleIsValid(network, schedule)
if verbose:
msg = "We're safe!" if good else "We failed!"
print(msg)
return good
##
# \fn generate_realization(network)
# \brief Uniformly at random pick values for contingent edges in STNU
def generate_realization(network: STN, gauss=True) -> dict:
realization = {}
for nodes, edge in network.contingentEdges.items():
assert edge.dtype != None
if edge.dtype() == "gaussian":
generated = random.gauss(edge.mu, edge.sigma)
while generated < min(-edge.Cji, edge.Cij) or generated > max(-edge.Cji, edge.Cij):
generated = random.gauss(edge.mu, edge.sigma)
realization[nodes[1]] = generated
elif edge.dtype() == "uniform":
generated = random.uniform(edge.dist_lb, edge.dist_ub)
counter = 0
while generated < min(-edge.Cji, edge.Cij) or generated > max(-edge.Cji, edge.Cij):
generated = random.uniform(edge.dist_lb, edge.dist_ub)
counter += 1
if counter > 1000:
print('over 1000 regenerations')
realization[nodes[1]] = generated
return realization