Free cookie consent management tool by TermsFeed Policy Generator

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

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