-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathread.py
More file actions
1794 lines (1464 loc) · 62.1 KB
/
read.py
File metadata and controls
1794 lines (1464 loc) · 62.1 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
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
from logging import error
import struct
import numpy as np
import pandas as pd
import os
import seaborn as sns
import matplotlib.pyplot as plt
import re
import argparse
# v3 = {'version' : 24}
acum_status_array = 16 * [0]
# Global setting to control whether plots are shown
SHOW_PLOTS = True
def read_struct(fileContent, repetition_idx: int, struct_size: int, offset: int):
measured = {}
struct_idx = offset + (repetition_idx * struct_size)
head = struct_idx
print("Start reading at Byte:", head)
# Read Position
next = head + 8
x_cord = struct.unpack("d", fileContent[head:next])[0]
measured["x-cord"] = x_cord
head = next
next = head + 8
y_cord = struct.unpack("d", fileContent[head:next])[0]
measured["y-cord"] = y_cord
head = next
next = head + 8
z_cord = struct.unpack("d", fileContent[head:next])[0]
measured["z-cord"] = z_cord
# Read Position Index
head = next
next = head + 4
x_idx = struct.unpack("i", fileContent[head:next])[0]
measured["x-idx"] = x_idx
head = next
next = head + 4
y_idx = struct.unpack("i", fileContent[head:next])[0]
measured["y-idx"] = y_idx
head = next
next = head + 4
z_idx = struct.unpack("i", fileContent[head:next])[0]
measured["z-idx"] = z_idx
# Read Voltage Level
head = next
next = head + 4
voltage_level = struct.unpack("i", fileContent[head:next])[0]
measured["v-level"] = voltage_level
# Read Polarity
head = next
next = head + 1
polarity = struct.unpack("B", fileContent[head:next])[0]
measured["polarity"] = polarity
# Read Coil Type based on submitted Info
head = next
next = head + 1
coil_sel = struct.unpack("B", fileContent[head:next])[0]
measured["coil-type-in"] = coil_sel
# Read Plaintext based on submitted Info
head = next
next = head + 16
input = struct.unpack(16 * "B", fileContent[head:next])
input_hex = "0x"
for i in input:
input_hex += f"{i:02x}"
measured["plain-in"] = input_hex
print(measured["plain-in"])
# Read Ciphertext
head = next
next = head + 16
cipher_output = struct.unpack(16 * "B", fileContent[head:next])
cipher_output_hex = "0x"
for i in cipher_output:
cipher_output_hex += f"{i:02x}"
measured["ctxt"] = cipher_output_hex
print(measured["ctxt"])
# Read Plaintext based on received Info
head = next
next = head + 16
plain_output = struct.unpack(16 * "B", fileContent[head:next])
plain_output_hex = ""
for i in plain_output:
plain_output_hex = f"{i:02x}" + plain_output_hex
plain_output_hex = "0x" + plain_output_hex
measured["plain-out"] = plain_output_hex
print(measured["plain-out"])
# Read Status based on received Info
head = next
next = head + 16
status_output = struct.unpack(16 * "B", fileContent[head:next])
status_output_hex = []
for i in status_output:
status_output_hex.append(hex(i))
for i in range(0, 16):
print(i, "\t", status_output_hex[i])
acum_status_array[i] = acum_status_array[i] | status_output[i]
print(acum_status_array)
# coils_lvt = {}
# coils_mvt = {}
# coils_hvt = {}
# M2_1,
# M4_1,
# M4_2,
# M4_3,
# M4_5,
# M7_1,
# M7_2,
# M7_3,
# M7_4,
# M7_5,
# M7_6,
# measured["coils-lvt-c10"]= (status_output[0] & 0b10000000) >> 7
# measured["coils-lvt-c9"] = (status_output[0] & 0b01000000) >> 6
# measured["coils-lvt-c8"] = (status_output[0] & 0b00100000) >> 5
# measured["coils-lvt-c7"] = (status_output[0] & 0b00010000) >> 4
# measured["coils-lvt-c6"] = (status_output[0] & 0b00001000) >> 3
# measured["coils-lvt-c5"] = (status_output[0] & 0b00000100) >> 2
# measured["coils-lvt-c4"] = (status_output[0] & 0b00000010) >> 1
# measured["coils-lvt-c3"] = (status_output[0] & 0b00000001) >> 0
# measured["coils-lvt-c2"] = (status_output[1] & 0b10000000) >> 7
# measured["coils-lvt-c1"] = (status_output[1] & 0b01000000) >> 6
# measured["coils-lvt-c0"] = (status_output[1] & 0b00100000) >> 5
# measured["coils-std-c6"] = (status_output[1] & 0b00000001) >> 0
# measured["coils-std-c5"] = (status_output[2] & 0b10000000) >> 7
# measured["coils-std-c4"] = (status_output[2] & 0b01000000) >> 6
# measured["coils-std-c3"] = (status_output[2] & 0b00100000) >> 5
# measured["coils-std-c2"] = (status_output[2] & 0b00010000) >> 4
# measured["coils-std-c1"] = (status_output[2] & 0b00001000) >> 3
# measured["coils-std-c0"] = (status_output[2] & 0b00000100) >> 2
# measured["coils-std-c10"]= (status_output[1] & 0b00010000) >> 4
# measured["coils-std-c9"] = (status_output[1] & 0b00001000) >> 3
# measured["coils-std-c8"] = (status_output[1] & 0b00000100) >> 2
# measured["coils-std-c7"] = (status_output[1] & 0b00000010) >> 1
# measured["coils-hvt-c10"]= (status_output[2] & 0b00000010) >> 1
# measured["coils-hvt-c9"] = (status_output[2] & 0b00000001) >> 0
# measured["coils-hvt-c8"] = (status_output[3] & 0b10000000) >> 7
# measured["coils-hvt-c7"] = (status_output[3] & 0b01000000) >> 6
# measured["coils-hvt-c6"] = (status_output[3] & 0b00100000) >> 5
# measured["coils-hvt-c5"] = (status_output[3] & 0b00010000) >> 4
# measured["coils-hvt-c4"] = (status_output[3] & 0b00001000) >> 3
# measured["coils-hvt-c3"] = (status_output[3] & 0b00000100) >> 2
# measured["coils-hvt-c2"] = (status_output[3] & 0b00000010) >> 1
# measured["coils-hvt-c1"] = (status_output[3] & 0b00000001) >> 0
# measured["coils-hvt-c0"] = (status_output[4] & 0b10000000) >> 7
# reg (original): |c10|c9|c8|c7|c6|c5|c4|c3 | c2|c1|c0
#
# reg (correct) : | c6|c5|c4|c3|c2|c1|c0|c10| c9|c8|c7
measured["coils-lvt-c6"] = (status_output[0] >> 7) & 0b1
measured["coils-lvt-c5"] = (status_output[0] >> 6) & 0b1
measured["coils-lvt-c4"] = (status_output[0] >> 5) & 0b1
measured["coils-lvt-c3"] = (status_output[0] >> 4) & 0b1
measured["coils-lvt-c2"] = (status_output[0] >> 3) & 0b1
measured["coils-lvt-c1"] = (status_output[0] >> 2) & 0b1
measured["coils-lvt-c0"] = (status_output[0] >> 1) & 0b1
measured["coils-lvt-c10"] = (status_output[0] >> 0) & 0b1
measured["coils-lvt-c9"] = (status_output[1] >> 7) & 0b1
measured["coils-lvt-c8"] = (status_output[1] >> 6) & 0b1
measured["coils-lvt-c7"] = (status_output[1] >> 5) & 0b1
measured["coils-std-c6"] = (status_output[1] >> 4) & 0b1
measured["coils-std-c5"] = (status_output[1] >> 3) & 0b1
measured["coils-std-c4"] = (status_output[1] >> 2) & 0b1
measured["coils-std-c3"] = (status_output[1] >> 1) & 0b1
measured["coils-std-c2"] = (status_output[1] >> 0) & 0b1
measured["coils-std-c1"] = (status_output[2] >> 7) & 0b1
measured["coils-std-c0"] = (status_output[2] >> 6) & 0b1
measured["coils-std-c10"] = (status_output[2] >> 5) & 0b1
measured["coils-std-c9"] = (status_output[2] >> 4) & 0b1
measured["coils-std-c8"] = (status_output[2] >> 3) & 0b1
measured["coils-std-c7"] = (status_output[2] >> 2) & 0b1
measured["coils-hvt-c6"] = (status_output[2] >> 1) & 0b1
measured["coils-hvt-c5"] = (status_output[2] >> 0) & 0b1
measured["coils-hvt-c4"] = (status_output[3] >> 7) & 0b1
measured["coils-hvt-c3"] = (status_output[3] >> 6) & 0b1
measured["coils-hvt-c2"] = (status_output[3] >> 5) & 0b1
measured["coils-hvt-c1"] = (status_output[3] >> 4) & 0b1
measured["coils-hvt-c0"] = (status_output[3] >> 3) & 0b1
measured["coils-hvt-c10"] = (status_output[3] >> 2) & 0b1
measured["coils-hvt-c9"] = (status_output[3] >> 1) & 0b1
measured["coils-hvt-c8"] = (status_output[3] >> 0) & 0b1
measured["coils-hvt-c7"] = (status_output[4] >> 7) & 0b1
for i in range(0, 7):
if (status_output[4] >> i) & 0x1 == 1:
print(f"At bit position {i} in byte 4 an unexpected 1 was found")
return -1
# coils = {}
# coils["hvt"] = coils_hvt
# coils["mvt"] = coils_mvt
# coils["lvt"] = coils_lvt
# measured["coils"] = coils
measured["coil-type-out"] = status_output[8]
version = status_output[10] >> 3
measured["version"] = version
# The Pinout is exposed through Byte 10 and 11.
# Byte 11 is solely related to coils, while only 3 bit (the lsb) of Byte 10
# are related to the coils.
# coils_pinout = {}
measured["coils-pinout-c10"] = (status_output[10] & 0b00000100) >> 2
measured["coils-pinout-c9"] = (status_output[10] & 0b00000010) >> 1
measured["coils-pinout-c8"] = (status_output[10] & 0b00000001) >> 0
measured["coils-pinout-c7"] = (status_output[11] & 0b10000000) >> 7
measured["coils-pinout-c6"] = (status_output[11] & 0b01000000) >> 6
measured["coils-pinout-c5"] = (status_output[11] & 0b00100000) >> 5
measured["coils-pinout-c4"] = (status_output[11] & 0b00010000) >> 4
measured["coils-pinout-c3"] = (status_output[11] & 0b00001000) >> 3
measured["coils-pinout-c2"] = (status_output[11] & 0b00000100) >> 2
measured["coils-pinout-c1"] = (status_output[11] & 0b00000010) >> 1
measured["coils-pinout-c0"] = (status_output[11] & 0b00000001) >> 0
# measured["coils-pout"] = coils_pinout
measured["check-sum"] = (
(status_output[12] << 16) | (status_output[13] << 8) | status_output[14]
)
# print("Check sum: ", hex(measured["check-sum"]>>3)) # must be shifted for 1co5ef
measured["timeout"] = status_output[15]
head = next
next = head + 2
# NOTE: Why do I have here pinout again?
# Do I process it in c++ already?
# NOTE: For now I am going to ignore that
coil_pinout = struct.unpack("BB", fileContent[head:next])
coil_pinout_hex = [coil_pinout[1], coil_pinout[0]]
head = next
next = head + 1
hasResponse = struct.unpack("B", fileContent[head:next])[0]
measured["has-response"] = hasResponse
# I think this is the place holder for the number of entries in a file thing
# which is only used once per file in the beginning.
# head = next
# next = head+3
# padding = struct.unpack(3*"B", fileContent[head:next])
DEBUG = 0
if DEBUG == 1:
print("\nX Position: ", x_cord)
print("y Position: ", y_cord)
print("z Position: ", z_cord)
print("X Idx: ", x_idx)
print("y Idy: ", y_idx)
print("z Idz: ", z_idx)
print("Voltage Level: ", voltage_level)
print("Polarity: ", polarity)
print("Input: ", input)
print("hex(Input): ", input_hex)
print("cipher_output: ", cipher_output)
print("hex(cipher_output): ", cipher_output_hex)
print("plain_output: ", plain_output)
print("hex(plain_output): ", plain_output_hex)
print("status_output: ", status_output)
print("hex(status_output): ", status_output_hex)
print("coil_pinout:", coil_pinout)
print("coil_pinout_hex :", coil_pinout_hex)
print("Was response received (0:Yes, -1:No): ", hasResponse)
print(measured)
return measured
def read_all_structs_in_file(
start_byte_idx: int,
struct_size: int,
num_measurments,
low_jitter_delay,
fileContent,
):
measurments = []
for i in range(0, num_measurments):
print("\n")
measured = read_struct(fileContent, i, struct_size, start_byte_idx)
measured["rep-idx"] = i
measured["low-jitter-delay"] = low_jitter_delay
measurments.append(measured)
print("\n")
return measurments
def process_file(file_path):
with open(file_path, mode="rb") as file:
fileContent = file.read()
# Extract the number after "LJD" and before ".dat" from the file_path
pattern = re.compile(r"LJD(\d+)\.dat")
match = pattern.search(file_path)
low_jitter_delay = 0
if match:
low_jitter_delay = match.group(1)
print(f"Extracted LJD number from file {file_path}: {low_jitter_delay }")
else:
print(f"No LJD number found in file {file_path}")
num_measurments = struct.unpack("i", fileContent[:4])[0]
print(f"Number of measurements in file {file_path}: {num_measurments}")
start_byte_idx = 4
struct_size = 0x70
print("\n\n\n")
measurements = read_all_structs_in_file(
start_byte_idx, struct_size, num_measurments, low_jitter_delay, fileContent
)
print("\n\n\n")
return measurements
def process_directory(root_dir):
all_measurements = []
for dirpath, _, filenames in os.walk(root_dir):
for filename in filenames:
if filename.endswith(".dat"): # Check if the file is a .dat file
file_path = os.path.join(dirpath, filename)
print("Parsing ", file_path)
measurements = process_file(file_path)
all_measurements.extend(measurements)
return all_measurements
def invert_x_idx(max_x_idx, x_idx):
return max_x_idx - x_idx
# Function to perform XOR operation
def xor_binary_strings(binary_str1, binary_str2):
# Convert binary strings to integers
int1 = int(binary_str1, 2)
int2 = int(binary_str2, 2)
# Perform XOR
xor_result = int1 ^ int2
# Convert the result back to a binary string, removing the '0b' prefix
return bin(xor_result)[2:].zfill(max(len(binary_str1), len(binary_str2)))
def check_detection_reg(row):
columns_to_check = [
"coils-hvt-c10",
"coils-hvt-c9",
"coils-hvt-c8",
"coils-hvt-c7",
"coils-hvt-c6",
"coils-hvt-c5",
"coils-hvt-c4",
"coils-hvt-c3",
"coils-hvt-c2",
"coils-hvt-c1",
"coils-hvt-c0",
"coils-std-c10",
"coils-std-c9",
"coils-std-c8",
"coils-std-c7",
"coils-std-c6",
"coils-std-c5",
"coils-std-c4",
"coils-std-c3",
"coils-std-c2",
"coils-std-c1",
"coils-std-c0",
"coils-lvt-c10",
"coils-lvt-c9",
"coils-lvt-c8",
"coils-lvt-c7",
"coils-lvt-c6",
"coils-lvt-c5",
"coils-lvt-c4",
"coils-lvt-c3",
"coils-lvt-c2",
"coils-lvt-c1",
"coils-lvt-c0",
]
if any(row[col] == 1 for col in columns_to_check):
return "Detected"
else:
return "Undetected"
def check_detection_pin(row):
columns_to_check = [
"coils-pinout-c10",
"coils-pinout-c9",
"coils-pinout-c8",
"coils-pinout-c7",
"coils-pinout-c6",
"coils-pinout-c5",
"coils-pinout-c4",
"coils-pinout-c3",
"coils-pinout-c2",
"coils-pinout-c1",
"coils-pinout-c0",
]
if any(row[col] == 1 for col in columns_to_check):
return "Detected"
else:
return "Undetected"
def detect_corrupted_plaintext_register(df: pd.DataFrame):
print("Checking if a plaintext was corrupted in the input register...")
df["ptx-corrupted"] = np.where(df["plain-in"] == df["plain-out"], 0, 1)
def detect_faulted_ciphertext_computetation(df: pd.DataFrame):
print("Checking if encryption was corrupted...")
df["ctx-computation-faulted"] = np.where(
df["ctxt"] == "0x3925841d02dc09fbdc118597196a0b32", 0, 1
)
def detect_if_coils_observed_emfi(df: pd.DataFrame):
print("Checking if coils detected emfi...")
df["coil-reg-detection"] = df.apply(check_detection_reg, axis=1)
df["coil-pin-detection"] = df.apply(check_detection_pin, axis=1)
def preprocessing(df: pd.DataFrame, clean, results_dir, experiment_directory):
preprocessed_df_cache_file = (
results_dir + "/" + experiment_directory + "/" + "dataframe_preprocessed"
)
if not clean:
try:
cached = os.path.exists(preprocessed_df_cache_file + ".parquet")
cached = cached and os.path.exists(preprocessed_df_cache_file + ".csv")
if cached:
print("[*] Reading preprocessed data frame...")
df = pd.read_parquet(
preprocessed_df_cache_file + ".parquet", engine="pyarrow"
)
else:
clean = True
except Exception as e:
print(f"Error reading cache files: {e}")
clean = True # Force recomputation if reading fails
if clean:
print("Invert x-idx for y-idx%2==1 ...")
max_x_idx = df["x-idx"].max()
max_y_idx = df["y-idx"].max()
df.loc[df["y-idx"] % 2 == 1, "x-idx"] = df.loc[
df["y-idx"] % 2 == 1, "x-idx"
].apply(lambda x: invert_x_idx(max_x_idx, x))
print("Rotate ...")
df["x-idx"] = max_x_idx - df["x-idx"]
df["y-idx"] = max_y_idx - df["y-idx"]
detect_corrupted_plaintext_register(df)
detect_faulted_ciphertext_computetation(df)
detect_if_coils_observed_emfi(df)
print("[*] Writing preprocessed data frame...")
df.to_csv(preprocessed_df_cache_file + ".csv")
df.to_parquet(preprocessed_df_cache_file + ".parquet", engine="pyarrow")
print("The keys of preprocessed dataframe are:")
keys = df.columns
print(keys)
print("\n")
return df
def get_number_of_corrupted_plaintext(df: pd.DataFrame):
number_of_corrupterd_plaintext = df["ptx-corrupted"].sum()
print(f"Number of faulted input registers: {number_of_corrupterd_plaintext}\n")
return number_of_corrupterd_plaintext
def get_number_of_corrupted_ciphertext(df: pd.DataFrame):
number_of_corrupted_encryptions = df["ctx-computation-faulted"].sum()
print(f"Number of faulted encryptions: {number_of_corrupted_encryptions}\n")
return number_of_corrupted_encryptions
def get_number_of_coil_detections(df: pd.DataFrame):
detection_reg_count = df["coil-reg-detection"].value_counts().get("Detected", 0)
print("Coil emfi observation count (reg): ", detection_reg_count)
detection_pin_count = df["coil-pin-detection"].value_counts().get("Detected", 0)
print("Coil emfi observation count (pin): ", detection_pin_count)
return detection_reg_count, detection_pin_count
def get_number_of_measurments(df: pd.DataFrame, measurment_type=""):
print("[*] Counting number of measurments" + measurment_type + "...")
num_measurments = df.shape[0]
print("[+] Count: ", num_measurments)
return num_measurments
def get_number_of_measurments_per_position(df: pd.DataFrame):
print("Computing the number of measurments per position...")
pair_counts = df.groupby(["x-idx", "y-idx"]).size().reset_index(name="count")
most_common_count = pair_counts["count"].mode()
num_diff_counts = len(most_common_count)
print("Measurments per position: ")
print(f"{most_common_count[0]} (num dif counts {num_diff_counts})")
return most_common_count[0]
def add_kosef_indicator_to_heatmap(plt, heatmap_data):
# Add the "KOSEF" indicator
rotation_angle = 0
plt.text(
x=heatmap_data.columns.max() + 1,
y=heatmap_data.index.max() + 1,
s="KOSEF",
rotation=rotation_angle,
fontsize=12,
color="black",
)
def compute_voltage_vs_effective_faults_and_timeout_plot(
df: pd.DataFrame, export_table: bool
):
print("Computing count of effective faults per voltage level...")
grouped = df.groupby(["v-level"])["ctx-computation-faulted"].sum().reset_index()
grouped_timeout = df.groupby(["v-level"])["timeout"].sum().reset_index()
grouped.merge(grouped_timeout, on="v-level", how="left")
grouped["ratio"] = grouped["ctx-computation-faulted"] / grouped_timeout["timeout"]
if export_table:
print(grouped)
plt.figure(figsize=(12, 6))
plt.plot(
grouped["v-level"],
grouped["ctx-computation-faulted"],
marker="o",
linestyle="-",
)
plt.title("Plot of ctx-computation-faulted vs v-level")
plt.xlabel("Voltage EM Emitter")
plt.ylabel("Effective Fault Count")
plt.grid(True)
# plt.show()
def compute_low_jitter_delay_vs_faults_effective_and_timeout_plot(
df: pd.DataFrame, export_table: bool
):
print("Computing count of effective fault per low jitter delay...")
grouped_effective_faults = (
df.groupby(["low-jitter-delay"])["ctx-computation-faulted"].sum().reset_index()
)
grouped_timeout = df.groupby(["low-jitter-delay"])["timeout"].sum().reset_index()
grouped = grouped_effective_faults.merge(grouped_timeout, on="low-jitter-delay")
grouped["ratio"] = grouped["timeout"] / grouped["ctx-computation-faulted"]
if export_table:
print(grouped)
plt.figure(figsize=(12, 6))
plt.plot(
grouped_effective_faults["low-jitter-delay"],
grouped_effective_faults["ctx-computation-faulted"],
marker="o",
linestyle="-",
)
plt.xlabel("Low Jitter Delay [ns]")
plt.ylabel("Effective Fault Count")
plt.grid(True)
# plt.show()
def compute_coordinates_detection_heatmap(
df: pd.DataFrame, coil: str, export_dir, id="", clean=False
):
heatmap_data = None
filename = f"detection-heatmap-coil{coil}-id-{id}"
csv_filename = os.path.join(export_dir, f"{filename}.csv")
parquet_filename = os.path.join(export_dir, f"{filename}.parquet")
clean = clean or not os.path.exists(csv_filename)
clean = clean or not os.path.exists(parquet_filename)
if clean:
print("Computing coordinates-detection-heatmap-" + coil + "...")
grouped = df.groupby(["x-idx", "y-idx"])[coil].sum().reset_index()
heatmap_data = grouped.pivot(
index="y-idx", columns="x-idx", values=coil
).fillna(0)
wide_df = heatmap_data.reset_index().melt(
id_vars="y-idx", var_name="x-idx", value_name="value"
)
wide_df = wide_df[["x-idx", "y-idx", "value"]]
wide_df = wide_df.sort_values(by=["y-idx", "x-idx"])
wide_df.to_csv(csv_filename, index=False)
heatmap_data.to_parquet(parquet_filename)
print(f"Exported data for {id} to {csv_filename} and {parquet_filename}")
else:
heatmap_data = pd.read_parquet(parquet_filename, engine="pyarrow")
# Calculate total accumulation
total_accumulation = heatmap_data.sum().sum()
print(f"{coil} has reacted: {total_accumulation} times")
plt.figure(figsize=(10, 10))
sns.heatmap(heatmap_data, annot=True, fmt="g", cmap="viridis")
add_kosef_indicator_to_heatmap(plt, heatmap_data)
plt.title("Heatmap of Detecting Faults " + coil)
plt.xlabel("X Coordinate")
plt.ylabel("Y Coordinate")
# plt.show()
return heatmap_data
def compute_coordinates_detection_heatmap_pinout_based(
df: pd.DataFrame, type_: str, coil: str, export_dir, id="", clean=False, show=False
):
heatmap_data = None
filename = f"detection-heatmap-coil{coil}-{type_}-pinout-based-id-{id}"
csv_filename = os.path.join(export_dir, f"{filename}.csv")
parquet_filename = os.path.join(export_dir, f"{filename}.parquet")
clean = clean or not os.path.exists(csv_filename)
clean = clean or not os.path.exists(parquet_filename)
if clean:
print("Computing coordinates-detection-heatmap-pinout-based" + coil + "...")
cell_type = None
# HVT = 0,
# SVT = 1,
# LVT = 2
if type_ == "lvt":
cell_type = 2
elif type_ == "std":
cell_type = 1
elif type_ == "hvt":
cell_type = 0
else:
print("Wrong cell type")
exit(-1)
df_filtered_by_cell_type = df.loc[df["coil-type-in"] == cell_type]
grouped = (
df_filtered_by_cell_type.groupby(["x-idx", "y-idx"])[coil]
.sum()
.reset_index()
)
heatmap_data = grouped.pivot(
index="y-idx", columns="x-idx", values=coil
).fillna(0)
wide_df = heatmap_data.reset_index().melt(
id_vars="y-idx", var_name="x-idx", value_name="value"
)
wide_df = wide_df[["x-idx", "y-idx", "value"]]
wide_df = wide_df.sort_values(by=["y-idx", "x-idx"])
wide_df.to_csv(csv_filename, index=False)
heatmap_data.to_parquet(parquet_filename)
print(f"Exported data for {id} to {csv_filename} and {parquet_filename}")
else:
heatmap_data = pd.read_parquet(parquet_filename, engine="pyarrow")
# Calculate total accumulation
total_accumulation = heatmap_data.sum().sum()
print(f"{coil} has reacted: {total_accumulation} times")
plt.figure(figsize=(10, 10))
sns.heatmap(heatmap_data, annot=True, fmt="g", cmap="viridis")
add_kosef_indicator_to_heatmap(plt, heatmap_data)
plt.title("Heatmap of Detecting Faults " + coil + type_)
plt.xlabel("X Coordinate")
plt.ylabel("Y Coordinate")
if show == True:
plt.show()
return heatmap_data
def compute_coordinates_effective_faults_heatmap(
df: pd.DataFrame, export_dir, id="", clean=False
):
heatmap_data = None
filename = f"effective-fault-heatmap-id-{id}"
csv_filename = os.path.join(export_dir, f"{filename}.csv")
parquet_filename = os.path.join(export_dir, f"{filename}.parquet")
clean = clean or not os.path.exists(csv_filename)
clean = clean or not os.path.exists(parquet_filename)
if clean:
print("Computing coordinates-effective-faults-heatmap-" + id + "...")
grouped = (
df.groupby(["x-idx", "y-idx"])["ctx-computation-faulted"]
.sum()
.reset_index()
)
# Check if grouped dataframe is empty
if grouped.empty:
print(f"Warning: No data available for {id}, creating empty heatmap")
heatmap_data = pd.DataFrame()
else:
heatmap_data = grouped.pivot(
index="y-idx", columns="x-idx", values="ctx-computation-faulted"
).fillna(0)
# Determine the complete range of x and y indices, converting to int
x_idx_range = range(int(grouped["x-idx"].min()), int(grouped["x-idx"].max()) + 1)
y_idx_range = range(int(grouped["y-idx"].min()), int(grouped["y-idx"].max()) + 1)
print(heatmap_data)
heatmap_data = heatmap_data.reindex(
index=y_idx_range, columns=x_idx_range, fill_value=0
)
print(heatmap_data)
wide_df = heatmap_data.reset_index().melt(
id_vars="y-idx", var_name="x-idx", value_name="value"
)
wide_df = wide_df[["x-idx", "y-idx", "value"]]
wide_df = wide_df.sort_values(by=["y-idx", "x-idx"])
wide_df.to_csv(csv_filename, index=False)
heatmap_data.to_parquet(parquet_filename)
print(f"Exported data for {id} to {csv_filename} and {parquet_filename}")
else:
heatmap_data = pd.read_parquet(parquet_filename, engine="pyarrow")
# Only plot if we have data
if not heatmap_data.empty:
plt.figure(figsize=(10, 10))
sns.heatmap(heatmap_data, annot=True, fmt="g", cmap="viridis")
plt.title("Heatmap of Effective Faults in the Ciphertext " + id)
plt.xlabel("X Coordinate")
plt.ylabel("Y Coordinate")
if SHOW_PLOTS:
plt.show()
else:
print(f"Skipping plot for {id} due to empty data")
def compute_coordinates_timeout_heatmap(
df: pd.DataFrame, export_dir, id="", clean=False
):
heatmap_data = None
filename = f"timeout-heatmap-id-{id}"
csv_filename = os.path.join(export_dir, f"{filename}.csv")
parquet_filename = os.path.join(export_dir, f"{filename}.parquet")
clean = clean or not os.path.exists(csv_filename)
clean = clean or not os.path.exists(parquet_filename)
if clean:
print("Computing coordinates-timeouts-heatmap...")
grouped = df.groupby(["x-idx", "y-idx"])["timeout"].sum().reset_index()
heatmap_data = grouped.pivot(
index="y-idx", columns="x-idx", values="timeout"
).fillna(0)
wide_df = heatmap_data.reset_index().melt(
id_vars="y-idx", var_name="x-idx", value_name="value"
)
wide_df = wide_df[["x-idx", "y-idx", "value"]]
wide_df = wide_df.sort_values(by=["y-idx", "x-idx"])
wide_df.to_csv(csv_filename, index=False)
heatmap_data.to_parquet(parquet_filename)
print(f"Exported data for {id} to {csv_filename} and {parquet_filename}")
else:
heatmap_data = pd.read_parquet(parquet_filename, engine="pyarrow")
plt.figure(figsize=(10, 10))
sns.heatmap(heatmap_data, annot=True, fmt="g", cmap="viridis")
add_kosef_indicator_to_heatmap(plt, heatmap_data)
plt.title("Heatmap of Timeouts")
plt.xlabel("X Coordinate")
plt.ylabel("Y Coordinate")
if SHOW_PLOTS:
plt.show()
def compute_coordinates_effective_faults_timeout_ratio_heatmap(df: pd.DataFrame):
print("Computing coordinates-effective-faults-timeout-ratio-heatmap...")
# Group by x-idx and y-idx and sum both columns at once
grouped = (
df.groupby(["x-idx", "y-idx"])
.agg({"ctx-computation-faulted": "sum", "timeout": "sum"})
.reset_index()
)
# Compute the ratio
grouped["q"] = grouped["ctx-computation-faulted"] / grouped["timeout"]
# Fill NaN values (which occur when ctx-computation-faulted is 0)
grouped["q"] = grouped["q"].fillna(0)
# Find the maximum 'q' excluding infinity
max_q = grouped["q"][~np.isinf(grouped["q"])].max()
max_q_value = max_q.item() if pd.notna(max_q) else 0
print(f"The maximum 'q' excluding infinity is: {max_q}")
heatmap_data = grouped.pivot(index="y-idx", columns="x-idx", values="q").fillna(0)
vmin = 0
vmax = max_q_value
plt.figure(figsize=(10, 10))
sns.heatmap(heatmap_data, annot=True, fmt="g", cmap="viridis", vmin=vmin, vmax=vmax)
plt.title("Heatmap of Effective Faults / Timeout Ratio for Coordinates")
plt.xlabel("X Coordinate")
plt.ylabel("Y Coordinate")
# plt.show()
def compute_voltage_low_jitter_delay_effective_faults_timeout_ratio_heatmap(
df: pd.DataFrame,
):
print(
"Computing voltage-low-jitter-delay-effective-faults-timeout-ratio-heatmap..."
)
# Group by x-idx and y-idx and sum both columns at once
grouped = (
df.groupby(["v-level", "low-jitter-delay"])
.agg({"ctx-computation-faulted": "sum", "timeout": "sum"})
.reset_index()
)
# Compute the ratio
grouped["q"] = grouped["ctx-computation-faulted"] / grouped["timeout"]
# Fill NaN values (which occur when ctx-computation-faulted is 0)
grouped["q"] = grouped["q"].fillna(0)
heatmap_data = grouped.pivot(
index="v-level", columns="low-jitter-delay", values="q"
).fillna(0)
vmin = 0
vmax = 50
plt.figure(figsize=(10, 10))
sns.heatmap(heatmap_data, annot=True, fmt="g", cmap="viridis", vmin=vmin, vmax=vmax)
plt.title(
"Heatmap of Effective Faults / Timeout Ratio for Voltage and Low Jitter Delay"
)
plt.xlabel("Low Jitter Delay")
plt.ylabel("Voltage")
# plt.show()
def compute_voltage_low_jitter_delay_effective_faults_heatmap(
df: pd.DataFrame, export_dir, id="", clean=False
):
filename = f"voltage-vs-low-jitter-delay-effective-faults-heatmap-{id}"
csv_filename = os.path.join(export_dir, f"{filename}.csv")
parquet_filename = os.path.join(export_dir, f"{filename}-.parquet")
clean = clean or not os.path.exists(csv_filename)
clean = clean or not os.path.exists(parquet_filename)
if clean:
print("Computing voltage-low-jitter-effective-faults-heatmap" + id + "...")
grouped = (
df.groupby(["v-level", "low-jitter-delay"])["ctx-computation-faulted"]
.sum()
.reset_index()
)
# Check if grouped dataframe is empty
if grouped.empty:
print(f"Warning: No data available for {id}, creating empty heatmap")
x_idx_range = [15, 20, 25, 30, 35]
y_idx_range = range(50, 510, 10)
heatmap_data = pd.DataFrame(0, index=y_idx_range, columns=x_idx_range)
else:
heatmap_data = grouped.pivot(
index="v-level",
columns="low-jitter-delay",
values="ctx-computation-faulted",
).fillna(0)
x_idx_range = [15, 20, 25, 30, 35]
y_idx_range = range(50, 510, 10)
heatmap_data.columns = heatmap_data.columns.astype(int)
print(heatmap_data)
heatmap_data = heatmap_data.reindex(
index=y_idx_range, columns=x_idx_range, fill_value=0
)
print(heatmap_data)
wide_df = heatmap_data.reset_index().melt(
id_vars="v-level", var_name="low-jitter-delay", value_name="value"
)
wide_df = wide_df[["v-level", "low-jitter-delay", "value"]]
wide_df = wide_df.sort_values(by=["low-jitter-delay", "v-level"])
wide_df.to_csv(csv_filename, index=False)
heatmap_data.to_parquet(parquet_filename)
print(f"Exported data for {id} to {csv_filename} and {parquet_filename}")
else:
heatmap_data = pd.read_parquet(parquet_filename, engine="pyarrow")
plt.figure(figsize=(10, 10))
sns.heatmap(heatmap_data, annot=True, fmt="g", cmap="viridis")
plt.title("Heatmap of Effective Faults in the Ciphertext " + id)
plt.xlabel("Low Jiiter Delay")
plt.ylabel("Voltage")
if SHOW_PLOTS:
plt.show()
def compute_voltage_low_jitter_delay_timeout_heatmap(
df: pd.DataFrame, export_dir, id="", clean=False
):
filename = f"voltage-vs-low-jitter-delay-timeout-heatmap-{id}"
csv_filename = os.path.join(export_dir, f"{filename}.csv")
parquet_filename = os.path.join(export_dir, f"{filename}.parquet")
clean = clean or not os.path.exists(csv_filename)
clean = clean or not os.path.exists(parquet_filename)
if clean:
print("Computing voltage-low-jitter-timeouts-heatmap...")
grouped = (
df.groupby(["v-level", "low-jitter-delay"])["timeout"].sum().reset_index()
)
heatmap_data = grouped.pivot(
index="v-level", columns="low-jitter-delay", values="timeout"
).fillna(0)
# Define the complete range of indices
v_level_range = range(50, 501, 10) # From 50 to 500 in steps of 10
low_jitter_delay_range = [15, 20, 25, 30, 35]
# Reindex the heatmap_data to include all combinations of v-level and low-jitter-delay indices
heatmap_data = heatmap_data.reindex(
index=v_level_range, columns=low_jitter_delay_range, fill_value=0
)
wide_df = heatmap_data.reset_index().melt(
id_vars="v-level", var_name="low-jitter-delay", value_name="value"
)
wide_df.to_csv(csv_filename, index=False)
heatmap_data.to_parquet(parquet_filename)
print(f"Exported data for {id} to {csv_filename} and {parquet_filename}")
else:
heatmap_data = pd.read_parquet(parquet_filename, engine="pyarrow")
plt.figure(figsize=(10, 10))
sns.heatmap(heatmap_data, annot=True, fmt="g", cmap="viridis")
plt.title("Heatmap of Timeouts")
plt.xlabel("Low Jitter Delay")
plt.ylabel("Voltage")
# plt.show()
def compute_no_detection_reg_but_effective_fault_cases(