Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 15731 was 15731, checked in by rhanghof, 6 years ago

#2817:

  • Added a new packer.
  • Enhanced the material types.
  • Added extreme point pruning for layer support in the extrem point creators.
  • BinPacking3D: Added a graph for calculating weigth distribution of the items.
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
98    /// <summary>
99    /// 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
100    /// </summary>
101    /// <param name="remainingIds">List of remaining ids. After the method has been executed the list has to have less items</param>
102    /// <param name="packingBin">This object will be filled with some of the given items</param>
103    /// <param name="items">List of packing items. Some of the items will be assigned to the BinPacking3D object</param>
104    /// <param name="epCreationMethod"></param>
105    /// <param name="useStackingConstraints"></param>
106    protected void PackRemainingItems(ref IList<int> remainingIds, ref BinPacking3D packingBin, IList<PackingItem> items, ExtremePointCreationMethod epCreationMethod, bool useStackingConstraints) {
107      IExtremePointCreator extremePointCreator = ExtremePointCreatorFactory.CreateExtremePointCreator(epCreationMethod, useStackingConstraints);
108      var remainingNotWeightSupportedItems = new List<int>();
109      foreach (var itemId in new List<int>(remainingIds)) {
110        var item = items[itemId];       
111
112        // If an item doesn't support any weight it should have a minimum waste of the residual space.
113        // As long as there are weight supporting items left, put the non supporting items into a collection
114        // and try to find positions where they don't waste too much space.
115        // If there are no weight supporting items left the non supporting ones have to be treated as a supporting one.
116        if (item.SupportedWeight <= 0 && useStackingConstraints && remainingIds.Any(x => items[x].SupportedWeight > 0)) {
117          remainingNotWeightSupportedItems.Add(itemId);
118        } else if (!item.IsStackabel) {
119          PackingPosition position = FindPackingPositionForNotStackableItem(packingBin, item, useStackingConstraints);
120          // if a valid packing position could be found, the current item can be added to the given bin
121          if (position != null) {
122            PackItem(packingBin, itemId, item, position, extremePointCreator, useStackingConstraints);
123            remainingIds.Remove(itemId);
124          }
125        } else  {
126          PackingPosition position = FindPackingPositionForItem(packingBin, item, useStackingConstraints);
127          // if a valid packing position could be found, the current item can be added to the given bin
128          if (position != null) {
129            PackItem(packingBin, itemId, item, position, extremePointCreator, useStackingConstraints);
130            remainingIds.Remove(itemId);
131          }
132        }
133
134        // try to find a valid position for a non weight supporting item
135        var weightSupportedLeft = remainingIds.Any(x => items[x].SupportedWeight > 0);
136        foreach (var saId in new List<int>(remainingNotWeightSupportedItems)) {
137          item = items[saId];
138          PackingPosition position = null;
139          if (weightSupportedLeft) {
140            position = FindPackingPositionForWeightUnsupportedItem(packingBin, item, useStackingConstraints);
141          } else {
142            position = FindPackingPositionForItem(packingBin, item, useStackingConstraints);
143          }
144
145          if (position != null) {
146            PackItem(packingBin, saId, item, position, extremePointCreator, useStackingConstraints);
147            remainingIds.Remove(saId);
148            remainingNotWeightSupportedItems.Remove(saId);
149          }
150        }
151
152      }
153    }
154
155    /// <summary>
156    /// Finds a valid packing position for a not stackable item.
157    /// Not stackable means that an item can't be placed on another one and no other item can be placed on it.
158    /// The item will be rotated and tilted so it needs the minimum area.
159    /// </summary>
160    /// <param name="packingBin"></param>
161    /// <param name="packingItem"></param>
162    /// <param name="useStackingConstraints"></param>
163    /// <returns></returns>
164    private PackingPosition FindPackingPositionForNotStackableItem(BinPacking3D packingBin, PackingItem packingItem, bool useStackingConstraints) {
165      if (!useStackingConstraints) {
166        return FindPackingPositionForItem(packingBin, packingItem, useStackingConstraints);
167      }
168      var areas = new List<Tuple<double, bool, bool>>();
169      areas.Add(CalculateArea(packingItem, false, false));
170      if (packingItem.TiltEnabled) {
171        areas.Add(CalculateArea(packingItem, false, true));
172      }
173      if (packingItem.RotateEnabled) {
174        areas.Add(CalculateArea(packingItem, true, false));
175      }
176      if (packingItem.RotateEnabled && packingItem.TiltEnabled) {
177        areas.Add(CalculateArea(packingItem, true, true));
178      }
179
180      areas.Sort((x1, x2) => (int)(x1.Item1 - x2.Item1));
181      var orientation = areas.FirstOrDefault();
182      if (orientation == null) {
183        return null;
184      }
185
186
187      PackingItem newItem = new PackingItem(packingItem) {
188        Rotated = orientation.Item2,
189        Tilted = orientation.Item3
190      };
191
192      var rsds = new SortedSet<ResidualSpaceDifference>();
193      foreach (var ep in packingBin.ExtremePoints.Where(x => x.Key.Y == 0)) {
194        var position = ep.Key;
195        foreach (var rs in ep.Value) {
196          var rsd = ResidualSpaceDifference.Create(position, newItem, rs);
197          if (rsd != null) {
198            rsds.Add(rsd);
199          }
200        }
201      }
202      var d =  rsds.Where(x => packingBin.IsPositionFeasible(x.Item, x.Position, useStackingConstraints)).FirstOrDefault();
203
204      if (d == null) {
205        return null;
206      }
207
208      packingItem.Rotated = orientation.Item2;
209      packingItem.Tilted = orientation.Item3;
210      return d.Position;
211    }
212
213    Tuple<double, bool, bool> CalculateArea(PackingItem packingItem, bool rotated, bool tilted) {
214      var item = new PackingItem(packingItem) {
215        Rotated = rotated,
216        Tilted = tilted
217      };
218      return Tuple.Create<double, bool, bool>(item.Width * item.Depth, rotated, tilted);
219    }
220
221    /// <summary>
222    /// Tries to find a valid position for a non stackable item.
223    /// Positions will only be valid if the height difference of its residual space is smaller then the hight of the item.
224    /// </summary>
225    /// <param name="packingBin"></param>
226    /// <param name="packingItem"></param>
227    /// <param name="useStackingConstraints"></param>
228    /// <returns></returns>
229    private PackingPosition FindPackingPositionForWeightUnsupportedItem(BinPacking3D packingBin, PackingItem packingItem, bool useStackingConstraints) {
230      if (!CheckItemDimensions(packingBin, packingItem)) {
231        throw new BinPacking3DException($"The dimensions of the given item exceeds the bin dimensions. " +
232          $"Bin: ({packingBin.BinShape.Width} {packingBin.BinShape.Depth} {packingBin.BinShape.Height})" +
233          $"Item: ({packingItem.Width} {packingItem.Depth} {packingItem.Height})");
234      }
235      var rsds = CalculateResidalSpaceDifferences(packingBin, packingItem, useStackingConstraints).ToList();
236      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();
237
238      if (rsd == null) {
239        return null;
240      }
241
242      packingItem.Rotated = rsd.Item.Rotated;
243      packingItem.Tilted = rsd.Item.Tilted;
244      return rsd.Position;
245    }
246
247    protected override PackingPosition FindPackingPositionForItem(BinPacking3D packingBin, PackingItem packingItem, bool useStackingConstraints) {
248      if (!CheckItemDimensions(packingBin, packingItem)) {
249        throw new BinPacking3DException($"The dimensions of the given item exceeds the bin dimensions. " +
250          $"Bin: ({packingBin.BinShape.Width} {packingBin.BinShape.Depth} {packingBin.BinShape.Height})" +
251          $"Item: ({packingItem.Width} {packingItem.Depth} {packingItem.Height})");
252      }
253
254      var rsd = CalculateResidalSpaceDifferences(packingBin, packingItem, useStackingConstraints).Where(x => x != null).FirstOrDefault();
255
256      if (rsd == null) {
257        return null;
258      }
259
260      packingItem.Rotated = rsd.Item.Rotated;
261      packingItem.Tilted = rsd.Item.Tilted;
262      return rsd.Position;
263    }
264
265    /// <summary>
266    ///
267    /// </summary>
268    /// <param name="packingBin"></param>
269    /// <param name="packingItem"></param>
270    /// <param name="useStackingConstraints"></param>
271    /// <returns></returns>
272    private SortedSet<ResidualSpaceDifference> CalculateResidalSpaceDifferences(BinPacking3D packingBin, PackingItem packingItem, bool useStackingConstraints) {
273      var rsds = new SortedSet<ResidualSpaceDifference>();
274
275      rsds.Add(FindResidualSpaceDifferenceForItem(packingBin, packingItem, useStackingConstraints, rotated: false, tilted: false));
276
277      if (packingItem.TiltEnabled) {
278        rsds.Add(FindResidualSpaceDifferenceForItem(packingBin, packingItem, useStackingConstraints, rotated: false, tilted: true));
279      }
280      if (packingItem.RotateEnabled) {
281        rsds.Add(FindResidualSpaceDifferenceForItem(packingBin, packingItem, useStackingConstraints, rotated: true, tilted: false));
282      }
283      if (packingItem.RotateEnabled && packingItem.TiltEnabled) {
284        rsds.Add(FindResidualSpaceDifferenceForItem(packingBin, packingItem, useStackingConstraints, rotated: true, tilted: true));
285      }
286      return rsds;
287    }
288
289    /// <summary>
290    ///
291    /// </summary>
292    /// <param name="packingBin"></param>
293    /// <param name="packingItem"></param>
294    /// <param name="useStackingConstraints"></param>
295    /// <param name="rotated"></param>
296    /// <param name="tilted"></param>
297    /// <returns></returns>
298    protected ResidualSpaceDifference FindResidualSpaceDifferenceForItem(BinPacking3D packingBin, PackingItem packingItem, bool useStackingConstraints, bool rotated, bool tilted) {
299      PackingItem newItem = new PackingItem(packingItem) {
300        Rotated = rotated,
301        Tilted = tilted
302      };
303
304      var rsds = new SortedSet<ResidualSpaceDifference>();
305      foreach (var ep in packingBin.ExtremePoints) {
306        var position = ep.Key;
307        foreach (var rs in ep.Value) {
308          var rsd = ResidualSpaceDifference.Create(position, newItem, rs);
309          if (rsd != null) {
310            rsds.Add(rsd);
311          }
312        }
313      }
314      return rsds.Where(rsd => packingBin.IsPositionFeasible(rsd.Item, rsd.Position, useStackingConstraints)).FirstOrDefault();
315    }
316
317    protected override bool CheckItemDimensions(BinPacking3D packingBin, PackingItem item) {
318      bool ok = false;
319      int width = item.OriginalWidth;
320      int height = item.OriginalHeight;
321      int depth = item.OriginalDepth;
322
323      ok |= CheckItemDimensions(packingBin, width, height, depth);
324
325      if (item.RotateEnabled && item.TiltEnabled) {
326        ok |= CheckItemDimensions(packingBin, depth, height, width);//rotated
327        ok |= CheckItemDimensions(packingBin, height, width, depth);//tilted
328        ok |= CheckItemDimensions(packingBin, depth, width, height);//rotated & tilted
329      } else if (item.RotateEnabled) {
330        ok |= CheckItemDimensions(packingBin, depth, height, width);
331      } else if (item.TiltEnabled) {
332        ok |= CheckItemDimensions(packingBin, height, width, depth);
333      }
334
335      return ok;
336    }
337
338    private bool CheckItemDimensions(BinPacking3D packingBin, int width, int height, int depth) {
339      return base.CheckItemDimensions(packingBin, new PackingItem() {
340        OriginalWidth = width,
341        OriginalHeight = height,
342        OriginalDepth = depth
343      });
344    }
345
346
347    protected class ResidualSpaceDifference : IComparable {
348      public static ResidualSpaceDifference Create(PackingPosition position, PackingItem item, ResidualSpace rs) {
349        var x = rs.Width - item.Width;
350        var y = rs.Height - item.Height;
351        var z = rs.Depth - item.Depth;
352        // the item can't be places in the residual space
353        if (rs.IsZero() || x < 0 || y < 0 || z < 0) {
354          return null;
355        }
356
357        return new ResidualSpaceDifference() {
358          Position = position,
359          Item = item,
360          X = x,
361          Y = y,
362          Z = z
363        };
364      }
365
366      public ResidualSpaceDifference() { }
367
368      public PackingItem Item { get; set; }
369
370      public PackingPosition Position { get; set; }
371      public int X { get; set; }
372      public int Y { get; set; }
373      public int Z { get; set; }
374
375
376      public int CompareTo(object obj) {
377        if (!(obj is ResidualSpaceDifference)) {
378          return 0;
379        }
380        var rsd = obj as ResidualSpaceDifference;
381
382        var x = this.X - rsd.X;
383        var y = this.Y - rsd.Y;
384        var z = this.Z - rsd.Z;
385
386        if (x != 0) {
387          return x;
388        } else if (y != 0) {
389          return y;
390        } else if (z != 0) {
391          return z;
392        }
393
394        return 0;
395      }
396    }
397
398  }
399}
Note: See TracBrowser for help on using the repository browser.