This repository has been archived by the owner on Jan 28, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathanalyze_wotb_replays.py
executable file
·3369 lines (2969 loc) · 112 KB
/
analyze_wotb_replays.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/env python3
## PYTHON VERSION MUST BE 3.7 OR HIGHER
# Script Analyze WoT Blitz replays
import sys, argparse, json, os, concurrent, inspect, aiohttp, asyncio, aiofiles, aioconsole
import configparser, ssl, re, logging, time, xmltodict, collections, csv
from pathlib import Path
from asyncio import Queue, Task, create_task
from datetime import datetime, timedelta, date
from motor.motor_asyncio import (
AsyncIOMotorDatabase,
AsyncIOMotorClient,
)
import blitzutils1 as bu
from blitzutils1 import WG
from blitzutils1 import WoTinspector
from pyutils import FileQueue
logging.getLogger("asyncio").setLevel(logging.DEBUG)
WG_APP_ID = "df25c506c7944e48fbec67e8b74fd34e"
FILE_CONFIG = "blitzstats.ini"
DB_C_TANK_STATS = "WG_TankStats"
DB_C_PLAYER_STATS = "WG_PlayerStats"
DB_C_REPLAYS = "Replays"
N_PLAYERS = "Nplayers"
MISSING_STATS = "missing_stats"
wg: WG
wi: WoTinspector
REPLAY_N = 0
REPLAY_I = 0
STAT_TANK_BATTLE_MIN = 100
BATTLE_TIME_BUCKET = 3600 * 24 * 14
OPT_EXPORT_REPLAY_DIR = "export_replays"
OPT_EXPORT_CSV_FILE = "export.csv"
OPT_EXPORT_JSON_FILE = "export.json"
RE_SRC_IS_DB = re.compile(r"^DB:")
class StatFunc:
## For different player stat functions (global stats, tank tier stats, etc)
# 1st function = for forming stat_id, 2nd for DB stats query, 3rd for WG API stats query
STAT_FUNC = {
"tank_tier": [
"get_stat_id_tank_tier",
"get_db_tank_tier_stats",
"get_wg_tank_tier_stats",
"WR at tier",
],
"tank": [
"get_stat_id_tank",
"get_db_tank_stats",
"get_wg_tank_stats",
"WR in Tank",
],
"player": [
"get_stat_id_player",
"get_db_player_stats",
"get_wg_player_stats",
"Career WR",
],
"tier_x": [
"get_stat_id_player",
"get_db_tier_x_stats",
"get_wg_tier_x_stats",
"WR at tier X",
],
}
_DEFAULT = "player"
_stat_func = _DEFAULT
@classmethod
def get_default(cls):
return cls._DEFAULT
@classmethod
def get_stat_funcs(cls):
return cls.STAT_FUNC.keys()
@classmethod
def set_stat_func(cls, stat_func: str = _DEFAULT):
if stat_func in cls.STAT_FUNC.keys():
cls._stat_func = stat_func
else:
## ERROR
pass
return cls._stat_func
@classmethod
def get_stat_func(cls):
return cls._stat_func
@classmethod
def get_stat_id_func(cls):
return cls.STAT_FUNC[cls._stat_func][0]
@classmethod
def get_db_func(cls):
return cls.STAT_FUNC[cls._stat_func][1]
@classmethod
def get_wg_func(cls):
return cls.STAT_FUNC[cls._stat_func][2]
@classmethod
def get_title(cls):
return cls.STAT_FUNC[cls._stat_func][3]
replay_summary_flds = [
"battle_result",
"battle_type",
"map_name",
"battle_duration",
"room_type",
"protagonist",
"player_name",
"title",
"mastery_badge",
]
replay_details_flds = [
"damage_made",
"damage_assisted_track",
"damage_assisted",
"damage_received",
"damage_blocked",
"enemies_damaged",
"enemies_destroyed",
"hitpoints_left",
"time_alive",
"distance_travelled",
"base_capture_points",
"base_defend_points",
"wp_points_earned",
"wp_points_stolen",
"hits_received",
"hits_bounced",
"hits_splash",
"hits_pen",
"shots_made",
"shots_hit",
"shots_pen",
"shots_splash",
"enemies_spotted",
]
## Syntax: key == stat field in https://api.wotblitz.eu/wotb/tanks/stats/ (all.KEY)
## Value array [ 'Stat Title', [ 0, data buckets ....], scaling_factor_for_bucket_values, 'print_format' ]
histogram_fields = {
"wins": [
"Win rate",
[0, 0.35, 0.40, 0.45, 0.48, 0.5, 0.52, 0.55, 0.60, 0.65, 0.70, 1],
1,
"{:2.0%}",
],
"damage_dealt": [
"Avg. Dmg.",
[
0,
200,
300,
400,
500,
600,
700,
800,
900,
1000,
1100,
1200,
1300,
1400,
1500,
1750,
2000,
2250,
2500,
2750,
3000,
100e3,
],
1,
"{:3.0f}",
],
"battles": [
"Battles",
[0, 1000, 2500, 5000, 7000, 10e3, 15e3, 25e3, 50e3, 5e7],
0.001,
"{:.0f}k",
], # battles is a mandatory stat to include
}
def def_value_zero():
return 0
def def_value_BattleCategory():
return BattleCategory()
class BattleCategorizationList:
@staticmethod
def mk_battle_modes(modes: dict):
"""Make a list of battle modes as required for the _categorizations"""
mode_ids = modes.values()
id_max = max(mode_ids)
ret_modes = ["-"] * (id_max + 16)
for i in range(0, id_max + 16):
ret_modes[i] = "room_type=" + str(i)
for mode in modes:
id = modes[mode]
ret_modes[id] = mode
return ret_modes
_battle_modes = {
"Any": 0,
"Regular": 1,
"Training Room": 2,
"Tournament": 4,
"Quick Tournament": 5, # maybe?
"Rating": 7,
"Mad Games": 8,
"Realistic Battles": 22,
"Uprising": 23,
"Gravity Mode": 24,
"Skirmish": 25,
"Burning Games": 26,
}
_BATTLE_MODES = mk_battle_modes.__func__(_battle_modes)
_categorizations = {
"total": ["TOTAL", "total"],
"battle_result": ["Result", "category", ["Loss", "Win", "Draw"]],
"battle_type": ["Battle Type", "category", ["Encounter", "Supremacy"]],
"room_type": ["Battle Mode", "category", _BATTLE_MODES],
"top_tier": ["Tier", "category", ["Bottom tier", "Top tier"]],
"in_platoon": ["Platoon", "category", ["Solo", "Platoon"]],
"tank_tier": ["Tank Tier", "number"],
"is_premium": ["Tank Type", "category", ["Tech tree", "Premium"]],
"tank_type": ["Tank Class", "category", WG.TANK_TYPE_STR],
"tank_nation": ["Nation", "category", WG.NATION_STR],
"mastery_badge": [
"Battle Medal",
"category",
["-", "3rd Class", "2nd Class", "1st Class", "Mastery"],
],
"team_result": ["Team Result", "string"],
"player_wins": ["Player WR", "bucket", [0, 0.35, 0.45, 0.50, 0.55, 0.65], "%"],
"player_battles": [
"Player Battles",
"bucket",
[0, 500, 1000, 2500, 5e3, 10e3, 15e3, 25e3],
"int",
],
"player_damage_dealt": [
"Player Avg Dmg",
"bucket",
[0, 500, 1000, 1250, 1500, 1750, 2000, 2500],
"int",
],
"damage_made": [
"Player Dmg made",
"bucket",
[0, 500, 1000, 1250, 1500, 1750, 2000, 2500],
"int",
],
"enemies_destroyed": ["Player Kills", "number"],
"enemies_spotted": ["Player Spots", "number"],
"hit_rate": [
"Player Hit Rate",
"bucket",
[0, 0.25, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95],
"%",
],
"pen_rate": [
"Player Pen Rate",
"bucket",
[0, 0.25, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95],
"%",
],
"alive": [
"Time alive (pcs)",
"bucket",
[x / 100 for x in range(0, 100, 10)],
"%",
],
"time_alive": [
"Time alive (s)",
"bucket",
[x * 60 for x in range(0, 8)],
"int",
],
"battle_duration": [
"Battle Duration",
"bucket",
[x * 60 for x in range(0, 8)],
"int",
],
"distance_travelled": [
"Distance Driven",
"bucket",
[x * 250 for x in range(0, 20)],
"int",
],
"allies_wins": ["Allies WR", "bucket", [0, 0.35, 0.45, 0.50, 0.55, 0.65], "%"],
"allies_battles": [
"Player Battles",
"bucket",
[0, 500, 1000, 2500, 5e3, 10e3, 15e3, 25e3],
"int",
],
"allies_damage_dealt": [
"Player Avg Dmg",
"bucket",
[0, 500, 1000, 1250, 1500, 1750, 2000, 2500],
"int",
],
"enemies_wins": [
"Enemies WR",
"bucket",
[0, 0.35, 0.45, 0.50, 0.55, 0.65],
"%",
],
"enemies_battles": [
"Player Battles",
"bucket",
[0, 500, 1000, 2500, 5e3, 10e3, 15e3, 25e3],
"int",
],
"enemies_damage_dealt": [
"Player Avg Dmg",
"bucket",
[0, 500, 1000, 1250, 1500, 1750, 2000, 2500],
"int",
],
"player_name": ["Player", "string", 25],
"protagonist": ["account_id", "number"],
"tank_name": ["Tank", "string", 25],
"map_name": ["Map", "string", 20],
"battle": ["Battle", "string", 40],
"battle_i": ["Battle #", "number"],
}
_categorizations_default = [
"total",
"battle_result",
"battle_type",
"tank_tier",
"top_tier",
]
## Player stats based categorizations
_categorizations_stats = [
group + "_" + measure
for group in ["player", "allies", "enemies"]
for measure in ["wins", "battles", "damage_dealt"]
]
@classmethod
def get_categorizations_all(cls, cats: list = None) -> list:
try:
if cats is None:
return list(cls._categorizations.keys())
else:
return list(set(cls._categorizations.keys()) & set(cats))
except Exception as err:
bu.error(exception=err)
return None
@classmethod
def get_categorizations_stats(cls, cats=None, stats_cats=None):
try:
if cats is None:
return cls._categorizations_stats
else:
if stats_cats is None:
return cats
player_stat_filters = set(cls._categorizations_stats)
cats = set(cls.get_categorizations_all(cats))
if stats_cats:
cats = cats & player_stat_filters
else:
cats = cats - player_stat_filters
bu.debug(", ".join(list(cats)))
return list(cats)
except Exception as err:
bu.error(exception=err)
return None
@classmethod
def get_categorizations_default(cls):
return cls._categorizations_default
@classmethod
def set_categorizations_default(cls, cat_defaults: list):
try:
defaults = list()
for cat in cat_defaults:
if cat in cls.get_categorizations_all():
defaults.append(cat)
else:
bu.error(cat + " is not a defined categorization")
cls._categorizations_default = defaults
except Exception as err:
bu.error(exception=err)
@classmethod
def get_categorizations_extra(cls) -> list:
# return cls._categorizations_extra
return list(
set(cls._categorizations.keys()) - set(cls.get_categorizations_default())
)
@classmethod
def get_categorization_title(cls, cat: str) -> str:
try:
return cls._categorizations[cat][0]
except Exception as err:
bu.error(exception=err)
return None
@classmethod
def get_categorization_type(cls, cat: str) -> str:
try:
return cls._categorizations[cat][1]
except Exception as err:
bu.error(exception=err)
return None
@classmethod
def get_categorization_params(cls, cat: str) -> list:
try:
if len(cls._categorizations[cat]) > 2:
return cls._categorizations[cat][2:]
except Exception as err:
bu.error(exception=err)
return None
@classmethod
def help(cls):
for cat in cls.get_categorizations_all():
try:
ctitle = cls.get_categorization_title(cat)
ctype = cls.get_categorization_type(cat)
cparams = cls.get_categorization_params(cat)
if ctype == "number":
cat_tmp = BattleNumberCategorization(cat, ctitle)
elif ctype == "string":
cat_tmp = BattleStringCategorization(cat, ctitle, cparams)
elif ctype == "category":
cat_tmp = BattleClassCategorization(cat, ctitle, cparams[0])
elif ctype == "bucket":
cat_tmp = BattleBucketCategorization(
cat, ctitle, cparams[0], cparams[1]
)
else:
cat_tmp = BattleTotals(ctitle)
cat_tmp.help()
except KeyError as err:
bu.error(
"BattleCategorizationList(): Key not found: Category: " + cat,
exception=err,
)
except Exception as err:
bu.error("BattleCategorizationList()", exception=err)
@classmethod
def get_categorizations(cls, args: argparse.Namespace):
extra_cats = args.extra
only_extra = args.only_extra
if only_extra:
cats = list()
else:
cats = cls.get_categorizations_default()
if extra_cats is not None:
cats = cats + extra_cats
return cats
def __init__(self, cats: list):
self.urls = collections.OrderedDict()
self.url_title_max_len = 0
cats = list(set(cats)) # remove duplicates
# ordering
self.categorizations_list = [
cat for cat in self._categorizations if cat in cats
]
self.categorizations = dict()
for cat in self.categorizations_list:
try:
ctitle = self.get_categorization_title(cat)
ctype = self.get_categorization_type(cat)
cparams = self.get_categorization_params(cat)
if ctype == "total":
self.categorizations[cat] = BattleTotals(ctitle)
elif ctype == "number":
self.categorizations[cat] = BattleNumberCategorization(cat, ctitle)
elif ctype == "string":
self.categorizations[cat] = BattleStringCategorization(
cat, ctitle, cparams
)
elif ctype == "category":
self.categorizations[cat] = BattleClassCategorization(
cat, ctitle, cparams[0]
)
elif ctype == "bucket":
self.categorizations[cat] = BattleBucketCategorization(
cat, ctitle, cparams[0], cparams[1]
)
except KeyError as err:
bu.error(
"BattleCategorizationList(): Key not found: Category: " + cat,
exception=err,
)
except Exception as err:
bu.error("BattleCategorizationList()", exception=err)
def __iter__(self):
"""Returns the Iterator object"""
return BattleCategorizationListIterator(self)
def len(self):
return len(self.categorizations)
def get_categorization(self, cat: str):
"""Return a BattleCategorization for a category"""
try:
return self.categorizations[cat]
except Exception as err:
bu.error(exception=err)
return None
def record_result(self, result: dict):
try:
for cat in self.categorizations_list:
self.categorizations[cat].record_result(result)
except Exception as err:
bu.error(exception=err)
return None
def calc_results(self):
try:
for cat in self.categorizations_list:
self.categorizations[cat].calc_results()
except Exception as err:
bu.error(exception=err)
return None
def record_url(self, result):
try:
self.url_title_max_len = max(self.url_title_max_len, len(result["title"]))
self.urls[result["title"]] = result["url"]
except Exception as err:
bu.error(exception=err)
return None
def print_results(self):
try:
for cat in self.categorizations_list:
self.categorizations[cat].print_results()
self.print_urls()
except Exception as err:
bu.error(exception=err)
def print_urls(self):
try:
if len(self.urls) > 0:
print("\nURLs to Battle replays:")
for title in self.urls:
print(
("{:" + str(3 + self.url_title_max_len) + "}").format(title)
+ " : "
+ self.urls[title]
)
except Exception as err:
bu.error(exception=err)
def get_filter_categories(self, cat: str, filters: list) -> dict:
try:
return self.categorizations[str(cat)].get_filter_categories(filters)
except Exception as err:
bu.error(exception=err)
return None
def get_categories(self, result: dict) -> dict:
"""Get categories for each categorization in the CategorizationList() for a battle result"""
try:
res = dict()
for cat in self.categorizations_list:
res[cat] = self.categorizations[cat].get_category(result)
return res
except Exception as err:
bu.error(exception=err)
return None
def get_results_json(self):
try:
res = dict()
for cat in self.categorizations_list:
res[cat] = self.categorizations[cat].get_results_json()
res["replay_urls"] = self.urls
return res
except Exception as err:
bu.error(exception=err)
return None
def get_results_list(self, urls: bool = False):
try:
res = list()
for cat in self.categorizations_list:
res.append("")
res.extend(self.categorizations[cat].get_results_list())
if urls:
res.append("")
for url in self.urls:
res.append(url)
return res
except Exception as err:
bu.error(exception=err)
return None
class BattleCategorizationListIterator:
def __init__(self, btl_cats: BattleCategorizationList) -> None:
self._btl_cats = btl_cats
self._ndx = 0
def __next__(self):
if self._ndx < len(self._btl_cats.categorizations_list):
cat = self._btl_cats.categorizations_list[self._ndx]
res = self._btl_cats.categorizations[cat]
self._ndx += 1
return res
raise StopIteration
class BattleCategorization:
RESULT_CAT_HEADER_LEN = 15
RESULT_CAT_HEADER_FRMT = "{:_<" + str(RESULT_CAT_HEADER_LEN) + "s}"
RESULT_CAT_FRMT = "{:>" + str(RESULT_CAT_HEADER_LEN) + "s}"
def __init__(self, cat_key: str, title: str):
self.total_battles = 0
self.category_key = cat_key
self.title = title
self.categories = collections.defaultdict(def_value_BattleCategory)
def set_cat_header_format(self, header_len: int, left_aligned: bool = False):
self.RESULT_CAT_HEADER_LEN = header_len
self.RESULT_CAT_HEADER_FRMT = "{:_<" + str(header_len) + "s}"
if left_aligned:
self.RESULT_CAT_FRMT = "{:<" + str(header_len) + "s}"
else:
self.RESULT_CAT_FRMT = "{:>" + str(header_len) + "s}"
def get_categories(self):
"""Get category keys sorted"""
return sorted(self.categories.keys(), key=str.casefold)
### PER Child Class
def get_category(self, result: dict) -> str:
"""Get category. Must be implemented in the child classes"""
return "NONE"
def get_filter_categories(self, filters: list) -> list:
try:
if type(filters) != list:
filters = [filters]
return [x for x in filters if x in self.get_categories()]
except Exception as err:
bu.error("Category: " + str(self.category_key), exception=err)
return None
def help(self):
"""Help"""
FORMAT = "\t{:<15s}\t{}. Options:"
print(FORMAT.format(self.category_key, self.title), end=" ")
def record_result(self, result: dict) -> bool:
try:
cat = self.get_category(result)
self.categories[cat].record_result(result)
self.total_battles += 1
return True
except KeyError as err:
bu.error("Category key not found: " + cat, exception=err)
except Exception as err:
bu.error("Category key: " + cat, exception=err)
return False
def calc_results(self):
try:
for cat in self.get_categories():
self.categories[cat].calc_results(self.total_battles)
except Exception as err:
bu.error(exception=err)
def print_headers(self):
try:
if len(self.title) > self.RESULT_CAT_HEADER_LEN:
cat_name = self.title[: self.RESULT_CAT_HEADER_LEN]
else:
cat_name = self.title
header = self.RESULT_CAT_HEADER_FRMT.format(cat_name)
BattleCategory.print_headers(header)
return None
except Exception as err:
bu.error(exception=err)
def get_headers(self) -> list:
"""Get BattleCategory headers as list"""
try:
return BattleCategory.get_headers(self.title)
except Exception as err:
bu.error(exception=err)
return None
def print_results(self):
try:
bu.print_new_line()
self.print_headers()
for cat in self.get_categories():
if len(cat) > self.RESULT_CAT_HEADER_LEN:
cat_name = cat[: self.RESULT_CAT_HEADER_LEN]
else:
cat_name = cat
print(self.RESULT_CAT_FRMT.format(cat_name), end=" ")
self.categories[cat].print_results()
except KeyError as err:
bu.error("Key not found", err)
except Exception as err:
bu.error(exception=err)
return None
def get_results_json(self) -> dict:
"""Get results in JSON format"""
try:
results = dict()
results["categorization"] = self.title
results["category_key"] = self.category_key
for cat in self.get_categories():
results[cat] = self.categories[cat].get_results()
return results
except KeyError as err:
bu.error("Key not found", err)
return None
def get_results_list(self) -> list:
"""Get results in list format (for CSV printing)"""
try:
results = list()
results.append(self.get_headers())
for cat in self.get_categories():
results.append([cat] + self.categories[cat].get_results_list())
return results
except KeyError as err:
bu.error("Key not found", err)
return None
class BattleTotals(BattleCategorization):
TOTAL = "Total"
def __init__(self, title: str):
super().__init__(self.TOTAL, title)
def get_category(self, result: dict) -> str:
return self.TOTAL
def get_categories(self) -> str:
return [self.TOTAL]
def help(self):
super().help()
print("-")
class BattleClassCategorization(BattleCategorization):
"""Class for categorization by fixed classes with ID (int)"""
def __init__(self, cat_key: str, title: str, classes: list):
super().__init__(cat_key, title)
self.category_labels = classes
def help(self):
super().help()
labels = list()
for ndx in range(0, len(self.category_labels)):
labels.append(str(ndx) + "=" + self.category_labels[ndx])
print(", ".join(labels))
def get_category(self, result: dict) -> str:
"""Get category"""
cat_id = -1
try:
cat_id = result[self.category_key]
return self.category_labels[cat_id]
except KeyError as err:
bu.error(
"Category: " + str(self.category_key) + " ID: " + str(cat_id),
exception=err,
)
except Exception as err:
bu.error(
"Category: " + str(self.category_key) + " ID: " + str(cat_id),
exception=err,
)
return None
def get_filter_categories(self, filters: list) -> list:
try:
# bu.debug(str(filters), force=True)
if type(filters) != list:
filters = [filters]
bu.debug(str(self.category_labels))
res = list()
for ndx in filters:
if ndx in range(0, len(self.category_labels)):
res.append(self.category_labels[ndx])
return res
# return [ self.category_labels[int(x)] for x in filters if x in range(0, len(self.get_categories())) ]
except Exception as err:
bu.error("Category: " + str(self.category_key), exception=err)
return None
def get_categories(self) -> list:
try:
cats = list()
for cat in self.category_labels:
if cat in self.categories.keys():
cats.append(cat)
return cats
except KeyError as err:
bu.error("Key not found", exception=err)
except Exception as err:
bu.error(exception=err)
return None
class BattleStringCategorization(BattleCategorization):
"""Class for categorization by string"""
def __init__(self, cat_key: str, title: str, params: list):
super().__init__(cat_key, title)
if params is not None and len(params) > 0:
width = params[0]
left_align = True # align long category names left by default
if len(params) > 1:
left_align = params[1]
self.set_cat_header_format(width, left_align)
def get_category(self, result: dict) -> str:
"""Get category"""
try:
return result[self.category_key]
except KeyError as err:
bu.error("Category key: " + self.category_key + " not found", exception=err)
except Exception as err:
bu.error("Category: " + self.category_key, exception=err)
return None
def get_categories(self):
"""Get category keys sorted"""
try:
p_number_sort = re.compile(r"^(\d+): .+")
cats = list(self.categories.keys())
if p_number_sort.match(cats[0]) is not None:
ndxs = sorted(
range(len(cats)), key=lambda k: int(cats[k][: cats[k].find(":")])
)
return [cats[i] for i in ndxs]
else:
return sorted(cats, key=str.casefold)
except Exception as err:
bu.error("Category: " + self.category_key, exception=err)
return None
def get_filter_categories(self, filters: list) -> list:
try:
if type(filters) != list:
filters = [filters]
return [x for x in filters if x in self.get_categories()]
# return filters
except Exception as err:
bu.error("Category: " + str(self.category_key), exception=err)
return None
def help(self):
super().help()
print(self.title + " name")
class BattleNumberCategorization(BattleCategorization):
"""Class for categorization by number"""
def get_category(self, result: dict) -> str:
"""Get category as"""
try:
return str(result[self.category_key])
except KeyError as err:
bu.error("Category: " + str(self.category_key), exception=err)
except Exception as err:
bu.error("Category: " + str(self.category_key), exception=err)
return None
def get_categories(self) -> list:
try:
return map(str, sorted(map(int, self.categories.keys())))
except KeyError as err:
bu.error("Key not found", exception=err)
return None
def get_filter_categories(self, filters: list) -> list:
try:
if type(filters) != list:
filters = [filters]
return list(map(str, filters))
except Exception as err:
bu.error("Category: " + str(self.category_key), exception=err)
return None
def help(self):
super().help()
print("INTEGER")
class BattleBucketCategorization(BattleCategorization):
"""Class for categorization by buckets based on value"""
def __init__(self, cat_key: str, title: str, breaks: list, bucket_format=""):
try:
super().__init__(cat_key, title)
self.breaks = breaks
self.bucket_format = bucket_format
self.category_labels = self.mk_category_labels(breaks, bucket_format)
except Exception as err:
bu.error("BattleBucketCategorization()", exception=err)
def help(self):
super().help()
labels = list()
for ndx in range(0, len(self.category_labels)):
labels.append(str(ndx) + "=" + self.category_labels[ndx])
print(", ".join(labels))
def get_category(self, result: dict) -> str:
"""Get category"""
cat_id = -1
value = None
try:
value = result[self.category_key]
cat_id = self.find_bucket(value, self.breaks)
return self.category_labels[cat_id]
except KeyError as err:
bu.error(
"Category: "
+ str(self.category_key)
+ " value: "
+ str(value)
+ " cat ID: "
+ str(cat_id),
exception=err,
)
except Exception as err:
bu.error(
"Category: "
+ str(self.category_key)
+ " value: "
+ str(value)
+ " cat ID: "
+ str(cat_id),
exception=err,
)
return None