- Timestamp:
- 09/15/20 17:09:10 (4 years ago)
- Location:
- branches/2521_ProblemRefactoring/HeuristicLab.Problems.ExternalEvaluation/3.4
- Files:
-
- 5 deleted
- 8 edited
Legend:
- Unmodified
- Added
- Removed
-
branches/2521_ProblemRefactoring/HeuristicLab.Problems.ExternalEvaluation/3.4/ExternalEvaluationProblem.cs
r17226 r17747 1 1 #region License Information 2 2 /* HeuristicLab 3 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)3 * Copyright (C) 2002-2019 Heuristic and Evolutionary Algorithms Laboratory (HEAL) 4 4 * 5 5 * This file is part of HeuristicLab. … … 26 26 using System.Threading; 27 27 using Google.ProtocolBuffers; 28 using HEAL.Attic; 28 29 using HeuristicLab.Analysis; 29 30 using HeuristicLab.Common; … … 32 33 using HeuristicLab.Optimization; 33 34 using HeuristicLab.Parameters; 34 using HEAL.Attic;35 35 36 36 namespace HeuristicLab.Problems.ExternalEvaluation { … … 40 40 // BackwardsCompatibility3.3 41 41 // Rename class to SingleObjectiveExternalEvaluationProblem 42 public class ExternalEvaluationProblem : SingleObjectiveProblem<IEncoding<IEncodedSolution>, IEncodedSolution>, IExternalEvaluationProblem { 42 public class ExternalEvaluationProblem<TEncoding, TEncodedSolution> : SingleObjectiveProblem<TEncoding, TEncodedSolution>, IExternalEvaluationProblem 43 where TEncoding : class, IEncoding 44 where TEncodedSolution : class, IEncodedSolution { 43 45 44 46 public static new Image StaticItemImage { … … 56 58 get { return (IValueParameter<SolutionMessageBuilder>)Parameters["MessageBuilder"]; } 57 59 } 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"]; } 60 public IFixedValueParameter<SingleObjectiveOptimizationSupportScript<TEncodedSolution>> SupportScriptParameter { 61 get { return (IFixedValueParameter<SingleObjectiveOptimizationSupportScript<TEncodedSolution>>)Parameters["SupportScript"]; } 64 62 } 65 63 #endregion 66 64 67 65 #region Properties 68 public new IEncoding<IEncodedSolution>Encoding {66 public new TEncoding Encoding { 69 67 get { return base.Encoding; } 70 68 set { base.Encoding = value; } … … 79 77 get { return MessageBuilderParameter.Value; } 80 78 } 81 public SingleObjectiveOptimizationSupportScript OptimizationSupportScript {79 public SingleObjectiveOptimizationSupportScript<TEncodedSolution> OptimizationSupportScript { 82 80 get { return SupportScriptParameter.Value; } 83 81 } 84 private ISingleObjectiveOptimizationSupport OptimizationSupport {82 private ISingleObjectiveOptimizationSupport<TEncodedSolution> OptimizationSupport { 85 83 get { return SupportScriptParameter.Value; } 86 84 } … … 89 87 [StorableConstructor] 90 88 protected ExternalEvaluationProblem(StorableConstructorFlag _) : base(_) { } 91 protected ExternalEvaluationProblem(ExternalEvaluationProblem original, Cloner cloner) : base(original, cloner) { }89 protected ExternalEvaluationProblem(ExternalEvaluationProblem<TEncoding, TEncodedSolution> original, Cloner cloner) : base(original, cloner) { } 92 90 public override IDeepCloneable Clone(Cloner cloner) { 93 return new ExternalEvaluationProblem (this, cloner);91 return new ExternalEvaluationProblem<TEncoding, TEncodedSolution>(this, cloner); 94 92 } 95 public ExternalEvaluationProblem( )96 : base( ) {97 Parameters.Remove("Maximization"); // readonly in base class98 Parameters.Add(new FixedValueParameter<BoolValue>("Maximization", "Set to false if the problem should be minimized.", new BoolValue()));93 public ExternalEvaluationProblem(TEncoding encoding) 94 : base(encoding) { 95 MaximizationParameter.ReadOnly = false; 96 MaximizationParameter.Value = new BoolValue(); // is a read-only bool value in base class 99 97 Parameters.Add(new OptionalValueParameter<EvaluationCache>("Cache", "Cache of previously evaluated solutions.")); 100 98 Parameters.Add(new ValueParameter<CheckedItemCollection<IEvaluationServiceClient>>("Clients", "The clients that are used to communicate with the external application.", new CheckedItemCollection<IEvaluationServiceClient>() { new EvaluationServiceClient() })); 101 99 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()));100 Parameters.Add(new FixedValueParameter<SingleObjectiveOptimizationSupportScript<TEncodedSolution>>("SupportScript", "A script that can provide neighborhood and analyze the results of the optimization.", new SingleObjectiveOptimizationSupportScript<TEncodedSolution>(Results))); 103 101 104 102 Operators.Add(new BestScopeSolutionAnalyzer()); … … 106 104 107 105 #region Single Objective Problem Overrides 108 public override bool Maximization { 109 get { return Parameters.ContainsKey("Maximization") && ((IValueParameter<BoolValue>)Parameters["Maximization"]).Value.Value; } 106 public override ISingleObjectiveEvaluationResult Evaluate(TEncodedSolution solution, IRandom random, CancellationToken cancellationToken) { 107 var qualityMessage = Evaluate(BuildSolutionMessage(solution), cancellationToken); 108 if (!qualityMessage.HasExtension(SingleObjectiveQualityMessage.QualityMessage_)) 109 throw new InvalidOperationException("The received message is not a SingleObjectiveQualityMessage."); 110 var quality = qualityMessage.GetExtension(SingleObjectiveQualityMessage.QualityMessage_).Quality; 111 return new SingleObjectiveEvaluationResult(quality); 112 113 } 114 public virtual QualityMessage Evaluate(SolutionMessage solutionMessage, CancellationToken cancellationToken) { 115 return Cache == null 116 ? EvaluateOnNextAvailableClient(solutionMessage, cancellationToken) 117 : Cache.GetValue(solutionMessage, EvaluateOnNextAvailableClient, GetQualityMessageExtensions(), cancellationToken); 110 118 } 111 119 112 public virtual void SetMaximization(bool maximization) {113 MaximizationParameter.Value.Value = maximization;120 public override void Analyze(ISingleObjectiveSolutionContext<TEncodedSolution>[] solutions, IRandom random) { 121 OptimizationSupport.Analyze(solutions, random); 114 122 } 115 116 public override double Evaluate(IEncodedSolution individual, IRandom random) { 117 var qualityMessage = Evaluate(BuildSolutionMessage(individual)); 118 if (!qualityMessage.HasExtension(SingleObjectiveQualityMessage.QualityMessage_)) 119 throw new InvalidOperationException("The received message is not a SingleObjectiveQualityMessage."); 120 return qualityMessage.GetExtension(SingleObjectiveQualityMessage.QualityMessage_).Quality; 121 } 122 public virtual QualityMessage Evaluate(SolutionMessage solutionMessage) { 123 return Cache == null 124 ? EvaluateOnNextAvailableClient(solutionMessage) 125 : Cache.GetValue(solutionMessage, EvaluateOnNextAvailableClient, GetQualityMessageExtensions()); 126 } 127 128 public override void Analyze(IEncodedSolution[] individuals, double[] qualities, ResultCollection results, IRandom random) { 129 OptimizationSupport.Analyze(individuals, qualities, results, random); 130 } 131 132 public override IEnumerable<IEncodedSolution> GetNeighbors(IEncodedSolution individual, IRandom random) { 133 return OptimizationSupport.GetNeighbors(individual, random); 123 public override IEnumerable<TEncodedSolution> GetNeighbors(TEncodedSolution solutions, IRandom random) { 124 return OptimizationSupport.GetNeighbors(solutions, random); 134 125 } 135 126 #endregion … … 143 134 #region Evaluation 144 135 private HashSet<IEvaluationServiceClient> activeClients = new HashSet<IEvaluationServiceClient>(); 145 private object clientLock = new object();136 private readonly object clientLock = new object(); 146 137 147 private QualityMessage EvaluateOnNextAvailableClient(SolutionMessage message ) {138 private QualityMessage EvaluateOnNextAvailableClient(SolutionMessage message, CancellationToken cancellationToken) { 148 139 IEvaluationServiceClient client = null; 149 140 lock (clientLock) { … … 158 149 try { 159 150 return client.Evaluate(message, GetQualityMessageExtensions()); 160 } 161 finally { 151 } finally { 162 152 lock (clientLock) { 163 153 activeClients.Remove(client); … … 167 157 } 168 158 169 private SolutionMessage BuildSolutionMessage( IEncodedSolution solution, int solutionId = 0) {159 private SolutionMessage BuildSolutionMessage(TEncodedSolution solution, int solutionId = 0) { 170 160 lock (clientLock) { 171 161 SolutionMessage.Builder protobufBuilder = SolutionMessage.CreateBuilder(); … … 176 166 try { 177 167 MessageBuilder.AddToMessage(variable.Value, variable.Name, protobufBuilder); 178 } 179 catch (ArgumentException ex) { 168 } catch (ArgumentException ex) { 180 169 throw new InvalidOperationException(string.Format("ERROR while building solution message: Parameter {0} cannot be added to the message", Name), ex); 181 170 } -
branches/2521_ProblemRefactoring/HeuristicLab.Problems.ExternalEvaluation/3.4/HeuristicLab.Problems.ExternalEvaluation-3.4.csproj
r16816 r17747 138 138 <Compile Include="MultiObjectiveExternalEvaluationProblem.cs" /> 139 139 <Compile Include="ExternalEvaluationProblemInstances.cs" /> 140 <Compile Include=" SingleObjectiveExternalEvaluationProblem.cs" />140 <Compile Include="ExternalEvaluationProblem.cs" /> 141 141 <Compile Include="Interfaces\IEvaluationServiceClient.cs" /> 142 142 <Compile Include="Interfaces\IEvaluationChannel.cs" /> -
branches/2521_ProblemRefactoring/HeuristicLab.Problems.ExternalEvaluation/3.4/Interfaces/ISingleObjectiveOptimizationSupport.cs
r17745 r17747 30 30 where TEncodedSolution : class, IEncodedSolution { 31 31 32 void InitializeResults(); 32 33 void Analyze(ISingleObjectiveSolutionContext<TEncodedSolution>[] solutionContexts, IRandom random); 33 34 IEnumerable<TEncodedSolution> GetNeighbors(TEncodedSolution individual, IRandom random); -
branches/2521_ProblemRefactoring/HeuristicLab.Problems.ExternalEvaluation/3.4/Programmable/CompiledOptimizationSupport.cs
r17226 r17747 20 20 #endregion 21 21 22 using HeuristicLab.Optimization; 23 22 24 namespace HeuristicLab.Problems.ExternalEvaluation { 23 25 public abstract class CompiledOptimizationSupport { 24 26 25 27 public dynamic vars { get; set; } 28 public ResultCollection Results { get; set; } 26 29 } 27 30 } -
branches/2521_ProblemRefactoring/HeuristicLab.Problems.ExternalEvaluation/3.4/Programmable/MultiObjective/MultiObjectiveOptimizationSupportScript.cs
r16816 r17747 33 33 private MultiObjectiveOptimizationSupportScript(StorableConstructorFlag _) : base(_) { } 34 34 private MultiObjectiveOptimizationSupportScript(MultiObjectiveOptimizationSupportScript<TEncodedSolution> original, Cloner cloner) : base(original, cloner) { } 35 public MultiObjectiveOptimizationSupportScript() {35 public MultiObjectiveOptimizationSupportScript() : base() { 36 36 var codeTemplate = Templates.CompiledMultiObjectiveOptimizationSupport; 37 37 codeTemplate = codeTemplate.Replace("ENCODING_NAMESPACE", typeof(TEncodedSolution).Namespace); -
branches/2521_ProblemRefactoring/HeuristicLab.Problems.ExternalEvaluation/3.4/Programmable/OptimizationSupportScript.cs
r17226 r17747 23 23 using System.Linq; 24 24 using System.Reflection; 25 using HEAL.Attic; 25 26 using HeuristicLab.Common; 26 using H EAL.Attic;27 using HeuristicLab.Optimization; 27 28 using HeuristicLab.Scripting; 28 29 … … 38 39 } 39 40 41 [Storable] 42 private ResultCollection results; 43 public ResultCollection Results { 44 get { return results; } 45 } 46 40 47 [StorableConstructor] 41 48 protected OptimizationSupportScript(StorableConstructorFlag _) : base(_) { } … … 43 50 : base(original, cloner) { 44 51 variableStore = cloner.Clone(original.variableStore); 52 results = cloner.Clone(original.results); 45 53 } 46 47 protected OptimizationSupportScript()48 54 55 [Obsolete("Do not use this constructor.")] 56 protected OptimizationSupportScript() : base() { 49 57 variableStore = new VariableStore(); 50 58 } 51 59 52 protected OptimizationSupportScript( string code)53 : base( code) {60 protected OptimizationSupportScript(ResultCollection results) 61 : base() { 54 62 variableStore = new VariableStore(); 63 this.results = results; 55 64 } 56 65 … … 86 95 inst = (CompiledOptimizationSupport)Activator.CreateInstance(types.Single(x => typeof(CompiledOptimizationSupport).IsAssignableFrom(x))); 87 96 inst.vars = new Variables(VariableStore); 97 inst.Results = results; 88 98 } catch (Exception e) { 89 99 compiledInstance = null; … … 93 103 var concreteInst = inst as T; 94 104 if (concreteInst == null) 95 throw new OptimizationSupportException( "The optimization support class does not implement ISingleObjectiveOptimizationSupport." + Environment.NewLine + "Please implement that interface in the subclass of CompiledOptimizationSupport.");105 throw new OptimizationSupportException($"The optimization support class does not implement {typeof(T).FullName}." + Environment.NewLine + "Please implement that interface in the subclass of CompiledOptimizationSupport."); 96 106 97 107 CompiledInstance = concreteInst; -
branches/2521_ProblemRefactoring/HeuristicLab.Problems.ExternalEvaluation/3.4/Programmable/SingleObjective/CompiledSingleObjectiveOptimizationSupport.cs
r16816 r17747 8 8 public class CompiledSingleObjectiveOptimizationSupport : CompiledOptimizationSupport, ISingleObjectiveOptimizationSupport<SOLUTION_CLASS> { 9 9 10 public void Analyze(SOLUTION_CLASS[] solutions, double[] qualities, ResultCollection results, IRandom random) { 10 // private Result<StringValue> myResult; 11 12 public void InitializeResults() { 13 // Initialize the results that you intend to produce 14 // Uncomment the field above and the code below to add to the problem's results 15 // if (!Results.TryGetValue("My Result", out myResult)) 16 // Results.Add(myResult = new Result<StringValue>("My Result", "My result description.")); 17 } 18 19 public void Analyze(ISingleObjectiveSolutionContext<SOLUTION_CLASS>[] solutionContexts, IRandom random) { 11 20 // Use vars.yourVariable to access variables in the variable store i.e. yourVariable 12 21 // Write or update results given the range of vectors and resulting qualities 13 // Uncomment the following lines if you want to retrieve the best individual22 // Uncomment the following lines if you want to retrieve the current best individual 14 23 // Maximization: 15 // var best Index = qualities.Select((v, i) => Tuple.Create(i, v)).OrderByDescending(x => x.Item2).First().Item1;24 // var best = solutionContexts.OrderByDescending(x => x.EvaluationResult.Quality).First(); 16 25 // Minimization: 17 // var bestIndex = qualities.Select((v, i) => Tuple.Create(i, v)).OrderBy(x => x.Item2).First().Item1; 18 // var best = solutions[bestIndex]; 26 // var best = solutionContexts.OrderBy(x => x.EvaluationResult.Quality).First(); 27 // 28 // myResult.Value = new StringValue("Custom result"); 19 29 } 20 30 -
branches/2521_ProblemRefactoring/HeuristicLab.Problems.ExternalEvaluation/3.4/Programmable/SingleObjective/SingleObjectiveOptimizationSupportScript.cs
r17745 r17747 20 20 #endregion 21 21 22 using System; 22 23 using System.Collections.Generic; 23 24 using HEAL.Attic; … … 36 37 private SingleObjectiveOptimizationSupportScript(StorableConstructorFlag _) : base(_) { } 37 38 private SingleObjectiveOptimizationSupportScript(SingleObjectiveOptimizationSupportScript<TEncodedSolution> original, Cloner cloner) : base(original, cloner) { } 38 public SingleObjectiveOptimizationSupportScript() : base() { 39 [Obsolete("Do not use this constructor.")] 40 public SingleObjectiveOptimizationSupportScript() : this(null) { } 41 public SingleObjectiveOptimizationSupportScript(ResultCollection results) : base(results) { 39 42 var codeTemplate = Templates.CompiledSingleObjectiveOptimizationSupport; 40 43 codeTemplate = codeTemplate.Replace("ENCODING_NAMESPACE", typeof(TEncodedSolution).Namespace); … … 45 48 public override IDeepCloneable Clone(Cloner cloner) { 46 49 return new SingleObjectiveOptimizationSupportScript<TEncodedSolution>(this, cloner); 50 } 51 52 void ISingleObjectiveOptimizationSupport<TEncodedSolution>.InitializeResults() { 53 CompiledInstance.InitializeResults(); 47 54 } 48 55
Note: See TracChangeset
for help on using the changeset viewer.