-
Notifications
You must be signed in to change notification settings - Fork 111
/
analysis.py
2757 lines (2383 loc) · 109 KB
/
analysis.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Jan Koscielniak, (c) 2020
# Author: Hubert Kario, (c) 2020
# Released under Gnu GPL v2.0, see LICENSE file for details
"""Analysis of timing information."""
from __future__ import print_function
import csv
import getopt
import sys
import math
import multiprocessing as mp
from threading import Event, Thread
import shutil
from itertools import chain
from os.path import join
from collections import namedtuple
from itertools import combinations, repeat, chain
import os
import time
import numpy as np
from scipy import stats
import pandas as pd
import matplotlib as mpl
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from tlsfuzzer.utils.ordered_dict import OrderedDict
from tlsfuzzer.utils.progress_report import progress_report
from tlsfuzzer.utils.stats import skillings_mack_test
from tlsfuzzer.messages import div_ceil
TestPair = namedtuple('TestPair', 'index1 index2')
mpl.use('Agg')
VERSION = 8
_diffs = None
_DATA = None
def help_msg():
"""Print help message"""
print("""Usage: analysis [-o output]
-o output Directory where to place results (required)
and where timing.csv or measurements.csv is located
--no-ecdf-plot Don't create the ecdf_plot.png file
--no-scatter-plot Don't create the scatter_plot.png file
--no-conf-interval-plot Don't create the conf_interval_plot*.png files
--no-wilcoxon-test Don't run the Wilcoxon signed rank test
for pairwise measurements
--no-t-test Don't run the paired sample t-test for pairwise measurements
--no-sign-test [Hamming weight only] Don't run the sign test
--multithreaded-graph Create graph and calculate statistical tests at the
same time. Note: this increases memory usage of analysis by
a factor of 8.
--clock-frequency freq Assume that the times in the file are not specified in
seconds but rather in clock cycles of a clock running at
frequency 'freq' specified in MHz. Use when the clock source
are the raw reads from the Time Stamp Counter register or
similar.
--alpha num Acceptable probability of a false positive. Default: 1e-5.
--verbose Print the current task
--workers num Number of worker processes to use for paralelizable
computation. More workers will finish analysis faster, but
will require more memory to do so. By default: number of
threads available on the system (`os.cpu_count()`).
--status-delay num How often to print the status line for long-running
tasks in seconds.
--status-newline Use newline for printing status line, not carriage return,
works better with output redirection to file.
--bit-size Specifies that the program will analyze bit-size measurement
data from a measurements.csv file. A measurements.csv file
is expected as input and it should be in long-format
("row id,column id,value").
--Hamming-weight Specified that the analysis will expect data for analysing
Hamming weight data from a measurements.csv file.
The measurements.csv is expected as input in the long-format
("row id,column id,value")
--no-smart-analysis By default when analysing bit size the script will compute
how much data are needed to calculate small confidence
interval to the 4th bit size and use only this number of
data (if available). This option disables this feature and
uses all the available data.
--bit-size-desired-ci num The desired amount of ns (or lower) that the CIs
should have after the analysis up to recognition size
option. Used only with smart analysis. Default 1 ns.
--bit-recognition-size num The <num> biggest bit size will be used to
determine how many samples will be used to get the desired
CI from the analysis. Used only with smart analysis.
Default is 4.
--measurements Specifies the measurements file name that should be
analyzed.
The file must be present in the output dir. This flag only
works in combination the --bit-size flag.
--skip-sanity Skip sanity measurements from analysis (if any).
--help Display this message""")
def main():
"""Process arguments and start analysis."""
output = None
ecdf_plot = True
scatter_plot = True
conf_int_plot = True
multithreaded_graph = False
verbose = False
clock_freq = None
alpha = None
workers = None
delay = None
carriage_return = None
t_test = True
wilcoxon_test = True
sign_test = True
bit_size_analysis = False
smart_analysis = True
bit_size_desired_ci = 1e-9
bit_recognition_size = 4
measurements_filename = "measurements.csv"
skip_sanity = False
hamming_weight_analysis = False
argv = sys.argv[1:]
opts, args = getopt.getopt(argv, "o:",
["help", "no-ecdf-plot", "no-scatter-plot",
"no-conf-interval-plot",
"no-t-test",
"no-sign-test",
"no-wilcoxon-test",
"multithreaded-graph",
"clock-frequency=",
"alpha=",
"workers=",
"status-delay=",
"status-newline",
"bit-size",
"no-smart-analysis",
"bit-size-desired-ci=",
"bit-recognition-size=",
"measurements=",
"skip-sanity",
"Hamming-weight",
"verbose"])
for opt, arg in opts:
if opt == '-o':
output = arg
elif opt == "--help":
help_msg()
sys.exit(0)
elif opt == "--no-ecdf-plot":
ecdf_plot = False
elif opt == "--no-scatter-plot":
scatter_plot = False
elif opt == "--no-conf-interval-plot":
conf_int_plot = False
elif opt == "--no-sign-test":
sign_test = False
elif opt == "--no-t-test":
t_test = False
elif opt == "--no-wilcoxon-test":
wilcoxon_test = False
elif opt == "--multithreaded-graph":
multithreaded_graph = True
elif opt == "--clock-frequency":
clock_freq = float(arg) * 1000000 # in MHz
elif opt == "--alpha":
alpha = float(arg)
elif opt == "--workers":
workers = int(arg)
elif opt == "--verbose":
verbose = True
elif opt == "--status-delay":
delay = float(arg)
elif opt == "--status-newline":
carriage_return = '\n'
elif opt == "--bit-size":
bit_size_analysis = True
elif opt == "--Hamming-weight":
hamming_weight_analysis = True
elif opt == "--no-smart-analysis":
smart_analysis = False
elif opt == "--bit-size-desired-ci":
bit_size_desired_ci = float(arg) * 1e-9
elif opt == "--bit-recognition-size":
bit_recognition_size = int(arg)
elif opt == "--measurements":
measurements_filename = arg
elif opt == "--skip-sanity":
skip_sanity = True
if output:
analysis = Analysis(output, ecdf_plot, scatter_plot, conf_int_plot,
multithreaded_graph, verbose, clock_freq, alpha,
workers, delay, carriage_return,
bit_size_analysis or hamming_weight_analysis,
smart_analysis, bit_size_desired_ci,
bit_recognition_size, measurements_filename,
skip_sanity, wilcoxon_test, t_test, sign_test)
ret = analysis.generate_report(
bit_size=bit_size_analysis,
hamming_weight=hamming_weight_analysis
)
return ret
else:
raise ValueError("Missing -o option!")
class Analysis(object):
"""Analyse extracted timing information from csv file."""
def __init__(self, output, draw_ecdf_plot=True, draw_scatter_plot=True,
draw_conf_interval_plot=True, multithreaded_graph=False,
verbose=False, clock_frequency=None, alpha=None,
workers=None, delay=None, carriage_return=None,
bit_size_analysis=False, smart_bit_size_analysis=True,
bit_size_desired_ci=1e-9, bit_recognition_size=4,
measurements_filename="measurements.csv", skip_sanity=False,
run_wilcoxon_test=True, run_t_test=True, run_sign_test=True):
self.verbose = verbose
self.output = output
self.clock_frequency = clock_frequency
self.class_names = []
self.draw_ecdf_plot = draw_ecdf_plot
self.draw_scatter_plot = draw_scatter_plot
self.draw_conf_interval_plot = draw_conf_interval_plot
self.run_wilcoxon_test = run_wilcoxon_test
self.run_t_test = run_t_test
self.run_sign_test = run_sign_test
self.multithreaded_graph = multithreaded_graph
self.workers = workers
if alpha is None:
self.alpha = 1e-5
else:
self.alpha = alpha
self.delay = delay
self.carriage_return = carriage_return
self.measurements_filename = measurements_filename
self.skip_sanity = skip_sanity
if bit_size_analysis and smart_bit_size_analysis:
self._bit_size_data_limit = 10000 # staring amount of samples
self._bit_size_data_used = None
self._total_bit_size_data = 0
self._total_bit_size_data_used = 0
self.bit_size_desired_ci = bit_size_desired_ci
self.bit_recognition_size = \
bit_recognition_size if bit_recognition_size >= 0 else 1
else:
self._bit_size_data_limit = None
self._bit_size_data_used = None
self._total_bit_size_data = 0
self._total_bit_size_data_used = 0
if not bit_size_analysis:
data = self.load_data()
self.class_names = list(data)
else:
self._bit_size_sign_test = {}
self._bit_size_wilcoxon_test = {}
self._bit_size_bootstraping = {}
self._hamming_weight_report = ""
self._bit_size_methods = {
"mean": "Mean",
"median": "Median",
"trim_mean_05": "Trimmed mean (5%)",
"trim_mean_25": "Trimmed mean (25%)",
"trim_mean_45": "Trimmed mean (45%)",
"trimean": "Trimean"
}
def _convert_to_binary(self):
timing_bin_path = join(self.output, "timing.bin")
timing_csv_path = join(self.output, "timing.csv")
legend_csv_path = join(self.output, "legend.csv")
timing_bin_shape_path = join(self.output, "timing.bin.shape")
if os.path.isfile(timing_bin_path) and \
os.path.isfile(legend_csv_path) and \
os.path.isfile(timing_bin_shape_path) and \
os.path.getmtime(timing_csv_path) < \
os.path.getmtime(timing_bin_path):
return
if self.verbose:
start_time = time.time()
print("[i] Converting the data from text to binary format")
for chunk in pd.read_csv(timing_csv_path, chunksize=1,
dtype=np.float64):
self.class_names = list(chunk)
self._write_legend()
break
ncol = len(self.class_names)
rows_written = 0
# as we're dealing with 9 digits of precision (nanosecond range)
# and the responses can be assumed to take less than a second,
# we need to use the double precision IEEE floating point numbers
# load 512000 rows at a time so that we don't use more than 2000MiB
# (including pandas overhead) of memory at a time to process a file
# with 256 columns
csv_reader = pd.read_csv(timing_csv_path, chunksize=512000,
dtype=np.float64)
chunk = next(csv_reader)
if self.clock_frequency:
chunk = chunk / self.clock_frequency
timing_bin = np.memmap(timing_bin_path, dtype=np.float64,
mode="w+",
shape=(len(chunk.index), ncol),
order="C")
timing_bin[:, :] = chunk.iloc[:, :]
rows_written += len(chunk.index)
del timing_bin
for chunk in csv_reader:
timing_bin = np.memmap(timing_bin_path, dtype=np.float64,
mode="r+",
shape=(rows_written + len(chunk.index),
ncol),
order="C")
if self.clock_frequency:
chunk = chunk / self.clock_frequency
timing_bin[rows_written:, :] = chunk.iloc[:, :]
rows_written += len(chunk.index)
del timing_bin
with open(timing_bin_shape_path, "w") as f:
writer = csv.writer(f)
writer.writerow(["nrow", "ncol"])
writer.writerow([rows_written, ncol])
if self.verbose:
print("[i] Conversion of the data to binary format done in {:.3}s"
.format(time.time() - start_time))
def load_data(self):
"""Loads data into pandas Dataframe for generating plots and stats."""
self._convert_to_binary()
timing_bin_path = join(self.output, "timing.bin")
legend_csv_path = join(self.output, "legend.csv")
timing_bin_shape_path = join(self.output, "timing.bin.shape")
with open(timing_bin_shape_path, "r") as f:
reader = csv.reader(f)
if next(reader) != ["nrow", "ncol"]:
raise ValueError("Malformed {0} file, delete it and try again"
.format(timing_bin_shape_path))
nrow, ncol = next(reader)
nrow = int(nrow)
ncol = int(ncol)
legend = pd.read_csv(legend_csv_path)
if len(legend.index) != ncol:
raise ValueError("Inconsistent {0} and {1} files, delete and try "
"again".format(legend_csv_path,
timing_bin_shape_path))
columns = list(legend.iloc[:, 1])
timing_bin = np.memmap(timing_bin_path, dtype=np.float64,
mode="r", shape=(nrow, ncol), order="C")
data = pd.DataFrame(timing_bin, columns=columns, copy=False)
if self._bit_size_data_limit:
len_data = len(data)
if not self._bit_size_data_used:
self._bit_size_data_used = min(
len_data, self._bit_size_data_limit
)
start = 0
data_diff = len_data - self._bit_size_data_limit
if data_diff > 0:
start = np.random.randint(0, data_diff)
data = data.iloc[start:start + self._bit_size_data_limit]
else:
if not self._bit_size_data_used:
self._bit_size_data_used = len(data)
return data
@staticmethod
def _box_test(data1, data2, quantile_start, quantile_end):
"""
Internal configurable function to perform the box test.
:param int interval1: index to data representing first sample
:param int interval2: index to data representing second sample
:param float quantile_start: starting quantile of the box
:param float quantile_end: closing quantile of the box
:return: None on no difference, int index of smaller sample if there
is a difference
"""
box1_start, box1_end = np.quantile(data1,
[quantile_start, quantile_end])
box2_start, box2_end = np.quantile(data2,
[quantile_start, quantile_end])
if box1_start == box2_start or box1_end == box2_end:
# can return early because the intervals overlap
return None
intervals = {1: (box1_start, box1_end),
2: (box2_start, box2_end)}
is_smaller = min(box1_start, box2_start) == box1_start
smaller = 1 if is_smaller else 2
bigger = 2 if smaller == 1 else 1
if (intervals[smaller][0] < intervals[bigger][0] and
intervals[smaller][1] < intervals[bigger][0]):
if smaller == 1:
return '<'
else:
return '>'
return None
def box_test(self):
"""Cross-test all classes with the box test"""
if self.verbose:
start_time = time.time()
print("[i] Starting the box_test")
results = self.mt_process(self._box_test, (0.03, 0.04))
if self.verbose:
print("[i] box_test done in {:.3}s".format(time.time()-start_time))
return results
@staticmethod
def _wilcox_test(data1, data2):
return stats.wilcoxon(data1, data2)[1]
def wilcoxon_test(self):
"""Cross-test all classes with the Wilcoxon signed-rank test"""
if self.verbose:
start_time = time.time()
print("[i] Starting Wilcoxon signed-rank test")
ret = self.mt_process(self._wilcox_test)
if self.verbose:
print("[i] Wilcoxon signed-rank test done in {:.3}s".format(
time.time()-start_time))
return ret
@staticmethod
def _rel_t_test(data1, data2):
"""Calculate ttest statistic, return p-value."""
return stats.ttest_rel(data1, data2)[1]
def rel_t_test(self):
"""Cross-test all classes using the t-test for dependent, paired
samples."""
if self.verbose:
start_time = time.time()
print("[i] Starting t-test for dependent, paired samples")
ret = self.mt_process(self._rel_t_test)
if self.verbose:
print("[i] t-test for dependent, paired sample done in {:.3}s"
.format(time.time()-start_time))
return ret
# skip the coverage for this method as it doesn't have conditional
# statements and is tested by mt_process() coverage (we don't see it
# because coverage can't handle multiprocessing)
def _mt_process_runner(self, params): # pragma: no cover
pair, sum_func, args = params
data = self.load_data()
index1, index2 = pair
data1 = data.iloc[:, index1]
data2 = data.iloc[:, index2]
ret = sum_func(data1, data2, *args)
return pair, ret
def mt_process(self, sum_func, args=()):
"""Calculate sum_func values for all pairs of classes in data.
Uses multiprocessing for calculation
sum_func needs to accept two parameters, the values from first
and second sample.
Returns a dictionary with keys being the pairs of values and
values being the returns from the sum_func
"""
comb = list(combinations(list(range(len(self.class_names))), 2))
job_size = max(len(comb) // os.cpu_count(), 1)
with mp.Pool(self.workers) as pool:
pvals = list(pool.imap_unordered(
self._mt_process_runner,
zip(comb, repeat(sum_func), repeat(args)),
job_size))
results = dict(pvals)
return results
@staticmethod
def _sign_test(data1, data2, med, alternative):
diff = data2 - data1
try:
return stats.binomtest(sum(diff < med), sum(diff != med), p=0.5,
alternative=alternative).pvalue
except AttributeError:
return stats.binom_test([sum(diff < med), sum(diff > med)], p=0.5,
alternative=alternative)
def sign_test(self, med=0.0, alternative="two-sided"):
"""
Cross-test all classes using the sign test.
med: expected median value
alternative: the alternative hypothesis, "two-sided" by default,
can be "less" or "greater". If called with "less" and returned
p-value is much smaller than set alpha, then it's likely that the
*second* sample in a pair is bigger than the first one. IOW,
with "less" it tells the probability that second sample is smaller
than the first sample.
"""
if self.verbose:
start_time = time.time()
print("[i] Starting {} sign test".format(alternative))
ret = self.mt_process(self._sign_test, (med, alternative))
if self.verbose:
print("[i] Sign test for {} done in {:.3}s".format(
alternative, time.time()-start_time))
return ret
def friedman_test(self, result):
"""
Test all classes using Friedman chi-square test.
Note, as the scipy stats package uses a chisquare approximation, the
test results are valid only when we have more than 10 samples.
"""
if self.verbose:
start_time = time.time()
print("[i] Starting Friedman test")
data = self.load_data()
if len(self.class_names) < 3:
result.put(None)
return
_, pval = stats.friedmanchisquare(
*(data.iloc[:, i] for i in range(len(self.class_names))))
if self.verbose:
print("[i] Friedman test done in {:.3}s".format(
time.time()-start_time))
result.put(pval)
def _calc_percentiles(self):
data = self.load_data()
try:
quantiles_file_name = join(self.output, ".quantiles.tmp")
shutil.copyfile(join(self.output, "timing.bin"),
quantiles_file_name)
quant_in = np.memmap(quantiles_file_name,
dtype=np.float64,
mode="r+",
shape=data.shape)
percentiles = np.quantile(quant_in,
[0.05, 0.25, 0.5, 0.75, 0.95],
overwrite_input=True,
axis=0)
percentiles = pd.DataFrame(percentiles, columns=list(data),
copy=False)
return percentiles
finally:
del quant_in
os.remove(quantiles_file_name)
def box_plot(self):
"""Generate box plot for the test classes."""
if self.verbose:
start_time = time.time()
print("[i] Generating the box plot")
fig = Figure(figsize=(16, 12))
canvas = FigureCanvas(fig)
ax = fig.add_subplot(1, 1, 1)
data = self.load_data()
# a simpler alternative would use data.boxplot() but that
# copies the data to the mathplot object
# which means it doesn't keep it in a neat array.array, blowing up
# the memory usage significantly
# so calculate the values externally and just provide the computed
# quantiles to the boxplot drawing function
percentiles = self._calc_percentiles()
boxes = []
for name in percentiles:
vals = [i for i in percentiles.loc[:, name]]
boxes += [{'label': name,
'whislo': vals[0],
'q1': vals[1],
'med': vals[2],
'q3': vals[3],
'whishi': vals[4],
'fliers': []}]
ax.bxp(boxes, showfliers=False)
ax.set_xticks(list(range(len(data.columns)+1)))
ax.set_xticklabels([''] + list(range(len(data.columns))))
ax.set_title("Box plot")
ax.set_ylabel("Time")
ax.set_xlabel("Class index")
formatter = mpl.ticker.EngFormatter('s')
ax.get_yaxis().set_major_formatter(formatter)
canvas.print_figure(join(self.output, "box_plot.png"),
bbox_inches="tight")
if self.verbose:
print("[i] Box plot done in {:.3}s".format(time.time()-start_time))
def scatter_plot(self):
"""Generate scatter plot showing how the measurement went."""
if not self.draw_scatter_plot:
return None
if self.verbose:
start_time = time.time()
print("[i] Generating the scatter plots")
data = self.load_data()
fig = Figure(figsize=(16, 12))
canvas = FigureCanvas(fig)
ax = fig.add_subplot(1, 1, 1)
ax.plot(data, ".", fillstyle='none', alpha=0.6)
ax.set_title("Scatter plot")
ax.set_ylabel("Time")
ax.set_xlabel("Sample index")
ax.set_yscale("log")
formatter = mpl.ticker.EngFormatter('s')
ax.get_yaxis().set_major_formatter(formatter)
ax.get_yaxis().set_minor_formatter(formatter)
self.make_legend(ax)
canvas.print_figure(join(self.output, "scatter_plot.png"),
bbox_inches="tight")
quant = np.quantile(data, [0.005, 0.95])
# make sure the quantile point is visible on the graph
quant[0] *= 0.98
quant[1] *= 1.02
ax.set_ylim(quant)
canvas.print_figure(join(self.output, "scatter_plot_zoom_in.png"),
bbox_inches="tight")
if self.verbose:
print("[i] Scatter plots done in {:.3}s".format(
time.time()-start_time))
def diff_scatter_plot(self):
"""Generate scatter plot showing differences between samples."""
if not self.draw_scatter_plot:
return
if self.verbose:
start_time = time.time()
print("[i] Generating scatter plots of differences")
data = self.load_data()
fig = Figure(figsize=(16, 12))
canvas = FigureCanvas(fig)
axes = fig.add_subplot(1, 1, 1)
classnames = iter(data)
base = next(classnames)
base_data = data.loc[:, base]
values = pd.DataFrame()
for ctr, name in enumerate(classnames, start=1):
diff = data.loc[:, name] - base_data
values["{0}-0".format(ctr)] = diff
axes.plot(values, ".", fillstyle='none', alpha=0.6)
axes.set_title("Scatter plot of class differences")
axes.set_ylabel("Time")
axes.set_xlabel("Sample index")
formatter = mpl.ticker.EngFormatter('s')
axes.get_yaxis().set_major_formatter(formatter)
axes.legend(values, ncol=6, loc='upper center',
bbox_to_anchor=(0.5, -0.15))
canvas.print_figure(join(self.output, "diff_scatter_plot.png"),
bbox_inches="tight")
quant = np.quantile(values, [0.25, 0.75])
quant[0] *= 0.98
quant[1] *= 1.02
axes.set_ylim(quant)
canvas.print_figure(join(self.output, "diff_scatter_plot_zoom_in.png"),
bbox_inches="tight")
if self.verbose:
print("[i] scatter plots of differences done in {:.3}s".format(
time.time()-start_time))
def ecdf_plot(self):
"""Generate ECDF plot comparing distributions of the test classes."""
if not self.draw_ecdf_plot:
return None
if self.verbose:
start_time = time.time()
print("[i] Generating ECDF plots")
data = self.load_data()
fig = Figure(figsize=(16, 12))
canvas = FigureCanvas(fig)
ax = fig.add_subplot(1, 1, 1)
for classname in data:
values = data.loc[:, classname]
values = np.sort(values)
# provide only enough data points to plot a smooth graph
nbins = 16 * fig.dpi * 10
values = values[::max(len(values) // int(nbins), 1)]
levels = np.linspace(1. / len(values), 1, len(values))
ax.step(values, levels, where='post')
self.make_legend(ax)
ax.set_title("Empirical Cumulative Distribution Function")
ax.set_xlabel("Time")
ax.set_ylabel("Cumulative probability")
formatter = mpl.ticker.EngFormatter('s')
ax.get_xaxis().set_major_formatter(formatter)
canvas.print_figure(join(self.output, "ecdf_plot.png"),
bbox_inches="tight")
quant = np.quantile(values, [0.01, 0.95])
quant[0] *= 0.98
quant[1] *= 1.02
ax.set_xlim(quant)
canvas.print_figure(join(self.output, "ecdf_plot_zoom_in.png"),
bbox_inches="tight")
if self.verbose:
print("[i] ECDF plots done in {:.3}s".format(
time.time()-start_time))
def diff_ecdf_plot(self):
"""Generate ECDF plot of differences between test classes."""
if not self.draw_ecdf_plot:
return
if self.verbose:
start_time = time.time()
print("[i] Generating ECDF plots of differences")
data = self.load_data()
classnames = iter(data)
base = next(classnames)
base_data = data.loc[:, base]
# parameters for the zoomed-in graphs of ecdf
zoom_params = OrderedDict([("", (0, 1)),
("98", (0.01, 0.99)),
("33", (0.33, 0.66)),
("10", (0.45, 0.55))])
zoom_values = OrderedDict((name, [float("inf"), float("-inf")])
for name in zoom_params.keys())
# calculate the params for ECDF graphs
for classname in classnames:
values = data.loc[:, classname]
values = values-base_data
quantiles = np.quantile(values, list(chain(*zoom_params.values())))
quantiles = iter(quantiles)
for low, high, name in \
zip(quantiles, quantiles, zoom_params.keys()):
zoom_values[name][0] = min(zoom_values[name][0], low)
zoom_values[name][1] = max(zoom_values[name][1], high)
for name, quantiles, zoom_val in \
zip(zoom_params.keys(), zoom_params.values(),
zoom_values.values()):
fig = Figure(figsize=(16, 12))
canvas = FigureCanvas(fig)
axes = fig.add_subplot(1, 1, 1)
# rewind the iterator
classnames = iter(data)
next(classnames)
for classname in classnames:
# calculate the ECDF
values = data.loc[:, classname]
values = np.sort(values-base_data)
# provide only enough data points to plot a smooth graph
nbins = 16 * fig.dpi
min_pos = int(len(values) * quantiles[0])
max_pos = int(math.ceil(len(values) * quantiles[1]))
values = values[min_pos:max_pos:
max((max_pos-min_pos) // int(nbins), 1)]
levels = np.linspace(quantiles[0], quantiles[1],
len(values))
axes.step(values, levels, where='post')
fig.legend(list("{0}-0".format(i)
for i in range(1, len(list(values)))),
ncol=6,
loc='upper center',
bbox_to_anchor=(0.5, -0.05))
axes.set_title("Empirical Cumulative Distribution Function of "
"class differences")
axes.set_xlabel("Time")
axes.set_ylabel("Cumulative probability")
formatter = mpl.ticker.EngFormatter('s')
axes.get_xaxis().set_major_formatter(formatter)
if not name:
canvas.print_figure(join(self.output, "diff_ecdf_plot.png"),
bbox_inches="tight")
else:
axes.set_ylim(quantiles)
# make the bounds a little weaker so that the extreme positions
# are visible of graph too
axes.set_xlim([zoom_val[0]*0.98, zoom_val[1]*1.02])
canvas.print_figure(join(self.output,
"diff_ecdf_plot_zoom_in_{0}.png"
.format(name)),
bbox_inches="tight")
if self.verbose:
print("[i] ECDF plots of differences done in {:.3}s".format(
time.time()-start_time))
def make_legend(self, fig):
"""Generate common legend for plots that need it."""
data = self.load_data()
header = list(range(len(list(data))))
fig.legend(header,
ncol=6,
loc='upper center',
bbox_to_anchor=(0.5, -0.15)
)
@staticmethod
def _cent_tend_of_random_sample(reps=100):
"""
Calculate mean, median, trimmed means (5%, 25%, 45%) and trimean with
bootstrapping.
"""
ret = []
global _diffs
diffs = _diffs
for _ in range(reps):
boot = np.random.choice(diffs, replace=True, size=len(diffs))
q1, median, q3 = np.quantile(boot, [0.25, 0.5, 0.75])
# use tuple instead of a dict because tuples are much quicker
# to instantiate
ret.append((np.mean(boot, 0),
median,
stats.trim_mean(boot, 0.05, 0),
stats.trim_mean(boot, 0.25, 0),
stats.trim_mean(boot, 0.45, 0),
(q1+2*median+q3)/4))
return ret
@staticmethod
def _import_diffs(diffs):
global _diffs
_diffs = diffs
def _bootstrap_differences(self, pair, reps=5000, status=None):
"""Return a list of bootstrapped central tendencies of differences."""
# don't pickle the diffs as they are read-only, use a global to pass
# it to workers
global _diffs
# because the samples are not independent, we calculate mean of
# differences not a difference of means
data = self.load_data()
index1, index2 = pair
_diffs = data.iloc[:, index2] -\
data.iloc[:, index1]
job_count = os.cpu_count() * 4
job_size = max(reps // job_count, 1)
keys = ("mean", "median", "trim_mean_05", "trim_mean_25",
"trim_mean_45", "trimean")
ret = dict((k, list()) for k in keys)
with mp.Pool(self.workers, initializer=self._import_diffs,
initargs=(_diffs,)) as pool:
cent_tend = pool.imap_unordered(
self._cent_tend_of_random_sample,
chain(repeat(job_size, reps // job_size), [reps % job_size]))
for values in cent_tend:
# handle reps % job_size == 0
if not values:
continue
if status:
status[0] += len(values)
# transpose the results so that they can be added to lists
chunk = list(map(list, zip(*values)))
for key, i in zip(keys, range(len(keys))):
ret[key].extend(chunk[i])
_diffs = None
return ret
def _calc_exact_values(self, diff):
mean = np.mean(diff)
q1, median, q3 = np.quantile(diff, [0.25, 0.5, 0.75])
trim_mean_05 = stats.trim_mean(diff, 0.05, 0)
trim_mean_25 = stats.trim_mean(diff, 0.25, 0)
trim_mean_45 = stats.trim_mean(diff, 0.45, 0)
trimean = (q1 + 2*median + q3)/4
return {"mean": mean, "median": median,
"trim_mean_05": trim_mean_05,
"trim_mean_25": trim_mean_25,
"trim_mean_45": trim_mean_45,
"trimean": trimean}
def calc_diff_conf_int(self, pair, reps=5000, ci=0.95):
"""
Bootstrap a confidence interval for the central tendencies of
differences.
:param TestPair pair: identification of samples to calculate the
confidence interval
:param int reps: how many bootstraping repetitions to perform
:param float ci: confidence interval for the low and high estimate.
0.95, i.e. "2 sigma", by default
:return: dictionary of tuples with low estimate, estimate, and high
estimate of mean, median, trimmed mean (5%, 25%, 45%) and trimean
of differences of observations
"""
status = None
if self.verbose:
start_time = time.time()
print("[i] Calculating confidence intervals of central tendencies")
status = [0, reps, Event()]
kwargs = {}
kwargs['unit'] = ' bootstraps'
kwargs['delay'] = self.delay
kwargs['end'] = self.carriage_return
progress = Thread(target=progress_report, args=(status,),
kwargs=kwargs)
progress.start()
try:
cent_tend = self._bootstrap_differences(pair, reps, status=status)
finally:
if self.verbose:
status[2].set()
progress.join()
print()
data = self.load_data()
diff = data.iloc[:, pair[1]] - data.iloc[:, pair[0]]
exact_values = self._calc_exact_values(diff)
quantiles = [(1-ci)/2, 1-(1-ci)/2]
ret = {}
for key, value in exact_values.items():
calc_quant = np.quantile(cent_tend[key], quantiles)
ret[key] = (calc_quant[0], value, calc_quant[1])
if self.verbose:
print("[i] Confidence intervals of central tendencies done in "
"{:.3}s".format(time.time()-start_time))
return ret
def conf_interval_plot(self):
"""Generate the confidence inteval for differences between samples."""
if not self.draw_conf_interval_plot:
return
if self.verbose:
start_time = time.time()
print("[i] Graphing confidence interval plots")
reps = 5000
boots = {"mean": pd.DataFrame(),
"median": pd.DataFrame(),
"trim mean (5%)": pd.DataFrame(),
"trim mean (25%)": pd.DataFrame(),
"trim mean (45%)": pd.DataFrame(),
"trimean": pd.DataFrame()}
status = None
if self.verbose:
status = [0, reps * (len(self.class_names) - 1), Event()]
kwargs = {}