This repository was archived by the owner on Feb 12, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheuristics.py
257 lines (232 loc) · 8.92 KB
/
heuristics.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
# pyright: reportUnknownMemberType=false, reportUnusedCallResult=false
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import truncweibull_min # type: ignore[import]
import constants
from solver import models
from utils import demand_to_map, sp_to_map
def weibullshit(capacity: int):
return int(
capacity
* (
1
- float(
truncweibull_min.rvs(0.3, 0.05, 0.1, size=1).item() # type: ignore[reportUnknownArgumentType]
)
)
)
def get_maintenance_cost(
average_maint_cost: int, operating_time: int, life_expectancy: int
) -> float:
return float(
average_maint_cost # type: ignore[reportAny]
* (
1
+ (
((1.5) * (operating_time))
/ life_expectancy
* np.log2(((1.5) * (operating_time)) / life_expectancy)
)
)
)
class Solver:
operating_servers: dict[models.ServerGeneration, dict[str, list[tuple[int, int]]]]
actions: dict[int, list[models.SolutionEntry]]
def __init__(
self,
actions: list[models.SolutionEntry],
demand: (
list[models.Demand]
| dict[int, dict[models.ServerGeneration, dict[models.Sensitivity, int]]]
),
servers: list[models.Server] | dict[models.ServerGeneration, models.Server],
datacenters: list[models.Datacenter] | dict[str, models.Datacenter],
selling_prices: (
list[models.SellingPrices]
| dict[models.ServerGeneration, dict[models.Sensitivity, int]]
),
plot_generation: models.ServerGeneration | None = None,
) -> None:
self.actions = {}
self.operating_servers = {}
for action in actions:
if self.actions.get(action.timestep) is None:
self.actions[action.timestep] = []
self.actions[action.timestep].append(action)
if isinstance(demand, list):
self.demand = demand_to_map(demand)
else:
self.demand = demand
if isinstance(servers, list):
self.server_map = {server.server_generation: server for server in servers}
else:
self.server_map = servers
if isinstance(datacenters, list):
self.datacenter_map = {dc.datacenter_id: dc for dc in datacenters}
else:
self.datacenter_map = datacenters
if isinstance(selling_prices, list):
self.selling_prices = sp_to_map(selling_prices)
else:
self.selling_prices = selling_prices
self.plot_generation = plot_generation
def get_demand(
self, ts: int, generation: models.ServerGeneration, sen: models.Sensitivity
):
return (
self.demand[ts].get(generation, {}).get(sen, 0)
// self.server_map[generation].capacity
)
def heuristic_solve(self):
# Sort datacenter by lowest energy cost
cheap_datacenters = sorted(
self.datacenter_map.values(),
key=lambda dc: dc.cost_of_energy,
)
availability_by_datacenter: dict[
int, dict[str, dict[models.ServerGeneration, int]]
] = {
ts: {
dc: {sg: 0 for sg in models.ServerGeneration}
for dc in self.datacenter_map
}
for ts in range(1, 169)
}
for ts in range(1, 169):
ranking: list[tuple[models.ServerGeneration, models.Sensitivity, float]] = (
[]
)
optimal_capacities = {
sg: {sen: 0 for sen in models.Sensitivity}
for sg in models.ServerGeneration
}
for sen in models.Sensitivity:
# Calculate the expected profit of a single server of this type
# Find the total capacity for this sensitivity
slots_capacity = sum(
(
self.datacenter_map[dc].slots_capacity
if self.datacenter_map[dc].latency_sensitivity == sen
else 0
)
for dc in self.datacenter_map
)
for sg in models.ServerGeneration:
revenue = weibullshit(self.selling_prices[sg][sen])
energy_consumption = self.server_map[sg].energy_consumption
buying_cost = self.server_map[sg].purchase_price
maintenance_cost = sum(
get_maintenance_cost(
self.server_map[sg].average_maintenance_fee,
ts2,
self.server_map[sg].life_expectancy,
)
for ts2 in range(
1, min(168 - ts, self.server_map[sg].life_expectancy)
)
)
ranking.append(
(
sg,
sen,
revenue
- energy_consumption
- maintenance_cost
- buying_cost,
)
)
demand = self.get_demand(ts, sg, sen)
if demand == 0:
continue
# The optimal capacity should try to meet demand
meet_demand = demand
# But it can't exceed the datacenter capacity
meet_demand = (
min(
meet_demand,
slots_capacity // self.server_map[sg].slots_size,
)
if meet_demand > 0
else 0
)
c = 0
average_demand = 0
for ts2 in range(1, 169):
if self.get_demand(ts2, sg, sen) == 0:
continue
average_demand += self.get_demand(ts2, sg, sen)
c += 1
average_demand //= c
optimal_capacities[sg][sen] = min(meet_demand, average_demand)
# Sort the ranking by profitability (most profitable first)
ranking.sort(key=lambda x: x[2], reverse=True)
# Reduce optimal capacities to fit within datacenter slots
capacity_by_datacenter: dict[str, int] = {
dc: self.datacenter_map[dc].slots_capacity for dc in self.datacenter_map
}
for sg, sen, _ in ranking:
remaining_to_fill = (
optimal_capacities[sg][sen] * self.server_map[sg].slots_size
)
for dc in cheap_datacenters:
if dc.latency_sensitivity != sen:
continue
if remaining_to_fill == 0:
break
to_fill = min(
remaining_to_fill, capacity_by_datacenter[dc.datacenter_id]
)
availability_by_datacenter[ts][dc.datacenter_id][sg] += (
to_fill // self.server_map[sg].slots_size
)
capacity_by_datacenter[dc.datacenter_id] -= to_fill
remaining_to_fill -= to_fill
return availability_by_datacenter
if __name__ == "__main__":
models.scale = 1
seed = 123
np.random.seed(seed)
demand = constants.get_demand()
evaluator = Solver(
[],
demand,
constants.get_servers(),
constants.get_datacenters(),
constants.get_selling_prices(),
)
availability = evaluator.heuristic_solve()
gen = models.ServerGeneration.CPU_S1
# Extract data for CPU_S1
cpu_s1_availability = {
sen: [
sum(
(
availability[ts][dc][gen]
if evaluator.datacenter_map[dc].latency_sensitivity == sen
else 0
)
for dc in evaluator.datacenter_map
)
for ts in range(1, 169)
]
for sen in models.Sensitivity
}
cpu_s1_demand = {
sen: [evaluator.get_demand(ts, gen, sen) for ts in range(1, 169)]
for sen in models.Sensitivity
}
# Create the plot
_ = plt.figure(figsize=(12, 6))
# Plot availability for each datacenter
for sen, avail in cpu_s1_availability.items():
plt.plot(range(1, 169), avail, label=f"Availability {sen}")
# Plot demand for each sensitivity
for sen, dem in cpu_s1_demand.items():
plt.plot(range(1, 169), dem, label=f"Demand {sen.name}", linestyle="--")
plt.xlabel("Timestep")
plt.ylabel("Number of Servers")
plt.title("CPU S1 Availability and Demand")
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()