Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OaaS/HeuristicLab.Problems.ExternalEvaluation/3.3/ExternalEvaluator.cs @ 15325

Last change on this file since 15325 was 9363, checked in by spimming, 12 years ago

#1888:

  • Merged revisions from trunk
File size: 6.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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.Linq;
25using System.Threading;
26using Google.ProtocolBuffers;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Data;
30using HeuristicLab.Operators;
31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33
34namespace HeuristicLab.Problems.ExternalEvaluation {
35  [Item("ExternalEvaluationValuesCollector", "Creates a solution message, and communicates it via the driver to receive a quality message.")]
36  [StorableClass]
37  public class ExternalEvaluator : ValuesCollector, IExternalEvaluationProblemEvaluator {
38    protected HashSet<IEvaluationServiceClient> activeClients = new HashSet<IEvaluationServiceClient>();
39    protected object clientLock = new object();
40
41    #region Parameters
42    public ILookupParameter<DoubleValue> QualityParameter {
43      get { return (ILookupParameter<DoubleValue>)Parameters["Quality"]; }
44    }
45    public IValueLookupParameter<CheckedItemCollection<IEvaluationServiceClient>> ClientsParameter {
46      get { return (ValueLookupParameter<CheckedItemCollection<IEvaluationServiceClient>>)Parameters["Clients"]; }
47    }
48    public IValueParameter<SolutionMessageBuilder> MessageBuilderParameter {
49      get { return (IValueParameter<SolutionMessageBuilder>)Parameters["MessageBuilder"]; }
50    }
51    #endregion
52
53    #region Parameter Properties
54    protected SolutionMessageBuilder MessageBuilder {
55      get { return MessageBuilderParameter.Value; }
56    }
57    protected CheckedItemCollection<IEvaluationServiceClient> Clients {
58      get { return ClientsParameter.ActualValue; }
59    }
60    #endregion
61
62    #region Construction & Cloning
63    [StorableConstructor]
64    protected ExternalEvaluator(bool deserializing) : base(deserializing) { }
65    protected ExternalEvaluator(ExternalEvaluator original, Cloner cloner) : base(original, cloner) { }
66    public ExternalEvaluator()
67      : base() {
68      Parameters.Add(new LookupParameter<DoubleValue>("Quality", "The quality of the current solution."));
69      Parameters.Add(new ValueLookupParameter<CheckedItemCollection<IEvaluationServiceClient>>("Clients", "Collection of clients which communicate the the external process. These clients my be contacted in parallel."));
70      Parameters.Add(new ValueParameter<SolutionMessageBuilder>("MessageBuilder", "The message builder that converts from HeuristicLab objects to SolutionMessage representation.", new SolutionMessageBuilder()));
71    }
72    public override IDeepCloneable Clone(Cloner cloner) {
73      return new ExternalEvaluator(this, cloner);
74    }
75    [StorableHook(HookType.AfterDeserialization)]
76    private void AfterDeserialization() {
77      // BackwardsCompatibility3.3
78      #region Backwards compatible code, remove with 3.4
79      if (!Parameters.ContainsKey("Clients")) {
80        Parameters.Add(new ValueLookupParameter<CheckedItemCollection<IEvaluationServiceClient>>("Clients", "Collection of clients which communicate the the external process. These clients my be contacted in parallel."));
81        if (Parameters.ContainsKey("Client")) {
82          var client = ((IValueLookupParameter<IEvaluationServiceClient>)Parameters["Client"]).Value;
83          if (client != null)
84            ClientsParameter.Value = new CheckedItemCollection<IEvaluationServiceClient>() { client };
85          Parameters.Remove("Client");
86        }
87      }
88      #endregion
89    }
90    #endregion
91
92    public override IOperation Apply() {
93
94      QualityMessage answer = EvaluateOnNextAvailableClient(BuildSolutionMessage());
95
96      if (QualityParameter.ActualValue == null)
97        QualityParameter.ActualValue = new DoubleValue(answer.Quality);
98      else QualityParameter.ActualValue.Value = answer.Quality;
99
100      return base.Apply();
101    }
102
103    protected virtual QualityMessage EvaluateOnNextAvailableClient(SolutionMessage message) {
104      IEvaluationServiceClient client = null;
105      lock (clientLock) {
106        client = Clients.CheckedItems.FirstOrDefault(c => !activeClients.Contains(c));
107        while (client == null && Clients.CheckedItems.Count() > 0) {
108          Monitor.Wait(clientLock);
109          client = Clients.CheckedItems.FirstOrDefault(c => !activeClients.Contains(c));
110        }
111        if (client != null)
112          activeClients.Add(client);
113      }
114      try {
115        return client.Evaluate(message, GetQualityMessageExtensions());
116      } finally {
117        lock (clientLock) {
118          activeClients.Remove(client);
119          Monitor.PulseAll(clientLock);
120        }
121      }
122    }
123
124    protected virtual ExtensionRegistry GetQualityMessageExtensions() {
125      return ExtensionRegistry.CreateInstance();
126    }
127
128    protected virtual SolutionMessage BuildSolutionMessage() {
129      lock (clientLock) {
130        SolutionMessage.Builder protobufBuilder = SolutionMessage.CreateBuilder();
131        protobufBuilder.SolutionId = 0;
132        foreach (IParameter param in CollectedValues) {
133          IItem value = param.ActualValue;
134          if (value != null) {
135            ILookupParameter lookupParam = param as ILookupParameter;
136            string name = lookupParam != null ? lookupParam.TranslatedName : param.Name;
137            try {
138              MessageBuilder.AddToMessage(value, name, protobufBuilder);
139            } catch (ArgumentException ex) {
140              throw new InvalidOperationException(string.Format("ERROR while building solution message: Parameter {0} cannot be added to the message", name), ex);
141            }
142          }
143        }
144        return protobufBuilder.Build();
145      }
146    }
147
148  }
149}
Note: See TracBrowser for help on using the repository browser.