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

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

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

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