source: branches/2817-BinPackingSpeedup/HeuristicLab.Problems.BinPacking/3.3/3D/Packer/BinPackerMinRSLeft.cs @ 15705

Last change on this file since 15705 was 15705, checked in by rhanghof, 2 years ago

#2817

  • Former material is now the layer.
  • Added material enumeration
  • Modification at the minimum residual space left bin packer
File size: 16.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using System.Text;
26using System.Threading.Tasks;
27using HeuristicLab.Common;
28using HeuristicLab.Encodings.PermutationEncoding;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30using HeuristicLab.Problems.BinPacking3D.ExtremePointCreation;
31using HeuristicLab.Problems.BinPacking3D.ExtremePointPruning;
32
33namespace HeuristicLab.Problems.BinPacking3D.Packer {
34  internal class BinPackerMinRSLeft : BinPacker {
35    #region Constructors for HEAL
36    [StorableConstructor]
37    protected BinPackerMinRSLeft(bool deserializing) : base(deserializing) { }
38
39    public BinPackerMinRSLeft(BinPackerMinRSLeft original, Cloner cloner) : base(original, cloner) {
40    }
41
42    public override IDeepCloneable Clone(Cloner cloner) {
43      return new BinPackerMinRSLeft(this, cloner);
44    }
45    #endregion
46
47
48
49    public BinPackerMinRSLeft() : base() { }
50
51    /// <summary>
52    /// This proportion of the residual space left to the item height is used for deciding if a not stackable item should be placed.
53    /// </summary>
54    private const double NOT_STACKABLE_RS_LEFT_TO_ITEM_HEIGHT_PROPORTION = 1.1;
55
56    public override IList<BinPacking3D> PackItems(Permutation sortedItems, PackingShape binShape, IList<PackingItem> items, ExtremePointCreationMethod epCreationMethod, ExtremePointPruningMethod epPruningMethod, bool useStackingConstraints) {
57      var workingItems = CloneItems(items);
58      IList<BinPacking3D> packingList = new List<BinPacking3D>();
59      IList<int> remainingIds = new List<int>(sortedItems);
60
61      try {
62        while (remainingIds.Count > 0) {
63          BinPacking3D packingBin = new BinPacking3D(binShape);
64          PackRemainingItems(ref remainingIds, ref packingBin, workingItems, epCreationMethod, useStackingConstraints);
65          packingList.Add(packingBin);
66        }
67      } catch (BinPacking3DException e) {
68      }
69
70      ExtremePointPruningFactory.CreatePruning().PruneExtremePoints(epPruningMethod, packingList);
71
72      return packingList;
73    }
74
75
76    public override void PackItemsToPackingList(IList<BinPacking3D> packingList, Permutation sortedItems, PackingShape binShape, IList<PackingItem> items, ExtremePointCreationMethod epCreationMethod, ExtremePointPruningMethod epPruningMethod, bool useStackingConstraints) {
77      var workingItems = CloneItems(items);
78      IList<int> remainingIds = new List<int>(sortedItems);
79
80      try {
81        if (packingList.Count > 0) {
82          BinPacking3D packingBin = packingList.Last();
83          PackRemainingItems(ref remainingIds, ref packingBin, workingItems, epCreationMethod, useStackingConstraints);
84        }
85
86        while (remainingIds.Count > 0) {
87          BinPacking3D packingBin = new BinPacking3D(binShape);
88          PackRemainingItems(ref remainingIds, ref packingBin, workingItems, epCreationMethod, useStackingConstraints);
89          packingList.Add(packingBin);
90        }
91      } catch (BinPacking3DException e) {
92      }
93
94      ExtremePointPruningFactory.CreatePruning().PruneExtremePoints(epPruningMethod, packingList);
95    }
96
97    /// <summary>
98    /// Tries to pack the remainig items into a given BinPacking3D object. Each item could be packed into the BinPacking3D object will be removed from the list of remaining ids
99    /// </summary>
100    /// <param name="remainingIds">List of remaining ids. After the method has been executed the list has to have less items</param>
101    /// <param name="packingBin">This object will be filled with some of the given items</param>
102    /// <param name="items">List of packing items. Some of the items will be assigned to the BinPacking3D object</param>
103    /// <param name="epCreationMethod"></param>
104    /// <param name="useStackingConstraints"></param>
105    protected void PackRemainingItems(ref IList<int> remainingIds, ref BinPacking3D packingBin, IList<PackingItem> items, ExtremePointCreationMethod epCreationMethod, bool useStackingConstraints) {
106      IExtremePointCreator extremePointCreator = ExtremePointCreatorFactory.CreateExtremePointCreator(epCreationMethod, useStackingConstraints);
107      var remainingNotWeightSupportedItems = new List<int>();
108      foreach (var itemId in new List<int>(remainingIds)) {
109        var item = items[itemId];
110
111        // If an item doesn't support any weight it should have a minimum waste of the residual space.
112        // As long as there are weight supporting items left, put the non supporting items into a collection
113        // and try to find positions where they don't waste too much space.
114        // If there are no weight supporting items left the non supporting ones have to be treated as a supporting one.
115        if (item.SupportedWeight <= 0 && useStackingConstraints && remainingIds.Any(x => items[x].SupportedWeight > 0)) {
116          remainingNotWeightSupportedItems.Add(itemId);
117        } else if (!item.IsStackabel) {
118          PackingPosition position = FindPackingPositionForNotStackableItem(packingBin, item, useStackingConstraints);
119          // if a valid packing position could be found, the current item can be added to the given bin
120          if (position != null) {
121            PackItem(packingBin, itemId, item, position, extremePointCreator, useStackingConstraints);
122            remainingIds.Remove(itemId);
123          }
124        } else  {
125          PackingPosition position = FindPackingPositionForItem(packingBin, item, useStackingConstraints);
126          // if a valid packing position could be found, the current item can be added to the given bin
127          if (position != null) {
128            PackItem(packingBin, itemId, item, position, extremePointCreator, useStackingConstraints);
129            remainingIds.Remove(itemId);
130          }
131        }
132
133        // try to find a valid position for a non weight supporting item
134        var weightSupportedLeft = remainingIds.Any(x => items[x].SupportedWeight > 0);
135        foreach (var saId in new List<int>(remainingNotWeightSupportedItems)) {
136          item = items[saId];
137          PackingPosition position = null;
138          if (weightSupportedLeft) {
139            position = FindPackingPositionForWeightUnsupportedItem(packingBin, item, useStackingConstraints);
140          } else {
141            position = FindPackingPositionForItem(packingBin, item, useStackingConstraints);
142          }
143
144          if (position != null) {
145            PackItem(packingBin, saId, item, position, extremePointCreator, useStackingConstraints);
146            remainingIds.Remove(saId);
147            remainingNotWeightSupportedItems.Remove(saId);
148          }
149        }
150
151      }
152    }
153
154    /// <summary>
155    /// Finds a valid packing position for a not stackable item.
156    /// Not stackable means that an item can't be placed on another one and no other item can be placed on it.
157    /// The item will be rotated and tilted so it needs the minimum area.
158    /// </summary>
159    /// <param name="packingBin"></param>
160    /// <param name="packingItem"></param>
161    /// <param name="useStackingConstraints"></param>
162    /// <returns></returns>
163    private PackingPosition FindPackingPositionForNotStackableItem(BinPacking3D packingBin, PackingItem packingItem, bool useStackingConstraints) {
164      if (!useStackingConstraints) {
165        return FindPackingPositionForItem(packingBin, packingItem, useStackingConstraints);
166      }
167      var areas = new List<Tuple<double, bool, bool>>();
168      areas.Add(CalculateArea(packingItem, false, false));
169      if (packingItem.TiltEnabled) {
170        areas.Add(CalculateArea(packingItem, false, true));
171      }
172      if (packingItem.RotateEnabled) {
173        areas.Add(CalculateArea(packingItem, true, false));
174      }
175      if (packingItem.RotateEnabled && packingItem.TiltEnabled) {
176        areas.Add(CalculateArea(packingItem, true, true));
177      }
178
179      areas.Sort((x1, x2) => (int)(x1.Item1 - x2.Item1));
180      var orientation = areas.FirstOrDefault();
181      if (orientation == null) {
182        return null;
183      }
184
185
186      PackingItem newItem = new PackingItem(packingItem) {
187        Rotated = orientation.Item2,
188        Tilted = orientation.Item3
189      };
190
191      var rsds = new SortedSet<ResidualSpaceDifference>();
192      foreach (var ep in packingBin.ExtremePoints.Where(x => x.Key.Y == 0)) {
193        var position = ep.Key;
194        foreach (var rs in ep.Value) {
195          var rsd = ResidualSpaceDifference.Create(position, newItem, rs);
196          if (rsd != null) {
197            rsds.Add(rsd);
198          }
199        }
200      }
201      var d =  rsds.Where(x => packingBin.IsPositionFeasible(x.Item, x.Position, useStackingConstraints)).FirstOrDefault();
202
203      if (d == null) {
204        return null;
205      }
206
207      packingItem.Rotated = orientation.Item2;
208      packingItem.Tilted = orientation.Item3;
209      return d.Position;
210    }
211
212    Tuple<double, bool, bool> CalculateArea(PackingItem packingItem, bool rotated, bool tilted) {
213      var item = new PackingItem(packingItem) {
214        Rotated = rotated,
215        Tilted = tilted
216      };
217      return Tuple.Create<double, bool, bool>(item.Width * item.Depth, rotated, tilted);
218    }
219
220    /// <summary>
221    /// Tries to find a valid position for a non stackable item.
222    /// Positions will only be valid if the height difference of its residual space is smaller then the hight of the item.
223    /// </summary>
224    /// <param name="packingBin"></param>
225    /// <param name="packingItem"></param>
226    /// <param name="useStackingConstraints"></param>
227    /// <returns></returns>
228    private PackingPosition FindPackingPositionForWeightUnsupportedItem(BinPacking3D packingBin, PackingItem packingItem, bool useStackingConstraints) {
229      if (!CheckItemDimensions(packingBin, packingItem)) {
230        throw new BinPacking3DException($"The dimensions of the given item exceeds the bin dimensions. " +
231          $"Bin: ({packingBin.BinShape.Width} {packingBin.BinShape.Depth} {packingBin.BinShape.Height})" +
232          $"Item: ({packingItem.Width} {packingItem.Depth} {packingItem.Height})");
233      }
234      var rsds = CalculateResidalSpaceDifferences(packingBin, packingItem, useStackingConstraints).ToList();
235      var rsd = rsds.Where(x => x != null && (x.Y / (double)x.Item.Height) < NOT_STACKABLE_RS_LEFT_TO_ITEM_HEIGHT_PROPORTION).OrderByDescending(x => x.Y % x.Item.Height).FirstOrDefault();
236
237      if (rsd == null) {
238        return null;
239      }
240
241      packingItem.Rotated = rsd.Item.Rotated;
242      packingItem.Tilted = rsd.Item.Tilted;
243      return rsd.Position;
244    }
245
246    protected override PackingPosition FindPackingPositionForItem(BinPacking3D packingBin, PackingItem packingItem, bool useStackingConstraints) {
247      if (!CheckItemDimensions(packingBin, packingItem)) {
248        throw new BinPacking3DException($"The dimensions of the given item exceeds the bin dimensions. " +
249          $"Bin: ({packingBin.BinShape.Width} {packingBin.BinShape.Depth} {packingBin.BinShape.Height})" +
250          $"Item: ({packingItem.Width} {packingItem.Depth} {packingItem.Height})");
251      }
252
253      var rsd = CalculateResidalSpaceDifferences(packingBin, packingItem, useStackingConstraints).Where(x => x != null).FirstOrDefault();
254
255      if (rsd == null) {
256        return null;
257      }
258
259      packingItem.Rotated = rsd.Item.Rotated;
260      packingItem.Tilted = rsd.Item.Tilted;
261      return rsd.Position;
262    }
263
264    /// <summary>
265    ///
266    /// </summary>
267    /// <param name="packingBin"></param>
268    /// <param name="packingItem"></param>
269    /// <param name="useStackingConstraints"></param>
270    /// <returns></returns>
271    private SortedSet<ResidualSpaceDifference> CalculateResidalSpaceDifferences(BinPacking3D packingBin, PackingItem packingItem, bool useStackingConstraints) {
272      var rsds = new SortedSet<ResidualSpaceDifference>();
273
274      rsds.Add(FindResidualSpaceDifferenceForItem(packingBin, packingItem, useStackingConstraints, rotated: false, tilted: false));
275
276      if (packingItem.TiltEnabled) {
277        rsds.Add(FindResidualSpaceDifferenceForItem(packingBin, packingItem, useStackingConstraints, rotated: false, tilted: true));
278      }
279      if (packingItem.RotateEnabled) {
280        rsds.Add(FindResidualSpaceDifferenceForItem(packingBin, packingItem, useStackingConstraints, rotated: true, tilted: false));
281      }
282      if (packingItem.RotateEnabled && packingItem.TiltEnabled) {
283        rsds.Add(FindResidualSpaceDifferenceForItem(packingBin, packingItem, useStackingConstraints, rotated: true, tilted: true));
284      }
285      return rsds;
286    }
287
288    /// <summary>
289    ///
290    /// </summary>
291    /// <param name="packingBin"></param>
292    /// <param name="packingItem"></param>
293    /// <param name="useStackingConstraints"></param>
294    /// <param name="rotated"></param>
295    /// <param name="tilted"></param>
296    /// <returns></returns>
297    protected ResidualSpaceDifference FindResidualSpaceDifferenceForItem(BinPacking3D packingBin, PackingItem packingItem, bool useStackingConstraints, bool rotated, bool tilted) {
298      PackingItem newItem = new PackingItem(packingItem) {
299        Rotated = rotated,
300        Tilted = tilted
301      };
302
303      var rsds = new SortedSet<ResidualSpaceDifference>();
304      foreach (var ep in packingBin.ExtremePoints) {
305        var position = ep.Key;
306        foreach (var rs in ep.Value) {
307          var rsd = ResidualSpaceDifference.Create(position, newItem, rs);
308          if (rsd != null) {
309            rsds.Add(rsd);
310          }
311        }
312      }
313      return rsds.Where(rsd => packingBin.IsPositionFeasible(rsd.Item, rsd.Position, useStackingConstraints)).FirstOrDefault();
314    }
315
316    protected override bool CheckItemDimensions(BinPacking3D packingBin, PackingItem item) {
317      bool ok = false;
318      int width = item.OriginalWidth;
319      int height = item.OriginalHeight;
320      int depth = item.OriginalDepth;
321
322      ok |= CheckItemDimensions(packingBin, width, height, depth);
323
324      if (item.RotateEnabled && item.TiltEnabled) {
325        ok |= CheckItemDimensions(packingBin, depth, height, width);//rotated
326        ok |= CheckItemDimensions(packingBin, height, width, depth);//tilted
327        ok |= CheckItemDimensions(packingBin, depth, width, height);//rotated & tilted
328      } else if (item.RotateEnabled) {
329        ok |= CheckItemDimensions(packingBin, depth, height, width);
330      } else if (item.TiltEnabled) {
331        ok |= CheckItemDimensions(packingBin, height, width, depth);
332      }
333
334      return ok;
335    }
336
337    private bool CheckItemDimensions(BinPacking3D packingBin, int width, int height, int depth) {
338      return base.CheckItemDimensions(packingBin, new PackingItem() {
339        OriginalWidth = width,
340        OriginalHeight = height,
341        OriginalDepth = depth
342      });
343    }
344
345
346    protected class ResidualSpaceDifference : IComparable {
347      public static ResidualSpaceDifference Create(PackingPosition position, PackingItem item, ResidualSpace rs) {
348        var x = rs.Width - item.Width;
349        var y = rs.Height - item.Height;
350        var z = rs.Depth - item.Depth;
351        // the item can't be places in the residual space
352        if (rs.IsZero() || x < 0 || y < 0 || z < 0) {
353          return null;
354        }
355
356        return new ResidualSpaceDifference() {
357          Position = position,
358          Item = item,
359          X = x,
360          Y = y,
361          Z = z
362        };
363      }
364
365      public ResidualSpaceDifference() { }
366
367      public PackingItem Item { get; set; }
368
369      public PackingPosition Position { get; set; }
370      public int X { get; set; }
371      public int Y { get; set; }
372      public int Z { get; set; }
373
374
375      public int CompareTo(object obj) {
376        if (!(obj is ResidualSpaceDifference)) {
377          return 0;
378        }
379        var rsd = obj as ResidualSpaceDifference;
380
381        var x = this.X - rsd.X;
382        var y = this.Y - rsd.Y;
383        var z = this.Z - rsd.Z;
384
385        if (x != 0) {
386          return x;
387        } else if (y != 0) {
388          return y;
389        } else if (z != 0) {
390          return z;
391        }
392
393        return 0;
394      }
395    }
396
397  }
398}
Note: See TracBrowser for help on using the repository browser.