Free cookie consent management tool by TermsFeed Policy Generator

source: branches/RefactorPluginInfrastructure-2522/HeuristicLab.Problems.ExternalEvaluation/3.4/MultiObjectiveExternalEvaluationProblem.cs @ 14604

Last change on this file since 14604 was 13257, checked in by pfleck, 9 years ago

#1674

  • Adapted ItemName from ExternalEvaluationProblem and MultiObjectiveExternalEvaluationProblem.
  • Removed/Fixed the support script code in from the comments.
File size: 7.8 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("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    #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
94    #region Multi Objective Problem Overrides
95    public override bool[] Maximization {
96      get {
97        return Parameters.ContainsKey("Maximization") ? ((IValueParameter<BoolArray>)Parameters["Maximization"]).Value.ToArray() : new bool[0];
98      }
99    }
100
101    public override double[] Evaluate(Individual individual, IRandom random) {
102      var qualityMessage = Evaluate(BuildSolutionMessage(individual));
103      if (!qualityMessage.HasExtension(MultiObjectiveQualityMessage.QualityMessage_))
104        throw new InvalidOperationException("The received message is not a MultiObjectiveQualityMessage.");
105      return qualityMessage.GetExtension(MultiObjectiveQualityMessage.QualityMessage_).QualitiesList.ToArray();
106    }
107    public virtual QualityMessage Evaluate(SolutionMessage solutionMessage) {
108      return Cache == null
109        ? EvaluateOnNextAvailableClient(solutionMessage)
110        : Cache.GetValue(solutionMessage, EvaluateOnNextAvailableClient, GetQualityMessageExtensions());
111    }
112
113    public override void Analyze(Individual[] individuals, double[][] qualities, ResultCollection results, IRandom random) {
114      OptimizationSupport.Analyze(individuals, qualities, results, random);
115    }
116
117    #endregion
118
119    public virtual ExtensionRegistry GetQualityMessageExtensions() {
120      var extensions = ExtensionRegistry.CreateInstance();
121      extensions.Add(MultiObjectiveQualityMessage.QualityMessage_);
122      return extensions;
123    }
124
125    #region Evaluation
126    private HashSet<IEvaluationServiceClient> activeClients = new HashSet<IEvaluationServiceClient>();
127    private object clientLock = new object();
128
129    private QualityMessage EvaluateOnNextAvailableClient(SolutionMessage message) {
130      IEvaluationServiceClient client = null;
131      lock (clientLock) {
132        client = Clients.CheckedItems.FirstOrDefault(c => !activeClients.Contains(c));
133        while (client == null && Clients.CheckedItems.Any()) {
134          Monitor.Wait(clientLock);
135          client = Clients.CheckedItems.FirstOrDefault(c => !activeClients.Contains(c));
136        }
137        if (client != null)
138          activeClients.Add(client);
139      }
140      try {
141        return client.Evaluate(message, GetQualityMessageExtensions());
142      } finally {
143        lock (clientLock) {
144          activeClients.Remove(client);
145          Monitor.PulseAll(clientLock);
146        }
147      }
148    }
149
150    private SolutionMessage BuildSolutionMessage(Individual individual, int solutionId = 0) {
151      lock (clientLock) {
152        SolutionMessage.Builder protobufBuilder = SolutionMessage.CreateBuilder();
153        protobufBuilder.SolutionId = solutionId;
154        var scope = new Scope();
155        individual.CopyToScope(scope);
156        foreach (var variable in scope.Variables) {
157          try {
158            MessageBuilder.AddToMessage(variable.Value, variable.Name, protobufBuilder);
159          } catch (ArgumentException ex) {
160            throw new InvalidOperationException(string.Format("ERROR while building solution message: Parameter {0} cannot be added to the message", Name), ex);
161          }
162        }
163        return protobufBuilder.Build();
164      }
165    }
166    #endregion
167  }
168}
Note: See TracBrowser for help on using the repository browser.