Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.BioBoost/HeuristicLab.Problems.BioBoost/3.3/Operators/Mutation/PlantMover.cs @ 13069

Last change on this file since 13069 was 13069, checked in by gkronber, 8 years ago

#2499: imported source code for HeuristicLab.BioBoost from private repository with some changes

File size: 7.6 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Management.Instrumentation;
5using System.Text;
6using System.Threading.Tasks;
7using HeuristicLab.BioBoost.ProblemDescription;
8using HeuristicLab.BioBoost.Representation;
9using HeuristicLab.Common;
10using HeuristicLab.Core;
11using HeuristicLab.Data;
12using HeuristicLab.Encodings.IntegerVectorEncoding;
13using HeuristicLab.Operators;
14using HeuristicLab.Optimization;
15using HeuristicLab.Parameters;
16using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
17
18namespace HeuristicLab.BioBoost.Operators.Mutation {
19
20  public class PlantMover : SingleSuccessorOperator, IManipulator, IStochasticOperator {
21
22    #region Parameters
23    public LookupParameter<BioBoostProblemData> ProblemDataParameter { get { return (LookupParameter<BioBoostProblemData>) Parameters["ProblemData"]; } }
24    public LookupParameter<DistanceMatrix> DistanceMatrixParameter { get { return (LookupParameter<DistanceMatrix>) Parameters["DistanceMatrix"]; } }
25    public ValueParameter<BoolValue> DistanceMatrixInProblemDataParameter { get { return (ValueParameter<BoolValue>) Parameters["DistanceMatrixInProblemData"]; } }
26    public ValueLookupParameter<IntMatrix> RegionBoundsParameter { get { return (ValueLookupParameter<IntMatrix>) Parameters["RegionBounds"]; } }
27    public ILookupParameter<IRandom> RandomParameter { get { return (ILookupParameter<IRandom>) Parameters["Random"]; } }
28    public IValueLookupParameter<PercentValue> MergeAvoidanceProbabilityParameter { get { return (IValueLookupParameter<PercentValue>) Parameters["MergeAvoidanceProbability"]; } }
29    public IValueLookupParameter<PercentValue> SplitProbabilityParameter { get { return (IValueLookupParameter<PercentValue>) Parameters["SplitProbability"]; } }
30    public IValueLookupParameter<PercentValue> MovePercentageParameter { get { return (IValueLookupParameter<PercentValue>) Parameters["MovePercentage"]; } }
31    #endregion
32
33
34
35    #region Parameter Values
36    public BioBoostProblemData ProblemData { get { return ProblemDataParameter.ActualValue; } }
37    public IntMatrix RegionBounds { get { return RegionBoundsParameter.ActualValue; } }
38    public IRandom Random { get { return RandomParameter.ActualValue; } }
39    public bool DistanceMatrixInProblemData { get { return DistanceMatrixInProblemDataParameter.Value.Value; } }
40    public DistanceMatrix DistanceMatrix {
41      get {
42        if (DistanceMatrixInProblemData) {
43          return ((IValueParameter<DistanceMatrix>) ProblemData.Parameters[DistanceMatrixParameter.ActualName]).Value;
44        } else {
45          return DistanceMatrixParameter.ActualValue;
46        }
47      }
48    }
49    public double MergeAvoidanceProbability { get { return MergeAvoidanceProbabilityParameter.Value.Value; } }
50    public double SplitProbability { get { return SplitProbabilityParameter.Value.Value; } }
51    public double MovePercentage { get { return MovePercentageParameter.Value.Value; } }
52    #endregion
53
54    #region Construction & Cloning
55    [StorableConstructor]
56    public PlantMover(bool isDeserializing) {}
57    public PlantMover(PlantMover orig, Cloner cloner) : base(orig, cloner) {}
58
59    public PlantMover() {
60      Parameters.Add(new LookupParameter<BioBoostProblemData>("ProblemData", "The data store of the detailed problem description."));
61      Parameters.Add(new LookupParameter<DistanceMatrix>("DistanceMatrix", "The distance matrix to use", "StreetDistanceMatrix")); // TODO: check this
62      Parameters.Add(new ValueParameter<BoolValue>("DistanceMatrixInProblemData", "Whether to look for the distance matrix in problem data or in scope.", new BoolValue(true)));
63      Parameters.Add(new ValueLookupParameter<IntMatrix>("RegionBounds", "The limits of valid region ids."));
64      Parameters.Add(new LookupParameter<IRandom>("Random", "The random number generator."));
65      Parameters.Add(new ValueLookupParameter<PercentValue>("MergeAvoidanceProbability", "Probability that a moved plant will avoid existing plant locations.", new PercentValue(1)));
66      Parameters.Add(new ValueLookupParameter<PercentValue>("SplitProbability", "Probability that only part of the suppliers will follow to the new location.", new PercentValue(0)));
67      Parameters.Add(new ValueLookupParameter<PercentValue>("MovePercentage", "In case a plant is split, the percentage of suppliers that will move.", new PercentValue(0.5)));
68    }
69
70    public override IDeepCloneable Clone(Cloner cloner) {
71      return new PlantMover(this, cloner);
72    }
73    #endregion
74
75    public override IOperation Apply() {
76      var scope = ExecutionContext.Scope;
77      var dm = DistanceMatrix;
78      var feedstock =
79        ProblemData.TransportTargets.CheckedItems.ElementAt(
80          Random.Next(ProblemData.TransportTargets.CheckedItems.Count())).Value.Value;
81      string product = null;
82      var productLinks = ProblemData.ProductLinks;
83      for (int i = 0; i < productLinks.Rows; i++) {
84        if (productLinks[i, 0] == feedstock)
85          product = productLinks[i, 1];
86      }
87      var supplyTransports = scope.Variables[LayerDescriptor.TransportTargets.NameWithPrefix(feedstock)].Value as IntegerVector;
88      var productTransportName = LayerDescriptor.TransportTargets.NameWithPrefix(product);
89      var productTransports = product == null || !scope.Variables.ContainsKey(productTransportName) ? null
90        : scope.Variables[productTransportName].Value as IntegerVector;
91      if (supplyTransports != null) {
92        var plants = supplyTransports.Select((target, source) => new {target, source}).GroupBy(p => p.target).ToList();
93        var plant = plants.ElementAt(Random.Next(plants.Count));
94        var forbiddenRegions = new HashSet<int>();
95        if (Random.NextDouble() > MergeAvoidanceProbability) {
96          forbiddenRegions = new HashSet<int>(plants.Select(p => p.Key));
97        }
98        var newTarget = FindNewTarget(plant.Key, Random, dm, forbiddenRegions);
99        bool split = Random.NextDouble() < SplitProbability;
100        foreach (var supplier in plant) {
101          if (!split || Random.NextDouble() <= MovePercentage) {
102            supplyTransports[supplier.source] = newTarget;
103          }
104        }
105        if (productTransports != null) {
106          var temp = productTransports[newTarget];
107          productTransports[newTarget] = productTransports[plant.Key];
108          productTransports[plant.Key] = temp;
109        }
110      }
111      return base.Apply();
112    }
113
114    private int FindNewTarget(int oldTarget, IRandom random, DistanceMatrix distances, HashSet<int> forbiddenRegions) {
115      var neighborDistances = new double[0].Select((d, idx) => new {index = idx, distance = d}).ToList();
116      var maxDistance = 0d;
117      for (int j = 0; j < distances.Columns; j++) {
118        if (forbiddenRegions.Contains(j)) continue;
119        var dist = distances[oldTarget, j];
120        neighborDistances.Add(new {index = j, distance = dist});
121        maxDistance = Math.Max(dist, maxDistance);
122      }
123      neighborDistances = neighborDistances.Select(p => new {p.index, distance = maxDistance - p.distance}).ToList();
124      neighborDistances.Sort((a, b) => b.distance.CompareTo(a.distance));
125      var totalDistance = neighborDistances.Sum(p => p.distance);
126      var threshold = random.NextDouble()*totalDistance;
127      var sum = 0d;
128      var index = 0;
129      while (index < neighborDistances.Count && sum < threshold) {
130        sum += neighborDistances[index].distance;
131        index++;
132      }
133      index = Math.Min(index, neighborDistances.Count - 1);
134      return neighborDistances[index].index;
135    }
136
137  }
138}
Note: See TracBrowser for help on using the repository browser.