Spaces:
Sleeping

FajarHidaa commited on
Commit
5e00351
Β·
verified Β·
1 Parent(s): 1d9cd4b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +285 -72
app.py CHANGED
@@ -344,6 +344,18 @@ def calculate_waste(rolls, original_dims):
344
  return total_roll - total_true, (total_roll - total_true) / total_roll * 100 if total_roll else 100
345
 
346
 
 
 
 
 
 
 
 
 
 
 
 
 
347
  def simulated_annealing(rects, roll_width, max_height, allow_rotation,
348
  pack_algo, sort_algo, original_dims,
349
  initial_temp=100, cooling=0.995, max_iter=3000):
@@ -400,11 +412,55 @@ def simulated_annealing(rects, roll_width, max_height, allow_rotation,
400
  # 8. MULTI-WIDTH MULTI-ROLL (FIXED: tambah original_dims parameter)
401
  # --------------------------------------------------------------------------
402
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
403
  def pack_multi_width_multi_roll(rects, widths, max_height, allow_rotation,
404
  original_dims, # <-- FIX: tambah parameter ini
405
- pack_algo=None, sort_algo=None, reverse=False):
 
406
  """
407
  Packing di mana TIAP ROLL boleh beda lebar.
 
 
 
 
 
 
 
 
 
408
  """
409
  remaining = list(reversed(rects)) if reverse else rects[:]
410
  all_rolls = []
@@ -414,51 +470,124 @@ def pack_multi_width_multi_roll(rects, widths, max_height, allow_rotation,
414
  if not remaining:
415
  break
416
 
417
- best_roll = None
418
- best_waste = float('inf')
419
- best_width = None
420
- best_remaining = None
421
-
422
  for w in widths:
423
- kwargs = {"rotation": allow_rotation}
424
- if pack_algo:
425
- kwargs["pack_algo"] = pack_algo
426
- if sort_algo:
427
- kwargs["sort_algo"] = sort_algo
428
- packer = newPacker(**kwargs)
429
- for rect_w, rect_h, rid in remaining:
430
- packer.add_rect(rect_w, rect_h, rid=rid)
431
- packer.add_bin(w, max_height)
432
- packer.pack()
433
-
434
- if len(packer) == 0 or len(packer[0]) == 0:
435
  continue
 
 
436
 
437
- placed = packer[0]
438
- used_height = max(r.y + r.height for r in placed)
439
- placed_ids = {r.rid for r in placed}
440
 
441
- # FIX: gunakan parameter original_dims, bukan variabel global
442
- true_area = sum(
443
- (original_dims[rid][0] * original_dims[rid][1])
444
- for _, _, rid in remaining if rid in placed_ids
445
- )
446
- roll_area = w * used_height
447
- waste = roll_area - true_area
448
 
449
- if waste < best_waste:
450
- best_waste = waste
451
- best_roll = (placed, used_height, w)
452
- best_width = w
453
- best_remaining = [r for r in remaining if r[2] not in placed_ids]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
454
 
455
- if best_roll is None:
456
- return all_rolls, len(remaining)
457
 
458
- all_rolls.append(best_roll)
459
- remaining = best_remaining
460
 
461
- return all_rolls, len(remaining)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
462
 
463
 
464
  # --------------------------------------------------------------------------
@@ -629,7 +758,7 @@ def search_single_width(rects, original_dims, total_rects, max_height,
629
  if not_placed > 0:
630
  stats.insert(7, f"⚠️ Item TIDAK muat : {not_placed}")
631
 
632
- return img, "\n".join(stats), waste, waste_pct, num_rolls, tried, hit_target
633
 
634
 
635
  # --------------------------------------------------------------------------
@@ -694,41 +823,121 @@ def process(roll_widths_text, margin, allow_rotation, search_mode, target_waste_
694
  # MULTI-WIDTH MULTI-ROLL
695
  if enable_multiwidth and search_mode in ("pro", "exhaustive"):
696
  tried = 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
697
  for pack_algo in [None, MaxRectsBssf, GuillotineBssfSas]:
698
  for sort_algo in [None, SORT_AREA]:
699
  for reverse in [False, True]:
700
  tried += 1
701
- # FIX: pass original_dims ke fungsi
702
  rolls, not_placed = pack_multi_width_multi_roll(
703
  rects, all_widths, max_height, allow_rotation,
704
- original_dims, # <-- FIX: pass original_dims
705
- pack_algo, sort_algo, reverse
706
  )
707
- if not rolls:
708
- continue
709
- waste, waste_pct = calculate_waste(rolls, original_dims)
710
- if not_placed == 0:
711
- key = (waste, len(rolls), 0)
712
- if best_key is None or key < best_key:
713
- best_key = key
714
- img, total_true, total_roll, total_rot = render_multi_roll(
715
- rolls, original_dims, margin
716
- )
717
- is_g, g_v = is_guillotine_cuttable(rolls, margin)
718
- stats = [
719
- "🎯 MULTI-WIDTH MULTI-ROLL (tiap roll beda lebar)",
720
- f"πŸ† Mode : MULTI-WIDTH",
721
- f"πŸ” Iterasi dicoba : {tried}",
722
- f"πŸ“¦ Jumlah roll : {len(rolls)}",
723
- f"πŸ“ Lebar per roll : {', '.join(f'{w:.0f}' for _, _, w in rolls)} cm",
724
- f"πŸ“ Total panjang : {sum(h for _, h, _ in rolls):.1f} cm",
725
- f"βœ… Item ditempatkan : {sum(len(p) for p, _, _ in rolls)} / {total_rects}",
726
- f"♻️ TOTAL WASTE : {waste:.1f} cmΒ²",
727
- f"πŸ“Š Persentase waste : {waste_pct:.2f}% (target: ≀{target_waste_pct}%)",
728
- f"πŸ”ͺ Guillotine cuttable : {'βœ… Ya' if is_g else f'⚠️ Tidak ({g_v} pelanggaran)'}",
729
- ]
730
- best_overall = (img, "\n".join(stats), waste, waste_pct)
731
- best_width = "multi"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
732
 
733
  # SINGLE-WIDTH per lebar
734
  for width in all_widths:
@@ -752,7 +961,7 @@ def process(roll_widths_text, margin, allow_rotation, search_mode, target_waste_
752
  f"πŸ“Š Persentase waste : {waste_pct:.2f}%",
753
  ]
754
 
755
- key = (waste, num_rolls, sum(h for _, h, _ in rolls))
756
  if best_key is None or key < best_key:
757
  best_key = key
758
  best_overall = (img, "\n".join(stats), waste, waste_pct)
@@ -764,7 +973,7 @@ def process(roll_widths_text, margin, allow_rotation, search_mode, target_waste_
764
  break
765
 
766
  else:
767
- img, stats, waste, waste_pct, num_rolls, tried, hit = search_single_width(
768
  rects, original_dims, total_rects, max_height,
769
  width, margin, bool(allow_rotation),
770
  search_mode, target_waste_pct, 4.0
@@ -775,8 +984,11 @@ def process(roll_widths_text, margin, allow_rotation, search_mode, target_waste_
775
  width_results.append((width, None, None, None, "Gagal"))
776
  continue
777
 
778
- key = (waste if waste is not None else float('inf'),
779
- num_rolls if num_rolls else 99, 0)
 
 
 
780
  if best_key is None or key < best_key:
781
  best_key = key
782
  best_overall = (img, stats, waste, waste_pct)
@@ -796,8 +1008,9 @@ def process(roll_widths_text, margin, allow_rotation, search_mode, target_waste_
796
  for w, waste, wpct, rolls, note in sorted_r[:10]:
797
  mark = " ⭐ PALING HEMAT" if w == best_width else ""
798
  target = " 🎯" if isinstance(wpct, (int, float)) and wpct <= target_waste_pct else ""
 
799
  comparison.append(
800
- f" {'βœ…' if w == best_width else ' '} {w:g} cm β†’ "
801
  f"{rolls} roll, waste {waste:.1f} cmΒ² ({note}){mark}{target}"
802
  )
803
 
 
344
  return total_roll - total_true, (total_roll - total_true) / total_roll * 100 if total_roll else 100
345
 
346
 
347
+ def unified_key(waste, num_rolls, not_placed):
348
+ """
349
+ Langkah 5: format key SATU-SATUNYA yang dipakai untuk membandingkan
350
+ hasil single-width, multi-width, dan mode cepat, supaya perbandingan
351
+ `key < best_key` semantiknya valid di seluruh jalur di process().
352
+ Item yang tidak muat diberi penalti besar (bukan diskualifikasi total),
353
+ supaya solusi yang menempatkan semua item selalu diprioritaskan tapi
354
+ solusi hampir-sempurna tetap bisa bersaing.
355
+ """
356
+ return (waste + not_placed * 1e6, num_rolls, not_placed)
357
+
358
+
359
  def simulated_annealing(rects, roll_width, max_height, allow_rotation,
360
  pack_algo, sort_algo, original_dims,
361
  initial_temp=100, cooling=0.995, max_iter=3000):
 
412
  # 8. MULTI-WIDTH MULTI-ROLL (FIXED: tambah original_dims parameter)
413
  # --------------------------------------------------------------------------
414
 
415
+ def _try_pack_width(remaining, w, max_height, allow_rotation, pack_algo, sort_algo, original_dims):
416
+ """
417
+ Helper: coba pack 'remaining' rects ke satu bin lebar w. Return None kalau
418
+ gagal, atau (waste, placed, used_height, new_remaining) kalau berhasil.
419
+ Dipakai bersama oleh pack_multi_width_multi_roll (greedy dan lookahead).
420
+ """
421
+ kwargs = {"rotation": allow_rotation}
422
+ if pack_algo:
423
+ kwargs["pack_algo"] = pack_algo
424
+ if sort_algo:
425
+ kwargs["sort_algo"] = sort_algo
426
+ packer = newPacker(**kwargs)
427
+ for rect_w, rect_h, rid in remaining:
428
+ packer.add_rect(rect_w, rect_h, rid=rid)
429
+ packer.add_bin(w, max_height)
430
+ packer.pack()
431
+
432
+ if len(packer) == 0 or len(packer[0]) == 0:
433
+ return None
434
+
435
+ placed = packer[0]
436
+ used_height = max(r.y + r.height for r in placed)
437
+ placed_ids = {r.rid for r in placed}
438
+
439
+ true_area = sum(
440
+ (original_dims[rid][0] * original_dims[rid][1])
441
+ for _, _, rid in remaining if rid in placed_ids
442
+ )
443
+ roll_area = w * used_height
444
+ waste = roll_area - true_area
445
+ new_remaining = [r for r in remaining if r[2] not in placed_ids]
446
+ return waste, placed, used_height, new_remaining
447
+
448
+
449
  def pack_multi_width_multi_roll(rects, widths, max_height, allow_rotation,
450
  original_dims, # <-- FIX: tambah parameter ini
451
+ pack_algo=None, sort_algo=None, reverse=False,
452
+ lookahead=False, lookahead_k=3):
453
  """
454
  Packing di mana TIAP ROLL boleh beda lebar.
455
+
456
+ Langkah 4: bila lookahead=True, alih-alih langsung memilih lebar dengan
457
+ waste terkecil untuk roll SAAT INI saja (murni greedy), fungsi ini
458
+ mengambil top-`lookahead_k` kandidat lebar berdasar waste roll ini, lalu
459
+ untuk tiap kandidat mengintip 1 roll ke depan (waste terbaik yang bisa
460
+ dicapai pada sisa item) dan memilih kandidat dengan total waste gabungan
461
+ (roll ini + estimasi roll berikutnya) terkecil. Ini membantu menghindari
462
+ jebakan lokal di mana pilihan yang "tampak" optimal untuk roll saat ini
463
+ justru membuat sisa item sulit dinestik secara efisien di roll berikutnya.
464
  """
465
  remaining = list(reversed(rects)) if reverse else rects[:]
466
  all_rolls = []
 
470
  if not remaining:
471
  break
472
 
473
+ candidates = []
 
 
 
 
474
  for w in widths:
475
+ res = _try_pack_width(remaining, w, max_height, allow_rotation,
476
+ pack_algo, sort_algo, original_dims)
477
+ if res is None:
 
 
 
 
 
 
 
 
 
478
  continue
479
+ waste, placed, used_height, new_remaining = res
480
+ candidates.append((waste, placed, used_height, w, new_remaining))
481
 
482
+ if not candidates:
483
+ return all_rolls, len(remaining)
 
484
 
485
+ candidates.sort(key=lambda c: c[0])
 
 
 
 
 
 
486
 
487
+ if not lookahead or len(candidates) <= 1:
488
+ chosen = candidates[0]
489
+ else:
490
+ topk = candidates[:lookahead_k]
491
+ chosen = None
492
+ best_total = float('inf')
493
+ for waste, placed, used_height, w, new_remaining in topk:
494
+ if new_remaining:
495
+ # Intip 1 langkah ke depan: waste terbaik di antara semua
496
+ # lebar untuk sisa item setelah kandidat ini dipilih.
497
+ next_best = float('inf')
498
+ for w2 in widths:
499
+ res2 = _try_pack_width(new_remaining, w2, max_height, allow_rotation,
500
+ pack_algo, sort_algo, original_dims)
501
+ if res2 is not None and res2[0] < next_best:
502
+ next_best = res2[0]
503
+ total = waste + (next_best if next_best != float('inf') else 0)
504
+ else:
505
+ total = waste
506
+ if total < best_total:
507
+ best_total = total
508
+ chosen = (waste, placed, used_height, w, new_remaining)
509
+
510
+ _, placed, used_height, w, new_remaining = chosen
511
+ all_rolls.append((placed, used_height, w))
512
+ remaining = new_remaining
513
 
514
+ return all_rolls, len(remaining)
 
515
 
 
 
516
 
517
+ # --------------------------------------------------------------------------
518
+ # 8b. SIMULATED ANNEALING UNTUK MULTI-WIDTH MULTI-ROLL (Langkah 2)
519
+ # --------------------------------------------------------------------------
520
+
521
+ def simulated_annealing_multi_width(rects, widths, max_height, allow_rotation,
522
+ pack_algo, sort_algo, original_dims,
523
+ initial_temp=100, cooling=0.995, max_iter=1500):
524
+ """
525
+ Versi SA dari simulated_annealing(), tapi memakai pack_multi_width_multi_roll
526
+ sebagai fungsi evaluasi sehingga tiap roll boleh punya lebar berbeda.
527
+ Key evaluasi memakai (waste, not_placed) supaya solusi yang menempatkan
528
+ semua item tetap diprioritaskan, tapi solusi dengan sedikit item tidak
529
+ muat tidak langsung dibuang (lihat _mw_score).
530
+ """
531
+ def _mw_score(rolls, not_placed):
532
+ waste, _ = calculate_waste(rolls, original_dims)
533
+ # Penalti besar per item tidak muat, tapi tidak diskualifikasi total
534
+ return waste + not_placed * 1e6, waste
535
+
536
+ current = rects[:]
537
+ best = rects[:]
538
+ best_result = None
539
+ best_not_placed = None
540
+ best_waste = float('inf')
541
+ best_score = float('inf')
542
+
543
+ current_result, current_not_placed = pack_multi_width_multi_roll(
544
+ current, widths, max_height, allow_rotation, original_dims, pack_algo, sort_algo, False
545
+ )
546
+ if not current_result:
547
+ return None, float('inf'), None
548
+ current_score, current_waste = _mw_score(current_result, current_not_placed)
549
+ best_result, best_not_placed, best_waste, best_score = (
550
+ current_result, current_not_placed, current_waste, current_score
551
+ )
552
+
553
+ temp = initial_temp
554
+
555
+ for _ in range(max_iter):
556
+ neighbor = current[:]
557
+ op = random.choice(['swap', 'reverse', 'insert'])
558
+ if op == 'swap' and len(neighbor) > 1:
559
+ a, b = random.sample(range(len(neighbor)), 2)
560
+ neighbor[a], neighbor[b] = neighbor[b], neighbor[a]
561
+ elif op == 'reverse' and len(neighbor) > 2:
562
+ a, b = sorted(random.sample(range(len(neighbor)), 2))
563
+ neighbor[a:b + 1] = list(reversed(neighbor[a:b + 1]))
564
+ elif op == 'insert' and len(neighbor) > 1:
565
+ a = random.randint(0, len(neighbor) - 1)
566
+ b = random.randint(0, len(neighbor) - 1)
567
+ item = neighbor.pop(a)
568
+ neighbor.insert(b, item)
569
+
570
+ rolls, not_placed = pack_multi_width_multi_roll(
571
+ neighbor, widths, max_height, allow_rotation, original_dims, pack_algo, sort_algo, False
572
+ )
573
+ if not rolls:
574
+ continue
575
+
576
+ score, waste = _mw_score(rolls, not_placed)
577
+
578
+ if score < best_score:
579
+ best_score = score
580
+ best_waste = waste
581
+ best_not_placed = not_placed
582
+ best = neighbor[:]
583
+ best_result = rolls
584
+ if score < current_score or random.random() < math.exp((current_score - score) / max(temp, 0.001)):
585
+ current = neighbor[:]
586
+ current_score = score
587
+
588
+ temp *= cooling
589
+
590
+ return best_result, best_waste, best_not_placed
591
 
592
 
593
  # --------------------------------------------------------------------------
 
758
  if not_placed > 0:
759
  stats.insert(7, f"⚠️ Item TIDAK muat : {not_placed}")
760
 
761
+ return img, "\n".join(stats), waste, waste_pct, num_rolls, tried, hit_target, not_placed
762
 
763
 
764
  # --------------------------------------------------------------------------
 
823
  # MULTI-WIDTH MULTI-ROLL
824
  if enable_multiwidth and search_mode in ("pro", "exhaustive"):
825
  tried = 0
826
+ mw_best_rolls = None
827
+ mw_best_not_placed = None
828
+ mw_best_config = None
829
+ # key global untuk multi-width sendiri: (waste + penalti not_placed, num_rolls)
830
+ # dibandingkan terpisah dari single-width supaya kombinasi terbaik multi-width
831
+ # yang benar-benar ditemukan (bukan cuma kombinasi pertama yang all-placed)
832
+ mw_best_key = None
833
+
834
+ def _mw_key(rolls, not_placed):
835
+ waste, _ = calculate_waste(rolls, original_dims)
836
+ return unified_key(waste, len(rolls), not_placed)
837
+
838
+ def _consider_mw(rolls, not_placed, config_name):
839
+ nonlocal mw_best_rolls, mw_best_not_placed, mw_best_config, mw_best_key
840
+ if not rolls:
841
+ return
842
+ key = _mw_key(rolls, not_placed)
843
+ if mw_best_key is None or key < mw_best_key:
844
+ mw_best_key = key
845
+ mw_best_rolls = rolls
846
+ mw_best_not_placed = not_placed
847
+ mw_best_config = config_name
848
+
849
+ # --- Fase A: grid search dasar (kombinasi algo x sort x reverse) ---
850
  for pack_algo in [None, MaxRectsBssf, GuillotineBssfSas]:
851
  for sort_algo in [None, SORT_AREA]:
852
  for reverse in [False, True]:
853
  tried += 1
 
854
  rolls, not_placed = pack_multi_width_multi_roll(
855
  rects, all_widths, max_height, allow_rotation,
856
+ original_dims, pack_algo, sort_algo, reverse
 
857
  )
858
+ algo_name = pack_algo.__name__ if pack_algo else "Default"
859
+ config = f"[Grid] {algo_name}+{get_sort_name(sort_algo)}{' rev' if reverse else ''}"
860
+ _consider_mw(rolls, not_placed, config)
861
+
862
+ # --- Fase B (Langkah 1): pre-sort strategies, sama seperti single-width ---
863
+ if search_mode in ("pro", "exhaustive"):
864
+ for sort_name, sorted_rects in get_pre_sort_strategies(rects):
865
+ for pack_algo in [None, MaxRectsBssf, GuillotineBssfSas]:
866
+ for reverse in [False, True]:
867
+ tried += 1
868
+ rolls, not_placed = pack_multi_width_multi_roll(
869
+ sorted_rects, all_widths, max_height, allow_rotation,
870
+ original_dims, pack_algo, SORT_NONE, reverse
871
+ )
872
+ algo_name = pack_algo.__name__ if pack_algo else "Default"
873
+ config = f"[MW-PreSort:{sort_name}] {algo_name}{' rev' if reverse else ''}"
874
+ _consider_mw(rolls, not_placed, config)
875
+
876
+ # --- Fase C (Langkah 2): Simulated Annealing versi multi-width ---
877
+ if search_mode in ("pro", "exhaustive"):
878
+ sa_mw_configs = [
879
+ (None, None), (MaxRectsBssf, SORT_AREA), (GuillotineBssfSas, SORT_AREA)
880
+ ]
881
+ for pack_algo, sort_algo in sa_mw_configs:
882
+ tried += 1
883
+ sa_rolls, sa_waste, sa_not_placed = simulated_annealing_multi_width(
884
+ rects, all_widths, max_height, allow_rotation,
885
+ pack_algo, sort_algo, original_dims,
886
+ initial_temp=100, cooling=0.995,
887
+ max_iter=2500 if search_mode == "exhaustive" else 1200
888
+ )
889
+ if sa_rolls:
890
+ algo_name = pack_algo.__name__ if pack_algo else "Default"
891
+ config = f"[MW-SA] {algo_name} (waste {sa_waste:.1f})"
892
+ _consider_mw(sa_rolls, sa_not_placed, config)
893
+
894
+ # --- Fase D (Langkah 4): pilihan lebar dgn lookahead 1-langkah ---
895
+ # Dibatasi ke beberapa config saja karena tiap panggilan lebih mahal
896
+ # (evaluasi top-k kandidat x semua lebar untuk mengintip roll berikutnya).
897
+ if search_mode in ("pro", "exhaustive"):
898
+ lookahead_configs = [(None, None), (MaxRectsBssf, SORT_AREA)]
899
+ for pack_algo, sort_algo in lookahead_configs:
900
+ for sort_name, sorted_rects in [("default", rects), ("area_desc",
901
+ sorted(rects, key=lambda r: r[0] * r[1], reverse=True))]:
902
+ tried += 1
903
+ rolls, not_placed = pack_multi_width_multi_roll(
904
+ sorted_rects, all_widths, max_height, allow_rotation,
905
+ original_dims, pack_algo, sort_algo, False,
906
+ lookahead=True, lookahead_k=3
907
+ )
908
+ algo_name = pack_algo.__name__ if pack_algo else "Default"
909
+ config = f"[MW-Lookahead:{sort_name}] {algo_name}"
910
+ _consider_mw(rolls, not_placed, config)
911
+
912
+ # --- Bandingkan hasil terbaik multi-width dengan best_overall global ---
913
+ if mw_best_rolls is not None:
914
+ waste, waste_pct = calculate_waste(mw_best_rolls, original_dims)
915
+ key = unified_key(waste, len(mw_best_rolls), mw_best_not_placed)
916
+ if best_key is None or key < best_key:
917
+ best_key = key
918
+ img, total_true, total_roll, total_rot = render_multi_roll(
919
+ mw_best_rolls, original_dims, margin
920
+ )
921
+ is_g, g_v = is_guillotine_cuttable(mw_best_rolls, margin)
922
+ stats = [
923
+ "🎯 MULTI-WIDTH MULTI-ROLL (tiap roll beda lebar)",
924
+ f"πŸ† Algoritma terpilih : {mw_best_config}",
925
+ f"πŸ” Iterasi dicoba (multi-width): {tried}",
926
+ f"πŸ“¦ Jumlah roll : {len(mw_best_rolls)}",
927
+ f"πŸ“ Lebar per roll : {', '.join(f'{w:.0f}' for _, _, w in mw_best_rolls)} cm",
928
+ f"πŸ“ Total panjang : {sum(h for _, h, _ in mw_best_rolls):.1f} cm",
929
+ f"βœ… Item ditempatkan : {sum(len(p) for p, _, _ in mw_best_rolls)} / {total_rects}",
930
+ f"♻️ TOTAL WASTE : {waste:.1f} cmΒ²",
931
+ f"πŸ“Š Persentase waste : {waste_pct:.2f}% (target: ≀{target_waste_pct}%)",
932
+ f"πŸ”ͺ Guillotine cuttable : {'βœ… Ya' if is_g else f'⚠️ Tidak ({g_v} pelanggaran)'}",
933
+ ]
934
+ if mw_best_not_placed:
935
+ stats.insert(7, f"⚠️ Item TIDAK muat : {mw_best_not_placed}")
936
+ best_overall = (img, "\n".join(stats), waste, waste_pct)
937
+ best_width = "multi"
938
+ # Langkah 6 (persiapan): masukkan hasil multi-width ke tabel perbandingan juga
939
+ width_results.append(("multi", waste, waste_pct, len(mw_best_rolls), f"{waste_pct:.2f}%"))
940
+ global_tried += tried
941
 
942
  # SINGLE-WIDTH per lebar
943
  for width in all_widths:
 
961
  f"πŸ“Š Persentase waste : {waste_pct:.2f}%",
962
  ]
963
 
964
+ key = unified_key(waste, num_rolls, not_placed)
965
  if best_key is None or key < best_key:
966
  best_key = key
967
  best_overall = (img, "\n".join(stats), waste, waste_pct)
 
973
  break
974
 
975
  else:
976
+ img, stats, waste, waste_pct, num_rolls, tried, hit, sw_not_placed = search_single_width(
977
  rects, original_dims, total_rects, max_height,
978
  width, margin, bool(allow_rotation),
979
  search_mode, target_waste_pct, 4.0
 
984
  width_results.append((width, None, None, None, "Gagal"))
985
  continue
986
 
987
+ key = unified_key(
988
+ waste if waste is not None else float('inf'),
989
+ num_rolls if num_rolls else 99,
990
+ sw_not_placed if sw_not_placed is not None else 0,
991
+ )
992
  if best_key is None or key < best_key:
993
  best_key = key
994
  best_overall = (img, stats, waste, waste_pct)
 
1008
  for w, waste, wpct, rolls, note in sorted_r[:10]:
1009
  mark = " ⭐ PALING HEMAT" if w == best_width else ""
1010
  target = " 🎯" if isinstance(wpct, (int, float)) and wpct <= target_waste_pct else ""
1011
+ w_label = "MULTI (beda lebar)" if w == "multi" else f"{w:g} cm"
1012
  comparison.append(
1013
+ f" {'βœ…' if w == best_width else ' '} {w_label} β†’ "
1014
  f"{rolls} roll, waste {waste:.1f} cmΒ² ({note}){mark}{target}"
1015
  )
1016