Free cookie consent management tool by TermsFeed Policy Generator

source: branches/VRP/HeuristicLab.Problems.VehicleRouting/3.4/Encodings/General/Moves/MultiVRPMoveOperator/MultiVRPMoveGenerator.cs @ 6772

Last change on this file since 6772 was 6772, checked in by svonolfe, 13 years ago

Added support for multiple moves in tabu search (#1177)

File size: 8.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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.Linq;
24using HeuristicLab.Collections;
25using HeuristicLab.Core;
26using HeuristicLab.Operators;
27using HeuristicLab.Optimization;
28using HeuristicLab.Parameters;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30using HeuristicLab.PluginInfrastructure;
31using HeuristicLab.Data;
32using System.Collections.Generic;
33using HeuristicLab.Problems.VehicleRouting.Interfaces;
34using HeuristicLab.Problems.VehicleRouting.Variants;
35using HeuristicLab.Common;
36
37namespace HeuristicLab.Problems.VehicleRouting.Encodings.General {
38  [Item("MultiVRPMoveGenerator", "Randomly selects and applies its move generators.")]
39  [StorableClass]
40  public class MultiVRPMoveGenerator : CheckedMultiOperator<IMultiVRPMoveGenerator>, IMultiVRPMoveOperator,
41    IStochasticOperator, IMoveGenerator, IGeneralVRPOperator, IMultiVRPOperator {
42    public override bool CanChangeName {
43      get { return false; }
44    }
45
46    public IValueLookupParameter<IntValue> SelectedOperatorsParameter {
47      get { return (IValueLookupParameter<IntValue>)Parameters["SelectedOperators"]; }
48    }
49
50    public ILookupParameter<IVRPEncoding> VRPToursParameter {
51      get { return (ILookupParameter<IVRPEncoding>)Parameters["VRPTours"]; }
52    }
53
54    public ILookupParameter VRPMoveParameter {
55      get { return (ILookupParameter)Parameters["VRPMove"]; }
56    }
57
58    public ILookupParameter<IVRPProblemInstance> ProblemInstanceParameter {
59      get { return (LookupParameter<IVRPProblemInstance>)Parameters["ProblemInstance"]; }
60    }
61
62    public IVRPProblemInstance ProblemInstance {
63      get { return ProblemInstanceParameter.ActualValue; }
64    }
65
66    public ValueLookupParameter<DoubleArray> ProbabilitiesParameter {
67      get { return (ValueLookupParameter<DoubleArray>)Parameters["Probabilities"]; }
68    }
69    public ILookupParameter<IRandom> RandomParameter {
70      get { return (ILookupParameter<IRandom>)Parameters["Random"]; }
71    }
72
73    public DoubleArray Probabilities {
74      get { return ProbabilitiesParameter.Value; }
75      set { ProbabilitiesParameter.Value = value; }
76    }
77
78    [StorableConstructor]
79    private MultiVRPMoveGenerator(bool deserializing) : base(deserializing) { }
80    public MultiVRPMoveGenerator()
81      : base() {
82      Parameters.Add(new ValueLookupParameter<IntValue>("SelectedOperators", "The number of selected operators.", new IntValue(1)));
83      Parameters.Add(new LookupParameter<IRandom>("Random", "The pseudo random number generator which should be used for stochastic manipulation operators."));
84      Parameters.Add(new ValueLookupParameter<DoubleArray>("Probabilities", "The array of relative probabilities for each operator.", new DoubleArray()));
85      Parameters.Add(new LookupParameter<IVRPProblemInstance>("ProblemInstance", "The VRP problem instance"));
86
87      Parameters.Add(new LookupParameter<IVRPEncoding>("VRPTours", "The VRP tours."));
88      Parameters.Add(new LookupParameter<IVRPMove>("VRPMove", "The generated moves."));
89    }
90
91    public override IDeepCloneable Clone(Cloner cloner) {
92      return new MultiVRPMoveGenerator(this, cloner);
93    }
94
95    protected MultiVRPMoveGenerator(MultiVRPMoveGenerator original, Cloner cloner)
96      : base(original, cloner) {
97    }
98
99    public void SetOperators(IEnumerable<IOperator> operators) {
100      foreach (IOperator op in operators) {
101        if (op is IMultiVRPMoveGenerator && !(op is MultiOperator<IMultiVRPMoveGenerator>)) {
102          Operators.Add(op.Clone() as IMultiVRPMoveGenerator, true);
103        }
104      }
105    }
106
107    protected override void Operators_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<IMultiVRPMoveGenerator>> e) {
108      base.Operators_ItemsRemoved(sender, e);
109      if (Probabilities != null && Probabilities.Length > Operators.Count) {
110        List<double> probs = new List<double>(Probabilities.Cast<double>());
111        var sorted = e.Items.OrderByDescending(x => x.Index);
112        foreach (IndexedItem<IMultiVRPMoveGenerator> item in sorted)
113          if (probs.Count > item.Index) probs.RemoveAt(item.Index);
114        Probabilities = new DoubleArray(probs.ToArray());
115      }
116    }
117
118    protected override void Operators_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<IndexedItem<IMultiVRPMoveGenerator>> e) {
119      base.Operators_ItemsReplaced(sender, e);
120      ParameterizeMoveGenerators();
121    }
122
123    protected override void Operators_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<IMultiVRPMoveGenerator>> e) {
124      base.Operators_ItemsAdded(sender, e);
125      ParameterizeMoveGenerators();
126
127      if (Probabilities != null && Probabilities.Length < Operators.Count) {
128        double avg = (Probabilities.Where(x => x > 0).Count() > 0) ? (Probabilities.Where(x => x > 0).Average()) : (1);
129        // add the average of all probabilities in the respective places (the new operators)
130        var added = e.Items.OrderBy(x => x.Index).ToList();
131        int insertCount = 0;
132        DoubleArray probs = new DoubleArray(Operators.Count);
133        for (int i = 0; i < Operators.Count; i++) {
134          if (insertCount < added.Count && i == added[insertCount].Index) {
135            probs[i] = avg;
136            insertCount++;
137          } else if (i - insertCount < Probabilities.Length) {
138            probs[i] = Probabilities[i - insertCount];
139          } else probs[i] = avg;
140        }
141        Probabilities = probs;
142      }
143    }
144
145    private void ParameterizeMoveGenerators() {
146      foreach (IMultiVRPMoveOperator moveGenerator in Operators.OfType<IMultiVRPMoveOperator>()) {
147        moveGenerator.ProblemInstanceParameter.ActualName = ProblemInstanceParameter.Name;
148        moveGenerator.VRPToursParameter.ActualName = VRPToursParameter.Name;
149        moveGenerator.VRPMoveParameter.ActualName = VRPMoveParameter.Name;
150      }
151      foreach (IStochasticOperator moveGenerator in Operators.OfType<IStochasticOperator>()) {
152        moveGenerator.RandomParameter.ActualName = RandomParameter.Name;
153      }
154    }
155
156    public override IOperation Apply() {
157      if (Operators.Count == 0) throw new InvalidOperationException(Name + ": Please add at least one VRP move generator choose from.");
158      OperationCollection next = new OperationCollection(base.Apply());
159
160      for (int i = 0; i < SelectedOperatorsParameter.ActualValue.Value; i++) {
161        IRandom random = RandomParameter.ActualValue;
162        DoubleArray probabilities = ProbabilitiesParameter.ActualValue;
163        if (probabilities.Length != Operators.Count) {
164          throw new InvalidOperationException(Name + ": The list of probabilities has to match the number of operators");
165        }
166        IOperator successor = null;
167        var checkedOperators = Operators.CheckedItems;
168        if (checkedOperators.Count() > 0) {
169          // select a random operator from the checked operators
170          double sum = (from indexedItem in checkedOperators select probabilities[indexedItem.Index]).Sum();
171          if (sum == 0) throw new InvalidOperationException(Name + ": All selected operators have zero probability.");
172          double r = random.NextDouble() * sum;
173          sum = 0;
174          foreach (var indexedItem in checkedOperators) {
175            sum += probabilities[indexedItem.Index];
176            if (sum > r) {
177              successor = indexedItem.Value;
178              break;
179            }
180          }
181        }
182
183        if (successor != null) {
184          next.Insert(0, ExecutionContext.CreateChildOperation(successor));
185        }
186      }
187
188      return next;
189    }
190  }
191}
Note: See TracBrowser for help on using the repository browser.