Free cookie consent management tool by TermsFeed Policy Generator

source: branches/WebJobManager/HeuristicLab.Problems.ExternalEvaluation/3.4/MultiObjectiveExternalEvaluationProblem.cs @ 16003

Last change on this file since 16003 was 13656, checked in by ascheibe, 9 years ago

#2582 created branch for Hive Web Job Manager

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