Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 7128 was 7128, checked in by epitzer, 12 years ago

#1696 Integrate fitness landscape analysis plugins from Heureka! repository.

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