Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ProgrammableProblem/HeuristicLab.Problems.ExternalEvaluation/3.4/ExternalEvaluationProblem.cs @ 11899

Last change on this file since 11899 was 11899, checked in by abeham, 10 years ago

#2174:

  • Added regions to structure code
  • Added compile call to the default creator
File size: 7.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2014 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.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Data;
31using HeuristicLab.Optimization;
32using HeuristicLab.Parameters;
33using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
34using HeuristicLab.Problems.Programmable;
35
36namespace HeuristicLab.Problems.ExternalEvaluation {
37  [Item("External Evaluation Problem", "A problem that is evaluated in a different process.")]
38  [Creatable("Problems")]
39  [StorableClass]
40  public sealed class ExternalEvaluationProblem : SingleObjectiveBasicProblem<IEncoding> {
41
42    public static new Image StaticItemImage {
43      get { return HeuristicLab.Common.Resources.VSImageLibrary.Type; }
44    }
45
46    #region Parameters
47    public OptionalValueParameter<EvaluationCache> CacheParameter {
48      get { return (OptionalValueParameter<EvaluationCache>)Parameters["Cache"]; }
49    }
50    public IValueParameter<CheckedItemCollection<IEvaluationServiceClient>> ClientsParameter {
51      get { return (IValueParameter<CheckedItemCollection<IEvaluationServiceClient>>)Parameters["Clients"]; }
52    }
53    public IValueParameter<SolutionMessageBuilder> MessageBuilderParameter {
54      get { return (IValueParameter<SolutionMessageBuilder>)Parameters["MessageBuilder"]; }
55    }
56    public IFixedValueParameter<SingleObjectiveOptimizationSupportScript> SupportScriptParameter {
57      get { return (IFixedValueParameter<SingleObjectiveOptimizationSupportScript>)Parameters["SupportScript"]; }
58    }
59    #endregion
60
61    #region Properties
62    public EvaluationCache Cache {
63      get { return CacheParameter.Value; }
64    }
65    public CheckedItemCollection<IEvaluationServiceClient> Clients {
66      get { return ClientsParameter.Value; }
67    }
68    public SolutionMessageBuilder MessageBuilder {
69      get { return MessageBuilderParameter.Value; }
70    }
71    public SingleObjectiveOptimizationSupportScript OptimizationSupportScript {
72      get { return SupportScriptParameter.Value; }
73    }
74    private ISingleObjectiveOptimizationSupport OptimizationSupport {
75      get { return SupportScriptParameter.Value; }
76    }
77    #endregion
78
79    [StorableConstructor]
80    private ExternalEvaluationProblem(bool deserializing) : base(deserializing) { }
81    private ExternalEvaluationProblem(ExternalEvaluationProblem original, Cloner cloner)
82      : base(original, cloner) {
83      CompileSupportScript();
84    }
85    public override IDeepCloneable Clone(Cloner cloner) {
86      return new ExternalEvaluationProblem(this, cloner);
87    }
88    public ExternalEvaluationProblem()
89      : base() {
90      Parameters.Add(new OptionalValueParameter<EvaluationCache>("Cache", "Cache of previously evaluated solutions."));
91      Parameters.Add(new ValueParameter<CheckedItemCollection<IEvaluationServiceClient>>("Clients", "The clients that are used to communicate with the external application.", new CheckedItemCollection<IEvaluationServiceClient>() { new EvaluationServiceClient() }));
92      Parameters.Add(new ValueParameter<SolutionMessageBuilder>("MessageBuilder", "The message builder that converts from HeuristicLab objects to SolutionMessage representation.", new SolutionMessageBuilder()));
93      Parameters.Add(new FixedValueParameter<SingleObjectiveOptimizationSupportScript>("SupportScript", "A script that can provide neighborhood and analyze the results of the optimization.", new SingleObjectiveOptimizationSupportScript()));
94      CompileSupportScript();
95    }
96
97    [StorableHook(HookType.AfterDeserialization)]
98    private void AfterDeserialization() {
99      CompileSupportScript();
100    }
101
102    private void CompileSupportScript() {
103      try {
104        OptimizationSupportScript.Compile();
105      } catch (SingleObjectiveOptimizationSupportException ex) {
106        PluginInfrastructure.ErrorHandling.ShowErrorDialog("Support script doesn't compile.", ex);
107      }
108    }
109
110    #region Single Objective Problem Overrides
111    public override bool Maximization {
112      get { return Parameters.ContainsKey("Maximization") && ((IValueParameter<BoolValue>)Parameters["Maximization"]).Value.Value; }
113    }
114
115    public override double Evaluate(Individual individual, IRandom random) {
116      return Cache == null ? EvaluateOnNextAvailableClient(BuildSolutionMessage(individual)).Quality
117        : Cache.GetValue(BuildSolutionMessage(individual), m => EvaluateOnNextAvailableClient(m).Quality);
118    }
119
120    public override void Analyze(Individual[] individuals, double[] qualities, ResultCollection results, IRandom random) {
121      OptimizationSupport.Analyze(individuals, qualities, results, random);
122    }
123
124    public override IEnumerable<Individual> GetNeighbors(Individual individual, IRandom random) {
125      return OptimizationSupport.GetNeighbors(individual, random);
126    }
127    #endregion
128
129    #region Evaluation Helpers
130    private HashSet<IEvaluationServiceClient> activeClients = new HashSet<IEvaluationServiceClient>();
131    private object clientLock = new object();
132    private QualityMessage EvaluateOnNextAvailableClient(SolutionMessage message) {
133      IEvaluationServiceClient client = null;
134      lock (clientLock) {
135        client = Clients.CheckedItems.FirstOrDefault(c => !activeClients.Contains(c));
136        while (client == null && Clients.CheckedItems.Any()) {
137          Monitor.Wait(clientLock);
138          client = Clients.CheckedItems.FirstOrDefault(c => !activeClients.Contains(c));
139        }
140        if (client != null)
141          activeClients.Add(client);
142      }
143      try {
144        return client.Evaluate(message, GetQualityMessageExtensions());
145      } finally {
146        lock (clientLock) {
147          activeClients.Remove(client);
148          Monitor.PulseAll(clientLock);
149        }
150      }
151    }
152
153    private ExtensionRegistry GetQualityMessageExtensions() {
154      return ExtensionRegistry.CreateInstance();
155    }
156
157    private SolutionMessage BuildSolutionMessage(Individual individual) {
158      lock (clientLock) {
159        SolutionMessage.Builder protobufBuilder = SolutionMessage.CreateBuilder();
160        protobufBuilder.SolutionId = 0;
161        var scope = new Scope();
162        individual.CopyToScope(scope);
163        foreach (var variable in scope.Variables) {
164          try {
165            MessageBuilder.AddToMessage(variable.Value, variable.Name, protobufBuilder);
166          } catch (ArgumentException ex) {
167            throw new InvalidOperationException(string.Format("ERROR while building solution message: Parameter {0} cannot be added to the message", name), ex);
168          }
169        }
170        return protobufBuilder.Build();
171      }
172    }
173    #endregion
174  }
175}
Note: See TracBrowser for help on using the repository browser.