-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaether.py
More file actions
1415 lines (1357 loc) · 65.1 KB
/
aether.py
File metadata and controls
1415 lines (1357 loc) · 65.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
#!/usr/bin/env python3
"""
Hashcat Rule Performance Benchmark Tool with Advanced Visualizations
Full rule support: implements all Hashcat transformations, reject rules, etc.
"""
import pyopencl as cl
import numpy as np
import time
import os
import json
import argparse
from pathlib import Path
from typing import List, Dict, Tuple, Any
import sys
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from datetime import datetime
# Color codes for terminal output
class Colors:
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
MAGENTA = '\033[95m'
CYAN = '\033[96m'
WHITE = '\033[97m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
# Visualization styles
plt.style.use('seaborn-v0_8')
sns.set_palette("husl")
# ============================================================================
# COMPLETE HASHCAT RULE ENGINE KERNEL
# ============================================================================
OPENCL_KERNEL_SOURCE = """
#define MAX_WORD_LEN 256
#define MAX_RULE_LEN 16
#define MAX_OUTPUT_LEN 512
int is_lower(uchar c) {
return (c >= 'a' && c <= 'z');
}
int is_upper(uchar c) {
return (c >= 'A' && c <= 'Z');
}
int is_digit(uchar c) {
return (c >= '0' && c <= '9');
}
int is_alnum(uchar c) {
return is_lower(c) || is_upper(c) || is_digit(c);
}
uchar toggle_case(uchar c) {
if (is_lower(c)) return c - 32;
if (is_upper(c)) return c + 32;
return c;
}
uchar to_lower(uchar c) {
if (is_upper(c)) return c + 32;
return c;
}
uchar to_upper(uchar c) {
if (is_lower(c)) return c - 32;
return c;
}
int parse_position(uchar c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'A' && c <= 'Z') return c - 'A' + 10;
if (c >= 'a' && c <= 'z') return c - 'a' + 10;
return 0;
}
int count_char(const uchar* str, int len, uchar x) {
int cnt = 0;
for (int i = 0; i < len; i++) if (str[i] == x) cnt++;
return cnt;
}
__kernel void rule_processor(
__global const uchar* words,
__global const uchar* rules,
__global uchar* results,
const uint num_words,
const uint num_rules,
const uint max_word_len,
const uint max_rule_len,
const uint max_result_len)
{
uint global_id = get_global_id(0);
uint word_idx = global_id / num_rules;
uint rule_idx = global_id % num_rules;
if (word_idx >= num_words || rule_idx >= num_rules) return;
uint word_offset = word_idx * max_word_len;
uint rule_offset = rule_idx * max_rule_len;
uint result_offset = global_id * max_result_len;
uchar word[MAX_WORD_LEN];
int word_len = 0;
for (int i = 0; i < max_word_len; i++) {
uchar c = words[word_offset + i];
if (c == 0) break;
word[i] = c;
word_len++;
}
uchar rule[MAX_RULE_LEN];
int rule_len = 0;
for (int i = 0; i < max_rule_len; i++) {
uchar c = rules[rule_offset + i];
if (c == 0) break;
rule[i] = c;
rule_len++;
}
uchar output[MAX_OUTPUT_LEN];
int out_len = 0;
int changed = 0;
for (int i = 0; i < max_result_len; i++) results[result_offset + i] = 0;
if (rule_len == 0 || word_len == 0) return;
// ======================= SIMPLE RULES (1 char) =======================
if (rule_len == 1) {
switch (rule[0]) {
case 'l':
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = to_lower(word[i]);
changed = 1;
break;
case 'u':
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = to_upper(word[i]);
changed = 1;
break;
case 'c':
out_len = word_len;
if (word_len > 0) {
output[0] = to_upper(word[0]);
for (int i = 1; i < word_len; i++) output[i] = to_lower(word[i]);
}
changed = 1;
break;
case 'C':
out_len = word_len;
if (word_len > 0) {
output[0] = to_lower(word[0]);
for (int i = 1; i < word_len; i++) output[i] = to_upper(word[i]);
}
changed = 1;
break;
case 't':
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = toggle_case(word[i]);
changed = 1;
break;
case 'r':
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = word[word_len - 1 - i];
changed = 1;
break;
case 'k':
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = word[i];
if (word_len >= 2) {
output[0] = word[1];
output[1] = word[0];
changed = 1;
}
break;
case 'K':
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = word[i];
if (word_len >= 2) {
output[word_len-2] = word[word_len-1];
output[word_len-1] = word[word_len-2];
changed = 1;
}
break;
case ':':
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = word[i];
changed = 0;
break;
case 'd':
if (word_len * 2 <= MAX_OUTPUT_LEN) {
out_len = word_len * 2;
for (int i = 0; i < word_len; i++) {
output[i] = word[i];
output[word_len + i] = word[i];
}
changed = 1;
}
break;
case 'f':
if (word_len * 2 <= MAX_OUTPUT_LEN) {
out_len = word_len * 2;
for (int i = 0; i < word_len; i++) {
output[i] = word[i];
output[word_len + i] = word[word_len - 1 - i];
}
changed = 1;
}
break;
case 'p':
if (word_len + 1 <= MAX_OUTPUT_LEN) {
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = word[i];
output[out_len++] = 's';
changed = 1;
}
break;
case 'z':
if (word_len + 1 <= MAX_OUTPUT_LEN) {
output[0] = word[0];
for (int i = 0; i < word_len; i++) output[i+1] = word[i];
out_len = word_len + 1;
changed = 1;
}
break;
case 'Z':
if (word_len + 1 <= MAX_OUTPUT_LEN) {
for (int i = 0; i < word_len; i++) output[i] = word[i];
output[word_len] = word[word_len-1];
out_len = word_len + 1;
changed = 1;
}
break;
case 'q':
if (word_len * 2 <= MAX_OUTPUT_LEN) {
int idx = 0;
for (int i = 0; i < word_len; i++) {
output[idx++] = word[i];
output[idx++] = word[i];
}
out_len = word_len * 2;
changed = 1;
}
break;
case 'E':
out_len = word_len;
int cap = 1;
for (int i = 0; i < word_len; i++) {
if (cap && is_lower(word[i])) output[i] = word[i] - 32;
else output[i] = word[i];
if (word[i] == ' ' || word[i] == '-' || word[i] == '_') cap = 1;
else cap = 0;
}
changed = 1;
break;
// Memory placeholders – no effect
case 'M': case '4': case '6': case '_':
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = word[i];
changed = 0;
break;
case 'Q':
changed = -1;
break;
default:
changed = 0;
break;
}
}
// ======================= TWO‑CHAR RULES =======================
else if (rule_len == 2) {
uchar cmd = rule[0];
uchar arg = rule[1];
int n = parse_position(arg);
switch (cmd) {
case 'T':
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = word[i];
if (n < word_len) { output[n] = toggle_case(word[n]); changed = 1; }
break;
case 'D':
out_len = 0;
for (int i = 0; i < word_len; i++) {
if (i != n) output[out_len++] = word[i];
else changed = 1;
}
break;
case 'L':
out_len = 0;
for (int i = n; i < word_len; i++) output[out_len++] = word[i];
changed = (n > 0);
break;
case 'R':
out_len = (n + 1 < word_len) ? n + 1 : word_len;
for (int i = 0; i < out_len; i++) output[i] = word[i];
changed = (out_len != word_len);
break;
case '+':
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = word[i];
if (n < word_len && word[n] < 255) { output[n] = word[n] + 1; changed = 1; }
break;
case '-':
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = word[i];
if (n < word_len && word[n] > 0) { output[n] = word[n] - 1; changed = 1; }
break;
case '.':
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = word[i];
if (n < word_len && word[n] < 255) { output[n] = word[n] + 1; changed = 1; }
break;
case ',':
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = word[i];
if (n < word_len && word[n] > 0) { output[n] = word[n] - 1; changed = 1; }
break;
case '^':
if (word_len + 1 <= MAX_OUTPUT_LEN) {
output[0] = arg;
for (int i = 0; i < word_len; i++) output[i+1] = word[i];
out_len = word_len + 1;
changed = 1;
}
break;
case '$':
if (word_len + 1 <= MAX_OUTPUT_LEN) {
for (int i = 0; i < word_len; i++) output[i] = word[i];
output[word_len] = arg;
out_len = word_len + 1;
changed = 1;
}
break;
case '@':
out_len = 0;
for (int i = 0; i < word_len; i++) {
if (word[i] != arg) output[out_len++] = word[i];
else changed = 1;
}
break;
case '!':
{
int reject = 0;
for (int i = 0; i < word_len; i++) {
if (word[i] == arg) { reject = 1; break; }
}
if (reject) changed = -1;
else {
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = word[i];
changed = 0;
}
}
break;
case '/':
{
int found = 0;
for (int i = 0; i < word_len; i++) if (word[i] == arg) { found = 1; break; }
if (!found) changed = -1;
else {
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = word[i];
changed = 0;
}
}
break;
case 'p':
{
int mult = n <= 0 ? 1 : n;
int total_len = word_len * mult;
if (total_len <= MAX_OUTPUT_LEN) {
out_len = total_len;
for (int i = 0; i < mult; i++)
for (int j = 0; j < word_len; j++)
output[i*word_len + j] = word[j];
changed = 1;
}
}
break;
case '(':
if (word_len == 0 || word[0] != arg) changed = -1;
else {
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = word[i];
changed = 0;
}
break;
case ')':
if (word_len == 0 || word[word_len-1] != arg) changed = -1;
else {
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = word[i];
changed = 0;
}
break;
case '<':
if (word_len > n) changed = -1;
else {
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = word[i];
changed = 0;
}
break;
case '>':
if (word_len < n) changed = -1;
else {
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = word[i];
changed = 0;
}
break;
case '_':
if (word_len != n) changed = -1;
else {
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = word[i];
changed = 0;
}
break;
case '=':
if (n >= word_len || word[n] != arg) changed = -1;
else {
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = word[i];
changed = 0;
}
break;
case '%':
{
int cnt = count_char(word, word_len, arg);
if (cnt < n) changed = -1;
else {
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = word[i];
changed = 0;
}
}
break;
case 'y':
{
int nn = n;
if (nn > word_len) nn = word_len;
if (word_len + nn <= MAX_OUTPUT_LEN) {
out_len = word_len + nn;
for (int i = 0; i < word_len; i++) output[i] = word[i];
for (int i = 0; i < nn; i++) output[word_len + i] = word[i];
changed = 1;
}
}
break;
case 'Y':
{
int nn = n;
if (nn > word_len) nn = word_len;
if (word_len + nn <= MAX_OUTPUT_LEN) {
out_len = word_len + nn;
for (int i = 0; i < word_len; i++) output[i] = word[i];
for (int i = 0; i < nn; i++) output[word_len + i] = word[word_len - nn + i];
changed = 1;
}
}
break;
case 39: // apostrophe rule: truncate at N
{
int nn = n;
if (nn > word_len) nn = word_len;
out_len = nn;
for (int i = 0; i < nn; i++) output[i] = word[i];
changed = (nn != word_len);
}
break;
default:
changed = 0;
break;
}
}
// ======================= THREE‑CHAR RULES =======================
else if (rule_len == 3) {
uchar cmd = rule[0];
uchar arg1 = rule[1];
uchar arg2 = rule[2];
if (cmd == 's') {
out_len = word_len;
for (int i = 0; i < word_len; i++) {
output[i] = (word[i] == arg1) ? arg2 : word[i];
}
changed = 1;
}
else if (cmd == '*') {
int n = parse_position(arg1);
int m = parse_position(arg2);
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = word[i];
if (n < word_len && m < word_len && n != m) {
uchar temp = output[n];
output[n] = output[m];
output[m] = temp;
changed = 1;
}
}
else if (cmd == 'x') {
int n = parse_position(arg1);
int m = parse_position(arg2);
if (n < word_len) {
out_len = 0;
for (int i = n; i < word_len && out_len < m; i++) {
output[out_len++] = word[i];
}
changed = 1;
}
}
else if (cmd == 'O') {
int n = parse_position(arg1);
int m = parse_position(arg2);
out_len = 0;
for (int i = 0; i < word_len; i++) {
if (i >= n && i < n + m) continue;
output[out_len++] = word[i];
}
changed = (out_len != word_len);
}
else if (cmd == 'i') {
int n = parse_position(arg1);
if (word_len + 1 <= MAX_OUTPUT_LEN) {
out_len = 0;
for (int i = 0; i < word_len; i++) {
if (i == n) output[out_len++] = arg2;
output[out_len++] = word[i];
}
if (n >= word_len) output[out_len++] = arg2;
changed = 1;
}
}
else if (cmd == 'o') {
int n = parse_position(arg1);
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = word[i];
if (n < word_len) {
output[n] = arg2;
changed = 1;
}
}
else if (cmd == 'T') {
int n = parse_position(arg1);
int m = parse_position(arg2);
if (n > m) { int t = n; n = m; m = t; }
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = word[i];
for (int i = n; i <= m && i < word_len; i++) {
output[i] = toggle_case(word[i]);
}
changed = 1;
}
else if (cmd == '?') {
int n = parse_position(arg1);
if (n >= word_len || word[n] != arg2) changed = -1;
else {
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = word[i];
changed = 0;
}
}
else if (cmd == '=') {
int n = parse_position(arg1);
if (n < word_len && word[n] == arg2) changed = -1;
else {
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = word[i];
changed = 0;
}
}
else if (cmd == 'e') {
uchar sep = arg1;
out_len = word_len;
int cap = 1;
for (int i = 0; i < word_len; i++) {
if (cap && is_lower(word[i])) output[i] = word[i] - 32;
else output[i] = word[i];
if (word[i] == sep) cap = 1;
else cap = 0;
}
changed = 1;
}
else if (cmd == '3') {
int n = parse_position(arg1);
uchar sep = arg2;
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = word[i];
int count = 0;
for (int i = 0; i < word_len; i++) {
if (word[i] == sep) {
count++;
if (count == n && i+1 < word_len) {
output[i+1] = toggle_case(word[i+1]);
changed = 1;
break;
}
}
}
}
else if (cmd == '{') {
int n = parse_position(arg1);
if (n <= 0) n = 1;
out_len = word_len;
for (int i = 0; i < word_len; i++) {
int src = (i + n) % word_len;
output[i] = word[src];
}
changed = 1;
}
else if (cmd == '}') {
int n = parse_position(arg1);
if (n <= 0) n = 1;
out_len = word_len;
for (int i = 0; i < word_len; i++) {
int src = (i - n + word_len) % word_len;
output[i] = word[src];
}
changed = 1;
}
else if (cmd == '[') {
int n = parse_position(arg1);
if (n > word_len) n = word_len;
out_len = word_len - n;
for (int i = n; i < word_len; i++) output[i-n] = word[i];
changed = 1;
}
else if (cmd == ']') {
int n = parse_position(arg1);
if (n > word_len) n = word_len;
out_len = word_len - n;
for (int i = 0; i < out_len; i++) output[i] = word[i];
changed = 1;
}
else if (cmd == 'v') {
int n = parse_position(arg1);
uchar x = arg2;
if (n > 0 && word_len + (word_len / n) <= MAX_OUTPUT_LEN) {
out_len = 0;
for (int i = 0; i < word_len; i++) {
output[out_len++] = word[i];
if ((i+1) % n == 0 && i+1 < word_len) {
output[out_len++] = x;
}
}
changed = 1;
}
}
else {
changed = 0;
}
}
// ======================= FOUR‑CHAR RULES (memory placeholders) =======================
else if (rule_len == 4) {
// Memory operations not implemented – treat as no-op
out_len = word_len;
for (int i = 0; i < word_len; i++) output[i] = word[i];
changed = 0;
}
// ======================= OUTPUT =======================
if (changed <= 0) out_len = 0;
if (out_len > 0 && changed > 0) {
for (int i = 0; i < out_len && i < max_result_len - 1; i++) {
results[result_offset + i] = output[i];
}
results[result_offset + out_len] = 0;
} else {
results[result_offset] = 0;
}
}
"""
# ============================================================================
# REST OF THE SCRIPT (unchanged except for minor adjustments)
# ============================================================================
# The following classes and functions remain largely the same as in the original,
# but we keep them here for completeness. They use the new kernel.
# ============================================================================
def print_banner():
"""Print enhanced banner"""
banner = f"""
{Colors.BOLD}{Colors.CYAN}
╔════════════════════════════════════════════════════════════════╗
║ HASHCAT RULE PERFORMANCE BENCHMARK ║
║ Advanced Visualization Edition ║
║ Michelson-Morley Inspired ║
╚════════════════════════════════════════════════════════════════╝
{Colors.END}
{Colors.YELLOW}
🔬 Scientific-Grade Performance Analysis
📊 Advanced Data Visualization
⚡ OpenCL GPU Acceleration
🎯 Michelson-Morley Precision Methodology
{Colors.END}
"""
print(banner)
class VisualizationEngine:
"""Advanced visualization engine for benchmark results"""
def __init__(self, output_dir: str):
self.output_dir = output_dir
os.makedirs(output_dir, exist_ok=True)
self.setup_styles()
def setup_styles(self):
plt.rcParams['figure.figsize'] = [12, 8]
plt.rcParams['font.size'] = 10
plt.rcParams['axes.titlesize'] = 14
plt.rcParams['axes.labelsize'] = 12
def create_performance_radar(self, rule_performance: List[Tuple[str, Dict]], filename: str):
if not rule_performance: return
top_rules = rule_performance[:20]
rules = [f"{rule[:15]}..." if len(rule) > 15 else rule for rule, _ in top_rules]
times = [data['execution_time'] * 1000000 for _, data in top_rules]
ops_sec = [data['operations_per_sec'] / 1000 for _, data in top_rules]
cv_values = [data['metrics']['cv_percent'] for _, data in top_rules]
times_norm = self.normalize_data(times, invert=True)
ops_norm = self.normalize_data(ops_sec)
cv_norm = self.normalize_data(cv_values, invert=True)
categories = ['Speed\n(μs)', 'Throughput\n(K ops/sec)', 'Consistency\n(CV %)']
fig, ax = plt.subplots(figsize=(14, 10), subplot_kw=dict(projection='polar'))
angles = np.linspace(0, 2*np.pi, len(categories), endpoint=False).tolist()
angles += angles[:1]
for i, (rule, time_n, ops_n, cv_n) in enumerate(zip(rules, times_norm, ops_norm, cv_norm)):
values = [time_n, ops_n, cv_n]
values += values[:1]
ax.plot(angles, values, 'o-', linewidth=2, label=rule, markersize=6, alpha=0.7)
ax.fill(angles, values, alpha=0.1)
ax.set_xticks(angles[:-1])
ax.set_xticklabels(categories)
ax.set_ylim(0, 1)
ax.set_yticks([])
ax.grid(True, alpha=0.3)
plt.title('Rule Performance Radar Chart\n(Top 20 Rules)', size=16, pad=20)
plt.legend(bbox_to_anchor=(1.2, 1.0), loc='upper left')
plt.tight_layout()
plt.savefig(os.path.join(self.output_dir, f"{filename}_radar.png"), dpi=300, bbox_inches='tight')
plt.close()
print(f"{Colors.GREEN}Radar chart saved: {filename}_radar.png{Colors.END}")
def create_performance_heatmap(self, rule_performance: List[Tuple[str, Dict]], filename: str):
if not rule_performance: return
rule_types = {}
for rule, data in rule_performance:
rule_char = rule[0] if rule else '?'
if rule_char not in rule_types:
rule_types[rule_char] = []
rule_types[rule_char].append(data['execution_time'] * 1000000)
rule_chars = list(rule_types.keys())
performance_data = []
for char in rule_chars:
times = rule_types[char]
if times:
performance_data.append(np.mean(times))
if not performance_data: return
grid_size = int(np.ceil(np.sqrt(len(rule_chars))))
heatmap_data = np.full((grid_size, grid_size), np.nan)
char_labels = np.full((grid_size, grid_size), '', dtype=object)
for idx, (char, perf) in enumerate(zip(rule_chars, performance_data)):
row = idx // grid_size
col = idx % grid_size
if row < grid_size and col < grid_size:
heatmap_data[row, col] = perf
char_labels[row, col] = char
fig, ax = plt.subplots(figsize=(12, 10))
im = ax.imshow(heatmap_data, cmap='RdYlGn_r', aspect='auto')
for i in range(grid_size):
for j in range(grid_size):
if not np.isnan(heatmap_data[i, j]):
ax.text(j, i, f"{char_labels[i, j]}\n{heatmap_data[i, j]:.1f}μs",
ha="center", va="center", color="black", fontsize=8,
bbox=dict(boxstyle="round,pad=0.3", facecolor='white', alpha=0.7))
plt.colorbar(im, ax=ax, label='Execution Time (μs)')
ax.set_title('Rule Type Performance Heatmap\n(Lower = Faster)', pad=20)
ax.set_xticks([])
ax.set_yticks([])
plt.tight_layout()
plt.savefig(os.path.join(self.output_dir, f"{filename}_heatmap.png"), dpi=300, bbox_inches='tight')
plt.close()
print(f"{Colors.GREEN}Heatmap saved: {filename}_heatmap.png{Colors.END}")
def create_statistical_summary(self, rule_performance: List[Tuple[str, Dict]], filename: str):
if not rule_performance:
print(f"{Colors.YELLOW}No performance data available for statistical summary{Colors.END}")
return
try:
rules = [rule for rule, _ in rule_performance]
times = [data['execution_time'] * 1000000 for _, data in rule_performance if 'execution_time' in data]
cv_values = [data['metrics']['cv_percent'] for _, data in rule_performance if 'metrics' in data and 'cv_percent' in data['metrics']]
ops_sec = [data['operations_per_sec'] for _, data in rule_performance if 'operations_per_sec' in data]
if not times:
print(f"{Colors.RED}No execution time data available for statistical summary{Colors.END}")
return
fig, axes = plt.subplots(2, 2, figsize=(16, 12))
# 1. Performance distribution
axes[0,0].hist(times, bins=30, alpha=0.7, color='skyblue', edgecolor='black')
axes[0,0].axvline(np.mean(times), color='red', linestyle='--', label=f'Mean: {np.mean(times):.2f}μs')
axes[0,0].axvline(np.median(times), color='green', linestyle='--', label=f'Median: {np.median(times):.2f}μs')
axes[0,0].set_xlabel('Execution Time (μs)')
axes[0,0].set_ylabel('Frequency')
axes[0,0].set_title('Performance Distribution')
axes[0,0].legend()
axes[0,0].grid(True, alpha=0.3)
# 2. Consistency vs Performance
if times and cv_values and len(times) == len(cv_values):
scatter = axes[0,1].scatter(times, cv_values, c=ops_sec if ops_sec else times, cmap='viridis', alpha=0.6, s=50, edgecolors='black', linewidth=0.5)
axes[0,1].set_xlabel('Execution Time (μs)')
axes[0,1].set_ylabel('Coefficient of Variation (%)')
axes[0,1].set_title('Performance vs Consistency')
plt.colorbar(scatter, ax=axes[0,1], label='Operations/sec' if ops_sec else 'Execution Time (μs)')
axes[0,1].grid(True, alpha=0.3)
else:
axes[0,1].text(0.5, 0.5, 'Insufficient data', ha='center', va='center', transform=axes[0,1].transAxes)
axes[0,1].set_title('Performance vs Consistency (No Data)')
# 3. Top 10 fastest rules
if rule_performance:
top_10 = rule_performance[:min(10, len(rule_performance))]
top_rules = [f"{rule[:15]}..." if len(rule) > 15 else rule for rule, _ in top_10]
top_times = [data['execution_time'] * 1000000 for _, data in top_10]
bars = axes[1,0].barh(top_rules, top_times, color=plt.cm.Greens_r(np.linspace(0.2, 0.8, len(top_rules))))
axes[1,0].set_xlabel('Execution Time (μs)')
axes[1,0].set_title('Top 10 Fastest Rules')
axes[1,0].grid(True, alpha=0.3, axis='x')
for bar in bars:
width = bar.get_width()
axes[1,0].text(width, bar.get_y() + bar.get_height()/2, f'{width:.2f}μs', ha='left', va='center', fontsize=8)
else:
axes[1,0].text(0.5, 0.5, 'No rule performance data', ha='center', va='center', transform=axes[1,0].transAxes)
axes[1,0].set_title('Top 10 Fastest Rules (No Data)')
# 4. Performance categories
if times:
fast = len([t for t in times if t < 10])
medium = len([t for t in times if 10 <= t < 100])
slow = len([t for t in times if t >= 100])
categories = ['Fast (<10μs)', 'Medium (10-100μs)', 'Slow (≥100μs)']
counts = [fast, medium, slow]
colors = ['#2ecc71', '#f39c12', '#e74c3c']
valid_categories = [cat for cat, cnt in zip(categories, counts) if cnt > 0]
valid_counts = [cnt for cnt in counts if cnt > 0]
valid_colors = [colors[i] for i, cnt in enumerate(counts) if cnt > 0]
if valid_counts:
axes[1,1].pie(valid_counts, labels=valid_categories, colors=valid_colors, autopct='%1.1f%%', startangle=90)
axes[1,1].set_title('Performance Categories Distribution')
else:
axes[1,1].text(0.5, 0.5, 'No performance category data', ha='center', va='center', transform=axes[1,1].transAxes)
axes[1,1].set_title('Performance Categories (No Data)')
else:
axes[1,1].text(0.5, 0.5, 'No execution time data', ha='center', va='center', transform=axes[1,1].transAxes)
axes[1,1].set_title('Performance Categories (No Data)')
plt.suptitle('Comprehensive Statistical Summary', fontsize=16, y=0.98)
plt.tight_layout()
plt.savefig(os.path.join(self.output_dir, f"{filename}_statistical.png"), dpi=300, bbox_inches='tight')
plt.close()
print(f"{Colors.GREEN}Statistical summary saved: {filename}_statistical.png{Colors.END}")
except Exception as e:
print(f"{Colors.RED}Error creating statistical summary: {e}{Colors.END}")
def create_performance_distribution(self, rule_performance: List[Tuple[str, Dict]], filename: str):
if not rule_performance:
print(f"{Colors.YELLOW}No performance data available for distribution plot{Colors.END}")
return
try:
times = [data['execution_time'] * 1000000 for _, data in rule_performance if 'execution_time' in data]
if not times:
print(f"{Colors.RED}No execution time data available{Colors.END}")
return
fig, axes = plt.subplots(2, 2, figsize=(15, 10))
# 1. Histogram with density
axes[0,0].hist(times, bins=30, alpha=0.7, color='lightblue', edgecolor='black', density=True, label='Distribution')
try:
from scipy.stats import gaussian_kde
density = gaussian_kde(times)
xs = np.linspace(min(times), max(times), 200)
axes[0,0].plot(xs, density(xs), 'r-', linewidth=2, label='Density Curve')
except ImportError:
pass
axes[0,0].axvline(np.mean(times), color='red', linestyle='--', linewidth=2, label=f'Mean: {np.mean(times):.2f}μs')
axes[0,0].axvline(np.median(times), color='green', linestyle='--', linewidth=2, label=f'Median: {np.median(times):.2f}μs')
axes[0,0].set_xlabel('Execution Time (μs)')
axes[0,0].set_ylabel('Density')
axes[0,0].set_title('Performance Distribution with Density Curve')
axes[0,0].legend()
axes[0,0].grid(True, alpha=0.3)
# 2. Box plot
box_plot = axes[0,1].boxplot([times], vert=True, patch_artist=True,
boxprops=dict(facecolor='lightgreen', alpha=0.7),
medianprops=dict(color='red', linewidth=2))
axes[0,1].set_ylabel('Execution Time (μs)')
axes[0,1].set_title('Performance Box Plot')
axes[0,1].set_xticks([1])
axes[0,1].set_xticklabels(['All Rules'])
axes[0,1].grid(True, alpha=0.3)
stats_text = f"""Statistics:
Mean: {np.mean(times):.2f}μs
Median: {np.median(times):.2f}μs
Std: {np.std(times):.2f}μs
Min: {np.min(times):.2f}μs
Max: {np.max(times):.2f}μs
Q1: {np.percentile(times, 25):.2f}μs
Q3: {np.percentile(times, 75):.2f}μs"""
axes[0,1].text(1.05, 0.95, stats_text, transform=axes[0,1].transAxes,
verticalalignment='top', bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5),
fontfamily='monospace', fontsize=8)
# 3. Cumulative distribution
sorted_times = np.sort(times)
cdf = np.arange(1, len(sorted_times)+1) / len(sorted_times)
axes[1,0].plot(sorted_times, cdf, 'b-', linewidth=2, label='CDF')
axes[1,0].set_xlabel('Execution Time (μs)')
axes[1,0].set_ylabel('Cumulative Probability')
axes[1,0].set_title('Cumulative Distribution Function')
axes[1,0].grid(True, alpha=0.3)
axes[1,0].legend()
for p in [25,50,75,90,95]:
p_val = np.percentile(times, p)
axes[1,0].axvline(p_val, color='red', linestyle='--', alpha=0.7)
axes[1,0].text(p_val, 0.5, f'{p}%', rotation=90, va='center', ha='right')
# 4. Violin plot
try:
violin_parts = axes[1,1].violinplot([times], showmeans=True, showmedians=True)
for pc in violin_parts['bodies']:
pc.set_facecolor('lightcoral')
pc.set_alpha(0.7)
violin_parts['cmeans'].set_color('green')
violin_parts['cmedians'].set_color('blue')
axes[1,1].set_ylabel('Execution Time (μs)')
axes[1,1].set_title('Performance Violin Plot')
axes[1,1].set_xticks([1])
axes[1,1].set_xticklabels(['All Rules'])
axes[1,1].grid(True, alpha=0.3)
except:
axes[1,1].hist(times, bins=30, alpha=0.7, color='lightcoral', edgecolor='black')
axes[1,1].set_xlabel('Execution Time (μs)')
axes[1,1].set_ylabel('Frequency')
axes[1,1].set_title('Performance Distribution (Fallback)')
axes[1,1].grid(True, alpha=0.3)
plt.suptitle('Detailed Performance Distribution Analysis', fontsize=16, y=0.98)
plt.tight_layout()
plt.savefig(os.path.join(self.output_dir, f"{filename}_distribution.png"), dpi=300, bbox_inches='tight')
plt.close()
print(f"{Colors.GREEN}Performance distribution saved: {filename}_distribution.png{Colors.END}")
except Exception as e:
print(f"{Colors.RED}Error creating performance distribution: {e}{Colors.END}")
def normalize_data(self, data: List[float], invert: bool = False) -> List[float]:
if not data: return []
min_val, max_val = min(data), max(data)
if max_val == min_val: return [0.5] * len(data)
norm = [(x - min_val) / (max_val - min_val) for x in data]
if invert: norm = [1 - x for x in norm]
return norm
def generate_dashboard(self, performance_data: Dict, filename: str):
print(f"{Colors.CYAN}Generating comprehensive visualization dashboard...{Colors.END}")
if 'rule_performance' in performance_data:
rp = performance_data['rule_performance']
self.create_performance_radar(rp, filename)
self.create_performance_heatmap(rp, filename)
self.create_statistical_summary(rp, filename)
self.create_performance_distribution(rp, filename)
print(f"{Colors.GREEN}Dashboard generation complete!{Colors.END}")
class RulePerformanceTester:
def __init__(self, platform_index=0, device_index=0):
self.visualizer = None
self.setup_opencl(platform_index, device_index)
def setup_opencl(self, platform_index: int, device_index: int):
try:
platforms = cl.get_platforms()
if not platforms: raise RuntimeError("No OpenCL platforms found")
platform = platforms[platform_index]
devices = platform.get_devices(cl.device_type.GPU)
if not devices:
print(f"{Colors.YELLOW}No GPU devices found, trying CPU...{Colors.END}")
devices = platform.get_devices(cl.device_type.CPU)
if not devices: raise RuntimeError("No OpenCL devices found")
device = devices[device_index]
print(f"{Colors.GREEN}Using device: {device.name}{Colors.END}")
print(f"{Colors.CYAN}Device memory: {device.global_mem_size // (1024*1024)} MB{Colors.END}")
self.context = cl.Context([device])
self.queue = cl.CommandQueue(self.context)
try:
self.program = cl.Program(self.context, OPENCL_KERNEL_SOURCE).build()
self.kernel = cl.Kernel(self.program, 'rule_processor')
print(f"{Colors.GREEN}OpenCL kernel compiled successfully{Colors.END}")
except Exception as e:
print(f"{Colors.RED}Kernel compilation failed: {e}{Colors.END}")
try:
build_log = self.program.get_build_info(device, cl.program_build_info.LOG)
print(f"{Colors.YELLOW}Build log: {build_log}{Colors.END}")