-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolver.py
More file actions
executable file
·2334 lines (1911 loc) · 95.3 KB
/
Copy pathsolver.py
File metadata and controls
executable file
·2334 lines (1911 loc) · 95.3 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
import argparse
import csv
import os
import subprocess
import time
import random
import multiprocessing
import signal
import sys
# ============================================================================
# SLOT AND TYPE NORMALIZATION DATA STRUCTURES
# ============================================================================
# All slot and type names are normalized to lowercase canonical forms.
# This centralizes all naming variations in one place for easy maintenance.
# Canonical slot names (the "correct" names we use throughout the code)
CANONICAL_SLOTS = {
'helm', 'chest', 'shoulders', 'gloves', 'pants', 'boots', 'belt',
'amulet', 'medal', 'ring 1', 'ring 2'
}
# Slot name aliases: maps alternate names to canonical names
SLOT_ALIASES = {
'head': 'helm',
'helmet': 'helm',
'shoulder': 'shoulders',
'hands': 'gloves',
'leg': 'pants',
'legs': 'pants',
'foot': 'boots',
'waist': 'belt',
'rings': 'ring', # Plural form used in CSV for components/augments that apply to rings
'amulets': 'amulet', # Plural form used in CSV
}
# Special slot handling
# 'ring' (singular) matches both 'ring 1' and 'ring 2' for components/augments
# 'armor' expands to all armor pieces (helm, chest, shoulders, gloves, pants, boots, belt)
MULTI_SLOT_TYPES = {
'ring': ['ring 1', 'ring 2'],
'armor': ['helm', 'chest', 'shoulders', 'gloves', 'pants', 'boots', 'belt']
}
# Item type aliases for special types
ITEM_TYPE_ALIASES = {
'component': 'component',
'augment': 'augment',
}
# Global flag for interrupt handling
interrupted = False
def signal_handler(signum, frame):
"""Handle Ctrl+C gracefully."""
global interrupted
if not interrupted: # Only print message once
interrupted = True
print("\n\nInterrupted by user. Finishing current cycle and showing best results found so far...")
def check_and_convert_ods():
"""Checks if the ODS file is newer than the CSV and converts it if necessary."""
ods_file = 'grim_items.ods'
csv_file = 'grim_items.csv'
if not os.path.exists(csv_file) or os.path.getmtime(ods_file) > os.path.getmtime(csv_file):
print(f"'{ods_file}' is newer than '{csv_file}' or '{csv_file}' does not exist. Converting...")
try:
subprocess.run(
['libreoffice', '--headless', '--convert-to', 'csv', ods_file],
check=True,
capture_output=True,
text=True
)
print("Conversion successful.")
except (subprocess.CalledProcessError, FileNotFoundError) as e:
print(f"Error during conversion: {e}")
if isinstance(e, FileNotFoundError):
print("Please ensure 'libreoffice' is installed and in your PATH.")
else:
print(f"Stderr: {e.stderr}")
exit(1)
def parse_row_float(row, header, default_value=0):
"""Helper function to parse a row of floats with error handling."""
parsed_row = {}
for i, item in enumerate(row):
try:
parsed_row[header[i]] = float(item) if item else default_value
except ValueError:
parsed_row[header[i]] = default_value
return parsed_row
def normalize_slot_name(slot_name):
"""Normalize slot names to canonical form using centralized SLOT_ALIASES.
Args:
slot_name: Raw slot/gear type name from CSV
Returns:
Normalized slot name in lowercase canonical form
Examples:
'Head' -> 'helm'
'Shoulder' -> 'shoulders'
'Ring' -> 'ring' (special case, matches 'ring 1' and 'ring 2')
"""
if not slot_name:
return ''
normalized = slot_name.strip().lower()
return SLOT_ALIASES.get(normalized, normalized)
def normalize_item_type(item_type):
"""Normalize item type names (Component, Augment, etc).
Args:
item_type: Raw item type from CSV
Returns:
Normalized item type in lowercase
"""
if not item_type:
return ''
normalized = item_type.strip().lower()
return ITEM_TYPE_ALIASES.get(normalized, normalized)
def expand_applies_to(applies_to_str):
"""Parse and expand applies_to field, handling multi-slot types like 'armor' and 'ring'.
Args:
applies_to_str: Comma-separated list of slot names from CSV
Returns:
List of normalized slot names with multi-slot types expanded
Example:
'armor,amulet' -> ['helm', 'chest', 'shoulders', 'gloves', 'pants', 'boots', 'belt', 'amulet']
"""
if not applies_to_str:
return []
expanded = []
raw_slots = [s.strip() for s in applies_to_str.split(',') if s.strip()]
for slot in raw_slots:
normalized = normalize_slot_name(slot)
# Check if this is a multi-slot type that needs expansion
if normalized in MULTI_SLOT_TYPES:
expanded.extend(MULTI_SLOT_TYPES[normalized])
else:
expanded.append(normalized)
return expanded
def infer_component_augment_slots(items_needing_inference, equipped_base_gear):
"""Infer which slot a component/augment is equipped in based on tf count and applies_to.
Args:
items_needing_inference: List of component/augment items with tf > 0 but no equipped_in
equipped_base_gear: Dict of {slot: base_item} for currently equipped base gear
Returns:
Dict of {item_name: slot} for inferred assignments
List of warning messages for ambiguous cases
"""
inferred = {}
warnings = []
for item in items_needing_inference:
# Parse applies_to
applies_to_str = item.get('applies_to', '').strip()
if not applies_to_str:
warnings.append(
f"WARNING: {item['type']} '{item['name']}' has tf={item['tf']} but no applies_to field. "
f"Cannot infer slot."
)
continue
applies_to_raw = [s.strip() for s in applies_to_str.split(',') if s.strip()]
valid_slots = [normalize_slot_name(s) for s in applies_to_raw]
# Filter to only equipped slots
equipped_valid_slots = [
slot for slot in valid_slots
if slot in equipped_base_gear or
('ring' in valid_slots and slot in ['ring 1', 'ring 2'] and
(slot in equipped_base_gear))
]
# Handle 'ring' matching both ring 1 and ring 2
if 'ring' in valid_slots:
for ring_slot in ['ring 1', 'ring 2']:
if ring_slot in equipped_base_gear and ring_slot not in equipped_valid_slots:
equipped_valid_slots.append(ring_slot)
if len(equipped_valid_slots) == 0:
warnings.append(
f"WARNING: {item['type']} '{item['name']}' is marked as equipped (tf={item['tf']}) "
f"but no equipped gear matches applies_to='{applies_to_str}'. "
f"Please check your tf column or equipped_in column."
)
elif len(equipped_valid_slots) == 1:
# Unambiguous - only one possible slot
inferred[item['name']] = equipped_valid_slots[0]
else:
# Ambiguous - multiple possibilities
# Strategy: Use first valid slot and warn
inferred[item['name']] = equipped_valid_slots[0]
warnings.append(
f"WARNING: {item['type']} '{item['name']}' could be in {', '.join(equipped_valid_slots)}. "
f"Using {equipped_valid_slots[0]} as best guess. "
f"Specify equipped_in column for accuracy."
)
return inferred, warnings
def sort_rings_by_benefit(gear_dict, header, points_per_unit, max_points):
"""Sort rings so that highest benefit ring is always in ring 1.
This ensures consistent display across runs even when GA finds same rings in different order.
Called only during display phase, has no impact on solver performance.
Args:
gear_dict: Dict of {slot: {'base': item, 'component': item, 'augment': item}}
header: CSV header
points_per_unit: Benefit points per stat unit
max_points: Maximum benefit caps per stat
Returns:
Modified gear_dict with rings sorted by benefit (in-place modification)
"""
if 'ring 1' not in gear_dict or 'ring 2' not in gear_dict:
return gear_dict
# Calculate benefit for each ring slot (base + component + augment)
def calculate_slot_benefit(slot_data):
total_benefit = 0
for item in [slot_data.get('base'), slot_data.get('component'), slot_data.get('augment')]:
if not item:
continue
for stat, value in item.get('stats', {}).items():
if stat in points_per_unit:
capped_value = min(value, max_points.get(stat, float('inf')))
total_benefit += capped_value * points_per_unit[stat]
return total_benefit
ring1_benefit = calculate_slot_benefit(gear_dict['ring 1'])
ring2_benefit = calculate_slot_benefit(gear_dict['ring 2'])
# If ring 2 has higher benefit, swap them
if ring2_benefit > ring1_benefit:
gear_dict['ring 1'], gear_dict['ring 2'] = gear_dict['ring 2'], gear_dict['ring 1']
return gear_dict
def get_current_gear_with_components_augments(all_items, gear_by_type, components, augments):
"""Reconstruct the player's current full gear setup including components and augments.
Args:
all_items: All items from CSV (raw dict format)
gear_by_type: Dict of {type: [items]} for base gear
components: List of all component items
augments: List of all augment items
Returns:
Dict of {slot: {'base': item, 'component': item or None, 'augment': item or None}}
"""
# Find equipped base gear (tf=1)
equipped_base = {}
ring1_assigned = False
for item in all_items:
item_type_normalized = normalize_item_type(item.get('type', ''))
if item.get('tf') == '1' and item_type_normalized not in ['component', 'augment']:
gear_type = item['type']
if gear_type:
# Normalize and handle rings
normalized_type = normalize_slot_name(gear_type)
if normalized_type == 'ring':
if not ring1_assigned:
slot = 'ring 1'
ring1_assigned = True
else:
slot = 'ring 2'
else:
slot = normalized_type
# Check if slot is already occupied
if slot in equipped_base:
print(f"\nERROR: Multiple items selected for the same slot!")
print(f" Slot: {slot}")
print(f" First item: {equipped_base[slot]['name']}")
print(f" Second item: {item['name']}")
print(f"\nPlease ensure only ONE item has tf=1 for each gear slot.")
print(f"Check your CSV file (grim_items.csv) and set tf=0 for one of the above items.\n")
exit(1)
equipped_base[slot] = item
# Find equipped components and augments (tf > 0)
equipped_components = []
equipped_augments = []
for item in components:
tf_val = item.get('tf', '0')
try:
if int(tf_val) > 0:
equipped_components.append(item)
except (ValueError, TypeError):
pass
for item in augments:
tf_val = item.get('tf', '0')
try:
if int(tf_val) > 0:
equipped_augments.append(item)
except (ValueError, TypeError):
pass
# Infer slots for components/augments
slot_assignments_comp, warnings_comp = infer_component_augment_slots(
[c for c in equipped_components if not c.get('equipped_in', '').strip()],
equipped_base
)
slot_assignments_aug, warnings_aug = infer_component_augment_slots(
[a for a in equipped_augments if not a.get('equipped_in', '').strip()],
equipped_base
)
# Print warnings
for warning in warnings_comp + warnings_aug:
print(warning)
# Build final current gear state
current_gear = {}
for slot, base_item in equipped_base.items():
current_gear[slot] = {
'base': base_item,
'component': None,
'augment': None
}
# Assign components to slots
for comp in equipped_components:
# Check if equipped_in is explicitly specified
equipped_in_raw = comp.get('equipped_in', '').strip()
if equipped_in_raw:
# Handle comma-separated slots (e.g., "helm,chest")
slots = [normalize_slot_name(s) for s in equipped_in_raw.split(',') if s.strip()]
else:
slot = slot_assignments_comp.get(comp['name'])
slots = [slot] if slot else []
for slot in slots:
if slot and slot in current_gear:
current_gear[slot]['component'] = comp
# Assign augments to slots
for aug in equipped_augments:
# Check if equipped_in is explicitly specified
equipped_in_raw = aug.get('equipped_in', '').strip()
if equipped_in_raw:
# Handle comma-separated slots (e.g., "helm,chest")
slots = [normalize_slot_name(s) for s in equipped_in_raw.split(',') if s.strip()]
else:
slot = slot_assignments_aug.get(aug['name'])
slots = [slot] if slot else []
for slot in slots:
if slot and slot in current_gear:
current_gear[slot]['augment'] = aug
return current_gear
def get_gear_stats(gear_list, header):
"""Calculates the total stats for a list of gear."""
total_stats = {stat: 0.0 for stat in header}
for item in gear_list:
for stat, value in item.get('stats', {}).items():
total_stats[stat] += value
return total_stats
def display_stat_comparison(current_gear, recommended_gear, header, points_per_unit, max_points):
"""Displays a detailed comparison of stats and benefit scores."""
current_stats = get_gear_stats(current_gear, header)
recommended_stats = get_gear_stats(recommended_gear, header)
print("\n--- Stat Comparison ---")
print(f"{'Stat':<15} {'Weight':>8} {'Current':>10} {'New':>10} {'Change':>10} {'New Stats':>12} {'Max':>8}")
print(f"{'':<15} {'':>8} {'Benefit':>10} {'Benefit':>10} {'':>10} {'(Points)':>12} {'':>8}")
print("-" * 80)
total_current_benefit = 0
total_recommended_benefit = 0
for stat in header:
# Skip stats with zero or negative weight (metadata columns like tf, type, name, etc.)
weight = points_per_unit.get(stat, 0)
if weight <= 0:
continue
current_stat_points = current_stats.get(stat, 0)
recommended_stat_points = recommended_stats.get(stat, 0)
max_val = max_points.get(stat, float('inf'))
# Apply caps when calculating benefits for display
capped_current = min(current_stat_points, max_val)
capped_recommended = min(recommended_stat_points, max_val)
current_benefit = capped_current * weight
recommended_benefit = capped_recommended * weight
change = recommended_benefit - current_benefit
total_current_benefit += current_benefit
total_recommended_benefit += recommended_benefit
if current_stat_points != 0 or recommended_stat_points != 0:
max_display = str(round(max_val)) if max_val != float('inf') else "N/A"
print(f"{stat:<15} {weight:>8.2f} {round(current_benefit):>10} {round(recommended_benefit):>10} {round(change):>+10} {round(recommended_stat_points):>12} {max_display:>8}")
print("-" * 80)
total_change = total_recommended_benefit - total_current_benefit
print(f"{'Total Benefit':<15} {'':>8} {round(total_current_benefit):>10} {round(total_recommended_benefit):>10} {round(total_change):>+10}")
def display_stat_comparison_new(current_gear_dict, optimal_gear_dict, header, points_per_unit, max_points, baseline, current_benefit, optimal_benefit):
"""Displays compact stat comparison with baseline, cap-integrated display, and total points.
Args:
current_gear_dict: Dict of {slot: {'base': item, 'component': item, 'augment': item}}
optimal_gear_dict: Dict of {slot: {'base': item, 'component': item, 'augment': item}}
header: CSV header
points_per_unit: Benefit points per stat unit
max_points: Maximum benefit caps per stat
baseline: Baseline stat values from skills/difficulty
current_benefit: Pre-calculated current benefit score (from calculate_fitness)
optimal_benefit: Pre-calculated optimal benefit score (from calculate_fitness)
"""
# Column width constants for consistent formatting
COL_STAT_WIDTH = 10
COL_WEIGHT_WIDTH = 4
COL_CUROPT_WIDTH = 17 # Fits: "9999 → 9999 / 999" (supports up to 3-digit max values)
COL_POINTS_WIDTH = 3
COL_SOURCES_WIDTH = 80 # Increased from 77 (gained 3 chars from COL_CUROPT_WIDTH reduction)
SEP = " " # Standard separator between columns
# Calculate total stats for current and optimal (raw values from gear only, not including baseline)
def calculate_total_stats(gear_dict):
total_stats = {stat: 0.0 for stat in header}
for slot, gear_set in gear_dict.items():
# Base item
if gear_set.get('base'):
for stat, val in gear_set['base'].get('stats', {}).items():
total_stats[stat] += val
# Component
if gear_set.get('component'):
for stat, val in gear_set['component'].get('stats', {}).items():
total_stats[stat] += val
# Augment
if gear_set.get('augment'):
for stat, val in gear_set['augment'].get('stats', {}).items():
total_stats[stat] += val
return total_stats
current_stats = calculate_total_stats(current_gear_dict)
optimal_stats = calculate_total_stats(optimal_gear_dict)
# Display baseline stats section (only show non-zero values)
baseline_display = []
for stat in header:
# Skip stats with zero or negative weight (metadata columns like tf, type, name, etc.)
weight = points_per_unit.get(stat, 0)
if weight <= 0:
continue
baseline_val = baseline.get(stat, 0)
if baseline_val != 0:
baseline_display.append(f"{stat}: {baseline_val:+.0f}" if baseline_val != int(baseline_val) else f"{stat}: {int(baseline_val):+d}")
if baseline_display:
print("=" * 120)
print("BASELINE STATS (from skills + difficulty)")
print("=" * 120)
print(" | ".join(baseline_display))
print()
print("=" * 120)
print("STAT COMPARISON")
print("=" * 120)
print(f"{'Stat':<{COL_STAT_WIDTH}}{SEP}{'Wgt':>{COL_WEIGHT_WIDTH}}{SEP}{'Cur → Opt':<{COL_CUROPT_WIDTH}}{SEP}{'Pts':>{COL_POINTS_WIDTH}}{SEP}{'Sources (optimal)'}")
print("─" * 120)
# Collect stats with non-zero values
stats_to_display = []
for stat in header:
# Skip stats with zero or negative weight (metadata columns like tf, type, name, etc.)
weight = points_per_unit.get(stat, 0)
if weight <= 0:
continue
current_val = current_stats.get(stat, 0)
optimal_val = optimal_stats.get(stat, 0)
if current_val != 0 or optimal_val != 0:
stats_to_display.append(stat)
for stat in stats_to_display:
weight = points_per_unit.get(stat, 0)
current_val_gear = current_stats.get(stat, 0)
optimal_val_gear = optimal_stats.get(stat, 0)
baseline_val = baseline.get(stat, 0)
max_val = max_points.get(stat, float('inf'))
# Add baseline to gear stats to get total values
current_val = current_val_gear + baseline_val
optimal_val = optimal_val_gear + baseline_val
# Apply caps to total values
capped_optimal_total = min(optimal_val, max_val)
capped_baseline = min(baseline_val, max_val)
# Calculate marginal benefit points for optimal (gear contribution only)
gear_contribution = capped_optimal_total - capped_baseline
stat_optimal_benefit = gear_contribution * weight
# Calculate sources
sources = calculate_sources_for_stat(stat, optimal_gear_dict, header)
sources_str = format_sources_column(sources, max_width=COL_SOURCES_WIDTH)
# Format Cur → Opt column with aligned arrow and aligned slash
# Right-align current value, arrow, then right-align optimal (which aligns the /)
if max_val != float('inf'):
opt_str = f"{int(current_val):>4} → {int(optimal_val):>4} / {int(max_val)}"
else:
opt_str = f"{int(current_val):>4} → {int(optimal_val):>4}"
# Format points (total benefit from this stat)
points_str = f"{int(stat_optimal_benefit)}"
print(f"{stat:<{COL_STAT_WIDTH}}{SEP}{weight:>{COL_WEIGHT_WIDTH}.2f}{SEP}{opt_str:<{COL_CUROPT_WIDTH}}{SEP}{points_str:>{COL_POINTS_WIDTH}}{SEP}{sources_str}")
print("─" * 120)
# Use the pre-calculated benefit totals passed in as parameters
improvement = optimal_benefit - current_benefit
improvement_pct = (improvement / current_benefit * 100) if current_benefit > 0 else 0
print(f"TOTAL: {int(current_benefit)} → {int(optimal_benefit)} ({improvement:+.0f} points, {improvement_pct:+.1f}%)")
print("=" * 120)
def display_swap_analysis(currently_equipped, best_combination, points_per_unit, max_points):
"""Displays detailed analysis of each gear swap with stat-by-stat benefit breakdown."""
current_gear_map = {item['type']: item for item in currently_equipped}
best_gear_map = {item['type']: item for item in best_combination}
all_slots = sorted(list(set(current_gear_map.keys()) | set(best_gear_map.keys())))
# Collect all swaps with their benefit changes
swaps = []
for slot in all_slots:
current_item = current_gear_map.get(slot)
best_item = best_gear_map.get(slot)
if current_item and best_item and current_item['name'] != best_item['name']:
current_benefit = current_item.get('calculated_value', 0)
best_benefit = best_item.get('calculated_value', 0)
benefit_change = best_benefit - current_benefit
swaps.append({
'slot': slot,
'current_item': current_item,
'best_item': best_item,
'benefit_change': benefit_change
})
if not swaps:
return
# Sort by benefit change (highest improvement first)
swaps.sort(key=lambda x: x['benefit_change'], reverse=True)
print("\n=== DETAILED SWAP ANALYSIS ===")
print("(Sorted by benefit improvement, highest first)\n")
for i, swap in enumerate(swaps, 1):
slot = swap['slot']
current_item = swap['current_item']
best_item = swap['best_item']
benefit_change = swap['benefit_change']
print(f"{i}. {slot.upper()}: {current_item['name']} -> {best_item['name']}")
print(f" Net Change: {benefit_change:+.1f} benefit points")
print()
# Calculate stat differences
current_stats = current_item.get('stats', {})
best_stats = best_item.get('stats', {})
# Collect all stats that changed
all_stats = set(current_stats.keys()) | set(best_stats.keys())
stat_changes = []
for stat in all_stats:
if stat in ['tf', 'type', 'name', 'Total', 'calculated_value', 'stats']:
continue
current_val = current_stats.get(stat, 0)
best_val = best_stats.get(stat, 0)
if current_val != best_val:
weight = points_per_unit.get(stat, 0)
max_val = max_points.get(stat, float('inf'))
# Calculate capped benefits
current_capped = min(current_val, max_val)
best_capped = min(best_val, max_val)
current_benefit = current_capped * weight
best_benefit = best_capped * weight
benefit_diff = best_benefit - current_benefit
stat_changes.append({
'stat': stat,
'current_val': current_val,
'best_val': best_val,
'weight': weight,
'benefit_diff': benefit_diff,
'is_capped': best_capped < best_val or current_capped < current_val
})
# Sort by absolute benefit difference
stat_changes.sort(key=lambda x: abs(x['benefit_diff']), reverse=True)
# Display stat changes
print(f" {'Stat':<10} {'Old':>8} {'New':>8} {'Change':>8} {'Weight':>8} {'Benefit':>10}")
print(f" {'-'*62}")
for sc in stat_changes:
stat_display = sc['stat']
if sc['is_capped']:
stat_display += "*" # Mark capped stats with asterisk
val_change = sc['best_val'] - sc['current_val']
print(f" {stat_display:<10} {sc['current_val']:>8.1f} {sc['best_val']:>8.1f} "
f"{val_change:>+8.1f} x{sc['weight']:>6.2f} = {sc['benefit_diff']:>+8.1f}")
print()
print("* = Stat is at or exceeds cap (benefit calculation uses capped value)")
print()
def display_gear_comparison(currently_equipped, best_combination):
"""Displays a comparison table of currently equipped vs. recommended gear."""
print("\n**Currently Equipped Gear vs. Recommended Gear**")
print("\n| Slot | Current Gear | CurBen | | Recommended Gear | RecBen |")
print("| :-------- | :---------------------------------------------- | :----- | :- | :---------------------------------------------- | :----- |")
current_gear_map = {item['type']: item for item in currently_equipped}
best_gear_map = {item['type']: item for item in best_combination}
all_slots = sorted(list(set(current_gear_map.keys()) | set(best_gear_map.keys())))
total_current_benefit = 0
total_best_benefit = 0
for slot in all_slots:
current_item = current_gear_map.get(slot)
best_item = best_gear_map.get(slot)
# Format current item name with component/augment
if current_item:
current_name = current_item.get('display_name', current_item['name'])
else:
current_name = "None"
current_benefit = round(current_item.get('calculated_value', 0)) if current_item else 0
total_current_benefit += current_benefit
# Format best item name with component/augment
if best_item:
best_name = best_item.get('display_name', best_item['name'])
else:
best_name = "None"
best_benefit = round(best_item.get('calculated_value', 0)) if best_item else 0
total_best_benefit += best_benefit
change_indicator = "->" if current_name != best_name else ""
print(f"| {slot.capitalize():<9} | {current_name:<47} | {current_benefit:<6} | {change_indicator:<2} | {best_name:<47} | {best_benefit:<6} |")
print(f"| Total | {'':<47} | {total_current_benefit:<6} | | {'':<47} | {total_best_benefit:<6} |")
def _item_name(item):
"""Helper to safely get item name or None."""
return item['name'] if item else None
def format_item_stats(item, header, points_per_unit, max_width=80):
"""Format stats for a single item, sorted by benefit points.
Args:
item: Item dict with stats
header: CSV header
points_per_unit: Benefit points per stat unit
max_width: Maximum character width for stats display
Returns:
String like "rFire(50), hlth(100), +%ts(5)" sorted by benefit value
"""
if not item:
return ""
# Collect all stats with their values and benefit points
stats_with_benefit = []
for stat in header:
if stat in ['tf', 'type', 'name', 'Total', 'calculated_value', 'stats', 'applies_to', 'equipped_in', 'note', 'Misc', 'poten']:
continue
try:
value = float(item.get(stat, 0) or 0)
if value > 0:
weight = points_per_unit.get(stat, 0)
benefit = value * weight
stats_with_benefit.append((stat, value, benefit))
except (ValueError, TypeError):
pass
# Sort by benefit descending
stats_with_benefit.sort(key=lambda x: x[2], reverse=True)
# Format as stat(value)
formatted = []
for stat, value, _ in stats_with_benefit:
if value == int(value):
formatted.append(f"{stat}({int(value)})")
else:
formatted.append(f"{stat}({value:.1f})")
if not formatted:
return ""
result = ", ".join(formatted)
# If too long, truncate and add "+N"
if len(result) > max_width:
truncated = []
current_length = 0
for i, item_str in enumerate(formatted):
remaining_count = len(formatted) - i
suffix = f", +{remaining_count}" if remaining_count > 0 else ""
suffix_len = len(suffix)
# Can we fit this item plus the suffix?
if current_length == 0: # First item, no leading ", "
needed = len(item_str) + suffix_len
else:
needed = current_length + 2 + len(item_str) + suffix_len # +2 for ", "
if needed <= max_width:
truncated.append(item_str)
if current_length == 0:
current_length = len(item_str)
else:
current_length += 2 + len(item_str)
else:
# Add the suffix and break
result = ", ".join(truncated) + f", +{len(formatted) - len(truncated)}"
return result
result = ", ".join(truncated)
return result
def _format_item_line(current_item, optimal_item):
"""
Format a single item line (base/component/augment) with hybrid display logic.
Returns:
- "old → new" if changed
- "name" if unchanged (for verification)
- "(none) → name" if adding to empty slot
- None if both empty (don't show line)
"""
current_name = _item_name(current_item)
optimal_name = _item_name(optimal_item)
if current_name == optimal_name:
# No change - show for verification if equipped
return optimal_name if optimal_name else None
elif current_name is None and optimal_name:
# Adding to empty slot
return f"(none) → {optimal_name}"
elif current_name and optimal_name is None:
# Removing (rare)
return f"{current_name} → (none)"
elif current_name and optimal_name:
# Swapping
return f"{current_name} → {optimal_name}"
else:
return None
def display_gear_swaps_new(current_gear_dict, optimal_gear_dict, header, points_per_unit, swaps_only=False):
"""Displays recommended gear configuration with stats for each item.
Display rules:
- Changed items show: old → new stat(value), stat(value), ... (with arrow)
- Unchanged items show: name stat(value), stat(value), ... (for verification, no arrow)
- Empty slots don't show (no line at all)
Args:
current_gear_dict: Dict of {slot: {'base': item, 'component': item, 'augment': item}}
optimal_gear_dict: Dict of {slot: {'base': item, 'component': item, 'augment': item}}
header: CSV header
points_per_unit: Benefit points per stat unit
swaps_only: If True, only show slots with changes (default: False, show all gear)
"""
all_slots = sorted(set(list(current_gear_dict.keys()) + list(optimal_gear_dict.keys())))
# Find slots that have changes
changing_slots = []
for slot in all_slots:
current = current_gear_dict.get(slot, {})
optimal = optimal_gear_dict.get(slot, {})
# Check if anything changed in this slot
base_changed = (current.get('base', {}).get('name') if current.get('base') else None) != \
(optimal.get('base', {}).get('name') if optimal.get('base') else None)
comp_changed = (current.get('component', {}).get('name') if current.get('component') else None) != \
(optimal.get('component', {}).get('name') if optimal.get('component') else None)
aug_changed = (current.get('augment', {}).get('name') if current.get('augment') else None) != \
(optimal.get('augment', {}).get('name') if optimal.get('augment') else None)
if base_changed or comp_changed or aug_changed:
changing_slots.append(slot)
# Determine which slots to display
if swaps_only:
slots_to_display = changing_slots
header_text = f"RECOMMENDED CHANGES ({len(changing_slots)} slots)"
else:
slots_to_display = all_slots
header_text = "RECOMMENDED GEAR CONFIGURATION"
if not changing_slots:
print("=" * 120)
print("RECOMMENDED CHANGES")
print("=" * 120)
print("\n No changes needed - your current gear is optimal!\n")
print("=" * 120)
return
# Display header
print("=" * 120)
print(header_text)
print("=" * 120)
print()
# Display each slot
for slot in slots_to_display:
current = current_gear_dict.get(slot, {})
optimal = optimal_gear_dict.get(slot, {})
# Slot name
print(f"{slot.upper()}")
# Format each field (base/component/augment) using hybrid display logic
base_line = _format_item_line(current.get('base'), optimal.get('base'))
comp_line = _format_item_line(current.get('component'), optimal.get('component'))
aug_line = _format_item_line(current.get('augment'), optimal.get('augment'))
# Get stats for optimal items
base_stats = format_item_stats(optimal.get('base'), header, points_per_unit, max_width=80)
comp_stats = format_item_stats(optimal.get('component'), header, points_per_unit, max_width=80)
aug_stats = format_item_stats(optimal.get('augment'), header, points_per_unit, max_width=80)
# Show lines that have content (None means both empty, don't show)
if base_line:
stats_suffix = f" {base_stats}" if base_stats else ""
print(f" Base: {base_line}{stats_suffix}")
if comp_line:
stats_suffix = f" {comp_stats}" if comp_stats else ""
print(f" Component: {comp_line}{stats_suffix}")
if aug_line:
stats_suffix = f" {aug_stats}" if aug_stats else ""
print(f" Augment: {aug_line}{stats_suffix}")
print()
print("=" * 120)
def display_performance_summary(comparisons_evaluated, elapsed_time):
"""Displays a one-liner performance summary."""
if elapsed_time > 0:
comparisons_per_sec = comparisons_evaluated / elapsed_time
print(f"Evaluated {comparisons_evaluated:,} gearsets in {elapsed_time:.2f} seconds ({comparisons_per_sec:,.0f} comparisons/sec)\n")
else:
print(f"Evaluated {comparisons_evaluated:,} gearsets in {elapsed_time:.2f} seconds\n")
def display_execution_summary(comparisons_evaluated, elapsed_time, current_benefit, optimal_benefit, num_cores, generation):
"""Displays a 2-line execution summary at the bottom of output.
This is the most important summary info that stays visible without scrolling.
"""
# Line 1: Solver performance metrics
if elapsed_time > 0:
comparisons_per_sec = comparisons_evaluated / elapsed_time
# Format large numbers nicely (e.g., 24.7T, 4.94T/s)
def format_large_number(n):
if n >= 1e12:
return f"{n/1e12:.1f}T"
elif n >= 1e9:
return f"{n/1e9:.1f}B"
elif n >= 1e6:
return f"{n/1e6:.1f}M"
elif n >= 1e3:
return f"{n/1e3:.1f}K"
else:
return f"{n:.0f}"
eval_str = format_large_number(comparisons_evaluated)
rate_str = format_large_number(comparisons_per_sec)
print(f"Evaluated {eval_str} combinations in {elapsed_time:.1f}s ({rate_str}/s) | {num_cores} cores | Generation {generation}")
else:
print(f"Evaluated {comparisons_evaluated:,} combinations in {elapsed_time:.1f}s | {num_cores} cores | Generation {generation}")
# Line 2: Benefit score comparison
improvement = optimal_benefit - current_benefit
if current_benefit > 0:
improvement_pct = (improvement / current_benefit) * 100
print(f"Current: {current_benefit:.0f} pts | Optimal: {optimal_benefit:.0f} pts | Improvement: {improvement:+.0f} pts ({improvement_pct:+.1f}%)")
else:
print(f"Current: {current_benefit:.0f} pts | Optimal: {optimal_benefit:.0f} pts | Improvement: {improvement:+.0f} pts")
def calculate_sources_for_stat(stat_name, gear_dict, header):
"""Calculate which slots/components/augments contribute to a stat.
Args:
stat_name: Name of stat to analyze
gear_dict: Dict of {slot: {'base': item, 'component': item, 'augment': item}}
header: CSV header
Returns:
List of tuples: [(source_name, value), ...] sorted by value descending
"""
sources = []
total_comp_value = 0
total_aug_value = 0
for slot, gear_set in gear_dict.items():
# Base gear contribution
base_item = gear_set.get('base')
if base_item and stat_name in header:
try:
base_value = float(base_item.get(stat_name, 0) or 0)
if base_value > 0:
sources.append((slot, base_value))
except (ValueError, TypeError):
pass
# Component contribution (aggregate all components)
component = gear_set.get('component')
if component and stat_name in header:
try:
comp_value = float(component.get(stat_name, 0) or 0)
if comp_value > 0:
total_comp_value += comp_value
except (ValueError, TypeError):
pass
# Augment contribution (aggregate all augments)
augment = gear_set.get('augment')
if augment and stat_name in header:
try:
aug_value = float(augment.get(stat_name, 0) or 0)
if aug_value > 0:
total_aug_value += aug_value
except (ValueError, TypeError):
pass
# Add aggregated component/augment values
if total_comp_value > 0:
sources.append(('comp', total_comp_value))
if total_aug_value > 0: