Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2521_ProblemRefactoring/HeuristicLab.Encodings.LinearLinkageEncoding/3.4/LinearLinkage.cs @ 17187

Last change on this file since 17187 was 16751, checked in by mkommend, 6 years ago

#2521: Renamed Solution to EncodedSolution.

File size: 15.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2019 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 HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Optimization;
29using HEAL.Attic;
30
31namespace HeuristicLab.Encodings.LinearLinkageEncoding {
32  [Item("LinearLinkage", "Represents an LLE grouping of items.")]
33  [StorableType("91492281-3335-4F5A-82BA-BA76142DAD2D")]
34  public sealed class LinearLinkage : IntArray, IEncodedSolution {
35
36    [StorableConstructor]
37    private LinearLinkage(StorableConstructorFlag _) : base(_) { }
38    private LinearLinkage(LinearLinkage original, Cloner cloner) : base(original, cloner) { }
39    public LinearLinkage() { }
40
41    private LinearLinkage(int length) : base(length) { }
42    private LinearLinkage(int[] elements) : base(elements) { }
43
44    /// <summary>
45    /// Create a new LinearLinkage object where every element is in a seperate group.
46    /// </summary>
47    public static LinearLinkage SingleElementGroups(int length) {
48      var elements = new int[length];
49      for (var i = 0; i < length; i++) {
50        elements[i] = i;
51      }
52      return new LinearLinkage(elements);
53    }
54
55    /// <summary>
56    /// Create a new LinearLinkage object from an int[] in LLE
57    /// </summary>
58    /// <remarks>
59    /// This operation checks if the argument is a well formed LLE
60    /// and throws an ArgumentException otherwise.
61    /// </remarks>
62    /// <exception cref="ArgumentException">If <paramref name="lle"/> does not represent a valid LLE array.</exception>
63    /// <param name="lle">The LLE representation</param>
64    /// <returns>The linear linkage encoding in LLE format (with forward-links).</returns>
65    public static LinearLinkage FromForwardLinks(int[] lle) {
66      if (!Validate(lle))
67        throw new ArgumentException("Array is malformed and does not represent a valid LLE forward encoding.", "elements");
68      return new LinearLinkage(lle);
69    }
70
71    /// <summary>
72    /// Create a new LinearLinkage object by parsing a LLE-b representation
73    /// and modifing the underlying array so that it is in LLE representation.
74    /// </summary>
75    /// <remarks>
76    /// This operation runs in O(n) time, the parameter <paramref name="lleb"/> is not modified.
77    /// </remarks>
78    /// <exception cref="ArgumentException">If <paramref name="lleb"/> does not represent a valid LLE-b array.</exception>
79    /// <param name="lleb">The LLE-b representation (LLE with back-links)</param>
80    /// <returns>The linear linkage encoding in LLE format (with forward-links).</returns>
81    public static LinearLinkage FromBackLinks(int[] lleb) {
82      var result = new LinearLinkage(lleb.Length);
83      for (var i = lleb.Length - 1; i > 0; i--) {
84        if (lleb[i] == i) {
85          if (result[i] == 0) result[i] = i;
86          continue;
87        }
88        result[lleb[i]] = i;
89        if (result[i] == 0) result[i] = i;
90      }
91      if (!Validate(result.array))
92        throw new ArgumentException("Array is malformed and does not represent a valid LLE-b encoding (with back-links).", "lleb");
93      return result;
94    }
95
96    /// <summary>
97    /// Create a new LinearLinkage object by parsing an LLE-e representation
98    /// and modifing the underlying array so that it is in LLE representation.
99    /// </summary>
100    /// <remarks>
101    /// This operation runs in O(n) time, but requires additional memory
102    /// in form of a int[].
103    /// </remarks>
104    /// <param name="llee">The LLE-e representation</param>
105    /// <returns>The linear linkage encoding in LLE format (with forward-links).</returns>
106    public static LinearLinkage FromEndLinks(int[] llee) {
107      var result = new LinearLinkage(llee.Length);
108      result.SetEndLinks(llee);
109      return result;
110    }
111
112    /// <summary>
113    /// Create a new LinearLinkage object by translating
114    /// an enumeration of groups into the underlying array representation.
115    /// </summary>
116    /// <remarks>
117    /// Throws an ArgumentException when there is an element assigned to
118    /// multiple groups or elements that are not assigned to any group.
119    /// </remarks>
120    /// <param name="grouping">The grouping of the elements, each element must
121    /// be part of exactly one group.</param>
122    public static LinearLinkage FromGroups(int length, IEnumerable<IEnumerable<int>> grouping) {
123      var result = new LinearLinkage(length);
124      result.SetGroups(grouping);
125      return result;
126    }
127
128    public override IDeepCloneable Clone(Cloner cloner) {
129      return new LinearLinkage(this, cloner);
130    }
131
132    /// <summary>
133    /// This method parses the encoded array and calculates the membership of
134    /// each element to the groups. It starts at the lowest element.
135    /// </summary>
136    /// <remarks>
137    /// Runtime complexity of this method is O(n) where n is the length of the
138    /// array.
139    /// </remarks>
140    /// <exception cref="InvalidOperationException">If this object is not vaild LLE.</exception>
141    /// <returns>An enumeration of all groups.</returns>
142    public IEnumerable<List<int>> GetGroups() {
143      var len = array.Length;
144      var used = new bool[len];
145      for (var i = 0; i < len; i++) {
146        if (used[i]) continue;
147        var curr = i;
148        var next = array[curr];
149        var group = new List<int> { curr };
150        while (next > curr && next < len && !used[next]) {
151          used[curr] = true;
152          curr = next;
153          next = array[next];
154          group.Add(curr);
155        }
156        if (curr != next) throw new InvalidOperationException("Array is malformed and does not represent a valid LLE forward encoding.");
157        used[curr] = true;
158        yield return group;
159      }
160    }
161
162    /// <summary>
163    /// This method parses the encoded array and gathers all elements
164    /// that belong to the same group as element <paramref name="index"/>.
165    /// </summary>
166    /// <param name="index">The element whose group should be returned.
167    /// </param>
168    /// <returns>The element at <paramref name="index"/> and all other
169    /// elements in the same group.</returns>
170    public IEnumerable<int> GetGroup(int index) {
171      foreach (var n in GetGroupForward(index))
172        yield return n;
173      // the element index has already been yielded
174      foreach (var n in GetGroupBackward(index).Skip(1))
175        yield return n;
176    }
177
178    /// <summary>
179    /// This method parses the encoded array and gathers the element
180    /// <paramref name="index"/> as well as subsequent elements that
181    /// belong to the same group.
182    /// </summary>
183    /// <param name="index">The element from which subsequent (having a
184    /// larger number) elements in the group should be returned.
185    /// </param>
186    /// <returns>The element <paramref name="index"/> and all subsequent
187    /// elements in the same group.</returns>
188    public IEnumerable<int> GetGroupForward(int index) {
189      yield return index;
190      var next = array[index];
191      if (next == index) yield break;
192      int prev;
193      do {
194        yield return next;
195        prev = next;
196        next = array[next];
197      } while (next != prev);
198    }
199
200    /// <summary>
201    /// This method parses the encoded array and gathers the element
202    /// given <paramref name="index"/> as well as preceeding elements that
203    /// belong to the same group.
204    /// </summary>
205    /// <remarks>
206    /// Warning, this code has performance O(index) as the array has to
207    /// be fully traversed backwards from the given index.
208    /// </remarks>
209    /// <param name="index">The element from which preceeding (having a
210    /// smaller number) elements in the group should be returned.
211    /// </param>
212    /// <returns>The element <paramref name="index"/> and all preceeding
213    /// elements in the same group.</returns>
214    public IEnumerable<int> GetGroupBackward(int index) {
215      yield return index;
216      var next = array[index];
217      // return preceding elements in group
218      for (var prev = index - 1; prev >= 0; prev--) {
219        if (array[prev] != next) continue;
220        next = prev;
221        yield return next;
222      }
223    }
224
225    /// <summary>
226    /// This method translates an enumeration of groups into the underlying
227    /// array representation.
228    /// </summary>
229    /// <remarks>
230    /// Throws an ArgumentException when there is an element assigned to
231    /// multiple groups or elements that are not assigned to any group.
232    /// </remarks>
233    /// <param name="grouping">The grouping of the elements, each element must
234    /// be part of exactly one group.</param>
235    /// <exception cref="ArgumentException">If <paramref name="grouping"/> cannot be converted
236    /// to a valid LLE representation. For instance, because elements are too big or too small,
237    /// or they're contained in multiple groups, or there are elements not assigned to any group.
238    /// </exception>
239    public void SetGroups(IEnumerable<IEnumerable<int>> grouping) {
240      var len = array.Length;
241      var used = new bool[len];
242      foreach (var group in grouping) {
243        var prev = -1;
244        foreach (var g in group.OrderBy(x => x)) {
245          if (g < prev || g >= len) throw new ArgumentException(string.Format("Element {0} is bigger than {1} or smaller than 0.", g, len - 1), "grouping");
246          if (prev >= 0) array[prev] = g;
247          prev = g;
248          if (used[prev]) {
249            throw new ArgumentException(string.Format("Element {0} is contained at least twice.", prev), "grouping");
250          }
251          used[prev] = true;
252        }
253        array[prev] = prev;
254      }
255      if (!used.All(x => x))
256        throw new ArgumentException(string.Format("Elements are not assigned a group: {0}", string.Join(", ", used.Select((x, i) => new { x, i }).Where(x => !x.x).Select(x => x.i))));
257    }
258
259    /// <summary>
260    /// Performs a check whether the array represents a valid LLE encoding.
261    /// </summary>
262    /// <remarks>
263    /// The runtime complexity of this method is O(n) where n is the length of
264    /// the array.
265    /// </remarks>
266    /// <returns>True if the encoding is valid.</returns>
267    public bool Validate() {
268      return Validate(array);
269    }
270
271    private static bool Validate(int[] array) {
272      var len = array.Length;
273      var used = new bool[len];
274      for (var i = 0; i < len; i++) {
275        if (used[i]) continue;
276        var curr = i;
277        var next = array[curr];
278        while (next > curr && next < len && !used[next]) {
279          used[curr] = true;
280          curr = next;
281          next = array[next];
282        }
283        if (curr != next) return false;
284        used[curr] = true;
285      }
286      return true;
287    }
288
289    /// <summary>
290    /// This method flattens tree structures that may be present in groups.
291    /// These tree structures may be created by e.g. merging two groups by
292    /// linking one end node to the end node of another.
293    /// Consider following array: 5, 5, 6, 4, 4, 7, 7, 7, 8.
294    /// This results in the following tree structure for group 7:
295    ///      7
296    ///    /   \
297    ///   5     6
298    ///  / \    |
299    /// 0   1   2
300    /// After this operation the array will be 1, 2, 5, 4, 4, 6, 7, 7, 8.
301    /// Representing a tree with one branch: 0 -> 1 -> 2 -> 5 -> 6 -> 7.
302    /// </summary>
303    /// <remarks>
304    /// The method first converts the array to LLE-e format and then
305    /// linearizes the links. This requires two passes of the whole array
306    /// as well as another copy of the underlying array.
307    /// The runtime complexity is O(n).
308    ///
309    /// The method assumes that there are no back links present.
310    /// </remarks>
311    public void LinearizeTreeStructures() {
312      // Step 1: Convert the array into LLE-e
313      ToEndLinksInplace(array);
314      // Step 2: For all groups linearize the links
315      SetEndLinks(array);
316    }
317
318    /// <summary>
319    /// Creates a copy of the underlying array and turns it into LLE-e.
320    /// </summary>
321    /// <remarks>
322    /// LLE-e is a special format where each element points to the
323    /// ending item of a group.
324    /// The LLE representation 1, 2, 4, 5, 4, 6, 7, 7 would become
325    /// 4, 4, 4, 7, 4, 7, 7, 7 in LLE-e.
326    ///
327    /// This operation runs in O(n) time.
328    /// </remarks>
329    /// <exception cref="ArgumentException">In case, this object does not
330    /// represent a valid LLE encoding.
331    /// </exception>
332    /// <returns>An integer array in LLE-e representation</returns>
333    public int[] ToEndLinks() {
334      var result = (int[])array.Clone();
335      ToEndLinksInplace(result);
336      return result;
337    }
338
339    private static void ToEndLinksInplace(int[] array) {
340      var length = array.Length;
341      for (var i = length - 1; i >= 0; i--) {
342        var next = array[i];
343        if (next > i) {
344          array[i] = array[next];
345        } else if (next < i) {
346          throw new ArgumentException("Array is malformed and does not represent a valid LLE encoding.", "array");
347        }
348      }
349    }
350
351    /// <summary>
352    /// Parses an LLE-e representation and modifies the underlying array
353    /// so that it is in LLE representation.
354    /// </summary>
355    /// <remarks>
356    /// This operation runs in O(n) time, but requires additional memory
357    /// in form of a int[].
358    /// </remarks>
359    /// <param name="llee">The LLE-e representation</param>
360    /// <exception cref="ArgumentException">
361    /// If <paramref name="llee"/> does not contain a valid LLE-e representation or
362    /// has a different length to the given instance.
363    /// </exception>
364    public void SetEndLinks(int[] llee) {
365      var length = array.Length;
366      if (length != llee.Length) {
367        throw new ArgumentException(string.Format("Expected length {0} but length was {1}", length, llee.Length), "llee");
368      }
369      // If we are ok with mutating llee we can avoid this clone
370      var lookup = (int[])llee.Clone();
371      for (var i = length - 1; i >= 0; i--) {
372        var end = llee[i];
373        if (end == i) {
374          array[i] = end;
375        } else if (end > i && end < length) {
376          array[i] = lookup[end];
377          lookup[end] = i;
378        } else {
379          throw new ArgumentException("Array is malformed and does not represent a valid LLE-e end encoding.", "llee");
380        }
381      }
382    }
383
384    /// <summary>
385    /// Creates a copy of the underlying array and turns it into LLE-b.
386    /// </summary>
387    /// <remarks>
388    /// LLE-b is a special format where each element points to the
389    /// predecessor instead of the successor.
390    /// The LLE representation 1, 2, 4, 5, 4, 6, 7, 7
391    /// would become           0, 0, 1, 3, 2, 3, 5, 6 in LLE-b.
392    ///
393    /// This operation runs in O(n) time.
394    /// </remarks>
395    /// <returns>An integer array in LLE-b representation</returns>
396    public int[] ToBackLinks() {
397      var result = new int[array.Length];
398      var zeroLink = array[0];
399      for (var i = 0; i < array.Length; i++) {
400        if (array[i] == i) {
401          if (result[i] == 0 && i != zeroLink) result[i] = i;
402          continue;
403        }
404        result[array[i]] = i;
405        if (result[i] == 0 && i != zeroLink) result[i] = i;
406      }
407      return result;
408    }
409  }
410}
Note: See TracBrowser for help on using the repository browser.