#region License Information /* HeuristicLab * Copyright (C) 2002-2016 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.Collections.Generic; using System.Drawing; using System.Linq; using HeuristicLab.Common; using HeuristicLab.Core; using HeuristicLab.Optimization; using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; using HeuristicLab.Problems.DataAnalysis; namespace HeuristicLab.GoalSeeking { internal enum GoalSeekingOptimizerAction { None, Prepare, Start, Stop, Pause } [StorableClass] [Item("GoalSeeking Optimizer", "A wrapper for the GoalSeekingProblem class to facilitate adding models and problem data.")] [Creatable("Algorithms")] public class GoalSeekingOptimizer : NamedItem, IOptimizer, IStorableContent { [Storable] private IGoalSeekingProblem problem; public IGoalSeekingProblem Problem { get { return problem; } set { if (value == null || value == problem) return; problem = value; // the problem takes precedence over the algorithm. if the algorithm is unsuitable we remove it. if (optimizer != null && !optimizer.ProblemType.IsInstanceOfType(problem)) { optimizer = null; OnAlgorithmChanged(); } if (optimizer != null) optimizer.Problem = problem; } } [Storable] private IAlgorithm optimizer; public IAlgorithm Optimizer { get { return optimizer; } set { if (value == null || value == optimizer) return; // make sure the algorithm is suitable for the problem. if (problem != null && !value.ProblemType.IsInstanceOfType(problem)) throw new InvalidOperationException("The algorithm is incompatible with the problem."); optimizer = value; optimizer.Problem = problem; RegisterOptimizerEvents(); OnAlgorithmChanged(); } } [Storable] private IRegressionProblemData problemData; public IRegressionProblemData ProblemData { get { return problemData; } set { if (value == null || value == problemData) return; if (problem == null) throw new InvalidOperationException("Cannot set problem data. Please configure a problem first."); problemData = value; problem.Configure(problemData, problemData.TrainingIndices.First()); OnProblemDataChanged(); } } private GoalSeekingOptimizerAction gsoAction; public GoalSeekingOptimizer() { Name = "Goal Seeking Optimizer"; } [StorableConstructor] protected GoalSeekingOptimizer(bool deserializing) : base(deserializing) { } [StorableHook(HookType.AfterDeserialization)] private void AfterDeserialization() { if (optimizer != null) RegisterOptimizerEvents(); } protected GoalSeekingOptimizer(GoalSeekingOptimizer original, Cloner cloner) : base(original, cloner) { this.Optimizer = (IAlgorithm)original.Optimizer.Clone(cloner); this.Problem = (IGoalSeekingProblem)original.Problem.Clone(cloner); this.ProblemData = (IRegressionProblemData)original.ProblemData.Clone(cloner); } public override IDeepCloneable Clone(Cloner cloner) { return new GoalSeekingOptimizer(this, cloner); } public EventHandler ProblemChanged; private void OnProblemChanged() { var changed = ProblemChanged; if (changed != null) changed(this, EventArgs.Empty); } public EventHandler AlgorithmChanged; private void OnAlgorithmChanged() { var changed = AlgorithmChanged; if (changed != null) changed(this, EventArgs.Empty); } public EventHandler ProblemDataChanged; private void OnProblemDataChanged() { var changed = ProblemDataChanged; if (changed != null) changed(this, EventArgs.Empty); } private int calculatedRows; public void Start() { if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused)) throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState)); if (optimizer == null) return; gsoAction = GoalSeekingOptimizerAction.Start; if (Optimizer.ExecutionState == ExecutionState.Stopped) { Optimizer.Prepare(clearRuns: true); calculatedRows = 0; var row = problemData.TrainingIndices.Skip(calculatedRows).First(); problem.Configure(problemData, row); optimizer.Prepare(); } optimizer.Start(); } public void Pause() { if (ExecutionState != ExecutionState.Started) throw new InvalidOperationException(string.Format("Pause not allowed in execution state \"{0}\".", ExecutionState)); if (optimizer == null) return; gsoAction = GoalSeekingOptimizerAction.Pause; if (optimizer.ExecutionState != ExecutionState.Started) return; // a race-condition may occur when the algorithm has changed the state by itself in the meantime try { optimizer.Pause(); } catch (InvalidOperationException) { } } public void Stop() { if ((ExecutionState != ExecutionState.Started) && (ExecutionState != ExecutionState.Paused)) throw new InvalidOperationException(string.Format("Stop not allowed in execution state \"{0}\".", ExecutionState)); if (optimizer == null) return; gsoAction = GoalSeekingOptimizerAction.Stop; if (optimizer.ExecutionState != ExecutionState.Started && optimizer.ExecutionState != ExecutionState.Paused) { OnStopped(); return; } // a race-condition may occur when the algorithm has changed the state by itself in the meantime try { optimizer.Stop(); } catch (InvalidOperationException) { } } public void Prepare() { Prepare(false); } public void Prepare(bool clearRuns) { if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused) && (ExecutionState != ExecutionState.Stopped)) throw new InvalidOperationException(string.Format("Prepare not allowed in execution state \"{0}\".", ExecutionState)); if (optimizer != null) { ExecutionTime = TimeSpan.Zero; if (clearRuns) optimizer.Runs.Clear(); gsoAction = GoalSeekingOptimizerAction.Prepare; // a race-condition may occur when the algorithm has changed the state by itself in the meantime try { optimizer.Prepare(clearRuns); } catch (InvalidOperationException) { } } else { ExecutionState = ExecutionState.Stopped; } } [Storable] private TimeSpan executionTime; public TimeSpan ExecutionTime { get { if ((Optimizer != null) && (Optimizer.ExecutionState != ExecutionState.Stopped)) return executionTime + Optimizer.ExecutionTime; else return executionTime; } private set { executionTime = value; OnExecutionTimeChanged(); } } public RunCollection Runs { get { if (optimizer == null) return new RunCollection(); // return an empty run collection return Optimizer.Runs; } } public IEnumerable NestedOptimizers { get; } public string Filename { get; set; } public new static Image StaticItemImage { get { return HeuristicLab.Common.Resources.VSImageLibrary.Event; } } public override Image ItemImage { get { if (ExecutionState == ExecutionState.Prepared) return HeuristicLab.Common.Resources.VSImageLibrary.BatchRunPrepared; else if (ExecutionState == ExecutionState.Started) return HeuristicLab.Common.Resources.VSImageLibrary.BatchRunStarted; else if (ExecutionState == ExecutionState.Paused) return HeuristicLab.Common.Resources.VSImageLibrary.BatchRunPaused; else if (ExecutionState == ExecutionState.Stopped) return HeuristicLab.Common.Resources.VSImageLibrary.BatchRunStopped; else return base.ItemImage; } } #region Events protected override void OnNameChanged() { base.OnNameChanged(); } #region event firing public ExecutionState ExecutionState { get; private set; } public event EventHandler ExecutionStateChanged; private void OnExecutionStateChanged() { EventHandler handler = ExecutionStateChanged; if (handler != null) handler(this, EventArgs.Empty); } public event EventHandler ExecutionTimeChanged; private void OnExecutionTimeChanged() { EventHandler handler = ExecutionTimeChanged; if (handler != null) handler(this, EventArgs.Empty); } public event EventHandler Prepared; private void OnPrepared() { gsoAction = GoalSeekingOptimizerAction.None; ExecutionState = ExecutionState.Prepared; EventHandler handler = Prepared; if (handler != null) handler(this, EventArgs.Empty); } public event EventHandler Started; private void OnStarted() { ExecutionState = ExecutionState.Started; EventHandler handler = Started; if (handler != null) handler(this, EventArgs.Empty); } public event EventHandler Paused; private void OnPaused() { gsoAction = GoalSeekingOptimizerAction.None; ExecutionState = ExecutionState.Paused; EventHandler handler = Paused; if (handler != null) handler(this, EventArgs.Empty); } public event EventHandler Stopped; private void OnStopped() { gsoAction = GoalSeekingOptimizerAction.None; ExecutionState = ExecutionState.Stopped; EventHandler handler = Stopped; if (handler != null) handler(this, EventArgs.Empty); } public event EventHandler> ExceptionOccurred; private void OnExceptionOccurred(Exception exception) { EventHandler> handler = ExceptionOccurred; if (handler != null) handler(this, new EventArgs(exception)); } public event EventHandler OptimizerChanged; private void OnOptimizerChanged() { EventHandler handler = OptimizerChanged; if (handler != null) handler(this, EventArgs.Empty); } public event EventHandler RepetitionsChanged; private void OnRepetitionsChanged() { EventHandler handler = RepetitionsChanged; if (handler != null) handler(this, EventArgs.Empty); } public event EventHandler RepetetionsCounterChanged; private void OnRepetitionsCounterChanged() { EventHandler handler = RepetetionsCounterChanged; if (handler != null) handler(this, EventArgs.Empty); } #endregion #region optimizer event handlers private void RegisterOptimizerEvents() { optimizer.ExceptionOccurred += Optimizer_ExceptionOccurred; optimizer.ExecutionTimeChanged += Optimizer_ExecutionTimeChanged; optimizer.Paused += Optimizer_Paused; optimizer.Prepared += Optimizer_Prepared; optimizer.Started += Optimizer_Started; optimizer.Stopped += Optimizer_Stopped; } private void DeregisterOptimizerEvents() { optimizer.ExceptionOccurred -= Optimizer_ExceptionOccurred; optimizer.ExecutionTimeChanged -= Optimizer_ExecutionTimeChanged; optimizer.Paused -= Optimizer_Paused; optimizer.Prepared -= Optimizer_Prepared; optimizer.Started -= Optimizer_Started; optimizer.Stopped -= Optimizer_Stopped; } private void Optimizer_ExceptionOccurred(object sender, EventArgs e) { OnExceptionOccurred(e.Value); } private void Optimizer_ExecutionTimeChanged(object sender, EventArgs e) { OnExecutionTimeChanged(); } private void Optimizer_Paused(object sender, EventArgs e) { if (ExecutionState == ExecutionState.Started) { OnPaused(); } } private void Optimizer_Prepared(object sender, EventArgs e) { if (gsoAction == GoalSeekingOptimizerAction.Prepare || ExecutionState == ExecutionState.Stopped) { calculatedRows = 0; ExecutionTime = TimeSpan.Zero; OnPrepared(); } } private void Optimizer_Started(object sender, EventArgs e) { if (ExecutionState != ExecutionState.Started) { OnStarted(); } } private void Optimizer_Stopped(object sender, EventArgs e) { calculatedRows++; ExecutionTime += optimizer.ExecutionTime; var remainingRows = problemData.TrainingIndices.Skip(calculatedRows); if (gsoAction == GoalSeekingOptimizerAction.Stop) OnStopped(); else if (!remainingRows.Any()) OnStopped(); else if (gsoAction == GoalSeekingOptimizerAction.Pause) OnPaused(); else if (gsoAction == GoalSeekingOptimizerAction.Start) { var row = remainingRows.First(); problem.Configure(problemData, row); optimizer.Prepare(); optimizer.Start(); } else if (ExecutionState == ExecutionState.Started) { OnPaused(); } else OnStopped(); } #endregion #endregion } }