Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.ExternalEvaluation/3.4/ExternalEvaluationProblem.cs @ 13498

Last change on this file since 13498 was 13498, checked in by abeham, 8 years ago

#2551: added setter to maximization property also

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