Free cookie consent management tool by TermsFeed Policy Generator

source: branches/histogram/HeuristicLab.Problems.ExternalEvaluation/3.3/ExternalEvaluator.cs @ 6322

Last change on this file since 6322 was 6195, checked in by abeham, 14 years ago

#1465

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