Free cookie consent management tool by TermsFeed Policy Generator

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