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

Last change on this file since 13180 was 13180, checked in by pfleck, 4 years ago

#1674

  • ProtoBuff QualityMessages
    • Changed the QualityMessage to be able to be used for single- and multi-objective problems.
    • The new SingleObjectiveQualityMessage and MultiObjectiveQualityMessage now "inherits" from QualityMessages to be able to be used in a polymorph manner.
    • This is done via protobuf's nested extensions (see http://www.indelible.org/ink/protobuf-polymorphism/).
  • EvaluationCache
    • The EvaluationCache now now stores the QualityMessage instead of a single double. This way the cache can be used for single- and multi-objective problems and additionally opens the possibility to extend the quality message with any data. (previously extended data was lost when the cache was persisted and loaded again)
    • When deserializing an older version of the cache a new single objective quality message is created from the double value. This way, no compatibility is broken and version must not be incremented.
  • Adapted the ExternalEvaluationProblem to the changes of the EvaluationCache and the QualityMessage.
  • Added a MultiObjectiveExternalEvaluationProblem on basis of the ExternalEvaluationProblem and added a IExternalEvaluationProblem interface.
File size: 7.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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("Multi Objective External Evaluation Problem", "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    #endregion
59
60    #region Properties
61    public EvaluationCache Cache {
62      get { return CacheParameter.Value; }
63    }
64    public CheckedItemCollection<IEvaluationServiceClient> Clients {
65      get { return ClientsParameter.Value; }
66    }
67    public SolutionMessageBuilder MessageBuilder {
68      get { return MessageBuilderParameter.Value; }
69    }
70    //public MultiObjectiveOptimizationSupportScript OptimizationSupportScript {
71    //  get { return SupportScriptParameter.Value; }
72    //}
73    //private IMultiObjectiveOptimizationSupport OptimizationSupport {
74    //  get { return SupportScriptParameter.Value; }
75    //}
76    #endregion
77
78    [StorableConstructor]
79    protected MultiObjectiveExternalEvaluationProblem(bool deserializing) : base(deserializing) { }
80    protected MultiObjectiveExternalEvaluationProblem(MultiObjectiveExternalEvaluationProblem original, Cloner cloner) : base(original, cloner) { }
81    public override IDeepCloneable Clone(Cloner cloner) {
82      return new MultiObjectiveExternalEvaluationProblem(this, cloner);
83    }
84    public MultiObjectiveExternalEvaluationProblem()
85      : base() {
86      Parameters.Remove("Maximization"); // readonly in base class
87      Parameters.Add(new FixedValueParameter<BoolArray>("Maximization", "Set to false if the problem should be minimized.", new BoolArray()));
88      Parameters.Add(new OptionalValueParameter<EvaluationCache>("Cache", "Cache of previously evaluated solutions."));
89      Parameters.Add(new ValueParameter<CheckedItemCollection<IEvaluationServiceClient>>("Clients", "The clients that are used to communicate with the external application.", new CheckedItemCollection<IEvaluationServiceClient>() { new EvaluationServiceClient() }));
90      Parameters.Add(new ValueParameter<SolutionMessageBuilder>("MessageBuilder", "The message builder that converts from HeuristicLab objects to SolutionMessage representation.", new SolutionMessageBuilder()) { Hidden = true });
91      //Parameters.Add(new FixedValueParameter<MultiObjectiveOptimizationSupportScript>("SupportScript", "A script that can analyze the results of the optimization.", new MultiObjectiveOptimizationSupportScript()));
92
93      //Operators.Add(new BestScopeSolutionAnalyzer()); pareto front
94    }
95
96    #region Multi Objective Problem Overrides
97    public override bool[] Maximization {
98      get {
99        return Parameters.ContainsKey("Maximization") ? ((IValueParameter<BoolArray>)Parameters["Maximization"]).Value.ToArray() : new bool[0];
100      }
101    }
102
103    public override double[] Evaluate(Individual individual, IRandom random) {
104      var qualityMessage = Evaluate(BuildSolutionMessage(individual));
105      if (!qualityMessage.HasExtension(MultiObjectiveQualityMessage.QualityMessage_))
106        throw new InvalidOperationException("The received message is not a MultiObjectiveQualityMessage.");
107      return qualityMessage.GetExtension(MultiObjectiveQualityMessage.QualityMessage_).QualitiesList.ToArray();
108    }
109    public virtual QualityMessage Evaluate(SolutionMessage solutionMessage) {
110      return Cache == null
111        ? EvaluateOnNextAvailableClient(solutionMessage)
112        : Cache.GetValue(solutionMessage, EvaluateOnNextAvailableClient, GetQualityMessageExtensions());
113    }
114
115    public override void Analyze(Individual[] individuals, double[][] qualities, ResultCollection results, IRandom random) {
116      //OptimizationSupport.Analyze(individuals, qualities, results, random);
117    }
118
119    #endregion
120
121    public virtual ExtensionRegistry GetQualityMessageExtensions() {
122      var extensions = ExtensionRegistry.CreateInstance();
123      extensions.Add(MultiObjectiveQualityMessage.QualityMessage_);
124      return extensions;
125    }
126
127    #region Evaluation
128    private HashSet<IEvaluationServiceClient> activeClients = new HashSet<IEvaluationServiceClient>();
129    private object clientLock = new object();
130
131    private QualityMessage EvaluateOnNextAvailableClient(SolutionMessage message) {
132      IEvaluationServiceClient client = null;
133      lock (clientLock) {
134        client = Clients.CheckedItems.FirstOrDefault(c => !activeClients.Contains(c));
135        while (client == null && Clients.CheckedItems.Any()) {
136          Monitor.Wait(clientLock);
137          client = Clients.CheckedItems.FirstOrDefault(c => !activeClients.Contains(c));
138        }
139        if (client != null)
140          activeClients.Add(client);
141      }
142      try {
143        return client.Evaluate(message, GetQualityMessageExtensions());
144      } finally {
145        lock (clientLock) {
146          activeClients.Remove(client);
147          Monitor.PulseAll(clientLock);
148        }
149      }
150    }
151
152    private SolutionMessage BuildSolutionMessage(Individual individual, int solutionId = 0) {
153      lock (clientLock) {
154        SolutionMessage.Builder protobufBuilder = SolutionMessage.CreateBuilder();
155        protobufBuilder.SolutionId = solutionId;
156        var scope = new Scope();
157        individual.CopyToScope(scope);
158        foreach (var variable in scope.Variables) {
159          try {
160            MessageBuilder.AddToMessage(variable.Value, variable.Name, protobufBuilder);
161          } catch (ArgumentException ex) {
162            throw new InvalidOperationException(string.Format("ERROR while building solution message: Parameter {0} cannot be added to the message", Name), ex);
163          }
164        }
165        return protobufBuilder.Build();
166      }
167    }
168    #endregion
169  }
170}
Note: See TracBrowser for help on using the repository browser.