#region License Information
/* HeuristicLab
* Copyright (C) 2002-2017 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
*
* This file is part of HeuristicLab.
*
* HeuristicLab is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HeuristicLab is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HeuristicLab. If not, see .
*/
#endregion
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using HeuristicLab.Analysis;
using HeuristicLab.Common;
using HeuristicLab.Core;
using HeuristicLab.Data;
using HeuristicLab.Optimization;
using HeuristicLab.Parameters;
using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
namespace HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms {
[Item("Context-based Algorithm", "Algorithms that make use of contexts to facilitate applying operators.")]
[StorableClass]
public abstract class ContextAlgorithm : BasicAlgorithm
where TContext : class, IContext, new()
where TEncoding : class, IEncoding {
public override Type ProblemType {
get { return typeof(SingleObjectiveBasicProblem); }
}
public new SingleObjectiveBasicProblem Problem {
get { return (SingleObjectiveBasicProblem)base.Problem; }
set { base.Problem = value; }
}
[Storable]
private TContext context;
public TContext Context {
get { return context; }
}
[Storable]
private ValueParameter analyzerParameter;
public IValueParameter AnalyzerParameter {
get { return analyzerParameter; }
}
[Storable]
private FixedValueParameter maximumIterationsParameter;
public IFixedValueParameter MaximumIterationsParameter {
get { return maximumIterationsParameter; }
}
[Storable]
private FixedValueParameter maximumEvaluationsParameter;
public IFixedValueParameter MaximumEvaluationsParameter {
get { return maximumEvaluationsParameter; }
}
[Storable]
private FixedValueParameter maximumRuntimeParameter;
public IFixedValueParameter MaximumRuntimeParameter {
get { return maximumRuntimeParameter; }
}
[Storable]
private FixedValueParameter stopAtBestKnownQualityParameter;
public IFixedValueParameter StopAtBestKnownQualityParameter {
get { return stopAtBestKnownQualityParameter; }
}
public IAnalyzer Analyzer {
get { return analyzerParameter.Value; }
set { analyzerParameter.Value = value; }
}
public int MaximumIterations {
get { return maximumIterationsParameter.Value.Value; }
set { maximumIterationsParameter.Value.Value = value; }
}
public int MaximumEvaluations {
get { return maximumEvaluationsParameter.Value.Value; }
set { maximumEvaluationsParameter.Value.Value = value; }
}
public TimeSpan MaximumRuntime {
get { return maximumRuntimeParameter.Value.Value; }
set { maximumRuntimeParameter.Value.Value = value; }
}
public bool StopAtBestKnownQuality {
get { return stopAtBestKnownQualityParameter.Value.Value; }
set { stopAtBestKnownQualityParameter.Value.Value = value; }
}
private Stopwatch stopwatch;
[Storable]
private TimeSpan elapsed;
[Storable]
private IndexedDataTable qualityPerClock;
[Storable]
private IndexedDataRow firstHitGraph;
[StorableConstructor]
protected ContextAlgorithm(bool deserializing) : base(deserializing) { }
protected ContextAlgorithm(ContextAlgorithm original, Cloner cloner)
: base(original, cloner) {
context = cloner.Clone(original.context);
analyzerParameter = cloner.Clone(original.analyzerParameter);
maximumIterationsParameter = cloner.Clone(original.maximumIterationsParameter);
maximumEvaluationsParameter = cloner.Clone(original.maximumEvaluationsParameter);
maximumRuntimeParameter = cloner.Clone(original.maximumRuntimeParameter);
stopAtBestKnownQualityParameter = cloner.Clone(original.stopAtBestKnownQualityParameter);
elapsed = original.elapsed;
qualityPerClock = cloner.Clone(original.qualityPerClock);
firstHitGraph = cloner.Clone(original.firstHitGraph);
if (context != null)
context.BestQualityChanged += ContextOnBestQualityChanged;
}
protected ContextAlgorithm()
: base() {
Parameters.Add(analyzerParameter = new ValueParameter("Analyzer", "The analyzers that are used to perform an analysis of the solutions.", new MultiAnalyzer()));
Parameters.Add(maximumIterationsParameter = new FixedValueParameter("MaximumIterations", "The number of iterations that the algorithm should run or < 1 to ignore.", new IntValue(0)));
Parameters.Add(maximumEvaluationsParameter = new FixedValueParameter("MaximumEvaluations", "The number of evaluated solutions that the algorithm should perform or < 1 to ignore.", new IntValue(0)));
Parameters.Add(maximumRuntimeParameter = new FixedValueParameter("MaximumRuntime", "The timespan that the algorithm is allowed to run.", new TimeSpanValue(TimeSpan.FromMinutes(1))));
Parameters.Add(stopAtBestKnownQualityParameter = new FixedValueParameter("StopAtBestKnownQuality", "Whether the algorithm should terminate if the best known quality has been found.", new BoolValue(true)));
}
protected override void Initialize(CancellationToken cancellationToken) {
base.Initialize(cancellationToken);
context = new TContext();
context.Scope.Variables.Add(new Variable("Results", Results));
context.BestQualityChanged += ContextOnBestQualityChanged;
IExecutionContext ctxt = null;
foreach (var item in Problem.ExecutionContextItems)
ctxt = new Core.ExecutionContext(ctxt, item, Context.Scope);
ctxt = new Core.ExecutionContext(ctxt, this, Context.Scope);
context.Parent = ctxt;
context.Iterations = 0;
context.EvaluatedSolutions = 0;
context.BestQuality = double.NaN;
qualityPerClock = new IndexedDataTable("Quality Per Clock");
firstHitGraph = new IndexedDataRow("First-hit Graph");
qualityPerClock.Rows.Add(firstHitGraph);
Results.Add(new Result("QualityPerClock", qualityPerClock));
elapsed = TimeSpan.Zero;
stopwatch = Stopwatch.StartNew();
}
protected override void Run(CancellationToken cancellationToken) {
if (stopwatch == null || !stopwatch.IsRunning) stopwatch = Stopwatch.StartNew();
}
private void ContextOnBestQualityChanged(object sender, EventArgs e) {
if (double.IsNaN(Context.BestQuality)) return;
var newEntry = Tuple.Create((elapsed + stopwatch.Elapsed).TotalSeconds, Context.BestQuality);
if (firstHitGraph.Values.Count == 0) {
firstHitGraph.Values.Add(newEntry); // record the first data
firstHitGraph.Values.Add(Tuple.Create(newEntry.Item1, newEntry.Item2)); // last entry records max number of evaluations
return;
}
var improvement = firstHitGraph.Values.Last().Item2 != newEntry.Item2;
if (improvement) {
firstHitGraph.Values[firstHitGraph.Values.Count - 1] = newEntry; // record the improvement
firstHitGraph.Values.Add(Tuple.Create(newEntry.Item1, newEntry.Item2)); // last entry records max number of evaluations
} else {
firstHitGraph.Values[firstHitGraph.Values.Count - 1] = Tuple.Create(newEntry.Item1, newEntry.Item2);
}
}
public override void Prepare() {
if (context != null) {
context.BestQualityChanged -= ContextOnBestQualityChanged;
context = null;
}
base.Prepare();
}
protected override void OnPaused() {
elapsed += stopwatch.Elapsed;
stopwatch.Reset();
firstHitGraph.Values[firstHitGraph.Values.Count - 1] = Tuple.Create(elapsed.TotalSeconds, Context.BestQuality);
base.OnPaused();
}
protected override void OnStopped() {
if (stopwatch.IsRunning) {
elapsed += stopwatch.Elapsed;
stopwatch.Reset();
firstHitGraph.Values[firstHitGraph.Values.Count - 1] = Tuple.Create(elapsed.TotalSeconds, Context.BestQuality);
}
// base call must be done last as the results will be cloned and a run is created
base.OnStopped();
}
[StorableHook(HookType.AfterDeserialization)]
private void AfterDeserialization() {
if (context != null) context.BestQualityChanged += ContextOnBestQualityChanged;
}
protected virtual bool StoppingCriterion() {
return MaximumIterations > 0 && Context.Iterations > MaximumIterations
|| MaximumEvaluations > 0 && Context.EvaluatedSolutions > MaximumEvaluations
|| MaximumRuntime > TimeSpan.Zero && ExecutionTime > MaximumRuntime
|| StopAtBestKnownQuality && !double.IsNaN(Problem.BestKnownQuality)
&& Context.BestQuality.IsAlmost(Problem.BestKnownQuality);
}
}
}