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

Last change on this file since 17270 was 17270, checked in by abeham, 3 years ago

#2521: worked on removing virtual from Maximization for single-objective problems

File size: 8.3 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.ReadOnly = false;
96      MaximizationParameter.Value = new BoolValue(); // is a read-only boolvalue in base class
97      Parameters.Add(new OptionalValueParameter<EvaluationCache>("Cache", "Cache of previously evaluated solutions."));
98      Parameters.Add(new ValueParameter<CheckedItemCollection<IEvaluationServiceClient>>("Clients", "The clients that are used to communicate with the external application.", new CheckedItemCollection<IEvaluationServiceClient>() { new EvaluationServiceClient() }));
99      Parameters.Add(new ValueParameter<SolutionMessageBuilder>("MessageBuilder", "The message builder that converts from HeuristicLab objects to SolutionMessage representation.", new SolutionMessageBuilder()) { Hidden = true });
100      Parameters.Add(new FixedValueParameter<SingleObjectiveOptimizationSupportScript<TEncodedSolution>>("SupportScript", "A script that can provide neighborhood and analyze the results of the optimization.", new SingleObjectiveOptimizationSupportScript<TEncodedSolution>()));
101
102      Operators.Add(new BestScopeSolutionAnalyzer());
103    }
104
105    #region Single Objective Problem Overrides
106    public override double Evaluate(TEncodedSolution solution, IRandom random) {
107      var qualityMessage = Evaluate(BuildSolutionMessage(solution));
108      if (!qualityMessage.HasExtension(SingleObjectiveQualityMessage.QualityMessage_))
109        throw new InvalidOperationException("The received message is not a SingleObjectiveQualityMessage.");
110      return qualityMessage.GetExtension(SingleObjectiveQualityMessage.QualityMessage_).Quality;
111    }
112    public virtual QualityMessage Evaluate(SolutionMessage solutionMessage) {
113      return Cache == null
114        ? EvaluateOnNextAvailableClient(solutionMessage)
115        : Cache.GetValue(solutionMessage, EvaluateOnNextAvailableClient, GetQualityMessageExtensions());
116    }
117
118    public override void Analyze(TEncodedSolution[] solutions, double[] qualities, ResultCollection results, IRandom random) {
119      OptimizationSupport.Analyze(solutions, qualities, results, random);
120    }
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 object clientLock = new object();
136
137    private QualityMessage EvaluateOnNextAvailableClient(SolutionMessage message) {
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      }
151      finally {
152        lock (clientLock) {
153          activeClients.Remove(client);
154          Monitor.PulseAll(clientLock);
155        }
156      }
157    }
158
159    private SolutionMessage BuildSolutionMessage(TEncodedSolution solution, int solutionId = 0) {
160      lock (clientLock) {
161        SolutionMessage.Builder protobufBuilder = SolutionMessage.CreateBuilder();
162        protobufBuilder.SolutionId = solutionId;
163        var scope = new Scope();
164        ScopeUtil.CopyEncodedSolutionToScope(scope, Encoding, solution);
165        foreach (var variable in scope.Variables) {
166          try {
167            MessageBuilder.AddToMessage(variable.Value, variable.Name, protobufBuilder);
168          }
169          catch (ArgumentException ex) {
170            throw new InvalidOperationException(string.Format("ERROR while building solution message: Parameter {0} cannot be added to the message", Name), ex);
171          }
172        }
173        return protobufBuilder.Build();
174      }
175    }
176    #endregion
177  }
178}
Note: See TracBrowser for help on using the repository browser.