Free cookie consent management tool by TermsFeed Policy Generator

source: branches/FitnessLandscapeAnalysis/HeuristicLab.Analysis.FitnessLandscape/MultiTrajectory/MultiTrajectoryAnalysis.cs @ 13376

Last change on this file since 13376 was 7202, checked in by epitzer, 13 years ago

#1696: Add static item image according to #1651

File size: 27.0 KB
Line 
1using System;
2using System.Linq;
3using System.Collections.Generic;
4using HeuristicLab.Common;
5using HeuristicLab.Core;
6using HeuristicLab.Data;
7using HeuristicLab.Optimization;
8using HeuristicLab.Parameters;
9using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
10using HeuristicLab.PluginInfrastructure;
11using HeuristicLab.Encodings.BinaryVectorEncoding;
12using HeuristicLab.Encodings.RealVectorEncoding;
13using HeuristicLab.Encodings.PermutationEncoding;
14using HeuristicLab.Common.Resources;
15using System.Drawing;
16
17namespace HeuristicLab.Analysis.FitnessLandscape.MultiTrajectory {
18
19  [Item("Multi Trajectory Analysis", "Host for performing and aggregating several algorithm runs for an overarching analysis.")]
20  [Creatable("Analysis")]
21  [StorableClass]
22  public class MultiTrajectoryAnalysis : ParameterizedNamedItem, IAlgorithm, IStorableContent {
23
24    public IEnumerable<IOptimizer> NestedOptimizers {
25      get {
26        if (Algorithm != null)
27          yield return Algorithm;
28        if (SampleGenerationAlgorithm != null)
29          yield return SampleGenerationAlgorithm;
30      }
31    }
32
33    #region Parameters
34    public OperatorParameter PreassignedSolutionCreatorParameter {
35      get { return (OperatorParameter)Parameters["PreassignedSolutionCreator"]; }
36    }
37    public ValueParameter<IntValue> NrOfSamplesParameter {
38      get { return (ValueParameter<IntValue>)Parameters["NrOfSamples"]; }
39    }
40    public ValueParameter<BoolValue> SaveIndividualTrailsParameter {
41      get { return (ValueParameter<BoolValue>)Parameters["SaveIndividualTrails"]; }
42    }
43    public ValueParameter<BoolValue> PrepareAfterStopParameter {
44      get { return (ValueParameter<BoolValue>)Parameters["PrepareAfterStop"]; }
45    }
46    public ValueParameter<CheckedItemList<IAggregator>> AggregatorsParameter {
47      get { return (ValueParameter<CheckedItemList<IAggregator>>)Parameters["Aggregators"]; }
48    }
49
50
51    #endregion
52
53    #region Parameter Values
54    public PreassignedSolutionCreator PreassignedSolutionCreator {
55      get { return (PreassignedSolutionCreator)PreassignedSolutionCreatorParameter.Value; }
56      set { PreassignedSolutionCreatorParameter.Value = value; }
57    }
58    public IntValue NrOfSamples {
59      get { return NrOfSamplesParameter.Value; }
60    }
61    public bool SaveIndividualTrails {
62      get { return SaveIndividualTrailsParameter.Value.Value; }
63    }
64    public bool PrepareAfterStop {
65      get { return PrepareAfterStopParameter.Value.Value; }
66    }
67    public CheckedItemList<IAggregator> Aggregators {
68      get { return AggregatorsParameter.Value; }
69    }
70    #endregion
71
72    #region Construction and Cloning
73    [StorableConstructor]
74    protected MultiTrajectoryAnalysis(bool deserializing)
75      : base(deserializing) {
76      RegisterEvents();
77    }
78    protected MultiTrajectoryAnalysis(MultiTrajectoryAnalysis original, Cloner cloner)
79      : base(original, cloner) {
80      algorithm = cloner.Clone(original.algorithm);
81      currentAlgorithm = cloner.Clone(original.currentAlgorithm);
82      executionBaseTime = new TimeSpan(original.executionBaseTime.Ticks);
83      executionTime = new TimeSpan(original.executionTime.Ticks);
84      results = cloner.Clone(original.results);
85      running = original.running;
86      preparing = original.preparing;
87      runs = cloner.Clone(original.runs);
88      sampleGenerationAlgorithm = cloner.Clone(original.sampleGenerationAlgorithm);
89      StepNr = original.StepNr;
90      storeAlgorithmInEachRun = original.storeAlgorithmInEachRun;
91      subAlgorithmRuns = cloner.Clone(original.subAlgorithmRuns);
92      RegisterEvents();
93    }
94    public MultiTrajectoryAnalysis() {
95      Parameters.Add(new OperatorParameter("PreassignedSolutionCreator", "The operator that creates new solutions"));
96      Parameters.Add(new ValueParameter<IntValue>("NrOfSamples", "The number of samples to generate.", new IntValue(10)));
97      Parameters.Add(new ValueParameter<BoolValue>("SaveIndividualTrails", "Include all sub algorithm runs in the final run", new BoolValue(true)));
98      Parameters.Add(new ValueParameter<BoolValue>("PrepareAfterStop", "Automatically prepare algorithm after stopping to clean global scope and results (for large experiments)", new BoolValue(false)));
99      Parameters.Add(new ValueParameter<CheckedItemList<IAggregator>>("Aggregators", "List of aggretators for combining trajectory results.", new CheckedItemList<IAggregator>()));
100      currentAlgorithm = null;
101      algorithm = null;
102      executionBaseTime = new TimeSpan();
103      executionTime = new TimeSpan();
104      results = new ResultCollection();
105      running = false;
106      runs = new RunCollection();
107      sampleGenerationAlgorithm = null;
108      StepNr = -1;
109      storeAlgorithmInEachRun = false;
110      Aggregators.AddRange(ApplicationManager.Manager.GetInstances<IAggregator>());
111      RegisterEvents();
112      Prepare();
113    }
114    public override IDeepCloneable Clone(Cloner cloner) {
115      return new MultiTrajectoryAnalysis(this, cloner);
116    }
117    [StorableHook(HookType.AfterDeserialization)]
118    private void AfterDeserialization() {
119      if (algorithm != null && sampleGenerationAlgorithm != null) {
120        if (sampleGenerationAlgorithm.Problem == null) {
121          sampleGenerationAlgorithm.Problem = algorithm.Problem;
122        } else {
123          algorithm.Problem = sampleGenerationAlgorithm.Problem;
124        }
125      }
126      if (!Parameters.ContainsKey("Aggregators"))
127        Parameters.Add(new ValueParameter<CheckedItemList<IAggregator>>(
128          "Aggregators", "List of aggregators for combining trajectory results.",
129          new CheckedItemList<IAggregator>(ApplicationManager.Manager.GetInstances<IAggregator>())));
130      RegisterEvents();
131    }
132    #endregion
133
134    #region Fields & Properties
135
136    public new static Image StaticItemImage { get { return VSImageLibrary.Event; } }
137
138    public override Image ItemImage {
139      get {
140        switch (ExecutionState) {
141          case ExecutionState.Prepared: return VSImageLibrary.ExecutablePrepared;
142          case ExecutionState.Started: return VSImageLibrary.ExecutableStarted;
143          case ExecutionState.Paused: return VSImageLibrary.ExecutablePaused;
144          case ExecutionState.Stopped: return VSImageLibrary.ExecutableStopped;
145          default: return base.ItemImage;
146        }
147      }
148    }
149
150    [Storable]
151    private RunCollection subAlgorithmRuns;
152
153    public new ParameterCollection Parameters {
154      get { return base.Parameters; }
155    }
156
157    public Type ProblemType { get { return typeof(IHeuristicOptimizationProblem); } }
158    public string Filename { get; set; }
159
160    [Storable]
161    private IProblem preliminaryProblem;
162    public IProblem Problem {
163      get { return preliminaryProblem ?? algorithm.Problem; }
164      set {
165        if (ExecutionState != ExecutionState.Prepared && ExecutionState != ExecutionState.Stopped)
166          throw new InvalidOperationException("Cannot change algorithm while running or paused.");
167        if (algorithm == null)
168          preliminaryProblem = value;
169        else
170          algorithm.Problem = value;
171      }
172    }
173
174    [Storable]
175    private IAlgorithm algorithm;
176    public IAlgorithm Algorithm {
177      get { return algorithm; }
178      set {
179        if (algorithm == value)
180          return;
181        if (algorithm != null) {
182          DeregisterAlgorithmEvents();
183          ReuseOldProblem(algorithm, value);
184        }
185        algorithm = value;
186        if (algorithm != null) {
187          SyncAlgorithmProblems(algorithm, sampleGenerationAlgorithm);
188          RegisterAlgorithmEvents();
189        }
190        OnAlgorithmChanged();
191      }
192    }
193
194    [Storable]
195    private IAlgorithm sampleGenerationAlgorithm;
196    public IAlgorithm SampleGenerationAlgorithm {
197      get { return sampleGenerationAlgorithm; }
198      set {
199        if (sampleGenerationAlgorithm == value)
200          return;
201        if (sampleGenerationAlgorithm != null) {
202          DeregisterSampleGenerationAlgorithmEvents();
203          ReuseOldProblem(sampleGenerationAlgorithm, value);
204        }
205        sampleGenerationAlgorithm = value;
206        if (sampleGenerationAlgorithm != null) {
207          SyncAlgorithmProblems(sampleGenerationAlgorithm, algorithm);
208          RegisterSampleGenerationAlgorithmEvents();
209        }
210        OnSampleGenerationAlgorithmChanged();
211      }
212    }
213
214    private static void ReuseOldProblem(IAlgorithm oldAlgorithm, IAlgorithm newValue) {
215      if (oldAlgorithm.Problem != null && newValue != null && newValue.Problem == null)
216        newValue.Problem = oldAlgorithm.Problem;
217    }
218
219    private void SyncAlgorithmProblems(IAlgorithm newAlgorithm, IAlgorithm otherAlgorithm) {
220      if (otherAlgorithm != null) {
221        if (otherAlgorithm.Problem != null) {
222          newAlgorithm.Problem = otherAlgorithm.Problem;
223        } else {
224          otherAlgorithm.Problem = newAlgorithm.Problem;
225        }
226      } else {
227        if (preliminaryProblem != null) {
228          newAlgorithm.Problem = preliminaryProblem;
229          preliminaryProblem = null;
230        }
231      }
232    }
233
234    [Storable]
235    private RunCollection runs;
236    public RunCollection Runs {
237      get { return runs; }
238    }
239
240    [Storable]
241    private ResultCollection results;
242    public ResultCollection Results {
243      get { return results; }
244    }
245
246    [Storable]
247    private bool storeAlgorithmInEachRun;
248    public bool StoreAlgorithmInEachRun {
249      get { return storeAlgorithmInEachRun; }
250      set {
251        if (storeAlgorithmInEachRun == value)
252          return;
253        storeAlgorithmInEachRun = value;
254        OnStoreAlgorithmInEachRunChanged();
255      }
256    }
257
258    [Storable]
259    private ExecutionState executionState;
260    public ExecutionState ExecutionState {
261      get { return executionState; }
262      set {
263        if (executionState == value)
264          return;
265        executionState = value;
266        OnExecutionStateChanged();
267        OnItemImageChanged();
268      }
269    }
270
271    [Storable]
272    private TimeSpan executionBaseTime;
273    [Storable]
274    private TimeSpan executionTime;
275    public TimeSpan ExecutionTime {
276      get { return executionTime; }
277      set {
278        if (executionTime == value)
279          return;
280        executionTime = value;
281        OnExecutionTimeChanged();
282      }
283    }
284
285    #endregion
286
287    #region Events
288    public event EventHandler AlgorithmChanged;
289    public event EventHandler SampleGenerationAlgorithmChanged;
290    public event EventHandler ProblemChanged;
291    public event EventHandler StoreAlgorithmInEachRunChanged;
292    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
293    public event EventHandler ExecutionStateChanged;
294    public event EventHandler ExecutionTimeChanged;
295    public event EventHandler Paused;
296    public event EventHandler Prepared;
297    public event EventHandler Started;
298    public event EventHandler Stopped;
299
300    #region firing
301    protected virtual void OnAlgorithmChanged() {
302      EventHandler handler = AlgorithmChanged;
303      if (handler != null)
304        handler(this, EventArgs.Empty);
305    }
306    protected virtual void OnSampleGenerationAlgorithmChanged() {
307      EventHandler handler = SampleGenerationAlgorithmChanged;
308      if (handler != null)
309        handler(this, EventArgs.Empty);
310    }
311    protected virtual void OnProblemChanged() {
312      SelectPreassignedSolutionCreator();
313      EventHandler handler = ProblemChanged;
314      if (handler != null)
315        handler(this, EventArgs.Empty);
316    }   
317    protected virtual void OnStoreAlgorithmInEachRunChanged() {
318      EventHandler handler = StoreAlgorithmInEachRunChanged;
319      if (handler != null)
320        handler(this, EventArgs.Empty);
321    }
322    protected virtual void OnExceptionOccurred(Exception args) {
323      EventHandler<EventArgs<Exception>> handler = ExceptionOccurred;
324      if (handler != null)
325        handler(this, new EventArgs<Exception>(args));
326    }
327    protected virtual void OnExecutionStateChanged() {
328      EventHandler handler = ExecutionStateChanged;
329      if (handler != null)
330        handler(this, EventArgs.Empty);
331      switch (ExecutionState) {
332        case ExecutionState.Prepared: OnPrepared(); break;
333        case ExecutionState.Started: OnStarted(); break;
334        case ExecutionState.Paused: OnPaused(); break;
335        case ExecutionState.Stopped: OnStopped(); break;
336      }
337    }
338    protected virtual void OnExecutionTimeChanged() {
339      EventHandler handler = ExecutionTimeChanged;
340      if (handler != null)
341        handler(this, EventArgs.Empty);
342    }
343    protected virtual void OnPaused() {
344      EventHandler handler = Paused;
345      if (handler != null)
346        handler(this, EventArgs.Empty);
347    }
348    protected virtual void OnPrepared() {
349      EventHandler handler = Prepared;
350      if (handler != null)
351        handler(this, EventArgs.Empty);
352    }
353    protected virtual void OnStarted() {
354      EventHandler handler = Started;
355      if (handler != null)
356        handler(this, EventArgs.Empty);
357    }
358    protected virtual void OnStopped() {
359      AggregateResults();
360      ClearSubAlgorithms();
361      CreateRun();
362      EventHandler handler = Stopped;
363      if (handler != null)
364        handler(this, EventArgs.Empty);
365      if (PrepareAfterStop) {
366        Prepare();
367        executionState = ExecutionState.Stopped;
368      }
369    }
370    #endregion
371    #endregion
372
373    public void CollectResultValues(IDictionary<string, IItem> values) {
374      values.Add("Execution Time", new TimeSpanValue(ExecutionTime));
375      values.Add("Time of Execution", new DateTimeValue(DateTime.Now));
376      CollectInnerResults(values, "", results);
377    }
378
379    private static void CollectInnerResults(IDictionary<string, IItem> values, string prefix, IEnumerable<IResult> results) {
380      foreach (var result in results) {
381        var innerResults = result.Value as IEnumerable<IResult>;
382        if (innerResults == null)
383          values.Add(string.Format("{0}{1}", prefix, result.Name), result.Value);
384        else
385          CollectInnerResults(values, string.Format("{0}{1}.", prefix, result.Name), innerResults);
386      }
387    }
388
389    [Storable]
390    bool running;
391
392    [Storable]
393    bool preparing;
394
395    [Storable]
396    private int StepNr;
397
398    [Storable]
399    IAlgorithm currentAlgorithm;
400
401    public void Prepare(bool clearRuns) {
402      if (clearRuns)
403        Runs.Clear();
404      Prepare();
405    }
406
407    public void Prepare() {
408      try {
409        preparing = true;
410        try {
411          if (Algorithm != null) {
412            Algorithm.Prepare();
413            Algorithm.StoreAlgorithmInEachRun = false;
414          }
415          if (SampleGenerationAlgorithm != null) {
416            SampleGenerationAlgorithm.Prepare();
417            SampleGenerationAlgorithm.StoreAlgorithmInEachRun = false;
418          }
419          ClearSubAlgorithms();
420          StepNr = -1;
421          ExecutionTime = new TimeSpan();
422          executionBaseTime = new TimeSpan();
423          results.Clear();
424          subAlgorithmRuns = new RunCollection();
425          results.Add(new Result("Sub Algorithm Runs", subAlgorithmRuns));
426          if (PreassignedSolutionCreator != null) {
427            if (PreassignedSolutionCreator.SolutionCollection != null)
428              PreassignedSolutionCreator.SolutionCollection.Clear();
429            PreassignedSolutionCreator.CurrentSolutionIndex = -1;
430          }
431          ExecutionState = ExecutionState.Prepared;
432        } catch (Exception) { }
433      } finally {
434        preparing = false;
435      }
436    }
437
438    public void Pause() {
439      try {
440        running = false;
441        if (currentAlgorithm != null) currentAlgorithm.Pause();
442        ExecutionState = ExecutionState.Paused;
443      } catch (Exception) { }
444    }
445
446    public void Start() {
447      running = true;
448      ExecutionState = ExecutionState.Started;
449      PerformNextStep();
450    }
451
452    public void Stop() {
453      running = false;
454      try {
455        if (currentAlgorithm != null) currentAlgorithm.Stop();
456      } catch (Exception) { }
457    }
458
459    protected virtual void PerformNextStep() {
460      PreassignedSolutionCreator.CurrentSolutionIndex = StepNr;
461      if (StepNr == -1) {
462        currentAlgorithm = SampleGenerationAlgorithm;
463        currentAlgorithm.Start();
464      } else if (StepNr < NrOfSamples.Value) {
465        currentAlgorithm = Algorithm;
466        IHeuristicOptimizationProblem problem = Algorithm.Problem as IHeuristicOptimizationProblem;
467        if (problem != null) {
468          SynchronizeParameters(problem.SolutionCreator, PreassignedSolutionCreator as ISolutionCreator);
469          if (PreassignedSolutionCreator != problem.SolutionCreator)
470            PreassignedSolutionCreator.OriginalSolutionCreator = problem.SolutionCreator;
471          problem.SolutionCreatorParameter.ActualValue = PreassignedSolutionCreator;
472        }
473        Algorithm.Prepare();
474        Algorithm.Runs.Clear();
475        Algorithm.Start();
476      } else {
477        ExecutionState = ExecutionState.Stopped;
478      }
479    }
480
481    private void ClearSubAlgorithms() {
482      if (sampleGenerationAlgorithm != null) {
483        sampleGenerationAlgorithm.Results.Clear();
484        sampleGenerationAlgorithm.Runs.Clear();
485      }
486      if (algorithm != null) {
487        algorithm.Results.Clear();
488        algorithm.Runs.Clear();
489      }
490    }
491
492    private void AggregateResults() {
493      if (subAlgorithmRuns == null)
494        return;
495      foreach (var aggregator in Aggregators)
496        aggregator.Reset();
497      foreach (IRun run in subAlgorithmRuns) {
498        foreach (var result in run.Results) {
499          foreach (var item in Aggregators.CheckedItems)
500            item.Value.MaybeAddResult(new Result(result.Key, result.Value));
501        }
502      }
503      foreach (var item in Aggregators.CheckedItems)
504        results.Add(item.Value.CreateResult());
505    }
506
507    public override void CollectParameterValues(IDictionary<string, IItem> values) {
508      base.CollectParameterValues(values);
509      values.Add("Algorithm Name", new StringValue(Name));
510      values.Add("Algorithm Type", new StringValue(this.GetType().GetPrettyName()));
511      if (Problem != null) {
512        Problem.CollectParameterValues(values);
513        values.Add("Problem Name", new StringValue(Problem.Name));
514        values.Add("Problem Type", new StringValue(Problem.GetType().GetPrettyName()));
515      }
516      CollectPrefixedParameterValues("Sampling", SampleGenerationAlgorithm, values);
517      CollectPrefixedParameterValues("Analysis", Algorithm, values);
518    }
519
520    private void CollectPrefixedParameterValues(string prefix, IAlgorithm algorithm, IDictionary<string, IItem> values) {
521      var innerValues = new Dictionary<string, IItem>();
522      algorithm.CollectParameterValues(innerValues);
523      foreach (var value in innerValues) {
524        values.Add(string.Format("{0}.{1}", prefix, value.Key), value.Value);
525      }
526    }   
527
528    protected virtual void CreateRun() {
529      Run run = new Run(Name, Description, this);
530      if (!SaveIndividualTrails)
531        run.Results.Remove("Sub Algorithm Runs");
532      Runs.Add(run);
533    }
534
535    #region Event registry
536    private void RegisterEvents() {
537      if (algorithm != null)
538        RegisterAlgorithmEvents();
539      if (sampleGenerationAlgorithm != null)
540        RegisterSampleGenerationAlgorithmEvents();
541    }
542    private void RegisterAlgorithmEvents() {
543      algorithm.ExceptionOccurred += algorithm_ExceptionOccurred;
544      algorithm.Started += algorithm_Started;
545      algorithm.Paused += algorithm_Paused;
546      algorithm.Prepared += algorithm_Prepared;
547      algorithm.Stopped += algorithm_Stopped;
548      algorithm.ExecutionTimeChanged += algorithm_ExecutionTimeChanged;
549      algorithm.ExecutionStateChanged += algorithm_ExecutionStateChanged;
550      algorithm.Runs.ItemsAdded += Algorithm_Runs_ItemsAdded;
551      algorithm.ProblemChanged += algorithm_ProblemChanged;
552    }
553    private void DeregisterAlgorithmEvents() {
554      algorithm.ExceptionOccurred -= algorithm_ExceptionOccurred;
555      algorithm.Started -= algorithm_Started;
556      algorithm.Paused -= algorithm_Paused;
557      algorithm.Prepared -= algorithm_Prepared;
558      algorithm.Stopped -= algorithm_Stopped;
559      algorithm.ExecutionTimeChanged -= algorithm_ExecutionTimeChanged;
560      algorithm.ExecutionStateChanged -= algorithm_ExecutionStateChanged;
561      algorithm.Runs.ItemsAdded -= Algorithm_Runs_ItemsAdded;
562      algorithm.ProblemChanged -= algorithm_ProblemChanged;
563    }
564    private void RegisterSampleGenerationAlgorithmEvents() {
565      sampleGenerationAlgorithm.ExceptionOccurred += algorithm_ExceptionOccurred;
566      sampleGenerationAlgorithm.Started += algorithm_Started;
567      sampleGenerationAlgorithm.Paused += algorithm_Paused;
568      sampleGenerationAlgorithm.Prepared += algorithm_Prepared;
569      sampleGenerationAlgorithm.Stopped += sampleGenerationAlgorithm_Stopped;
570      sampleGenerationAlgorithm.ExecutionTimeChanged += sampleGenerationAlgorithm_ExecutionTimeChanged;
571      sampleGenerationAlgorithm.ProblemChanged += algorithm_ProblemChanged;
572    }
573    private void DeregisterSampleGenerationAlgorithmEvents() {
574      sampleGenerationAlgorithm.ExceptionOccurred -= algorithm_ExceptionOccurred;
575      sampleGenerationAlgorithm.Started -= algorithm_Started;
576      sampleGenerationAlgorithm.Paused -= algorithm_Paused;
577      sampleGenerationAlgorithm.Prepared -= algorithm_Prepared;
578      sampleGenerationAlgorithm.Stopped -= sampleGenerationAlgorithm_Stopped;
579      sampleGenerationAlgorithm.ExecutionTimeChanged -= sampleGenerationAlgorithm_ExecutionTimeChanged;
580      sampleGenerationAlgorithm.ProblemChanged -= algorithm_ProblemChanged;
581    }
582    #endregion
583
584    #region Sub Algorithm Event Handling
585    void algorithm_ExecutionStateChanged(object sender, EventArgs e) {
586      IHeuristicOptimizationProblem problem = Algorithm.Problem as IHeuristicOptimizationProblem;
587      if (algorithm.ExecutionState == ExecutionState.Stopped && problem != null && problem.SolutionCreator is PreassignedSolutionCreator)
588        problem.SolutionCreatorParameter.ActualValue = ((PreassignedSolutionCreator)problem.SolutionCreator).OriginalSolutionCreator;
589    }
590    void algorithm_ExecutionTimeChanged(object sender, EventArgs e) {
591      ExecutionTime = executionBaseTime + algorithm.ExecutionTime;
592    }
593    void sampleGenerationAlgorithm_ExecutionTimeChanged(object sender, EventArgs e) {
594      ExecutionTime = executionBaseTime + sampleGenerationAlgorithm.ExecutionTime;
595    }
596    void algorithm_ExceptionOccurred(object sender, EventArgs<Exception> e) {
597      OnExceptionOccurred(e.Value);
598      ExecutionState = ExecutionState.Paused;
599    }
600    void algorithm_Started(object sender, EventArgs e) {
601      running = true;
602      ExecutionState = ExecutionState.Started;
603    }
604    void algorithm_Paused(object sender, EventArgs e) {
605      ExecutionState = ExecutionState.Paused;
606    }
607    void algorithm_Prepared(object sender, EventArgs e) {
608      if (executionState == ExecutionState.Stopped && !preparing)
609        Prepare();
610    }
611    void algorithm_Stopped(object sender, EventArgs e) {
612      if (running) {
613        executionBaseTime = executionTime + algorithm.ExecutionTime;
614        ExecutionTime = executionBaseTime;
615        StepNr++;
616        PerformNextStep();
617      } else {
618        ExecutionState = ExecutionState.Stopped;
619      }
620    }
621    void sampleGenerationAlgorithm_Stopped(object sender, EventArgs e) {
622      if (running) {
623        if (sampleGenerationAlgorithm.Results.ContainsKey("Samples")) {
624          IScope scope = sampleGenerationAlgorithm.Results["Samples"].Value as IScope;
625          if (scope != null)
626            PreassignedSolutionCreator.SolutionCollection = (IScope)scope.Clone();
627        }
628        executionBaseTime = executionTime + sampleGenerationAlgorithm.ExecutionTime;
629        ExecutionTime = executionBaseTime;
630        PreassignedSolutionCreator.CurrentSolutionIndex = 0;
631        StepNr++;
632        PerformNextStep();
633      } else {
634        ExecutionState = ExecutionState.Stopped;
635      }
636    }
637    void algorithm_ProblemChanged(object sender, EventArgs e) {
638      if (sender == algorithm && sampleGenerationAlgorithm != null)
639        sampleGenerationAlgorithm.Problem = algorithm.Problem;
640      if (sender == sampleGenerationAlgorithm && algorithm != null)
641        algorithm.Problem = sampleGenerationAlgorithm.Problem;
642      OnProblemChanged();
643    }
644    void Algorithm_Runs_ItemsAdded(object sender, Collections.CollectionItemsChangedEventArgs<IRun> e) {     
645      if (subAlgorithmRuns != null)
646        foreach (var run in e.Items) {
647          var slimRun = new Run();
648          foreach (var result in run.Results)
649            slimRun.Results.Add(result);
650          subAlgorithmRuns.Add(slimRun);
651          slimRun.Name = string.Format("Sub Algorithm Run {0}", subAlgorithmRuns.Count);
652        }
653    }
654    #endregion
655
656    #region Auxiliary Functions
657    private static void SynchronizeParameters(IParameterizedItem original, IParameterizedItem copy) {
658      foreach (IParameter origParam in original.Parameters) {
659        IParameter copyParam = null;
660        if (copy.Parameters.TryGetValue(origParam.Name, out copyParam))
661          SynchronizeParameters(origParam, copyParam);
662      }
663    }
664    private static void SynchronizeParameters(IParameter origParam, IParameter copyParam) {
665      if (origParam == null || copyParam == null)
666        return;
667      IValueParameter origValueParam = origParam as IValueParameter;
668      ILookupParameter origLookupParam = origParam as ILookupParameter;
669      IValueParameter copyValueParam = copyParam as IValueParameter;
670      ILookupParameter copyLookupParam = copyParam as ILookupParameter;
671      if (origValueParam != null && copyValueParam != null && copyValueParam.DataType.IsAssignableFrom(origValueParam.DataType))
672        copyValueParam.Value = origValueParam.Value;
673      if (origLookupParam != null && copyLookupParam != null)
674        copyLookupParam.ActualName = origLookupParam.ActualName;
675    }
676    private void SelectPreassignedSolutionCreator() {
677      var alg = Algorithm ?? SampleGenerationAlgorithm;
678      if (alg == null)
679        return;
680      IHeuristicOptimizationProblem problem = alg.Problem as IHeuristicOptimizationProblem;
681      if (problem != null) {
682        if (problem.SolutionCreator is IBinaryVectorCreator &&
683          (PreassignedSolutionCreator == null || !(PreassignedSolutionCreator is IBinaryVectorCreator)))
684          PreassignedSolutionCreator = new PreassignedBinaryVectorCreator();
685        else if (problem.SolutionCreator is IRealVectorCreator &&
686          (PreassignedSolutionCreator == null || !(PreassignedSolutionCreator is IRealVectorCreator)))
687          PreassignedSolutionCreator = new PreassignedRealVectorCreator();
688        else if (problem.SolutionCreator is IPermutationCreator &&
689          (PreassignedSolutionCreator == null || !(PreassignedSolutionCreator is IPermutationCreator)))
690          PreassignedSolutionCreator = new PreassignePermutationCreator();       
691      }     
692    }
693    #endregion
694
695  }
696}
Note: See TracBrowser for help on using the repository browser.