Free cookie consent management tool by TermsFeed Policy Generator

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