Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2521_ProblemRefactoring/HeuristicLab.Problems.ExternalEvaluation/3.4/MultiObjectiveExternalEvaluationProblem.cs @ 17315

Last change on this file since 17315 was 17315, checked in by abeham, 4 years ago

#2521: reverted r17309

File size: 8.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 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.Common;
30using HeuristicLab.Core;
31using HeuristicLab.Data;
32using HeuristicLab.Optimization;
33using HeuristicLab.Parameters;
34
35namespace HeuristicLab.Problems.ExternalEvaluation {
36  [Item("External Evaluation Problem (multi-objective)", "A multi-objective problem that is evaluated in a different process.")]
37  [Creatable(CreatableAttribute.Categories.ExternalEvaluationProblems, Priority = 200)]
38  [StorableType("CCA50199-A6AB-4C84-B4FA-0262CAF416EC")]
39  public class MultiObjectiveExternalEvaluationProblem<TEncoding, TEncodedSolution> : MultiObjectiveProblem<TEncoding, TEncodedSolution>, IExternalEvaluationProblem
40    where TEncoding : class, IEncoding<TEncodedSolution>
41    where TEncodedSolution : class, IEncodedSolution {
42
43    public static new Image StaticItemImage {
44      get { return HeuristicLab.Common.Resources.VSImageLibrary.Type; }
45    }
46
47    #region Parameters
48    public OptionalValueParameter<EvaluationCache> CacheParameter {
49      get { return (OptionalValueParameter<EvaluationCache>)Parameters["Cache"]; }
50    }
51    public IValueParameter<CheckedItemCollection<IEvaluationServiceClient>> ClientsParameter {
52      get { return (IValueParameter<CheckedItemCollection<IEvaluationServiceClient>>)Parameters["Clients"]; }
53    }
54    public IValueParameter<SolutionMessageBuilder> MessageBuilderParameter {
55      get { return (IValueParameter<SolutionMessageBuilder>)Parameters["MessageBuilder"]; }
56    }
57    public IFixedValueParameter<MultiObjectiveOptimizationSupportScript<TEncodedSolution>> SupportScriptParameter {
58      get { return (IFixedValueParameter<MultiObjectiveOptimizationSupportScript<TEncodedSolution>>)Parameters["SupportScript"]; }
59    }
60    #endregion
61
62    #region Properties
63    public new TEncoding Encoding {
64      get { return base.Encoding; }
65      set { base.Encoding = value; }
66    }
67    public EvaluationCache Cache {
68      get { return CacheParameter.Value; }
69    }
70    public CheckedItemCollection<IEvaluationServiceClient> Clients {
71      get { return ClientsParameter.Value; }
72    }
73    public SolutionMessageBuilder MessageBuilder {
74      get { return MessageBuilderParameter.Value; }
75    }
76    public MultiObjectiveOptimizationSupportScript<TEncodedSolution> OptimizationSupportScript {
77      get { return SupportScriptParameter.Value; }
78    }
79    private IMultiObjectiveOptimizationSupport<TEncodedSolution> OptimizationSupport {
80      get { return SupportScriptParameter.Value; }
81    }
82    #endregion
83
84    [StorableConstructor]
85    protected MultiObjectiveExternalEvaluationProblem(StorableConstructorFlag _) : base(_) { }
86    protected MultiObjectiveExternalEvaluationProblem(MultiObjectiveExternalEvaluationProblem<TEncoding, TEncodedSolution> original, Cloner cloner) : base(original, cloner) { }
87    public override IDeepCloneable Clone(Cloner cloner) {
88      return new MultiObjectiveExternalEvaluationProblem<TEncoding, TEncodedSolution>(this, cloner);
89    }
90    public MultiObjectiveExternalEvaluationProblem(TEncoding encoding)
91      : base(encoding) {
92      Parameters.Remove("Maximization"); // readonly in base class
93      Parameters.Add(new FixedValueParameter<BoolArray>("Maximization", "Set to false if the problem should be minimized.", new BoolArray()));
94      Parameters.Add(new OptionalValueParameter<EvaluationCache>("Cache", "Cache of previously evaluated solutions."));
95      Parameters.Add(new ValueParameter<CheckedItemCollection<IEvaluationServiceClient>>("Clients", "The clients that are used to communicate with the external application.", new CheckedItemCollection<IEvaluationServiceClient>() { new EvaluationServiceClient() }));
96      Parameters.Add(new ValueParameter<SolutionMessageBuilder>("MessageBuilder", "The message builder that converts from HeuristicLab objects to SolutionMessage representation.", new SolutionMessageBuilder()) { Hidden = true });
97      Parameters.Add(new FixedValueParameter<MultiObjectiveOptimizationSupportScript<TEncodedSolution>>("SupportScript", "A script that can analyze the results of the optimization.", new MultiObjectiveOptimizationSupportScript<TEncodedSolution>()));
98    }
99
100    #region Multi Objective Problem Overrides
101    public override bool[] Maximization {
102      get {
103        return Parameters.ContainsKey("Maximization") ? ((IValueParameter<BoolArray>)Parameters["Maximization"]).Value.ToArray() : new bool[0];
104      }
105    }
106
107    public virtual void SetMaximization(bool[] maximization) {
108      ((IStringConvertibleArray)MaximizationParameter.Value).Length = maximization.Length;
109      var array = MaximizationParameter.Value;
110      for (var i = 0; i < maximization.Length; i++)
111        array[i] = maximization[i];
112    }
113
114    public override double[] Evaluate(TEncodedSolution individual, IRandom random) {
115      var qualityMessage = Evaluate(BuildSolutionMessage(individual));
116      if (!qualityMessage.HasExtension(MultiObjectiveQualityMessage.QualityMessage_))
117        throw new InvalidOperationException("The received message is not a MultiObjectiveQualityMessage.");
118      return qualityMessage.GetExtension(MultiObjectiveQualityMessage.QualityMessage_).QualitiesList.ToArray();
119    }
120    public virtual QualityMessage Evaluate(SolutionMessage solutionMessage) {
121      return Cache == null
122        ? EvaluateOnNextAvailableClient(solutionMessage)
123        : Cache.GetValue(solutionMessage, EvaluateOnNextAvailableClient, GetQualityMessageExtensions());
124    }
125
126    public override void Analyze(TEncodedSolution[] individuals, double[][] qualities, ResultCollection results, IRandom random) {
127      OptimizationSupport.Analyze(individuals, qualities, results, random);
128    }
129
130    #endregion
131
132    public virtual ExtensionRegistry GetQualityMessageExtensions() {
133      var extensions = ExtensionRegistry.CreateInstance();
134      extensions.Add(MultiObjectiveQualityMessage.QualityMessage_);
135      return extensions;
136    }
137
138    #region Evaluation
139    private HashSet<IEvaluationServiceClient> activeClients = new HashSet<IEvaluationServiceClient>();
140    private object clientLock = new object();
141
142    private QualityMessage EvaluateOnNextAvailableClient(SolutionMessage message) {
143      IEvaluationServiceClient client = null;
144      lock (clientLock) {
145        client = Clients.CheckedItems.FirstOrDefault(c => !activeClients.Contains(c));
146        while (client == null && Clients.CheckedItems.Any()) {
147          Monitor.Wait(clientLock);
148          client = Clients.CheckedItems.FirstOrDefault(c => !activeClients.Contains(c));
149        }
150        if (client != null)
151          activeClients.Add(client);
152      }
153      try {
154        return client.Evaluate(message, GetQualityMessageExtensions());
155      }
156      finally {
157        lock (clientLock) {
158          activeClients.Remove(client);
159          Monitor.PulseAll(clientLock);
160        }
161      }
162    }
163
164    private SolutionMessage BuildSolutionMessage(TEncodedSolution solution, int solutionId = 0) {
165      lock (clientLock) {
166        SolutionMessage.Builder protobufBuilder = SolutionMessage.CreateBuilder();
167        protobufBuilder.SolutionId = solutionId;
168        var scope = new Scope();
169        ScopeUtil.CopyEncodedSolutionToScope(scope, Encoding, solution);
170        foreach (var variable in scope.Variables) {
171          try {
172            MessageBuilder.AddToMessage(variable.Value, variable.Name, protobufBuilder);
173          }
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.