Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.ExternalEvaluation/3.4/MultiObjectiveExternalEvaluationProblem.cs @ 14819

Last change on this file since 14819 was 14185, checked in by swagner, 8 years ago

#2526: Updated year of copyrights in license headers

File size: 8.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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.Drawing;
25using System.Linq;
26using System.Threading;
27using Google.ProtocolBuffers;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Data;
31using HeuristicLab.Optimization;
32using HeuristicLab.Parameters;
33using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
34
35namespace HeuristicLab.Problems.ExternalEvaluation {
36  [Item("External Evaluation Problem (multi-objective)", "A multi-objective problem that is evaluated in a different process.")]
37  [Creatable(CreatableAttribute.Categories.ExternalEvaluationProblems, Priority = 200)]
38  [StorableClass]
39  public class MultiObjectiveExternalEvaluationProblem : MultiObjectiveBasicProblem<IEncoding>, IExternalEvaluationProblem {
40
41    public static new Image StaticItemImage {
42      get { return HeuristicLab.Common.Resources.VSImageLibrary.Type; }
43    }
44
45    #region Parameters
46    public OptionalValueParameter<EvaluationCache> CacheParameter {
47      get { return (OptionalValueParameter<EvaluationCache>)Parameters["Cache"]; }
48    }
49    public IValueParameter<CheckedItemCollection<IEvaluationServiceClient>> ClientsParameter {
50      get { return (IValueParameter<CheckedItemCollection<IEvaluationServiceClient>>)Parameters["Clients"]; }
51    }
52    public IValueParameter<SolutionMessageBuilder> MessageBuilderParameter {
53      get { return (IValueParameter<SolutionMessageBuilder>)Parameters["MessageBuilder"]; }
54    }
55    public IFixedValueParameter<MultiObjectiveOptimizationSupportScript> SupportScriptParameter {
56      get { return (IFixedValueParameter<MultiObjectiveOptimizationSupportScript>)Parameters["SupportScript"]; }
57    }
58
59    private IFixedValueParameter<BoolArray> MaximizationParameter {
60      get { return (IFixedValueParameter<BoolArray>)Parameters["Maximization"]; }
61    }
62    #endregion
63
64    #region Properties
65    public new IEncoding Encoding {
66      get { return base.Encoding; }
67      set { base.Encoding = value; }
68    }
69    public EvaluationCache Cache {
70      get { return CacheParameter.Value; }
71    }
72    public CheckedItemCollection<IEvaluationServiceClient> Clients {
73      get { return ClientsParameter.Value; }
74    }
75    public SolutionMessageBuilder MessageBuilder {
76      get { return MessageBuilderParameter.Value; }
77    }
78    public MultiObjectiveOptimizationSupportScript OptimizationSupportScript {
79      get { return SupportScriptParameter.Value; }
80    }
81    private IMultiObjectiveOptimizationSupport OptimizationSupport {
82      get { return SupportScriptParameter.Value; }
83    }
84    #endregion
85
86    [StorableConstructor]
87    protected MultiObjectiveExternalEvaluationProblem(bool deserializing) : base(deserializing) { }
88    protected MultiObjectiveExternalEvaluationProblem(MultiObjectiveExternalEvaluationProblem original, Cloner cloner) : base(original, cloner) { }
89    public override IDeepCloneable Clone(Cloner cloner) {
90      return new MultiObjectiveExternalEvaluationProblem(this, cloner);
91    }
92    public MultiObjectiveExternalEvaluationProblem()
93      : base() {
94      Parameters.Remove("Maximization"); // readonly in base class
95      Parameters.Add(new FixedValueParameter<BoolArray>("Maximization", "Set to false if the problem should be minimized.", new BoolArray()));
96      Parameters.Add(new OptionalValueParameter<EvaluationCache>("Cache", "Cache of previously evaluated solutions."));
97      Parameters.Add(new ValueParameter<CheckedItemCollection<IEvaluationServiceClient>>("Clients", "The clients that are used to communicate with the external application.", new CheckedItemCollection<IEvaluationServiceClient>() { new EvaluationServiceClient() }));
98      Parameters.Add(new ValueParameter<SolutionMessageBuilder>("MessageBuilder", "The message builder that converts from HeuristicLab objects to SolutionMessage representation.", new SolutionMessageBuilder()) { Hidden = true });
99      Parameters.Add(new FixedValueParameter<MultiObjectiveOptimizationSupportScript>("SupportScript", "A script that can analyze the results of the optimization.", new MultiObjectiveOptimizationSupportScript()));
100    }
101
102    #region Multi Objective Problem Overrides
103    public override bool[] Maximization {
104      get {
105        return Parameters.ContainsKey("Maximization") ? ((IValueParameter<BoolArray>)Parameters["Maximization"]).Value.ToArray() : new bool[0];
106      }
107    }
108
109    public virtual void SetMaximization(bool[] maximization) {
110      ((IStringConvertibleArray)MaximizationParameter.Value).Length = maximization.Length;
111      var array = MaximizationParameter.Value;
112      for (var i = 0; i < maximization.Length; i++)
113        array[i] = maximization[i];
114    }
115
116    public override double[] Evaluate(Individual individual, IRandom random) {
117      var qualityMessage = Evaluate(BuildSolutionMessage(individual));
118      if (!qualityMessage.HasExtension(MultiObjectiveQualityMessage.QualityMessage_))
119        throw new InvalidOperationException("The received message is not a MultiObjectiveQualityMessage.");
120      return qualityMessage.GetExtension(MultiObjectiveQualityMessage.QualityMessage_).QualitiesList.ToArray();
121    }
122    public virtual QualityMessage Evaluate(SolutionMessage solutionMessage) {
123      return Cache == null
124        ? EvaluateOnNextAvailableClient(solutionMessage)
125        : Cache.GetValue(solutionMessage, EvaluateOnNextAvailableClient, GetQualityMessageExtensions());
126    }
127
128    public override void Analyze(Individual[] individuals, double[][] qualities, ResultCollection results, IRandom random) {
129      OptimizationSupport.Analyze(individuals, qualities, results, random);
130    }
131
132    #endregion
133
134    public virtual ExtensionRegistry GetQualityMessageExtensions() {
135      var extensions = ExtensionRegistry.CreateInstance();
136      extensions.Add(MultiObjectiveQualityMessage.QualityMessage_);
137      return extensions;
138    }
139
140    #region Evaluation
141    private HashSet<IEvaluationServiceClient> activeClients = new HashSet<IEvaluationServiceClient>();
142    private object clientLock = new object();
143
144    private QualityMessage EvaluateOnNextAvailableClient(SolutionMessage message) {
145      IEvaluationServiceClient client = null;
146      lock (clientLock) {
147        client = Clients.CheckedItems.FirstOrDefault(c => !activeClients.Contains(c));
148        while (client == null && Clients.CheckedItems.Any()) {
149          Monitor.Wait(clientLock);
150          client = Clients.CheckedItems.FirstOrDefault(c => !activeClients.Contains(c));
151        }
152        if (client != null)
153          activeClients.Add(client);
154      }
155      try {
156        return client.Evaluate(message, GetQualityMessageExtensions());
157      } finally {
158        lock (clientLock) {
159          activeClients.Remove(client);
160          Monitor.PulseAll(clientLock);
161        }
162      }
163    }
164
165    private SolutionMessage BuildSolutionMessage(Individual individual, int solutionId = 0) {
166      lock (clientLock) {
167        SolutionMessage.Builder protobufBuilder = SolutionMessage.CreateBuilder();
168        protobufBuilder.SolutionId = solutionId;
169        var scope = new Scope();
170        individual.CopyToScope(scope);
171        foreach (var variable in scope.Variables) {
172          try {
173            MessageBuilder.AddToMessage(variable.Value, variable.Name, protobufBuilder);
174          } catch (ArgumentException ex) {
175            throw new InvalidOperationException(string.Format("ERROR while building solution message: Parameter {0} cannot be added to the message", Name), ex);
176          }
177        }
178        return protobufBuilder.Build();
179      }
180    }
181    #endregion
182  }
183}
Note: See TracBrowser for help on using the repository browser.