Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2582 created branch for Hive Web Job Manager

File size: 8.3 KB
RevLine 
[3852]1#region License Information
2/* HeuristicLab
[12012]3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[3852]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
[3861]22using System;
23using System.Collections.Generic;
24using System.Linq;
[11892]25using System.Threading;
26using Google.ProtocolBuffers;
[3862]27using HeuristicLab.Common;
[3852]28using HeuristicLab.Core;
[3861]29using HeuristicLab.Data;
[11893]30using HeuristicLab.Optimization;
[3861]31using HeuristicLab.Parameters;
[3852]32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33
34namespace HeuristicLab.Problems.ExternalEvaluation {
[13257]35  [Item("External Evaluation Problem (multi-objective)", "A multi-objective problem that is evaluated in a different process.")]
[13180]36  [Creatable(CreatableAttribute.Categories.ExternalEvaluationProblems, Priority = 200)]
[3852]37  [StorableClass]
[13180]38  public class MultiObjectiveExternalEvaluationProblem : MultiObjectiveBasicProblem<IEncoding>, IExternalEvaluationProblem {
[4419]39
40
[13656]41
[11899]42    #region Parameters
[13656]43    public OptionalValueParameter<EvaluationCache> CacheParameter
44    {
[11892]45      get { return (OptionalValueParameter<EvaluationCache>)Parameters["Cache"]; }
[3861]46    }
[13656]47    public IValueParameter<CheckedItemCollection<IEvaluationServiceClient>> ClientsParameter
48    {
[6189]49      get { return (IValueParameter<CheckedItemCollection<IEvaluationServiceClient>>)Parameters["Clients"]; }
[3859]50    }
[13656]51    public IValueParameter<SolutionMessageBuilder> MessageBuilderParameter
52    {
[11892]53      get { return (IValueParameter<SolutionMessageBuilder>)Parameters["MessageBuilder"]; }
[3859]54    }
[13656]55    public IFixedValueParameter<MultiObjectiveOptimizationSupportScript> SupportScriptParameter
56    {
[13183]57      get { return (IFixedValueParameter<MultiObjectiveOptimizationSupportScript>)Parameters["SupportScript"]; }
58    }
[13500]59
[13656]60    private IFixedValueParameter<BoolArray> MaximizationParameter
61    {
[13500]62      get { return (IFixedValueParameter<BoolArray>)Parameters["Maximization"]; }
63    }
[11899]64    #endregion
[3852]65
[11899]66    #region Properties
[13656]67    public new IEncoding Encoding
68    {
[13491]69      get { return base.Encoding; }
70      set { base.Encoding = value; }
71    }
[13656]72    public EvaluationCache Cache
73    {
[11892]74      get { return CacheParameter.Value; }
[3860]75    }
[13656]76    public CheckedItemCollection<IEvaluationServiceClient> Clients
77    {
[11892]78      get { return ClientsParameter.Value; }
[3860]79    }
[13656]80    public SolutionMessageBuilder MessageBuilder
81    {
[11892]82      get { return MessageBuilderParameter.Value; }
[3860]83    }
[13656]84    public MultiObjectiveOptimizationSupportScript OptimizationSupportScript
85    {
[13183]86      get { return SupportScriptParameter.Value; }
87    }
[13656]88    private IMultiObjectiveOptimizationSupport OptimizationSupport
89    {
[13183]90      get { return SupportScriptParameter.Value; }
91    }
[11899]92    #endregion
[3860]93
[3861]94    [StorableConstructor]
[13180]95    protected MultiObjectiveExternalEvaluationProblem(bool deserializing) : base(deserializing) { }
96    protected MultiObjectiveExternalEvaluationProblem(MultiObjectiveExternalEvaluationProblem original, Cloner cloner) : base(original, cloner) { }
[4722]97    public override IDeepCloneable Clone(Cloner cloner) {
[13180]98      return new MultiObjectiveExternalEvaluationProblem(this, cloner);
[4722]99    }
[13180]100    public MultiObjectiveExternalEvaluationProblem()
[3852]101      : base() {
[12002]102      Parameters.Remove("Maximization"); // readonly in base class
[13180]103      Parameters.Add(new FixedValueParameter<BoolArray>("Maximization", "Set to false if the problem should be minimized.", new BoolArray()));
[11892]104      Parameters.Add(new OptionalValueParameter<EvaluationCache>("Cache", "Cache of previously evaluated solutions."));
[6189]105      Parameters.Add(new ValueParameter<CheckedItemCollection<IEvaluationServiceClient>>("Clients", "The clients that are used to communicate with the external application.", new CheckedItemCollection<IEvaluationServiceClient>() { new EvaluationServiceClient() }));
[13180]106      Parameters.Add(new ValueParameter<SolutionMessageBuilder>("MessageBuilder", "The message builder that converts from HeuristicLab objects to SolutionMessage representation.", new SolutionMessageBuilder()) { Hidden = true });
[13183]107      Parameters.Add(new FixedValueParameter<MultiObjectiveOptimizationSupportScript>("SupportScript", "A script that can analyze the results of the optimization.", new MultiObjectiveOptimizationSupportScript()));
[11892]108    }
[3861]109
[13180]110    #region Multi Objective Problem Overrides
[13656]111    public override bool[] Maximization
112    {
113      get
114      {
[13180]115        return Parameters.ContainsKey("Maximization") ? ((IValueParameter<BoolArray>)Parameters["Maximization"]).Value.ToArray() : new bool[0];
116      }
[3852]117    }
[11892]118
[13500]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
[13180]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();
[11892]131    }
[13180]132    public virtual QualityMessage Evaluate(SolutionMessage solutionMessage) {
133      return Cache == null
134        ? EvaluateOnNextAvailableClient(solutionMessage)
135        : Cache.GetValue(solutionMessage, EvaluateOnNextAvailableClient, GetQualityMessageExtensions());
136    }
[11892]137
[13180]138    public override void Analyze(Individual[] individuals, double[][] qualities, ResultCollection results, IRandom random) {
[13183]139      OptimizationSupport.Analyze(individuals, qualities, results, random);
[11893]140    }
141
[11899]142    #endregion
[11893]143
[13180]144    public virtual ExtensionRegistry GetQualityMessageExtensions() {
145      var extensions = ExtensionRegistry.CreateInstance();
146      extensions.Add(MultiObjectiveQualityMessage.QualityMessage_);
147      return extensions;
148    }
149
150    #region Evaluation
[11899]151    private HashSet<IEvaluationServiceClient> activeClients = new HashSet<IEvaluationServiceClient>();
152    private object clientLock = new object();
[13180]153
[11892]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));
[6189]161        }
[11892]162        if (client != null)
163          activeClients.Add(client);
[6189]164      }
[11892]165      try {
166        return client.Evaluate(message, GetQualityMessageExtensions());
[13656]167      }
168      finally {
[11892]169        lock (clientLock) {
170          activeClients.Remove(client);
171          Monitor.PulseAll(clientLock);
172        }
[7999]173      }
[6189]174    }
[3861]175
[13180]176    private SolutionMessage BuildSolutionMessage(Individual individual, int solutionId = 0) {
[11892]177      lock (clientLock) {
178        SolutionMessage.Builder protobufBuilder = SolutionMessage.CreateBuilder();
[13180]179        protobufBuilder.SolutionId = solutionId;
[11892]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);
[13656]185          }
186          catch (ArgumentException ex) {
[13180]187            throw new InvalidOperationException(string.Format("ERROR while building solution message: Parameter {0} cannot be added to the message", Name), ex);
[12504]188          }
[3872]189        }
[11892]190        return protobufBuilder.Build();
[3872]191      }
192    }
[11899]193    #endregion
[3852]194  }
195}
Note: See TracBrowser for help on using the repository browser.