#region License Information
/* HeuristicLab
* Copyright (C) 2002-2010 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
*
* This file is part of HeuristicLab.
*
* HeuristicLab is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HeuristicLab is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HeuristicLab. If not, see .
*/
#endregion
using System;
using System.Linq;
using HeuristicLab.Collections;
using HeuristicLab.Core;
using HeuristicLab.Operators;
using HeuristicLab.Optimization;
using HeuristicLab.Parameters;
using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
using HeuristicLab.PluginInfrastructure;
using HeuristicLab.Data;
using System.Collections.Generic;
namespace HeuristicLab.Problems.VehicleRouting.Encodings.General {
[Item("MultiVRPMoveGenerator", "Randomly selects and applies its move generators.")]
[StorableClass]
public class MultiVRPMoveGenerator : CheckedMultiOperator, IMultiVRPMoveOperator,
IStochasticOperator, IMultiMoveGenerator {
public override bool CanChangeName {
get { return false; }
}
public IValueLookupParameter SampleSizeParameter {
get { return (IValueLookupParameter)Parameters["SampleSize"]; }
}
public ILookupParameter VRPToursParameter {
get { return (ILookupParameter)Parameters["VRPTours"]; }
}
public ILookupParameter VRPMoveParameter {
get { return (ILookupParameter)Parameters["VRPMove"]; }
}
public int Cities {
get { return CoordinatesParameter.ActualValue.Rows - 1; }
}
public ILookupParameter CoordinatesParameter {
get { return (ILookupParameter)Parameters["Coordinates"]; }
}
public ILookupParameter DistanceMatrixParameter {
get { return (ILookupParameter)Parameters["DistanceMatrix"]; }
}
public ILookupParameter UseDistanceMatrixParameter {
get { return (ILookupParameter)Parameters["UseDistanceMatrix"]; }
}
public ILookupParameter VehiclesParameter {
get { return (ILookupParameter)Parameters["Vehicles"]; }
}
public ILookupParameter CapacityParameter {
get { return (ILookupParameter)Parameters["Capacity"]; }
}
public ILookupParameter DemandParameter {
get { return (ILookupParameter)Parameters["Demand"]; }
}
public ILookupParameter ReadyTimeParameter {
get { return (ILookupParameter)Parameters["ReadyTime"]; }
}
public ILookupParameter DueTimeParameter {
get { return (ILookupParameter)Parameters["DueTime"]; }
}
public ILookupParameter ServiceTimeParameter {
get { return (ILookupParameter)Parameters["ServiceTime"]; }
}
public ValueLookupParameter ProbabilitiesParameter {
get { return (ValueLookupParameter)Parameters["Probabilities"]; }
}
public ILookupParameter RandomParameter {
get { return (ILookupParameter)Parameters["Random"]; }
}
public DoubleArray Probabilities {
get { return ProbabilitiesParameter.Value; }
set { ProbabilitiesParameter.Value = value; }
}
[StorableConstructor]
private MultiVRPMoveGenerator(bool deserializing) : base(deserializing) { }
public MultiVRPMoveGenerator()
: base() {
Parameters.Add(new ValueLookupParameter("SampleSize", "The number of moves to generate."));
Parameters.Add(new LookupParameter("Random", "The pseudo random number generator which should be used for stochastic manipulation operators."));
Parameters.Add(new ValueLookupParameter("Probabilities", "The array of relative probabilities for each operator.", new DoubleArray()));
Parameters.Add(new ValueLookupParameter("Cities", "The city count."));
Parameters.Add(new LookupParameter("Coordinates", "The coordinates of the cities."));
Parameters.Add(new LookupParameter("DistanceMatrix", "The matrix which contains the distances between the cities."));
Parameters.Add(new LookupParameter("UseDistanceMatrix", "True if a distance matrix should be calculated and used for evaluation, otherwise false."));
Parameters.Add(new LookupParameter("Vehicles", "The number of vehicles."));
Parameters.Add(new LookupParameter("Capacity", "The capacity of each vehicle."));
Parameters.Add(new LookupParameter("Demand", "The demand of each customer."));
Parameters.Add(new LookupParameter("ReadyTime", "The ready time of each customer."));
Parameters.Add(new LookupParameter("DueTime", "The due time of each customer."));
Parameters.Add(new LookupParameter("ServiceTime", "The service time of each customer."));
Parameters.Add(new LookupParameter("VRPTours", "The VRP tours."));
Parameters.Add(new LookupParameter("VRPMove", "The generated moves."));
foreach (Type type in ApplicationManager.Manager.GetTypes(typeof(IMultiVRPMoveGenerator))) {
if (!typeof(MultiOperator).IsAssignableFrom(type))
Operators.Add((IMultiVRPMoveGenerator)Activator.CreateInstance(type), true);
}
}
protected override void Operators_ItemsRemoved(object sender, CollectionItemsChangedEventArgs> e) {
base.Operators_ItemsRemoved(sender, e);
if (Probabilities != null && Probabilities.Length > Operators.Count) {
List probs = new List(Probabilities.Cast());
var sorted = e.Items.OrderByDescending(x => x.Index);
foreach (IndexedItem item in sorted)
if (probs.Count > item.Index) probs.RemoveAt(item.Index);
Probabilities = new DoubleArray(probs.ToArray());
}
}
protected override void Operators_ItemsReplaced(object sender, CollectionItemsChangedEventArgs> e) {
base.Operators_ItemsReplaced(sender, e);
ParameterizeMoveGenerators();
}
protected override void Operators_ItemsAdded(object sender, CollectionItemsChangedEventArgs> e) {
base.Operators_ItemsAdded(sender, e);
ParameterizeMoveGenerators();
if (Probabilities != null && Probabilities.Length < Operators.Count) {
double avg = (Probabilities.Where(x => x > 0).Count() > 0) ? (Probabilities.Where(x => x > 0).Average()) : (1);
// add the average of all probabilities in the respective places (the new operators)
var added = e.Items.OrderBy(x => x.Index).ToList();
int insertCount = 0;
DoubleArray probs = new DoubleArray(Operators.Count);
for (int i = 0; i < Operators.Count; i++) {
if (insertCount < added.Count && i == added[insertCount].Index) {
probs[i] = avg;
insertCount++;
} else if (i - insertCount < Probabilities.Length) {
probs[i] = Probabilities[i - insertCount];
} else probs[i] = avg;
}
Probabilities = probs;
}
}
private void ParameterizeMoveGenerators() {
foreach (IMultiVRPMoveOperator moveGenerator in Operators.OfType()) {
if (moveGenerator.CoordinatesParameter != null) moveGenerator.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
if (moveGenerator.DistanceMatrixParameter != null) moveGenerator.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
if (moveGenerator.UseDistanceMatrixParameter != null) moveGenerator.UseDistanceMatrixParameter.ActualName = UseDistanceMatrixParameter.Name;
if (moveGenerator.VehiclesParameter != null) moveGenerator.VehiclesParameter.ActualName = VehiclesParameter.Name;
if (moveGenerator.CapacityParameter != null) moveGenerator.CapacityParameter.ActualName = CapacityParameter.Name;
if (moveGenerator.DemandParameter != null) moveGenerator.DemandParameter.ActualName = DemandParameter.Name;
if (moveGenerator.ReadyTimeParameter != null) moveGenerator.ReadyTimeParameter.ActualName = ReadyTimeParameter.Name;
if (moveGenerator.DueTimeParameter != null) moveGenerator.DueTimeParameter.ActualName = DueTimeParameter.Name;
if (moveGenerator.ServiceTimeParameter != null) moveGenerator.ServiceTimeParameter.ActualName = ServiceTimeParameter.Name;
moveGenerator.VRPToursParameter.ActualName = VRPToursParameter.Name;
moveGenerator.VRPMoveParameter.ActualName = VRPMoveParameter.Name;
}
foreach (IStochasticOperator moveGenerator in Operators.OfType()) {
moveGenerator.RandomParameter.ActualName = RandomParameter.Name;
}
}
public override IOperation Apply() {
if (Operators.Count == 0) throw new InvalidOperationException(Name + ": Please add at least one VRP move generator choose from.");
OperationCollection next = new OperationCollection(base.Apply());
for (int i = 0; i < SampleSizeParameter.ActualValue.Value; i++) {
IRandom random = RandomParameter.ActualValue;
DoubleArray probabilities = ProbabilitiesParameter.ActualValue;
if (probabilities.Length != Operators.Count) {
throw new InvalidOperationException(Name + ": The list of probabilities has to match the number of operators");
}
IOperator successor = null;
var checkedOperators = Operators.CheckedItems;
if (checkedOperators.Count() > 0) {
// select a random operator from the checked operators
double sum = (from indexedItem in checkedOperators select probabilities[indexedItem.Index]).Sum();
if (sum == 0) throw new InvalidOperationException(Name + ": All selected operators have zero probability.");
double r = random.NextDouble() * sum;
sum = 0;
foreach (var indexedItem in checkedOperators) {
sum += probabilities[indexedItem.Index];
if (sum > r) {
successor = indexedItem.Value;
break;
}
}
}
if (successor != null) {
next.Insert(0, ExecutionContext.CreateChildOperation(successor));
}
}
return next;
}
}
}