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

Last change on this file since 13491 was 13491, checked in by abeham, 5 years ago

#2551: made Encoding public get/set for external evaluation problems

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("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 new IEncoding Encoding {
62      get { return base.Encoding; }
63      set { base.Encoding = value; }
64    }
65    public EvaluationCache Cache {
66      get { return CacheParameter.Value; }
67    }
68    public CheckedItemCollection<IEvaluationServiceClient> Clients {
69      get { return ClientsParameter.Value; }
70    }
71    public SolutionMessageBuilder MessageBuilder {
72      get { return MessageBuilderParameter.Value; }
73    }
74    public MultiObjectiveOptimizationSupportScript OptimizationSupportScript {
75      get { return SupportScriptParameter.Value; }
76    }
77    private IMultiObjectiveOptimizationSupport OptimizationSupport {
78      get { return SupportScriptParameter.Value; }
79    }
80    #endregion
81
82    [StorableConstructor]
83    protected MultiObjectiveExternalEvaluationProblem(bool deserializing) : base(deserializing) { }
84    protected MultiObjectiveExternalEvaluationProblem(MultiObjectiveExternalEvaluationProblem original, Cloner cloner) : base(original, cloner) { }
85    public override IDeepCloneable Clone(Cloner cloner) {
86      return new MultiObjectiveExternalEvaluationProblem(this, cloner);
87    }
88    public MultiObjectiveExternalEvaluationProblem()
89      : base() {
90      Parameters.Remove("Maximization"); // readonly in base class
91      Parameters.Add(new FixedValueParameter<BoolArray>("Maximization", "Set to false if the problem should be minimized.", new BoolArray()));
92      Parameters.Add(new OptionalValueParameter<EvaluationCache>("Cache", "Cache of previously evaluated solutions."));
93      Parameters.Add(new ValueParameter<CheckedItemCollection<IEvaluationServiceClient>>("Clients", "The clients that are used to communicate with the external application.", new CheckedItemCollection<IEvaluationServiceClient>() { new EvaluationServiceClient() }));
94      Parameters.Add(new ValueParameter<SolutionMessageBuilder>("MessageBuilder", "The message builder that converts from HeuristicLab objects to SolutionMessage representation.", new SolutionMessageBuilder()) { Hidden = true });
95      Parameters.Add(new FixedValueParameter<MultiObjectiveOptimizationSupportScript>("SupportScript", "A script that can analyze the results of the optimization.", new MultiObjectiveOptimizationSupportScript()));
96    }
97
98    #region Multi Objective Problem Overrides
99    public override bool[] Maximization {
100      get {
101        return Parameters.ContainsKey("Maximization") ? ((IValueParameter<BoolArray>)Parameters["Maximization"]).Value.ToArray() : new bool[0];
102      }
103    }
104
105    public override double[] Evaluate(Individual individual, IRandom random) {
106      var qualityMessage = Evaluate(BuildSolutionMessage(individual));
107      if (!qualityMessage.HasExtension(MultiObjectiveQualityMessage.QualityMessage_))
108        throw new InvalidOperationException("The received message is not a MultiObjectiveQualityMessage.");
109      return qualityMessage.GetExtension(MultiObjectiveQualityMessage.QualityMessage_).QualitiesList.ToArray();
110    }
111    public virtual QualityMessage Evaluate(SolutionMessage solutionMessage) {
112      return Cache == null
113        ? EvaluateOnNextAvailableClient(solutionMessage)
114        : Cache.GetValue(solutionMessage, EvaluateOnNextAvailableClient, GetQualityMessageExtensions());
115    }
116
117    public override void Analyze(Individual[] individuals, double[][] qualities, ResultCollection results, IRandom random) {
118      OptimizationSupport.Analyze(individuals, qualities, results, random);
119    }
120
121    #endregion
122
123    public virtual ExtensionRegistry GetQualityMessageExtensions() {
124      var extensions = ExtensionRegistry.CreateInstance();
125      extensions.Add(MultiObjectiveQualityMessage.QualityMessage_);
126      return extensions;
127    }
128
129    #region Evaluation
130    private HashSet<IEvaluationServiceClient> activeClients = new HashSet<IEvaluationServiceClient>();
131    private object clientLock = new object();
132
133    private QualityMessage EvaluateOnNextAvailableClient(SolutionMessage message) {
134      IEvaluationServiceClient client = null;
135      lock (clientLock) {
136        client = Clients.CheckedItems.FirstOrDefault(c => !activeClients.Contains(c));
137        while (client == null && Clients.CheckedItems.Any()) {
138          Monitor.Wait(clientLock);
139          client = Clients.CheckedItems.FirstOrDefault(c => !activeClients.Contains(c));
140        }
141        if (client != null)
142          activeClients.Add(client);
143      }
144      try {
145        return client.Evaluate(message, GetQualityMessageExtensions());
146      } finally {
147        lock (clientLock) {
148          activeClients.Remove(client);
149          Monitor.PulseAll(clientLock);
150        }
151      }
152    }
153
154    private SolutionMessage BuildSolutionMessage(Individual individual, int solutionId = 0) {
155      lock (clientLock) {
156        SolutionMessage.Builder protobufBuilder = SolutionMessage.CreateBuilder();
157        protobufBuilder.SolutionId = solutionId;
158        var scope = new Scope();
159        individual.CopyToScope(scope);
160        foreach (var variable in scope.Variables) {
161          try {
162            MessageBuilder.AddToMessage(variable.Value, variable.Name, protobufBuilder);
163          } catch (ArgumentException ex) {
164            throw new InvalidOperationException(string.Format("ERROR while building solution message: Parameter {0} cannot be added to the message", Name), ex);
165          }
166        }
167        return protobufBuilder.Build();
168      }
169    }
170    #endregion
171  }
172}
Note: See TracBrowser for help on using the repository browser.