-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBankerAlgorithmSimulator.py
More file actions
398 lines (353 loc) · 15.3 KB
/
Copy pathBankerAlgorithmSimulator.py
File metadata and controls
398 lines (353 loc) · 15.3 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
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QGroupBox, QLabel, QLineEdit, QComboBox, QPushButton, QTextEdit, QMessageBox, QScrollArea
from PyQt5.QtCore import Qt
class BankerAlgorithmSimulator(QWidget):
def __init__(self, app):
super().__init__()
self.app = app
self.num_resources = 0
self.num_processes = 0
self.available = []
self.max_matrix = []
self.allocation_matrix = []
self.need_matrix = []
self.entries = []
self.alloc_entries = []
self.resize(1200, 900)
self.setMinimumSize(1000, 800)
self.init_ui()
self.create_initial_widgets()
self.show()
def init_ui(self):
self.setWindowTitle("银行家算法模拟器")
self.setStyleSheet("""
QWidget {
font-family: Arial;
font-size: 18px;
}
QPushButton {
padding: 12px;
background-color: #2196F3;
color: white;
border-radius: 5px;
font-size: 20px;
}
QPushButton:hover {
background-color: #1976D2;
}
QLineEdit, QComboBox, QTextEdit {
padding: 8px;
border: 1px solid #ccc;
border-radius: 3px;
font-size: 18px;
}
QGroupBox {
font-weight: bold;
margin-top: 15px;
padding: 10px;
font-size: 22px;
}
QLabel {
font-size: 18px;
}
QScrollArea {
border: 1px solid #ccc;
border-radius: 3px;
background-color: #f9f9f9;
}
""")
self.layout = QVBoxLayout()
self.layout.setSpacing(15)
self.setLayout(self.layout)
def create_initial_widgets(self):
self.initial_group = QGroupBox("请输入系统参数")
initial_layout = QVBoxLayout()
initial_layout.setSpacing(10)
res_row = QHBoxLayout()
res_row.addWidget(QLabel("资源类型的数量:"))
self.resource_entry = QLineEdit()
self.resource_entry.setFixedWidth(150)
res_row.addWidget(self.resource_entry)
res_row.addStretch()
initial_layout.addLayout(res_row)
proc_row = QHBoxLayout()
proc_row.addWidget(QLabel("进程数量:"))
self.process_entry = QLineEdit()
self.process_entry.setFixedWidth(150)
proc_row.addWidget(self.process_entry)
proc_row.addStretch()
initial_layout.addLayout(proc_row)
avail_row = QHBoxLayout()
avail_row.addWidget(QLabel("可用的资源 (逗号分隔):"))
self.available_entry = QLineEdit()
self.available_entry.setFixedWidth(250)
avail_row.addWidget(self.available_entry)
avail_row.addStretch()
initial_layout.addLayout(avail_row)
confirm_btn = QPushButton("确定")
confirm_btn.clicked.connect(self.create_input_widgets)
confirm_btn.setMinimumSize(150, 40)
initial_layout.addWidget(confirm_btn)
self.initial_group.setLayout(initial_layout)
self.layout.addWidget(self.initial_group)
def create_input_widgets(self):
try:
self.num_resources = int(self.resource_entry.text())
self.num_processes = int(self.process_entry.text())
available = [int(x) for x in self.available_entry.text().split(",")]
if self.num_resources <= 0 or self.num_processes <= 0:
raise ValueError("Number of resources and processes must be positive.")
if len(available) != self.num_resources:
raise ValueError("Available resources count must match number of resource types.")
if any(x < 0 for x in available):
raise ValueError("Available resources must be non-negative.")
self.available = available
except ValueError as e:
QMessageBox.critical(self, "Input Error", str(e))
return
self.initial_group.deleteLater()
# Main horizontal layout for side-by-side design
main_split_layout = QHBoxLayout()
main_split_layout.setSpacing(15)
# Left side: Inputs and Operations
self.left_layout = QVBoxLayout() # Store left_layout for later use in create_request_widgets
self.left_layout.setSpacing(15)
self.input_group = QGroupBox("请输入最大分配和需求矩阵")
input_layout = QVBoxLayout()
input_layout.setSpacing(10)
# Combined widget for both sections
combined_widget = QWidget()
combined_layout = QVBoxLayout()
combined_layout.setSpacing(10)
# Max Matrix inputs
combined_layout.addWidget(QLabel("最大需求矩阵:", styleSheet="font-weight: bold; font-size: 18px"))
max_widget = QWidget()
max_layout = QVBoxLayout()
max_layout.setSpacing(15)
max_header = QHBoxLayout()
max_header.addWidget(QLabel("进程"))
for i in range(self.num_resources):
max_header.addWidget(QLabel(f"R{i}"))
max_layout.addLayout(max_header)
self.entries = []
for i in range(self.num_processes):
row = QHBoxLayout()
row.addWidget(QLabel(f"P{i}"))
row_entries = []
for j in range(self.num_resources):
entry = QLineEdit()
entry.setFixedWidth(100)
row.addWidget(entry)
row_entries.append(entry)
self.entries.append(row_entries)
max_layout.addLayout(row)
max_widget.setLayout(max_layout)
combined_layout.addWidget(max_widget)
# Allocation Matrix inputs
combined_layout.addWidget(QLabel("分配矩阵:", styleSheet="font-weight: bold; font-size: 18px"))
alloc_widget = QWidget()
alloc_layout = QVBoxLayout()
alloc_layout.setSpacing(15)
alloc_header = QHBoxLayout()
alloc_header.addWidget(QLabel("进程"))
for i in range(self.num_resources):
alloc_header.addWidget(QLabel(f"R{i}"))
alloc_layout.addLayout(alloc_header)
self.alloc_entries = []
for i in range(self.num_processes):
row = QHBoxLayout()
row.addWidget(QLabel(f"P{i}"))
row_entries = []
for j in range(self.num_resources):
entry = QLineEdit()
entry.setFixedWidth(100)
row.addWidget(entry)
row_entries.append(entry)
self.alloc_entries.append(row_entries)
alloc_layout.addLayout(row)
alloc_widget.setLayout(alloc_layout)
combined_layout.addWidget(alloc_widget)
combined_widget.setLayout(combined_layout)
self.combined_scroll = QScrollArea()
self.combined_scroll.setWidgetResizable(True)
self.combined_scroll.setWidget(combined_widget)
self.combined_scroll.setMaximumHeight(400) # Reduced to accommodate request widgets
self.combined_scroll.setFixedWidth(580)
input_layout.addWidget(self.combined_scroll)
self.input_group.setLayout(input_layout)
self.left_layout.addWidget(self.input_group)
# Buttons
self.button_group = QHBoxLayout()
self.button_group.setSpacing(10)
init_btn = QPushButton("初始化")
init_btn.clicked.connect(self.initialize)
init_btn.setMinimumSize(150, 40)
self.button_group.addWidget(init_btn)
back_btn = QPushButton("返回")
back_btn.clicked.connect(self.back)
back_btn.setMinimumSize(150, 40)
self.button_group.addWidget(back_btn)
self.button_group.addStretch()
self.left_layout.addLayout(self.button_group)
self.left_layout.addStretch()
main_split_layout.addLayout(self.left_layout)
# Right side: Simulation Results
self.output_group = QGroupBox("系统状态")
out_layout = QVBoxLayout()
self.state_text = QTextEdit()
self.state_text.setReadOnly(True)
self.state_text.setFixedHeight(300)
out_layout.addWidget(self.state_text)
self.log_text = QTextEdit()
self.log_text.setReadOnly(True)
self.log_text.setFixedHeight(200)
out_layout.addWidget(self.log_text)
out_layout.addStretch()
self.output_group.setLayout(out_layout)
main_split_layout.addWidget(self.output_group)
self.layout.addLayout(main_split_layout)
def create_request_widgets(self):
# Remove any existing request group to avoid duplicates
if hasattr(self, 'request_group'):
self.request_group.deleteLater()
# Create request group
self.request_group = QGroupBox("请求资源")
request_layout = QVBoxLayout()
request_layout.setSpacing(10)
# Process selection
proc_row = QHBoxLayout()
proc_row.addWidget(QLabel("进程:"))
self.process_combo = QComboBox()
for i in range(self.num_processes):
self.process_combo.addItem(f"P{i}")
self.process_combo.setFixedWidth(150)
proc_row.addWidget(self.process_combo)
proc_row.addStretch()
request_layout.addLayout(proc_row)
# Request vector
req_row = QHBoxLayout()
req_row.addWidget(QLabel("请求量 (逗号分隔):"))
self.request_entry = QLineEdit()
self.request_entry.setFixedWidth(250)
req_row.addWidget(self.request_entry)
req_row.addStretch()
request_layout.addLayout(req_row)
# Request button
request_btn = QPushButton("请求")
request_btn.clicked.connect(self.request_resources)
request_btn.setMinimumSize(150, 40)
request_layout.addWidget(request_btn)
self.request_group.setLayout(request_layout)
self.left_layout.insertWidget(2, self.request_group) # Insert below input_group, above buttons
def validate_matrices(self):
self.max_matrix = []
self.allocation_matrix = []
self.need_matrix = []
try:
for i in range(self.num_processes):
max_row = [int(self.entries[i][j].text()) for j in range(self.num_resources)]
alloc_row = [int(self.alloc_entries[i][j].text()) for j in range(self.num_resources)]
if any(x < 0 for x in max_row) or any(x < 0 for x in alloc_row):
raise ValueError("Matrix entries must be non-negative.")
if any(alloc_row[j] > max_row[j] for j in range(self.num_resources)):
raise ValueError(f"Allocation exceeds Max for P{i}.")
self.max_matrix.append(max_row)
self.allocation_matrix.append(alloc_row)
self.need_matrix.append([max_row[j] - alloc_row[j] for j in range(self.num_resources)])
except ValueError as e:
QMessageBox.critical(self, "Input Error", f"Invalid matrix input: {str(e)}")
return False
return True
def check_safety(self, available, allocation, need):
work = available.copy()
finish = [False] * self.num_processes
safe_sequence = []
while len(safe_sequence) < self.num_processes:
found = False
for i in range(self.num_processes):
if not finish[i] and all(need[i][j] <= work[j] for j in range(self.num_resources)):
for j in range(self.num_resources):
work[j] += allocation[i][j]
finish[i] = True
safe_sequence.append(i)
found = True
break
if not found:
return False, []
return True, safe_sequence
def initialize(self):
if not self.validate_matrices():
return
is_safe, sequence = self.check_safety(self.available, self.allocation_matrix, self.need_matrix)
self.display_state(is_safe, sequence)
if is_safe:
self.log_text.setText("系统初始化. 初始状态安全.")
self.create_request_widgets()
else:
self.log_text.setText("系统初始化. 初始状态不安全!")
def display_state(self, is_safe, sequence):
state = f"可用资源: {self.available}\n\n最大矩阵:\n"
for i, row in enumerate(self.max_matrix):
state += f"P{i}: {row}\n"
state += "\n分配矩阵:\n"
for i, row in enumerate(self.allocation_matrix):
state += f"P{i}: {row}\n"
state += "\n需求矩阵:\n"
for i, row in enumerate(self.need_matrix):
state += f"P{i}: {row}\n"
state += f"\n安全: {is_safe}\n"
if is_safe:
state += f"安全序列: <{' '.join(f'P{i}' for i in sequence)}>\n"
self.state_text.setText(state)
def request_resources(self):
try:
process_id = int(self.process_combo.currentText()[1:])
request = [int(x) for x in self.request_entry.text().split(",")]
if len(request) != self.num_resources:
raise ValueError("Request vector must match number of resource types.")
if any(x < 0 for x in request):
raise ValueError("Request values must be non-negative.")
if any(request[j] > self.need_matrix[process_id][j] for j in range(self.num_resources)):
raise ValueError("Request exceeds Need.")
if any(request[j] > self.available[j] for j in range(self.num_resources)):
raise ValueError("Request exceeds Available.")
except ValueError as e:
QMessageBox.critical(self, "Input Error", f"Invalid request: {str(e)}")
self.log_text.append(f"Request failed: {str(e)}")
return
temp_available = self.available.copy()
temp_allocation = [row.copy() for row in self.allocation_matrix]
temp_need = [row.copy() for row in self.need_matrix]
for j in range(self.num_resources):
temp_available[j] -= request[j]
temp_allocation[process_id][j] += request[j]
temp_need[process_id][j] -= request[j]
is_safe, sequence = self.check_safety(temp_available, temp_allocation, temp_need)
if is_safe:
self.available = temp_available
self.allocation_matrix = temp_allocation
self.need_matrix = temp_need
self.display_state(is_safe, sequence)
self.log_text.append(f"请求 P{process_id} {request} 符合. 系统安全.")
else:
self.log_text.append(f"请求 P{process_id} {request} 不符合. 系统不安全.")
def reset(self):
if hasattr(self, 'input_group'):
self.input_group.deleteLater()
if hasattr(self, 'output_group'):
self.output_group.deleteLater()
if hasattr(self, 'request_group'):
self.request_group.deleteLater()
self.num_resources = 0
self.num_processes = 0
self.available = []
self.max_matrix = []
self.allocation_matrix = []
self.need_matrix = []
self.create_initial_widgets()
self.log_text.setText("系统重置.")
def back(self):
self.close()
self.app.show_module_selection()
def closeEvent(self, event):
self.app.show_module_selection()
event.accept()