-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoperatingsystemproject.py
More file actions
556 lines (453 loc) · 19.7 KB
/
operatingsystemproject.py
File metadata and controls
556 lines (453 loc) · 19.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
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
# -*- coding: utf-8 -*-
"""OperatingSystemProject.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1_h6iAHoq_-WZ-0-ddKPu3uC_yB-7_6R2
# Operating System Project
"""
# @title Master function
available_functions = {
"1": main_function_1,
"2": main_function_2,
"3": main_function_3,
"4": main_function_4,
"5": main_function_5
}
# Ask the user to choose a function to run
selected_function = input("Enter the number from the menu: \n1- Priority\n2- Perimeter SJF\n3- Round Robin\n4- Non-Primitive SJF\n5- First Come, First Served (FCFS)\n")
# Execute the selected function
if selected_function in available_functions:
available_functions[selected_function]()
else:
print("Invalid selection. Please choose a number between 1 and 5.")
# @title priority
import matplotlib.pyplot as plt
from tabulate import tabulate
# Priority خورازمية
def priority_scheduling(processes):
#تنظيم على اساس الاولوية
processes.sort(key=lambda x: x['priority'])
print("\nProcess Execution Order based on Priority Scheduling:")
total_wait_time = 0
total_turnaround_time = 0
time_elapsed = 0
process_table = [] # تخزين البيانات لعرضها على شكل جدول
process_names = []
start_times = []
burst_times = []
turnaround_times = []
for process in processes:
# حساب wait time و turnaround time
wait_time = time_elapsed
turnaround_time = wait_time + process['burst_time']
total_wait_time += wait_time
total_turnaround_time += turnaround_time
# توصيل معلومات البروسيس الى الجدول
process_table.append([process['name'], process['burst_time'], wait_time, turnaround_time])
# تحديث الوقت بشكل مستمر
process_names.append(process['name'])
start_times.append(time_elapsed)
burst_times.append(process['burst_time'])
turnaround_times.append(turnaround_time)
time_elapsed += process['burst_time']
avg_wait_time = total_wait_time / len(processes)
avg_turnaround_time = total_turnaround_time / len(processes)
# عرض المعلومات على شكل جدول
print(tabulate(process_table, headers=["🔤 Process", "⏲️ Burst Time ", "⏱️ Waiting Time ", "⏳ Turnaround Time "], tablefmt="grid"))
print(f"\n🕒 Average Waiting Time: {avg_wait_time:.2f}")
print(f"⏳ Average Turnaround Time: {avg_turnaround_time:.2f}")
# تصوير البروسيس على شكل Gantt-Chart
plt.figure(figsize=(14, 2))
# عرض Gantt-Chart
for i, process in enumerate(process_names):
plt.barh(0.4, burst_times[i], left=start_times[i], color='lightblue', edgecolor='black', height=0.8)
plt.text(start_times[i] + burst_times[i] / 2, 0.4, process, ha='center', va='center', color='black', fontsize=30)
# عرض معلومات الوقت في الشكل
for start, burst in zip(start_times, burst_times):
plt.text(start, -0.2, f"{start}", ha='center', va='center', fontsize=25)
plt.text(start_times[-1] + burst_times[-1], -0.2, f"{start_times[-1] + burst_times[-1]}", ha='center', va='center', fontsize=25)
plt.yticks([])
plt.xticks([])
plt.title('Gantt Chart - Priority Scheduling')
plt.tight_layout()
plt.show()
# Main function
def main_function_1():
print("Running main function 1")
processes = []
num_processes = int(input(" \"⭐ priority scheduling خوارزمية الاولوية ⭐\" \n \n Enter the number of processes: "))
for i in range(num_processes):
name = f"P{i + 1}"
print(f"\nProcess {name}:")
priority = int(input(f"🔢 Enter priority : "))
burst_time = int(input(f"⏲️ Enter burst time : "))
processes.append({'name': name, 'priority': priority, 'burst_time': burst_time})
priority_scheduling(processes)
# @title primitive SJF
import matplotlib.pyplot as plt
# === حساب الأوقات ===
def find_times(n, at, bt):
rt = bt.copy()
wt = [0] * n
tat = [0] * n
rt_time = [-1] * n # وقت الاستجابة
complete = 0
t = 0
minm = float('inf')
shortest = 0
check = False
while complete != n:
for j in range(n):
if at[j] <= t and rt[j] < minm and rt[j] > 0:
minm = rt[j]
shortest = j
check = True
if not check:
t += 1
continue
# حساب وقت الاستجابة أول مرة فقط
if rt_time[shortest] == -1:
rt_time[shortest] = t - at[shortest]
rt[shortest] -= 1
minm = rt[shortest]
if minm == 0:
minm = float('inf')
if rt[shortest] == 0:
complete += 1
check = False
finish_time = t + 1
wt[shortest] = finish_time - bt[shortest] - at[shortest]
if wt[shortest] < 0:
wt[shortest] = 0
t += 1
for i in range(n):
tat[i] = bt[i] + wt[i]
return wt, tat, rt_time
# === توليد مخطط جانت ===
def srtf_schedule(at, bt):
n = len(bt)
rt = bt.copy()
complete = 0
t = 0
gantt_chart = []
minm = float('inf')
shortest = 0
check = False
while complete != n:
for j in range(n):
if at[j] <= t and rt[j] < minm and rt[j] > 0:
minm = rt[j]
shortest = j
check = True
if not check:
gantt_chart.append("Idle")
t += 1
continue
rt[shortest] -= 1
gantt_chart.append(f"P{shortest + 1}")
if rt[shortest] == 0:
complete += 1
minm = float('inf')
check = False
t += 1
return gantt_chart
def main_function_2():
print("Running main function 2")
# إدخال عدد العمليات
n = int(input("أدخل عدد العمليات: "))
# إدخال أوقات الوصول والتنفيذ
processes = [f'P{i+1}' for i in range(n)]
arrival_time = []
burst_time = []
for i in range(n):
at = int(input(f"وقت الوصول للعملية {processes[i]}: "))
bt = int(input(f"وقت التنفيذ (Burst Time) للعملية {processes[i]}: "))
arrival_time.append(at)
burst_time.append(bt)
# تنفيذ الحسابات
wt, tat, rt_time = find_times(n, arrival_time, burst_time)
gantt = srtf_schedule(arrival_time, burst_time)
# ضغط الفترات في مخطط جانت
compressed = []
if gantt:
current = gantt[0]
start = 0
for i in range(1, len(gantt)):
if gantt[i] != current:
compressed.append((current, start, i))
current = gantt[i]
start = i
compressed.append((current, start, len(gantt)))
# === الرسم ===
fig, axs = plt.subplots(2, 1, figsize=(12, 5), gridspec_kw={'height_ratios': [1, 2]})
axs[0].axis('off')
columns = ['Process', 'Arrival Time', 'Burst Time', 'Waiting Time', 'Turnaround Time', 'Response Time']
cell_text = [[processes[i], arrival_time[i], burst_time[i], wt[i], tat[i], rt_time[i]] for i in range(n)]
table = axs[0].table(cellText=cell_text, colLabels=columns, loc='center', cellLoc='center')
table.scale(1, 2)
for task, start, end in compressed:
axs[1].barh(0, end - start, left=start, edgecolor='black')
axs[1].text((start + end) / 2, 0, task, va='center', ha='center', color='white', fontsize=9)
axs[1].set_xlim(0, len(gantt))
axs[1].set_yticks([])
axs[1].set_xticks(range(len(gantt)+1))
axs[1].set_title('Gantt Chart - SJF Preemptive (SRTF)')
axs[1].grid(axis='x')
plt.tight_layout()
plt.show()
# @title Round Robin (RR)
import matplotlib.pyplot as plt
import pandas as pd
class RoundRobinScheduler:
def __init__(self, processes, burst_times, quantum, arrival_times=None):
self.processes = processes
self.burst_times = burst_times
self.quantum = quantum
self.arrival_times = arrival_times if arrival_times is not None else [0] * len(processes)
def schedule(self):
if set(self.arrival_times) == {0}:
return self.schedule_no_arrival()
else:
return self.schedule_with_arrival()
def schedule_no_arrival(self):
n = len(self.processes)
remaining_bt = self.burst_times.copy()
waiting = [0] * n
turnaround = [0] * n
response = [-1] * n
timeline = []
current_time = 0
while True:
done = True
for i in range(n):
if remaining_bt[i] > 0:
done = False
if response[i] == -1:
response[i] = current_time
start = current_time
exec_time = min(remaining_bt[i], self.quantum)
current_time += exec_time
remaining_bt[i] -= exec_time
end = current_time
timeline.append((self.processes[i], start, end))
if remaining_bt[i] == 0:
turnaround[i] = current_time
waiting[i] = turnaround[i] - self.burst_times[i]
if done:
break
return waiting, turnaround, timeline, response
def schedule_with_arrival(self):
n = len(self.processes)
remaining_bt = self.burst_times.copy()
waiting = [0] * n
turnaround = [0] * n
response = [-1] * n
timeline = []
current_time = 0
ready_queue = []
completed = []
while len(completed) < n:
for i in range(n):
if self.arrival_times[i] <= current_time and i not in ready_queue and i not in completed:
ready_queue.append(i)
if not ready_queue:
next_time = min([self.arrival_times[i] for i in range(n) if i not in completed])
timeline.append(("IDLE", current_time, next_time))
current_time = next_time
continue
process_idx = ready_queue.pop(0)
if response[process_idx] == -1:
response[process_idx] = current_time - self.arrival_times[process_idx]
start = current_time
exec_time = min(remaining_bt[process_idx], self.quantum)
current_time += exec_time
remaining_bt[process_idx] -= exec_time
end = current_time
timeline.append((self.processes[process_idx], start, end))
if remaining_bt[process_idx] == 0:
completed.append(process_idx)
turnaround[process_idx] = current_time - self.arrival_times[process_idx]
waiting[process_idx] = turnaround[process_idx] - self.burst_times[process_idx]
else:
ready_queue.append(process_idx)
return waiting, turnaround, timeline, response
def print_results(self, waiting, turnaround, response):
df = pd.DataFrame({
"Process": self.processes,
"Arrival Time": self.arrival_times,
"Burst Time": self.burst_times,
"Waiting Time": waiting,
"Turnaround Time": turnaround,
"Response Time": response
})
print("\n", df.to_string(index=False))
print(f"\nAverage Waiting Time: {sum(waiting)/len(waiting):.2f}")
print(f"Average Turnaround Time: {sum(turnaround)/len(turnaround):.2f}")
print(f"Average Response Time: {sum(response)/len(response):.2f}")
def plot_gantt_chart(self, timeline):
fig, ax = plt.subplots(figsize=(10, 2))
for pid, start, end in timeline:
ax.barh(0, end-start, left=start, color="skyblue", edgecolor='black')
ax.text((start+end)/2, 0, pid, ha='center', va='center', fontsize=9)
ax.text(start, 0.3, str(start), ha='center', fontsize=8)
ax.text(end, 0.3, str(end), ha='center', fontsize=8)
plt.title('Gantt Chart - Round Robin')
plt.xlabel('Time')
plt.yticks([])
plt.tight_layout()
plt.show()
def main_function_3():
print("Running main function 3")
print("Round Robin Scheduler")
has_arrival = input("Do you have arrival times? (y/n): ").lower() == 'y'
n = int(input("Enter number of processes: "))
processes = [f"P{i+1}" for i in range(n)]
bursts, arrivals = [], []
for p in processes:
bursts.append(int(input(f"Enter Burst Time for {p}: ")))
if has_arrival:
for p in processes:
arrivals.append(int(input(f"Enter Arrival Time for {p}: ")))
else:
arrivals = None
quantum = int(input("Enter Time Quantum: "))
scheduler = RoundRobinScheduler(processes, bursts, quantum, arrivals)
waiting, turnaround, timeline, response = scheduler.schedule()
scheduler.print_results(waiting, turnaround, response)
scheduler.plot_gantt_chart(timeline)
# @title non-primitive SJF
import matplotlib.pyplot as plt
# ------------------------------------------------------- SJF Function ---------------------------------------------------------
def sjf_non_preemptive_with_arrival(processes):
# ترتيب العمليات حسب وقت الوصول فقط في البداية
original_processes = processes.copy() # الاحتفاظ بالترتيب الأصلي للعرض لاحقًا
processes.sort(key=lambda x: x[1]) # ترتيب العمليات حسب وقت الوصول
n = len(processes)
waiting_time = [0] * n #Waiting_time = [0,0,0,0]
turnaround_time = [0] * n #Turnaround_time = [0,0,0,0]
gantt_chart = []
current_time = 0
completed = 0
ready_queue = []
process_index = 0
final_order = [] # قائمة لترتيب العمليات النهائي
# معالجة كل عملية بناءً على وقت الوصول ووقت التنفيذ
while completed < n:
# إضافة العمليات التي وصلت إلى قائمة الانتظار
while process_index < n and processes[process_index][1] <= current_time:
ready_queue.append(processes[process_index])
process_index += 1
# إذا كانت قائمة الانتظار فارغة، تقدم الزمن إلى أقرب عملية قادمة
if not ready_queue:
current_time = processes[process_index][1]
continue
# اختيار أقصر عملية في قائمة الانتظار
ready_queue.sort(key=lambda x: x[2]) # Sort processes in the ready queue based on Shortest Burst time
current_process = ready_queue.pop(0) # pop the first process (previously sorted) from the ready Qeueue to start executing
name, arrival, burst = current_process # Split (current_process) Into three Variables (name, arrival, burst).
# حساب الأوقات
start_time = current_time
end_time = current_time + burst
waiting_time[completed] = start_time - arrival
turnaround_time[completed] = waiting_time[completed] + burst
gantt_chart.append((name, start_time, end_time))
final_order.append(current_process)
current_time = end_time
completed += 1
# حساب المتوسطات
avg_wtime = sum(waiting_time) / n
avg_ttime = sum(turnaround_time) / n
# طباعة الجدول بالترتيب النهائي بعد التنفيذ
print("\nProcess Table:")
print(f"{'Process':<10}{'Arrival Time':<15}{'Burst Time':<15}{'Waiting Time':<15}{'Turnaround Time':<15}")
for i, process in enumerate(final_order):
name, arrival, burst = process
print(f"{name:<10}{arrival:<15}{burst:<15}{waiting_time[i]:<15}{turnaround_time[i]:<15}")
print(f"\nAverage Waiting Time: {avg_wtime:.2f}")
print(f"Average Turnaround Time: {avg_ttime:.2f}")
# Gantt Chart
fig, ax = plt.subplots(figsize=(12, 2))
for p in gantt_chart:
name, start, end = p
ax.barh(y=0, width=end - start, left=start, height=0.8, align='center', color='skyblue', edgecolor='black')
ax.text((start + end) / 2, 0, name, ha='center', va='center', fontsize=12, fontweight='bold')
# رسم الأوقات (على محور x أسفل كل حد)
for p in gantt_chart:
name, start, end = p
ax.text(start, -0.6, str(start), ha='center', va='center', fontsize=10)
# عرض نهاية آخر عملية
ax.text(gantt_chart[-1][2], -0.6, str(gantt_chart[-1][2]), ha='center', va='center', fontsize=10)
# تنسيقات
ax.set_yticks([])
ax.set_ylim(-1, 1)
ax.set_xlim(0, gantt_chart[-1][2] + 1)
ax.set_xlabel("Time")
ax.set_title("Gantt Chart - SJF Non-Preemptive with Arrival Time", pad=20)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
plt.tight_layout()
plt.show()
def main_function_4():
print("Running main function 4")
# ------------------------------------------------------- استقبال المدخلات ---------------------------------------------------------
n = int(input("Enter the number of processes: "))
processes = []
use_arrival_time = input("Use arrival times? (yes/no): ").strip().lower()
for i in range(n):
if use_arrival_time == "yes":
at = int(input(f"Enter Arrival Time for P{i+1}: "))
else:
at = 0
bt = int(input(f"Enter Burst Time for P{i+1}: "))
processes.append([f'P{i+1}', at, bt])
# استدعاء الفنكشن
sjf_non_preemptive_with_arrival(processes)
# @title First Come, First Served (FCFS)
import matplotlib.pyplot as plt
def main_function_5():
print("Running main function 5")
n = int(input("Enter number of processes: "))
processes = [f'P{i+1}' for i in range(n)]
burst_times = []
arrival_times = []
# Input arrival and burst times
for i in range(n):
at = int(input(f"Enter arrival time for {processes[i]}: "))
bt = int(input(f"Enter burst time for {processes[i]}: "))
arrival_times.append(at)
burst_times.append(bt)
# Sort processes based on arrival times
info = sorted(zip(processes, arrival_times, burst_times), key=lambda x: x[1])
processes, arrival_times, burst_times = zip(*info)
start_times = []
waiting_times = []
turnaround_times = []
current_time = 0
# Calculate start times, waiting times, and turnaround times
for i in range(n):
if current_time < arrival_times[i]:
current_time = arrival_times[i]
start_times.append(current_time)
waiting_times.append(current_time - arrival_times[i])
current_time += burst_times[i]
turnaround_times.append(current_time - arrival_times[i])
# Print results
print("\nProcess\tArrival\tBurst\tWaiting\tTurnaround")
for i in range(n):
print(f"{processes[i]}\t{arrival_times[i]}\t{burst_times[i]}\t{waiting_times[i]}\t{turnaround_times[i]}")
# Plot Gantt chart
fig, gnt = plt.subplots()
gnt.set_ylim(0, 50)
gnt.set_xlim(0, max(start_times[i] + burst_times[i] for i in range(n)) + 1)
gnt.set_xlabel('Time')
gnt.set_yticks([])
gnt.set_title('Gantt Chart - FCFS with Arrival Time')
colors = plt.cm.get_cmap('tab10', n)
for i in range(n):
gnt.broken_barh([(start_times[i], burst_times[i])], (10, 10), facecolors=colors(i))
gnt.text(start_times[i] + burst_times[i]/2, 13, processes[i], ha='center', va='center')
gnt.text(start_times[i], 8, str(start_times[i]), ha='center')
gnt.text(start_times[-1] + burst_times[-1], 8, str(start_times[-1] + burst_times[-1]), ha='center')
plt.show()
# Ensure the main function runs when the script is executed