forked from jcobayliss/FFPHHS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
singlerun.py
346 lines (315 loc) · 12.3 KB
/
singlerun.py
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 9 12:25:22 2022
@author: SharonLechuga
"""
import random
import math
# Provides the methods to create and solve the firefighter problem
# This file is a modification of the ffp.py, which runs only a single iteration of a graph.
class FFP:
# Constructor
# fileName = The name of the file that contains the FFP instance
def __init__(self, fileName):
file = open(fileName, "r")
text = file.read()
tokens = text.split()
seed = int(tokens.pop(0))
self.n = int(tokens.pop(0))
model = int(tokens.pop(0))
int(tokens.pop(0)) # Ignored
# self.state contains the state of each node
# -1 On fire
# 0 Available for analysis
# 1 Protected
self.state = [0] * self.n
nbBurning = int(tokens.pop(0))
for i in range(nbBurning):
b = int(tokens.pop(0))
self.state[b] = -1
self.graph = []
for i in range(self.n):
self.graph.append([0] * self.n);
while tokens:
x = int(tokens.pop(0))
y = int(tokens.pop(0))
self.graph[x][y] = 1
self.graph[y][x] = 1
# Solves the FFP by using a given method and a number of firefighters
# method = Either a string with the name of one available heuristic or an object of class HyperHeuristic
# nbFighters = The number of available firefighters per turn
# debug = A flag to indicate if debugging messages are shown or not
def solve(self, method, nbFighters, debug = False):
spreading = True
if (debug):
print("Initial state:" + str(self.state))
t = 0
if (spreading):
if (debug):
print("Features")
print("")
print("Graph density: %1.4f" % (self.getFeature("EDGE_DENSITY")))
print("Average degree: %1.4f" % (self.getFeature("AVG_DEGREE")))
print("Burning nodes: %1.4f" % self.getFeature("BURNING_NODES"))
print("Burning edges: %1.4f" % self.getFeature("BURNING_EDGES"))
print("Nodes in danger: %1.4f" % self.getFeature("NODES_IN_DANGER"))
# It protects the nodes (based on the number of available firefighters)
for i in range(nbFighters):
heuristic = method
if (isinstance(method, HyperHeuristic)):
heuristic = method.nextHeuristic(self)
node = self.__nextNode(heuristic)[0]
if (node >= 0):
# The node is protected
self.state[node] = 1
# The node is disconnected from the rest of the graph
for j in range(len(self.graph[node])):
self.graph[node][j] = 0
self.graph[j][node] = 0
if (debug):
print("\tt" + str(t) + ": A firefighter protects node " + str(node))
# It spreads the fire among the unprotected nodes
spreading = False
state = self.state.copy()
for i in range(len(state)):
# If the node is on fire, the fire propagates among its neighbors
if (state[i] == -1):
for j in range(len(self.graph[i])):
if (self.graph[i][j] == 1 and state[j] == 0):
spreading = True
# The neighbor is also on fire
self.state[j] = -1
# The edge between the nodes is removed (it will no longer be used)
self.graph[i][j] = 0
self.graph[j][i] = 0
if (debug):
print("\tt" + str(t) + ": Fire spreads to node " + str(j))
t = t + 1
if (debug):
print("---------------")
if (debug):
print("Final state: " + str(self.state))
print("Solution evaluation: " + str(self.getFeature("BURNING_NODES")))
return self.getFeature("NODES_IN_DANGER"), self.__nextNode(heuristic)[1]
# Selects the next node to protect by a firefighter
# heuristic = A string with the name of one available heuristic
def __nextNode(self, heuristic):
index = -1
best = -1
for i in range(len(self.state)):
if (self.state[i] == 0):
index = i
break
value = -1
for i in range(len(self.state)):
if (self.state[i] == 0):
if (heuristic == "LDEG"):
# It prefers the node with the largest degree, but it only considers
# the nodes directly connected to a node on fire
for j in range(len(self.graph[i])):
if (self.graph[i][j] == 1 and self.state[j] == -1):
value = sum(self.graph[i])
break
elif (heuristic == "GDEG"):
value = sum(self.graph[i])
else:
print("=====================")
print("Critical error at FFP.__nextNode.")
print("Heuristic " + heuristic + " is not recognized by the system.")
print("The system will halt.")
print("=====================")
exit(0)
if (value > best):
best = value
index = i
# return best para conocer el numero de nodos protegidos con el nodo elegido
return index, best
# Returns the value of the feature provided as argument
# feature = A string with the name of one available feature
def getFeature(self, feature):
f = 0
if (feature == "EDGE_DENSITY"):
n = len(self.graph)
for i in range(len(self.graph)):
f = f + sum(self.graph[i])
f = f / (n * (n - 1))
elif (feature == "AVG_DEGREE"):
n = len(self.graph)
count = 0
for i in range(len(self.state)):
if (self.state[i] == 0):
f += sum(self.graph[i])
count += 1
if (count > 0):
f /= count
f /= (n - 1)
else:
f = 0
elif (feature == "BURNING_NODES"):
for i in range(len(self.state)):
if (self.state[i] == -1):
f += 1
f = f / len(self.state)
elif (feature == "BURNING_EDGES"):
n = len(self.graph)
for i in range(len(self.graph)):
for j in range(len(self.graph[i])):
if (self.state[i] == -1 and self.graph[i][j] == 1):
f += 1
f = f / (n * (n - 1))
elif (feature == "NODES_IN_DANGER"):
for j in range(len(self.state)):
for i in range(len(self.state)):
if (self.state[i] == -1 and self.graph[i][j] == 1):
f += 1
break
#Línea comentada para verificar el numero de nodos en peligro
f /= len(self.state)
else:
print("=====================")
print("Critical error at FFP._getFeature.")
print("Feature " + feature + " is not recognized by the system.")
print("The system will halt.")
print("=====================")
exit(0)
return f
# Returns the string representation of this problem
def __str__(self):
text = "n = " + str(self.n) + "\n"
text += "state = " + str(self.state) + "\n"
for i in range(self.n):
for j in range(self.n):
if (self.graph[i][j] == 1 and i < j):
text += "\t" + str(i) + " - " + str(j) + "\n"
return text
# def winner(self, nbFighters):
# save = []
# for hToUse in range(0,2,1):
# if (hToUse == 0):
# method = "LDEG"
# elif (hToUse == 1):
# method = "GDEG"
# save.append(problem.solve(method, nbFighters, True)[1])
# problem = FFP(fileName)
# if (save[0]>save[1]):
# winner = 1
# elif (save[0]<=save[1]):
# winner = 0
# return winner
# Provides the methods to create and use hyper-heuristics for the FFP
# This is a class you must extend it to provide the actual implementation
class HyperHeuristic:
# Constructor
# features = A list with the names of the features to be used by this hyper-heuristic
# heuristics = A list with the names of the heuristics to be used by this hyper-heuristic
def __init__(self, features, heuristics):
if (features):
self.features = features.copy()
else:
print("=====================")
print("Critical error at HyperHeuristic.__init__.")
print("The list of features cannot be empty.")
print("The system will halt.")
print("=====================")
exit(0)
if (heuristics):
self.heuristics = heuristics.copy()
else:
print("=====================")
print("Critical error at HyperHeuristic.__init__.")
print("The list of heuristics cannot be empty.")
print("The system will halt.")
print("=====================")
exit(0)
# Returns the next heuristic to use
# problem = The FFP instance being solved
def nextHeuristic(self, problem):
print("=====================")
print("Critical error at HyperHeuristic.nextHeuristic.")
print("The method has not been overriden by a valid subclass.")
print("The system will halt.")
print("=====================")
exit(0)
# Returns the string representation of this hyper-heuristic
def __str__(self):
print("=====================")
print("Critical error at HyperHeuristic.__str__.")
print("The method has not been overriden by a valid subclass.")
print("The system will halt.")
print("=====================")
exit(0)
# A dummy hyper-heuristic for testing purposes.
# The hyper-heuristic creates a set of randomly initialized rules.
# Then, when called, it measures the distance between the current state and the
# conditions in the rules
# The rule with the condition closest to the problem state is the one that fires
class DummyHyperHeuristic(HyperHeuristic):
# Constructor
# features = A list with the names of the features to be used by this hyper-heuristic
# heuristics = A list with the names of the heuristics to be used by this hyper-heuristic
# nbRules = The number of rules to be contained in this hyper-heuristic
def __init__(self, features, heuristics, nbRules, seed):
super().__init__(features, heuristics)
random.seed(seed)
self.conditions = []
self.actions = []
for i in range(nbRules):
self.conditions.append([0] * len(features))
for j in range(len(features)):
self.conditions[i][j] = random.random()
self.actions.append(heuristics[random.randint(0, len(heuristics) - 1)])
# Returns the next heuristic to use
# problem = The FFP instance being solved
def nextHeuristic(self, problem):
minDistance = float("inf")
index = -1
state = []
for i in range(len(self.features)):
state.append(problem.getFeature(self.features[i]))
print("\t" + str(state))
for i in range(len(self.conditions)):
distance = self.__distance(self.conditions[i], state)
if (distance < minDistance):
minDistance = distance
index = i
heuristic = self.actions[index]
print("\t\t=> " + str(heuristic) + " (R" + str(index) + ")")
return heuristic
# Returns the string representation of this dummy hyper-heuristic
def __str__(self):
text = "Features:\n\t" + str(self.features) + "\nHeuristics:\n\t" + str(self.heuristics) + "\nRules:\n"
for i in range(len(self.conditions)):
text += "\t" + str(self.conditions[i]) + " => " + self.actions[i] + "\n"
return text
# Returns the Euclidian distance between two vectors
def __distance(self, vectorA, vectorB):
distance = 0
for i in range(len(vectorA)):
distance += (vectorA[i] - vectorB[i]) ** 2
distance = math.sqrt(distance)
return distance
# Tests
# =====================
# Solves the problem using heuristic LDEG and one firefighter
# print("LDEG = " + str(problem.solve("LDEG", 1, True)))
# # Solves the problem using heuristic GDEG and one firefighter
# problem = FFP(fileName)
# print("GDEG = " + str(problem.solve("GDEG", 1, True)))
def winner(problem):
save = []
for hToUse in range(0, 2, 1):
# print("hToUse = ", hToUse)
if (hToUse == 0):
method = "LDEG"
elif (hToUse == 1):
method = "GDEG"
# problem = FFP(fileName)
# print(method + "= " + str(problem.solve(method, 1, True)))
save.append(problem.solve(method, 1, False)[1])
# print("save", save)
if (save[0] > save[1]):
winner = 0
elif (save[0] <= save[1]):
winner = 1
print("winner = ", winner)
return winner