-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathanalyze.py
1525 lines (1386 loc) · 54.2 KB
/
analyze.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
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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import re
import sys
from collections import defaultdict
from operator import attrgetter
from pathlib import Path
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from absl import app, flags
from matplotlib.patches import Patch
from tabulate import tabulate
from data import CSVReader
from main import FLAGS as main_flags
from utils import STATS_FUNCTIONS, log_statistics, setup_logging
# The formats that the Chrome trace can be output to.
TRACE_FORMATS = ("task", "taskgraph", "application", "resource", "scheduler")
# The formats that the task stats can be output to.
TASK_STATS_FORMATS = ("basic", "detailed")
FLAGS = flags.FLAGS
# Required inputs for either (csv_files, label) or (csv_files, conf_files)
flags.DEFINE_list("csv_files", None, "List of CSV files containing experiment logs")
flags.mark_flag_as_required("csv_files")
flags.register_validator(
"csv_files",
lambda value: all(f.endswith(".csv") for f in value),
message="All files must end with .csv extension",
)
flags.DEFINE_list("csv_labels", None, "List of labels to use for the experiment logs")
flags.register_validator(
"csv_labels",
lambda value: len(value) == len(FLAGS.csv_files) if value else True,
message="Mismatch between length of csv files and labels flags.",
)
flags.DEFINE_list("conf_files", None, "List of conf files used to run the experiments.")
flags.register_validator(
"conf_files",
lambda value: (len(value) == len(FLAGS.csv_files) if value else True)
and (all(f.endswith(".conf") for f in value) if value else True),
message="All files must end with .conf extension.",
)
flags.register_multi_flags_validator(
["csv_labels", "conf_files"],
lambda values: values["csv_labels"] is not None or values["conf_files"] is not None,
message="Atleast one of csv_labels or conf_files must be provided.",
)
flags.DEFINE_string("output_dir", ".", "The directory to output the graphs to.")
# Enable the restriction of events to a particular regular expression or time.
flags.DEFINE_string(
"task_name",
".*",
"Regular expression that restricts the plots to the given tasks.",
)
flags.DEFINE_list(
"between_time",
None,
"The time for which to show the results (for Chrome traces) [in microseconds]",
)
flags.register_validator(
"between_time",
lambda value: FLAGS.chrome_trace is not None if value else True,
message="The between_time flag can only be used for Chrome traces.",
)
flags.register_validator(
"between_time",
lambda value: len(value) <= 2 if value else True,
message="The between_time flag can have a maximum of two values.",
)
# Execution modes for the script.
flags.DEFINE_bool("all", False, "Plot or show statistics for all graphs.")
flags.DEFINE_bool(
"plot", False, "Plots the graph in addition to showing the statistics."
)
flags.DEFINE_string(
"chrome_trace",
None,
f"Outputs the CSV data as a Chrome trace. Allowed values: {TRACE_FORMATS}",
)
flags.register_validator(
"chrome_trace",
lambda value: value in TRACE_FORMATS if value is not None else True,
message=f"Only {TRACE_FORMATS} Chrome trace formats are allowed.",
)
# Allow the choice of seeing release times, deadlines and tasks with placement issues
# in Chrome trace.
flags.DEFINE_enum(
"show_deadlines",
None,
["never", "missed", "always"],
"Chooses if the deadline events are shown in the Chrome trace. "
"'never' shows no deadline events, 'missed' shows only deadlines that were missed, "
"and 'always' shows all deadlines.",
)
flags.register_validator(
"show_deadlines",
lambda value: FLAGS.chrome_trace is not None if value else True,
message="The show_deadlines flag can only be used for Chrome traces.",
)
flags.DEFINE_enum(
"show_release_times",
None,
["never", "intended", "always"],
"Chooses if the release time events are shown in the Chrome trace. "
"'never' shows no release time events, 'intended' shows only intended release "
"times that were set by the Simulator, and 'always' shows the actual release "
"times for all the tasks.",
)
flags.register_validator(
"show_release_times",
lambda value: FLAGS.chrome_trace is not None if value else True,
message="The show_release_times flag can only be used for Chrome traces.",
)
flags.DEFINE_boolean(
"with_placement_issues",
False,
"Show the tasks with the placement issues between the requested times.",
)
flags.register_validator(
"with_placement_issues",
lambda value: (
(FLAGS.chrome_trace == "resource" and FLAGS.between_time is not None)
if value
else True
),
message="Placement issues require resource traces with limited interval.",
)
# Allow the choice of statistics to show for the metrics.
flags.DEFINE_list("stat", "all", "The statistic to show for the given metric.")
flags.register_validator(
"stat",
lambda value: all(s in STATS_FUNCTIONS or s == "all" for s in value),
message=f"Only {tuple(STATS_FUNCTIONS.keys())} statistic functions are allowed.",
)
# Enumerate the different kinds of metrics.
flags.DEFINE_bool(
"sched_runtime", False, "Analyze the runtime of the scheduler invocations."
)
flags.DEFINE_string(
"sched_runtime_timeline_plot_name",
"sched_runtime_timeline.png",
"The filename of the scheduler runtime timeline plot",
)
flags.DEFINE_string(
"sched_runtime_cdf_plot_name",
"sched_runtime_cdf.png",
"The filename of the scheduler runtime CDF plot",
)
flags.DEFINE_bool(
"resource_utilization", False, "Analyze the resource utilization of the trace."
)
flags.DEFINE_string(
"resource_utilization_timeline_plot_name",
"resource_utilization_bar_chart.png",
"The filename of the resource utilization timeline plot",
)
flags.DEFINE_bool(
"task_placement",
False,
"Analyzes the number of placed and unplaced tasks in the trace.",
)
flags.DEFINE_string(
"task_placement_bar_chart_plot_name",
"tasks_placed_bar_chart.png",
"The filename of the task placement bar char plot",
)
flags.DEFINE_bool(
"task_slack",
False,
"Analyzes the placement and completion slack of the tasks in the trace.",
)
flags.DEFINE_string(
"task_slack_plot_name", "task_slack.png", "The filename of the task slack plot"
)
flags.DEFINE_bool("task_placement_delay", False, "Plot task placement delay")
flags.DEFINE_string(
"task_placement_delay_plot_name",
"task_placement_delay.png",
"The filename of the task start delay plot",
)
flags.DEFINE_bool(
"inter_task_time",
False,
"Analyzes the time difference between task releases.",
)
flags.DEFINE_string(
"inter_task_time_plot_name",
"inter_task_time.png",
"The filename of the inter-task time plot.",
)
flags.DEFINE_bool(
"missed_deadlines",
False,
"Analyzes the statistics about the missed deadlines from each invocation.",
)
flags.DEFINE_bool(
"plot_goodput_graph",
False,
"Plot the goodput of the scheduler runs",
)
flags.DEFINE_string(
"goodput_plot_name",
"goodput.png",
"The filename of the goodput plot.",
)
flags.DEFINE_string(
"goodput_plot_title",
"Goodput Comparison",
"The title of the goodput plot.",
)
flags.DEFINE_string(
"missed_deadline_plot_name",
"missed_deadline.png",
"The filename of the missed deadline plot.",
)
flags.DEFINE_bool(
"goodresource_utilization",
False,
"Plot a timeline of the good resource utilization. "
"A good resource utilization is defined as the utilization of the resource "
"for the use of a TaskGraph that meets its deadline.",
)
flags.DEFINE_string(
"goodresource_utilization_plot_name",
"goodresource_utilization.png",
"The filename of the good resource utilization plot.",
)
flags.DEFINE_bool(
"end_to_end_response_time",
False,
"Analyzes the end-to-end response time for each timestamp.",
)
flags.DEFINE_string(
"end_to_end_response_time_plot_name",
"end_to_end_response_time.png",
"The filename of the end-to-end response time plot.",
)
flags.DEFINE_string(
"task_stats",
None,
"Log basic or detailed statistics for each task grouped by the task name.",
)
flags.register_validator(
"task_stats",
lambda value: value in TASK_STATS_FORMATS if value is not None else True,
message=f"Only {TASK_STATS_FORMATS} formats are allowed for task statistics.",
)
flags.DEFINE_bool(
"aggregate_stats",
False,
"Log aggregate stats from a list of (csv_files, conf_files)",
)
flags.register_multi_flags_validator(
["aggregate_stats", "conf_files"],
lambda values: (
values["conf_files"] is not None if values["aggregate_stats"] else True
),
message="Config files must be provided to invoke the aggregate_stats mode.",
)
matplotlib.rcParams.update({"font.size": 16, "figure.autolayout": True})
matplotlib.rcParams["xtick.labelsize"] = 16
matplotlib.rcParams["ytick.labelsize"] = 16
plt.rcParams["font.family"] = "serif"
axes_fontsize = 16
markers = {"EDF": "o", "Gurobi": "x", "Z3": "+", "LSF": "^"}
colors = {"EDF": "r", "Gurobi": "b", "Z3": "y", "LSF": "b"}
logger = setup_logging("plotting")
def __parse_flagfile(path: str):
"""Parses the flagfile at the given path, and sets the FLAGS to contain the new
values.
Args:
path (str): The path to where the config file is stored.
"""
main_flags([__file__, f"--flagfile={path}"])
def analyze_resource_utilization(
csv_reader,
scheduler_csv_file,
scheduler_name,
output,
plot=False,
figure_size=(14, 10),
bar_width=1.0,
stats="all",
):
"""Analyzes the utilization of different resources on the workers.
If `plot` is `True`, the method plots a timeline of the utilization of different
resources on the workers.
Args:
csv_reader (`data.CSVReader`): The CSVReader instance containing the parsed
CSV file.
scheduler_csv_file (`str`): The path to the CSV file for which to plot results.
scheduler_name (`str`): The label to give to the scheduler.
output (`str`): The path to where the plot should be output to.
plot (`bool`) [default = False]: Plots the graphs if set to True.
figure_size (`Tuple[int, int]`) [default=(14, 10)]: The size of the plot.
stats (`Union[str, Sequence[str]`): The statistics to show for the metric.
"""
# Plotting defaults.
# hatches = ['//', '--', '**']
# alphas = np.arange(0.2, 1.2, 0.2)
resource_color = {"GPU": "red", "CPU": "green"}
# Worker Pool statistics
worker_pool_stats = csv_reader.get_worker_pool_utilizations(scheduler_csv_file)
# Find all the resource types in the system.
resource_types = set()
for wp_stats in worker_pool_stats:
for resource in wp_stats.resource_utilizations.keys():
resource_types.add(resource)
# Calculate the heights of utilization for each resource, after
# normalization.
resource_used_heights = {
resource: [
stat.resource_utilizations[resource][0]
/ sum(stat.resource_utilizations[resource])
for stat in worker_pool_stats
]
for resource in resource_types
}
sim_times_sec = [stat.simulator_time / 1000000 for stat in worker_pool_stats]
# resource_free_heights = {
# resource: [
# stat.resource_utilizations[resource][1] /
# sum(stat.resource_utilizations[resource])
# for stat in worker_pool_stats
# ]
# for resource in resource_types
# }
logger.debug("================== Resource Utilization ==================")
for resource_type in resource_types:
logger.debug("Utilization for {}".format(resource_type))
log_statistics(resource_used_heights[resource_type], logger, stats)
# Plot a histogram with the results.
if plot:
fig = plt.figure(figsize=figure_size)
# Keeping this for a little bit longer.
# x_vals = np.arange(1, len(worker_pool_stats) + 1)
# _ = [
# plt.bar(
# x_vals + bar_width * i,
# resource_used_heights[resource_type],
# width=bar_width,
# # edgecolor='black',
# # hatch=hatches[i],
# alpha=0.4,
# color=resource_color[resource_type],
# )
# for i, resource_type in enumerate(resource_types)
# ]
for i, resource_type in enumerate(resource_types):
plt.scatter(
sim_times_sec,
resource_used_heights[resource_type],
color=resource_color[resource_type],
)
plt.xlim(0, max(sim_times_sec))
plt.xlabel("Timeline [s]", fontsize=axes_fontsize)
plt.ylabel("Normalized Utilization", fontsize=axes_fontsize)
# Set the y limits so we can visualize the legend.
ax = fig.gca()
ax.set_ylim(0, 1.01)
plt.yticks([0, 0.5, 1.0])
legend_elements = [
Patch(
facecolor=resource_color[resource_type],
label=f"{scheduler_name}-{resource_type}",
)
for resource_type in resource_types
]
plt.legend(handles=legend_elements, framealpha=0)
plt.savefig(output, bbox_inches="tight")
def analyze_scheduler_runtime(
csv_reader,
scheduler_csv_files,
scheduler_labels,
timeline_output,
cdf_output,
plot=False,
figure_size=(14, 10),
stats="all",
):
"""Analyzes the runtime of the scheduler invocations from the CSV files.
If `plot` is `True`, the method plots a timeline and a CDF of the runtime of the
scheduler invocations.
Args:
csv_reader (`data.CSVReader`): The CSVReader instance containing the parsed
CSV file.
scheduler_csv_files (`Sequence[str]`): A list of paths to CSV files containing
the results.
scheduler_labels (`Sequence[str]`): A list of labels to give the schedulers.
timeline_output (`str`): The path to where the timeline plot should be output.
cdf_output (`str`): The path to where the CDF plot should be output.
plot (`bool`) [default = False]: Plots the graphs if set to True.
figure_size (`Tuple[int, int]`) [default=(14, 10)]: The size of the plot.
stats (`Union[str, Sequence[str]`): The statistics to show for the metric.
"""
# Retrieve the runtime of the scheduler invocations.
logger.debug("================= Scheduler runtime [ms] =================")
max_start_time = -sys.maxsize
max_runtime = -sys.maxsize
all_runtimes = []
all_start_times = []
for csv_file in scheduler_csv_files:
scheduler_invocations = csv_reader.get_scheduler_invocations(csv_file)
runtimes = list(map(attrgetter("runtime"), scheduler_invocations))
runtimes_ms = [runtime / 1000 for runtime in runtimes]
start_times = list(map(attrgetter("start_time"), scheduler_invocations))
start_times_ms = [start_time / 1000 for start_time in start_times]
max_start_time = max(max_start_time, max(start_times_ms))
max_runtime = max(max_runtime, max(runtimes_ms))
all_runtimes.append(runtimes_ms)
all_start_times.append(start_times_ms)
logger.debug(f"Stats for {csv_file}")
log_statistics(runtimes_ms, logger, stats)
# Plot a timelapse of the runtime of the scheduler.
if plot:
plt.figure(figsize=figure_size)
for i, label in enumerate(scheduler_labels):
plt.plot(
all_start_times[i],
all_runtimes[i],
label=label,
marker=markers[label],
color=colors[label],
)
plt.xlim(0, max_start_time)
plt.ylim(0, max(50, max([max(a_r) for a_r in all_runtimes])))
plt.xlabel("Timeline [ms]", fontsize=axes_fontsize)
plt.ylabel("Scheduler Runtime [ms]", fontsize=axes_fontsize)
plt.legend(frameon=False)
plt.savefig(timeline_output, bbox_inches="tight")
# Plot the CDF of the runtime of the scheduler invocations.
plt.figure(figsize=figure_size)
for i, label in enumerate(scheduler_labels):
count, bin_count = np.histogram(all_runtimes[i], bins=100)
pdf = count / sum(count)
cdf = np.cumsum(pdf)
plt.plot(bin_count[1:], cdf, label=label)
plt.xlim(0, max_runtime)
plt.ylim(0, 1)
plt.xlabel("Scheduler Runtime [ms]", fontsize=axes_fontsize)
plt.ylabel("CDF", fontsize=axes_fontsize)
plt.legend(frameon=False)
plt.savefig(cdf_output, bbox_inches="tight")
def analyze_task_placement(
csv_reader: CSVReader,
scheduler_csv_file,
scheduler_name,
output,
plot=False,
figure_size=(14, 10),
stats="all",
):
"""Analyzes the number of placed and unplaced tasks by each scheduler invocation.
Args:
csv_reader (`data.CSVReader`): The CSVReader instance containing the parsed
CSV file.
scheduler_csv_file (`str`): The path to the CSV file for which to plot results.
scheduler_name (`str`): The label to give to the scheduler.
output (`str`): The path to where the plot should be output to.
plot (`bool`) [default = False]: Plots the graphs if set to True.
figure_size (`Tuple[int, int]`) [default=(14, 10)]: The size of the plot.
stats (`Union[str, Sequence[str]`): The statistics to show for the metric.
"""
scheduler_invocations = csv_reader.get_scheduler_invocations(scheduler_csv_file)
# Calculate the heights of placed and unplaced tasks.
placed_task_heights = [
scheduler_invocation.num_placed_tasks
for scheduler_invocation in scheduler_invocations
]
unplaced_task_heights = [
scheduler_invocation.num_unplaced_tasks
for scheduler_invocation in scheduler_invocations
]
logger.debug("================== Num placed tasks ==================")
log_statistics(placed_task_heights, logger, stats)
logger.debug("================== Num unplaced tasks ==================")
log_statistics(unplaced_task_heights, logger, stats)
if plot:
# Plot a histogram with the results.
plt.figure(figsize=figure_size)
x_vals = np.arange(1, len(scheduler_invocations) + 1)
_ = plt.bar(
x_vals,
placed_task_heights,
# edgecolor='black',
# hatch='//',
alpha=0.4,
color="green",
)
_ = plt.bar(
x_vals,
unplaced_task_heights,
bottom=placed_task_heights,
# edgecolor='black',
# hatch='**',
alpha=0.4,
color="red",
)
# Add the axis labels.
plt.xlabel("Scheduler Run", fontsize=axes_fontsize)
plt.ylabel("Placed and Unplaced Tasks", fontsize=axes_fontsize)
plt.xlim(0, max(x_vals))
# Add the yticks
max_y_val = max(
scheduler_invocation.total_tasks
for scheduler_invocation in scheduler_invocations
)
plt.ylim(0, int(max_y_val))
# Set the legend.
legend_elements = [
Patch(facecolor="green", label=f"{scheduler_name} Placed Tasks"),
Patch(facecolor="red", label=f"{scheduler_name} Unplaced Tasks"),
]
plt.legend(handles=legend_elements, framealpha=0)
plt.savefig(output, bbox_inches="tight")
def analyze_inter_task_time(
csv_reader,
task_name_regex,
scheduler_csv_file,
scheduler_name,
output,
plot=False,
figure_size=(14, 10),
stats="all",
):
"""Analyzes the inter-task time for tasks that match the given regex.
The inter-task time is the actual time elapsed between the release time of two
successive invocations of a particular task.
Args:
csv_reader (`data.CSVReader`): The CSVReader instance containing the parsed
CSV file.
task_name_regex (`str`): The regular expression to match the task name to.
scheduler_csv_file (`str`): The path to the CSV file for which to plot results.
scheduler_name (`str`): The label to give to the scheduler.
output (`str`): The path to where the plot should be output to.
plot (`bool`) [default = False]: Plots the graphs if set to True.
figure_size (`Tuple[int, int]`) [default=(14, 10)]: The size of the plot.
stats (`Union[str, Sequence[str]`): The statistics to show for the metric.
"""
# Retrieve the tasks from the CSV file that match the given regular expression.
tasks = csv_reader.get_tasks(scheduler_csv_file)
task_map = defaultdict(list)
for task in tasks:
if re.match(task_name_regex, task.name):
task_map[task.name].append(task)
# Collect the inter-task time statistics and print them.
logger.debug("================== Inter-Task Time [ms] ==================")
logger.debug(f"Tasks that match the regex: {task_name_regex}")
inter_release_times = []
labels = []
for task_name, tasks in task_map.items():
sorted_tasks = sorted(tasks)
last_release = sorted_tasks[0].release_time
task_inter_release_time = []
for index in range(1, len(tasks)):
task_inter_release_time.append(
(sorted_tasks[index].release_time - last_release) / 1000
)
last_release = sorted_tasks[index].release_time
labels.append(task_name)
inter_release_times.append(task_inter_release_time)
logger.debug(f"Statistics for {task_name}:")
log_statistics(task_inter_release_time, logger, stats, offset=" ")
if plot:
plt.figure(figsize=figure_size)
plt.xlabel("Inter-Task Time [ms]", fontsize=axes_fontsize)
plt.hist(inter_release_times, label=labels, density=False, bins=100)
plt.legend(frameon=False)
plt.savefig(output, bbox_inches="tight")
def analyze_task_slack(
csv_reader,
task_name_regex,
scheduler_csv_file,
scheduler_name,
output,
plot=False,
figure_size=(14, 10),
stats="all",
):
"""Analyzes the actual and intended completion slack of the tasks.
The actual completion slack is defined as the time between the deadline and the
actual completion of the task, where a negative value defines a missed deadline.
The intended completion slack is defined as the time between the deadline and the
intended finish time of the task (as defined by its intended start time and
runtime).
Args:
csv_reader (`data.CSVReader`): The CSVReader instance containing the parsed
CSV file.
task_name_regex (`str`): The regular expression to match the task name to.
scheduler_csv_file (`str`): The path to the CSV file for which to plot results.
scheduler_name (`str`): The label to give to the scheduler.
output (`str`): The path to where the plot should be output to.
plot (`bool`) [default = False]: Plots the graphs if set to True.
figure_size (`Tuple[int, int]`) [default=(14, 10)]: The size of the plot.
stats (`Union[str, Sequence[str]`): The statistics to show for the metric.
"""
# Retrieve the tasks that match the given regular expression.
tasks = []
for task in csv_reader.get_tasks(scheduler_csv_file):
if re.match(task_name_regex, task.name):
tasks.append(task)
# Compute the time between the deadline and the actual completion of the task.
slack = [-task.get_deadline_delay() / 1000 for task in tasks]
logger.debug("================== Actual task completion slack [ms] ===============")
logger.debug(f"Tasks that match the regex: {task_name_regex}")
log_statistics(slack, logger, stats)
# Compute the time between the deadline and the intended completion of the task.
initial_slack = [
(task.deadline - task.release_time - task.runtime) / 1000 for task in tasks
]
logger.debug("================== Intended task completion slack [ms] =============")
logger.debug(f"Tasks that match the regex: {task_name_regex}")
log_statistics(initial_slack, logger, stats)
# If required, plot a histogram of the slack from the deadline for the tasks.
if plot:
plt.figure(figsize=figure_size)
plt.xlim(min(slack), max(slack))
plt.xlabel("Task Slack [ms]", fontsize=axes_fontsize)
plt.ylabel("Number of Tasks", fontsize=axes_fontsize)
plt.hist(
[slack, initial_slack],
label=[
f"{scheduler_name} Task Completion Slack",
f"{scheduler_name} Task Placement Slack",
],
density=False,
bins=100,
)
plt.legend(frameon=False)
plt.savefig(output, bbox_inches="tight")
def analyze_task_placement_delay(
csv_reader,
scheduler_csv_files,
scheduler_labels,
output,
plot=False,
figure_size=(14, 10),
stats="all",
):
"""Analyzes the placement delays from the given trace.
Args:
csv_reader (`data.CSVReader`): The CSVReader instance containing the parsed
CSV file.
scheduler_csv_files (`Sequence[str]`): A list of paths to CSV files containing
the results.
scheduler_labels (`Sequence[str]`): A list of labels to give the schedulers.
output (`str`): The path to where the plot should be output.
plot (`bool`) [default = True]: Show statistics only if set to False.
figure_size (`Tuple[int, int]`) [default=(14, 10)]: The size of the plot.
stats (`Union[str, Sequence[str]`): The statistics to show for the metric.
"""
logger.debug("================ Task placement delay [ms] ================")
placement_delays = []
min_delay = sys.maxsize
max_delay = -sys.maxsize
plot_colors = [colors[label] for label in scheduler_labels]
for csv_file in scheduler_csv_files:
placement_delay = [
task.get_placement_delay() / 1000 for task in csv_reader.get_tasks(csv_file)
]
placement_delays.append(placement_delay)
min_delay = min(min_delay, min(placement_delay))
max_delay = max(max_delay, max(placement_delay))
logger.debug(f"Placement delay stats for {csv_file}")
log_statistics(placement_delay, logger, stats)
if plot:
plt.figure(figsize=figure_size)
plt.xlim(min_delay, max_delay)
plt.xlabel("Task Placement Delay [ms]", fontsize=axes_fontsize)
plt.ylabel("Number of Tasks", fontsize=axes_fontsize)
plt.hist(
placement_delays,
density=False,
bins=100,
label=scheduler_labels,
color=plot_colors,
)
plt.legend(frameon=False)
plt.savefig(output, bbox_inches="tight")
def log_detailed_task_statistics(
task_name_regex: str, csv_reader: CSVReader, csv_file: str
):
"""Prints the detailed statistics for the given CSV file.
Args:
task_name_regex (`str`): The regular expression to match the task name to.
csv_reader (:py:class:`CSVReader`): The CSVReader instance containing the
results.
csv_file (str): The path to the CSV file to show the results for.
"""
# Get the tasks grouped by their name.
grouped_tasks = defaultdict(list)
for task in csv_reader.get_tasks(csv_file):
if re.match(task_name_regex, task.name):
grouped_tasks[task.name].append(task)
# Colorify the results.
R = "\033[0;31;40m"
G = "\033[0;32;40m"
D = "\033[0m"
# Log the results.
for task_name, tasks in grouped_tasks.items():
results = []
for task in tasks:
results.append(
tuple(
map(
lambda val: (
R + str(val) + D
if task.missed_deadline
else G + str(val) + D
),
(
task.timestamp,
str(task.id),
(
task.intended_release_time / 1000
if task.intended_release_time != -1
else "-"
),
task.release_time / 1000,
task.placement_time / 1000,
task.start_time / 1000,
task.runtime / 1000,
task.deadline / 1000,
task.completion_time / 1000,
task.missed_deadline,
len(task.skipped_times) > 0,
task.get_deadline_delay() / 1000,
task.get_placement_delay() / 1000,
(
task.get_release_delay() / 1000
if task.intended_release_time != -1
else "-"
),
),
)
)
)
logger.debug(
f"Detailed view for {task_name}:\n"
+ tabulate(
results,
headers=[
"Time",
"ID",
"Int Release",
"Release",
"Placement",
"Start",
"Runtime",
"Deadline",
"Completion",
"X Dline?",
"X Skipped",
"Dline Delay",
"Place Delay",
"Rels Delay",
],
tablefmt="grid",
showindex=True,
)
)
def analyze_missed_deadlines(
csv_reader,
task_name_regex,
scheduler_csv_file,
scheduler_name,
output,
plot=False,
figure_size=(14, 10),
stats="all",
):
"""Analyzes the number of missed deadlines by each task.
Args:
csv_reader (`data.CSVReader`): The CSVReader instance containing the parsed
CSV file.
task_name_regex (`str`): The regular expression to match the task name to.
scheduler_csv_file (`str`): The path to the CSV file for which to plot results.
scheduler_name (`str`): The label to give to the scheduler.
output (`str`): The path to where the plot should be output to.
plot (`bool`) [default = False]: Plots the graphs if set to True.
figure_size (`Tuple[int, int]`) [default=(14, 10)]: The size of the plot.
stats (`Union[str, Sequence[str]`): The statistics to show for the metric.
"""
# Group the missed deadlines by their task name (if regex is matched).
missed_deadline_by_task_name = defaultdict(list)
missed_deadline_delays = []
for task in csv_reader.get_tasks(scheduler_csv_file):
if re.match(task_name_regex, task.name) and task.missed_deadline:
missed_deadline_by_task_name[task.name].append(task)
missed_deadline_delays.append(task.get_deadline_delay() / 1000)
# Log the results.
logger.debug("================== Missed Deadlines ==================")
logger.debug(f"Tasks that match the regex: {task_name_regex}")
logger.debug(f"Average missed deadline delay: {np.mean(missed_deadline_delays)}")
for task_name, tasks in missed_deadline_by_task_name.items():
logger.debug(f"{task_name}")
missed_deadline_delays_per_task = [
task.get_deadline_delay() / 1000 for task in tasks
]
log_statistics(missed_deadline_delays_per_task, logger, stats, offset=" ")
if plot:
# Plot the number of missed deadlines by the method name.
plt.figure(figsize=figure_size)
plt.bar(
missed_deadline_by_task_name.keys(),
list(map(len, missed_deadline_by_task_name.values())),
)
plt.xticks(rotation=90)
plt.ylabel("Number of Missed Deadlines")
plt.savefig(output, bbox_inches="tight")
def analyze_end_to_end_response_time(
csv_reader,
scheduler_csv_file,
scheduler_label,
output,
plot=False,
figure_size=(14, 10),
stats="all",
):
"""Analyzes the end-to-end response time of each timestamp in the trace.
Args:
csv_reader (`data.CSVReader`): The CSVReader instance containing the parsed
CSV file.
scheduler_csv_file (`str`): The path to the CSV file for which to plot results.
output (`str`): The path to where the plot should be output to.
plot (`bool`) [default = False]: Plots the graphs if set to True.
figure_size (`Tuple[int, int]`) [default=(14, 10)]: The size of the plot.
stats (`Union[str, Sequence[str]`): The statistics to show for the metric.
"""
tasks = csv_reader.get_tasks(scheduler_csv_file)
timestamp_start_end = {}
for task in tasks:
if task.timestamp in timestamp_start_end:
release_time = min(
task.release_time, timestamp_start_end[task.timestamp][0]
)
completion_time = max(
task.completion_time, timestamp_start_end[task.timestamp][1]
)
timestamp_start_end[task.timestamp] = (release_time, completion_time)
else:
timestamp_start_end[task.timestamp] = (
task.release_time,
task.completion_time,
)
e2e_response_time = [(ct - rt) / 1000 for (rt, ct) in timestamp_start_end.values()]
logger.debug("================== End-to-end response time [ms] ==================")
log_statistics(e2e_response_time, logger, stats)
if plot:
plt.figure(figsize=figure_size)
plt.xlim(0, max(600, max(e2e_response_time)))
plt.xlabel("End-to-end response time [ms]", fontsize=axes_fontsize)
plt.hist(
e2e_response_time,
label=scheduler_label,
density=False,
range=(0, max(e2e_response_time)),
bins=100,
)
plt.legend(frameon=False)
plt.savefig(output, bbox_inches="tight")
def log_basic_task_statistics(
task_name_regex, csv_reader: CSVReader, csv_file: str, stat: str = "p50"
):
"""Prints the basic task statistics from the given CSV file.
Args:
task_name_regex (`str`): The regular expression to match the task name to.
csv_reader (:py:class:`CSVReader`): The CSVReader instance containing the
results.
csv_file (str): The path to the CSV file to show the results for.
stat (str): The stat to show in the table for the given tasks.
"""
# Get the Statistic function to use.
if stat not in STATS_FUNCTIONS:
raise ValueError(
f"Requested stat: {stat} not found in {STATS_FUNCTIONS.keys()}"
)
stat_function = STATS_FUNCTIONS[stat][0]
# Get the tasks grouped by their name.
tasks = defaultdict(list)
for task in csv_reader.get_tasks(csv_file):
if re.match(task_name_regex, task.name):
tasks[task.name].append(task)
# Gather the results.
results = []
total_release_delays = []
total_placement_delays = []
total_missed_deadline_delays = []
total_skipped = []
for task_name, grouped_tasks in tasks.items():
# Gather the number of skipped tasks.
skipped_tasks = list(
filter(lambda task: len(task.skipped_times) > 0, grouped_tasks)
)
total_skipped.extend(skipped_tasks)
# Gather release delays.
release_delays = [task.get_release_delay() / 1000 for task in grouped_tasks]
total_release_delays.extend(release_delays)
# Gather placement delays.