Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 15529 was 15290, checked in by jkarder, 7 years ago

#2258: fixed MultiTrajectoryAnalysis

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