source: branches/2521_ProblemRefactoring/HeuristicLab.Problems.ExternalEvaluation/3.4/SingleObjectiveExternalEvaluationProblem.cs @ 17546

Last change on this file since 17546 was 17546, checked in by abeham, 7 weeks ago

#2521: Introduce class to make parameter change handling easier, fix bug in SingleObjectiveProblem regarding MaximizationChanged

File size: 8.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2019 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 HEAL.Attic;
29using HeuristicLab.Analysis;
30using HeuristicLab.Common;
31using HeuristicLab.Core;
32using HeuristicLab.Data;
33using HeuristicLab.Optimization;
34using HeuristicLab.Parameters;
35
36namespace HeuristicLab.Problems.ExternalEvaluation {
37  [Item("External Evaluation Problem (single-objective)", "A problem that is evaluated in a different process.")]
38  [Creatable(CreatableAttribute.Categories.ExternalEvaluationProblems, Priority = 100)]
39  [StorableType("115EB3A5-A8A8-4A2E-9799-9485FE896DEC")]
40  // BackwardsCompatibility3.3
41  // Rename class to SingleObjectiveExternalEvaluationProblem
42  public class ExternalEvaluationProblem<TEncoding, TEncodedSolution> : SingleObjectiveProblem<TEncoding, TEncodedSolution>, IExternalEvaluationProblem
43    where TEncoding : class, IEncoding<TEncodedSolution>
44    where TEncodedSolution : class, IEncodedSolution {
45
46    public static new Image StaticItemImage {
47      get { return HeuristicLab.Common.Resources.VSImageLibrary.Type; }
48    }
49
50    #region Parameters
51    public OptionalValueParameter<EvaluationCache> CacheParameter {
52      get { return (OptionalValueParameter<EvaluationCache>)Parameters["Cache"]; }
53    }
54    public IValueParameter<CheckedItemCollection<IEvaluationServiceClient>> ClientsParameter {
55      get { return (IValueParameter<CheckedItemCollection<IEvaluationServiceClient>>)Parameters["Clients"]; }
56    }
57    public IValueParameter<SolutionMessageBuilder> MessageBuilderParameter {
58      get { return (IValueParameter<SolutionMessageBuilder>)Parameters["MessageBuilder"]; }
59    }
60    public IFixedValueParameter<SingleObjectiveOptimizationSupportScript<TEncodedSolution>> SupportScriptParameter {
61      get { return (IFixedValueParameter<SingleObjectiveOptimizationSupportScript<TEncodedSolution>>)Parameters["SupportScript"]; }
62    }
63    #endregion
64
65    #region Properties
66    public new TEncoding Encoding {
67      get { return base.Encoding; }
68      set { base.Encoding = value; }
69    }
70    public EvaluationCache Cache {
71      get { return CacheParameter.Value; }
72    }
73    public CheckedItemCollection<IEvaluationServiceClient> Clients {
74      get { return ClientsParameter.Value; }
75    }
76    public SolutionMessageBuilder MessageBuilder {
77      get { return MessageBuilderParameter.Value; }
78    }
79    public SingleObjectiveOptimizationSupportScript<TEncodedSolution> OptimizationSupportScript {
80      get { return SupportScriptParameter.Value; }
81    }
82    private ISingleObjectiveOptimizationSupport<TEncodedSolution> OptimizationSupport {
83      get { return SupportScriptParameter.Value; }
84    }
85    #endregion
86
87    [StorableConstructor]
88    protected ExternalEvaluationProblem(StorableConstructorFlag _) : base(_) { }
89    protected ExternalEvaluationProblem(ExternalEvaluationProblem<TEncoding, TEncodedSolution> original, Cloner cloner) : base(original, cloner) { }
90    public override IDeepCloneable Clone(Cloner cloner) {
91      return new ExternalEvaluationProblem<TEncoding, TEncodedSolution>(this, cloner);
92    }
93    public ExternalEvaluationProblem(TEncoding encoding)
94      : base(encoding) {
95      MaximizationParameter.ForceValue(new BoolValue()); // is a read-only bool value in base class
96      Parameters.Add(new OptionalValueParameter<EvaluationCache>("Cache", "Cache of previously evaluated solutions."));
97      Parameters.Add(new ValueParameter<CheckedItemCollection<IEvaluationServiceClient>>("Clients", "The clients that are used to communicate with the external application.", new CheckedItemCollection<IEvaluationServiceClient>() { new EvaluationServiceClient() }));
98      Parameters.Add(new ValueParameter<SolutionMessageBuilder>("MessageBuilder", "The message builder that converts from HeuristicLab objects to SolutionMessage representation.", new SolutionMessageBuilder()) { Hidden = true });
99      Parameters.Add(new FixedValueParameter<SingleObjectiveOptimizationSupportScript<TEncodedSolution>>("SupportScript", "A script that can provide neighborhood and analyze the results of the optimization.", new SingleObjectiveOptimizationSupportScript<TEncodedSolution>()));
100
101      Operators.Add(new BestScopeSolutionAnalyzer());
102    }
103
104    #region Single Objective Problem Overrides
105    public override ISingleObjectiveEvaluationResult Evaluate(TEncodedSolution solution, IRandom random, CancellationToken cancellationToken) {
106      var qualityMessage = Evaluate(BuildSolutionMessage(solution), cancellationToken);
107      if (!qualityMessage.HasExtension(SingleObjectiveQualityMessage.QualityMessage_))
108        throw new InvalidOperationException("The received message is not a SingleObjectiveQualityMessage.");
109      var quality = qualityMessage.GetExtension(SingleObjectiveQualityMessage.QualityMessage_).Quality;
110      return new SingleObjectiveEvaluationResult(quality);
111
112    }
113    public virtual QualityMessage Evaluate(SolutionMessage solutionMessage, CancellationToken cancellationToken) {
114      return Cache == null
115        ? EvaluateOnNextAvailableClient(solutionMessage, cancellationToken)
116        : Cache.GetValue(solutionMessage, EvaluateOnNextAvailableClient, GetQualityMessageExtensions(), cancellationToken);
117    }
118
119    public override void Analyze(TEncodedSolution[] solutions, double[] qualities, ResultCollection results, IRandom random) {
120      OptimizationSupport.Analyze(solutions, qualities, results, random);
121    }
122    public override IEnumerable<TEncodedSolution> GetNeighbors(TEncodedSolution solutions, IRandom random) {
123      return OptimizationSupport.GetNeighbors(solutions, random);
124    }
125    #endregion
126
127    public virtual ExtensionRegistry GetQualityMessageExtensions() {
128      var extensions = ExtensionRegistry.CreateInstance();
129      extensions.Add(SingleObjectiveQualityMessage.QualityMessage_);
130      return extensions;
131    }
132
133    #region Evaluation
134    private HashSet<IEvaluationServiceClient> activeClients = new HashSet<IEvaluationServiceClient>();
135    private readonly object clientLock = new object();
136
137    private QualityMessage EvaluateOnNextAvailableClient(SolutionMessage message, CancellationToken cancellationToken) {
138      IEvaluationServiceClient client = null;
139      lock (clientLock) {
140        client = Clients.CheckedItems.FirstOrDefault(c => !activeClients.Contains(c));
141        while (client == null && Clients.CheckedItems.Any()) {
142          Monitor.Wait(clientLock);
143          client = Clients.CheckedItems.FirstOrDefault(c => !activeClients.Contains(c));
144        }
145        if (client != null)
146          activeClients.Add(client);
147      }
148      try {
149        return client.Evaluate(message, GetQualityMessageExtensions());
150      } finally {
151        lock (clientLock) {
152          activeClients.Remove(client);
153          Monitor.PulseAll(clientLock);
154        }
155      }
156    }
157
158    private SolutionMessage BuildSolutionMessage(TEncodedSolution solution, int solutionId = 0) {
159      lock (clientLock) {
160        SolutionMessage.Builder protobufBuilder = SolutionMessage.CreateBuilder();
161        protobufBuilder.SolutionId = solutionId;
162        var scope = new Scope();
163        ScopeUtil.CopyEncodedSolutionToScope(scope, Encoding, solution);
164        foreach (var variable in scope.Variables) {
165          try {
166            MessageBuilder.AddToMessage(variable.Value, variable.Name, protobufBuilder);
167          } catch (ArgumentException ex) {
168            throw new InvalidOperationException(string.Format("ERROR while building solution message: Parameter {0} cannot be added to the message", Name), ex);
169          }
170        }
171        return protobufBuilder.Build();
172      }
173    }
174    #endregion
175  }
176}
Note: See TracBrowser for help on using the repository browser.