source: branches/HeuristicLab.DatastreamAnalysis/HeuristicLab.DatastreamAnalysis/3.4/DatastreamAnalysisOptimizer.cs @ 14710

Last change on this file since 14710 was 14710, checked in by jzenisek, 5 years ago

#2719 implemented ensemble model rating by introducing the new type RatedEnsembleModel; introduced performance indicator calculation in results;

File size: 31.3 KB
Line 
1#region License Information
2
3/* HeuristicLab
4 * Copyright (C) 2002-2016 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
5 *
6 * This file is part of HeuristicLab.
7 *
8 * HeuristicLab is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * HeuristicLab is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
20 */
21
22#endregion
23
24using System;
25using System.Collections.Generic;
26using System.ComponentModel;
27using System.Diagnostics;
28using System.Drawing;
29using System.Linq;
30using System.Threading;
31using System.Threading.Tasks;
32using HeuristicLab.Analysis;
33using HeuristicLab.Collections;
34using HeuristicLab.Common;
35using HeuristicLab.Core;
36using HeuristicLab.Data;
37using HeuristicLab.Optimization;
38using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
39using HeuristicLab.Problems.DataAnalysis;
40
41namespace HeuristicLab.DatastreamAnalysis {
42  internal enum DatastreamAnalysisOptimizerAction {
43    None,
44    Prepare,
45    Start,
46    Stop,
47    Pause
48  }
49
50  [StorableClass]
51  [Item("DatastreamAnalysis Optimizer",
52     "The main loop for evaluating ensemble models against a incoming datastream of time series fashion.")]
53  [Creatable(CreatableAttribute.Categories.Algorithms)]
54  public class DatastreamAnalysisOptimizer : Executable, IOptimizer, IStorableContent {
55    #region properties
56    public string Filename { get; set; }
57
58    private DatastreamAnalysisOptimizerAction daoAction;
59
60    public IEnumerable<IOptimizer> NestedOptimizers { get; }
61
62
63    [Storable]
64    protected ILog log;
65    public ILog Log {
66      get { return log; }
67    }
68
69    [Storable]
70    private ResultCollection results;
71
72    public ResultCollection Results {
73      get { return results; }
74    }
75
76    private double lastStateValue;
77    private double pR2Sum;
78    private int detectionCount;
79    private int evaluationCount;
80    private double exclusivitySum;
81    private double accuracySum;
82
83    private CancellationTokenSource cancellationTokenSource;
84    private bool stopPending;
85    private DateTime lastUpdateTime;
86    private bool prepared;
87    private bool finished;
88
89    [Storable]
90    protected int runsCounter;
91
92    [Storable]
93    private RunCollection runs;
94
95    public RunCollection Runs
96    {
97      get { return runs; }
98      protected set
99      {
100        if (value == null) throw new ArgumentNullException();
101        if (runs != value) {
102          if (runs != null) DeregisterRunsEvents();
103          runs = value;
104          if (runs != null) RegisterRunsEvents();
105        }
106      }
107    }
108
109    [Storable]
110    private IItemList<RatedEnsembleModel> ensembles;
111
112    public IItemList<RatedEnsembleModel> Ensembles {
113      get { return ensembles; }
114      set {
115        if (value == null || value == ensembles)
116          return;
117        if (!(value is IRatedEnsembleModel)) throw new ArgumentException("Invaid ensemble model type");
118        DeregisterEnsembleEvents();
119        ensembles = value;
120        RegisterEnsembleEvents();
121        OnEnsemblesChanged();
122        Prepare();
123      }
124    }
125
126
127    // VAR 1: datastream ~= problem data, VAR 2 (TODO): datastream = external source e.g. webservice, AMQP-Queue, etc.
128    [Storable]
129    private Datastream datastream;
130
131    public Datastream Datastream {
132      get { return datastream; }
133      set {
134        if (value == null || value == datastream)
135          return;
136        if(!(value is IDatastream)) throw new ArgumentException("Invalid datastream type");
137        DeregisterDatastreamEvents();
138        datastream = value;
139        RegisterDatastreamEvents();
140        OnDatastreamChanged();
141        Prepare();
142      }
143    }
144
145    #endregion properties
146
147    #region results properties
148    private int ResultsSlidingWindowMovements {
149      get { return ((IntValue)Results["Sliding Window Movements"].Value).Value; }
150      set { ((IntValue)Results["Sliding Window Movements"].Value).Value = value; }
151    }
152    private DataTable ResultsQualities {
153      get { return ((DataTable)Results["Qualities 1"].Value); }
154    }
155
156    private DataTable ResultsPeakQualities {
157      get { return ((DataTable) Results["Qualities 2"].Value); }
158    }
159
160    private const string ResultsQualitiesMSE = "Mean squared error";
161    private const string ResultsQualitiesPR2 = "Pearson R²";
162
163    private DataTable ResultsTargets {
164      get { return ((DataTable) Results["Targets"].Value); }
165    }
166
167    private DataTable ResultsStateDetection {
168      get { return ((DataTable) Results["State Detection"].Value);}
169    }
170
171    private const string ResultsTargetsReal = "Real";
172
173    private DataBarSet ResultsSWQualitiesBars {
174      get { return (DataBarSet) Results["Ensemble Comparison [SW-Quality]"].Value; }
175    }
176
177    private DataBarSet ResultsSWVotingBars {
178      get { return (DataBarSet) Results["Ensemble Comparison [SW-Voting]"].Value; }
179    }
180
181    private DataBarSet ResultsSonarQualitiesBars {
182      get { return (DataBarSet)Results["Ensemble Comparison [Sonar-Quality]"].Value; }
183    }
184
185    private DataBarSet ResultsSWPeakQualitiesBars {
186      get { return (DataBarSet)Results["Ensemble Comparison [SW-PeakQuality]"].Value; }
187    }
188
189    private double ResultsMeanPR2 {
190      get { return ((DoubleValue) Results["Mean PR2"].Value).Value; }
191      set { ((DoubleValue)Results["Mean PR2"].Value).Value = value; }
192    }
193
194    private double ResultsDetectionAccuracy {
195      get { return ((DoubleValue)Results["Detection Accuracy"].Value).Value; }
196      set { ((DoubleValue)Results["Detection Accuracy"].Value).Value = value; }
197    }
198
199    private double ResultsDetectionExclusivity {
200      get { return ((DoubleValue)Results["Detection Exclusivity"].Value).Value; }
201      set { ((DoubleValue)Results["Detection Exclusivity"].Value).Value = value; }
202    }
203
204    //private int ResultsTrueDetectionCount {
205    //  get { return ((IntValue)Results["True Detection Count"].Value).Value; }
206    //  set { ((IntValue)Results["True Detection Count"].Value).Value = value; }
207    //}
208
209    //private int ResultsFalseDetectionCount {
210    //  get { return ((IntValue)Results["False Detection Count"].Value).Value; }
211    //  set { ((IntValue)Results["False Detection Count"].Value).Value = value; }
212    //}
213
214    protected void SetupResults() {
215      evaluationCount = 0;
216      lastStateValue = 0.0;
217      pR2Sum = 0.0;
218      exclusivitySum = 0.0;
219      accuracySum = 0.0;
220      detectionCount = 0;
221      Results.Clear();
222      Results.Add(new Result("Sliding Window Movements", new IntValue(0)));
223      Results.Add(new Result("Qualities 1", new DataTable("Average Pearson R²")));
224      Results.Add(new Result("Qualities 2", new DataTable("Peak Pearson R²")));
225      Results.Add(new Result("Targets", new DataTable("Targets")));
226      Results.Add(new Result("State Detection", new DataTable("State Detection")));
227      Results.Add(new Result("Ensemble Comparison [SW-Quality]", new DataBarSet("Ensemble Comparison [SW-Quality]")));
228      Results.Add(new Result("Ensemble Comparison [SW-Voting]", new DataBarSet("Ensemble Comparison [SW-Voting]")));
229      Results.Add(new Result("Ensemble Comparison [Sonar-Quality]", new DataBarSet("Ensemble Comparison [Sonar-Quality]")));
230      Results.Add(new Result("Ensemble Comparison [SW-PeakQuality]", new DataBarSet("Ensemble Comparison [SW-PeakQuality]")));
231      Results.Add(new Result("Mean PR2", new DoubleValue()));
232      Results.Add(new Result("Detection Accuracy", new DoubleValue()));
233      Results.Add(new Result("Detection Exclusivity", new DoubleValue()));
234
235      ResultsTargets.Rows.Add(new DataRow(ResultsTargetsReal));
236      foreach (var ensemble in Ensembles) {
237        // targets table
238        ResultsTargets.Rows.Add(new DataRow(ensemble.Name));
239
240        ResultsStateDetection.Rows.Add(new DataRow(ensemble.Name));
241
242        // qualities (series)
243        //ResultsQualities.Rows.Add(new DataRow(ensemble.Name + " - " + ResultsQualitiesMSE));
244        ResultsQualities.Rows.Add(new DataRow(ensemble.Name));
245
246        ResultsPeakQualities.Rows.Add(new DataRow(ensemble.Name));
247
248        // qualities (bars)
249        ResultsSWQualitiesBars.Bars.Add(new DataBar(ensemble.Name, ensemble.QualityThreshold.Start, ensemble.QualityThreshold.End));
250
251        // voting (bars)
252        ResultsSWVotingBars.Bars.Add(new DataBar(ensemble.Name, ensemble.ConfidenceThreshold.Start, ensemble.ConfidenceThreshold.End));
253
254        // sonar quality (bars)
255        ResultsSonarQualitiesBars.Bars.Add(new DataBar(ensemble.Name, ensemble.QualityThreshold.Start, ensemble.QualityThreshold.End));
256
257        // quality peaks (bars)
258        ResultsSWPeakQualitiesBars.Bars.Add(new DataBar(ensemble.Name, ensemble.QualityThreshold.Start, ensemble.QualityThreshold.End));
259      }
260    }
261
262    #endregion
263
264    #region constructors, cloner,...
265    public DatastreamAnalysisOptimizer() : base() {
266      name = "Datastream Analysis";
267      log = new Log();
268      results = new ResultCollection();
269      ensembles = new ItemList<RatedEnsembleModel>();
270      datastream = new Datastream();
271      runsCounter = 0;
272      runs = new RunCollection();
273      Initialize();
274    }
275
276    [StorableConstructor]
277    protected DatastreamAnalysisOptimizer(bool deserializing) : base(deserializing) {
278    }
279
280    [StorableHook(HookType.AfterDeserialization)]
281    private void AfterDeserialization() {
282      Initialize();
283    }
284
285    protected DatastreamAnalysisOptimizer(DatastreamAnalysisOptimizer original, Cloner cloner) : base(original, cloner) {
286      name = original.name;
287      log = cloner.Clone(original.log);
288      results = cloner.Clone(original.results);
289      ensembles = (ItemList<RatedEnsembleModel>) original.Ensembles.Clone(cloner);
290      datastream = (Datastream) original.Datastream.Clone(cloner);
291      runsCounter = original.runsCounter;
292      runs = cloner.Clone(original.runs);
293      Initialize();
294    }
295
296    public override IDeepCloneable Clone(Cloner cloner) {
297      return new DatastreamAnalysisOptimizer(this, cloner);
298    }
299
300    private void Initialize() {
301      if (runs != null) RegisterRunsEvents();
302      if (datastream != null) RegisterDatastreamEvents();
303      if (ensembles != null) RegisterEnsembleEvents();
304    }
305    #endregion
306
307    #region control actions
308
309    public override void Prepare() {
310      if (ensembles == null || ensembles.Count == 0 || datastream == null || !datastream.SlidingWindowEvaluationPossible) return;
311      //if (ensembles.SelectMany(x => x.Models).Count() == 0) return;
312      base.Prepare();
313      OnPrepared();
314    }
315
316    public void Prepare(bool clearRuns) {
317      if (ensembles == null || ensembles.Count == 0 || datastream == null || !datastream.SlidingWindowEvaluationPossible) return;
318
319      base.Prepare();
320      if (clearRuns) runs.Clear();
321      OnPrepared();
322    }
323
324    public override void Start() {
325      if (ensembles == null || datastream == null) return;
326      base.Start();
327      cancellationTokenSource = new CancellationTokenSource();
328      stopPending = false;
329
330      if (prepared) {
331        SetupResults();
332        Datastream.InitializeState();
333      }
334
335      Task task = Task.Factory.StartNew(Run, cancellationTokenSource.Token, cancellationTokenSource.Token);
336      task.ContinueWith(t => {
337        try {
338          t.Wait();
339        }
340        catch (AggregateException ex) {
341          try {
342            ex.Flatten().Handle(x => x is OperationCanceledException);
343          } catch (AggregateException remaining) {
344            if(remaining.InnerExceptions.Count == 1) OnExceptionOccurred(remaining.InnerExceptions[0]);
345            else OnExceptionOccurred(remaining);
346          }
347        }
348        cancellationTokenSource.Dispose();
349        cancellationTokenSource = null;
350
351        // handle stop/pause
352        if (stopPending || finished) {
353          OnStopped();
354        } else {
355          OnPaused();
356        }
357      });
358    }
359
360    public override void Pause() {
361      if (ensembles == null || datastream == null) return;
362      base.Pause();
363      cancellationTokenSource.Cancel();
364    }
365
366    public override void Stop() {
367      if (ensembles == null || datastream == null) return;
368      base.Stop();
369      if (ExecutionState == ExecutionState.Paused) {
370        OnStopped();
371      } else {
372        stopPending = true;
373        cancellationTokenSource.Cancel();
374      }
375    }
376
377    protected override void OnPrepared() {
378      ExecutionTime = TimeSpan.Zero;
379      foreach (IStatefulItem statefulItem in this.GetObjectGraphObjects(new HashSet<object>() {Runs}).OfType<IStatefulItem>()) {
380        statefulItem.InitializeState();
381      }
382      results.Clear();
383      prepared = true;
384      finished = false;
385      Log.LogMessage("Datastream analysis prepared");
386      base.OnPrepared();
387    }
388
389    protected override void OnStarted() {
390      Log.LogMessage("Datastream analysis started");
391      base.OnStarted();
392    }
393
394    protected override void OnPaused() {
395      Log.LogMessage("Datastream analysis paused");
396      base.OnPaused();
397    }
398
399    protected override void OnStopped() {
400      try {
401        runsCounter++;
402        var run = new Run();
403        run.Filename = Filename;
404        run.Name = string.Format("{0} Run {1}", Name, runsCounter);
405        CollectParameterValues(run.Parameters);
406        CollectResultValues(run.Results);
407        runs.Add(run);
408      }
409      finally {
410        Log.LogMessage("Datastream analysis stopped");
411        base.OnStopped();
412      }
413    }
414
415    #endregion
416
417    #region run
418    private void Run(object state) {
419      CancellationToken cancellationToken = (CancellationToken) state;
420      OnStarted();
421      lastUpdateTime = DateTime.UtcNow;
422      System.Timers.Timer timer = new System.Timers.Timer(250);
423      timer.AutoReset = true;
424      timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
425      timer.Start();
426
427      try {
428        Run(cancellationToken);
429      }
430      finally {
431        timer.Elapsed -= new System.Timers.ElapsedEventHandler(timer_Elapsed);
432        timer.Stop();
433        ExecutionTime += DateTime.UtcNow - lastUpdateTime;
434      }
435
436      cancellationToken.ThrowIfCancellationRequested();
437    }
438
439    private int replayedIndex;
440
441    protected void Run(CancellationToken cancellationToken) {
442
443      if (prepared) {
444        replayedIndex = 0;
445        prepared = false;
446      }
447
448      try {
449
450        // play and evaluate initial window
451        PlayDatastream();
452        lastStateValue = Datastream.ProblemData.Dataset.GetDoubleValue("h", replayedIndex);
453        if (Datastream.SlidingWindowEvaluationPossible) Evaluate();
454        replayedIndex = Datastream.FitnessPartition.End;
455
456        do {
457          while(Datastream.SlidingWindowMovementPossible) {
458            cancellationToken.ThrowIfCancellationRequested();
459
460            // perform (delayed) window movement
461            Thread.Sleep(Datastream.SlidingWindowMovementDelay.Value);
462            Datastream.MoveSlidingWindow();
463            ResultsSlidingWindowMovements++;
464
465            // play and evaluate the moved window
466            PlayDatastream();
467            if (Datastream.SlidingWindowEvaluationPossible) Evaluate();
468            replayedIndex = Datastream.FitnessPartition.End;
469          }
470        } while (Datastream.UpdateAvailable);
471        finished = true;
472      }
473      catch (Exception ex) {
474        if (ex is ArgumentOutOfRangeException) throw ex;
475        if (ex is OperationCanceledException) throw ex;
476      }
477      finally {
478        // reset everything
479        //Prepare(true);
480      }
481    }
482
483    private void PlayDatastream() {
484      var problemData = Datastream.ProblemData;
485      var targetVarName = problemData.TargetVariable;
486
487      for (int i = replayedIndex; i < Datastream.FitnessPartition.End; i++) {
488        var realValue = problemData.Dataset.GetDoubleValue(targetVarName, i);
489        ResultsTargets.Rows[ResultsTargetsReal].Values.Add(realValue);
490      }
491    }
492   
493    private void Evaluate() {
494      evaluationCount++;
495      var problemData = Datastream.ProblemData;
496      var dataset = problemData.Dataset;
497      var targetVarName = problemData.TargetVariable;
498
499      var rows = Enumerable.Range(Datastream.FitnessPartition.Start, Datastream.FitnessPartition.Size);
500      var realValues = dataset.GetDoubleValues(targetVarName, rows);
501
502      int sonarSize = (int)(Datastream.FitnessPartition.Size * Datastream.SlidingWindowSonarRatio.Value);
503      var sonarStart = Datastream.FitnessPartition.End - sonarSize;
504      var sonarRows = Enumerable.Range(sonarStart, sonarSize);
505      var sonarRealValues = dataset.GetDoubleValues(targetVarName, sonarRows);
506
507      var winningEnsembleName = ensembles[0].Name;
508      var winningEnsemblePR2 = 0.0;
509      var winningEnsembleIdx = 0;
510      var ec = 0;
511      bool stateChangeInStep = false;
512      var curDetectionCount = 0;
513      var changeDetectionCount = 0;
514      double curStateValue = 0.0;
515      foreach (var ensemble in Ensembles) {
516
517        var sonarEstimatedValuesPerModelPerRow = ensemble.Model.Models.Select(x => x.GetEstimatedValues(datastream.ProblemData.Dataset, sonarRows).ToArray());
518        var sonarEstimatedValuesPerRow = Enumerable.Range(0, sonarSize).Select(r => sonarEstimatedValuesPerModelPerRow.Select(m => m[r]).Average()).ToArray();
519
520        var estimatedValuesPerModelPerRow = ensemble.Model.Models.Select(x => x.GetEstimatedValues(datastream.ProblemData.Dataset, rows).ToArray());
521        var estimatedValuesPerRow = Enumerable.Range(0, Datastream.FitnessPartition.Size).Select(r => estimatedValuesPerModelPerRow.Select(e => e[r]).Average()).ToArray(); // per row
522        var averageEstimatedValuesPerModel = estimatedValuesPerModelPerRow.Select(x => x.Average()); // per model
523        var averageEstimatedValue = averageEstimatedValuesPerModel.Average();
524
525        // calulate quality
526        //var mse = Math.Pow(averageEstimatedValue - realValues.Average(), 2);
527        OnlineCalculatorError error;
528        var pR = OnlinePearsonsRCalculator.Calculate(estimatedValuesPerRow, realValues, out error);
529        var pR2 = error == OnlineCalculatorError.None ? pR * pR : 0.0;
530
531        var sonarPR = OnlinePearsonsRCalculator.Calculate(sonarEstimatedValuesPerRow, sonarRealValues, out error);
532        var sonarPR2 = error == OnlineCalculatorError.None ? sonarPR * sonarPR : 0.0;
533   
534        var estimatedValuesPerModelPerRowArr = estimatedValuesPerModelPerRow.ToArray();
535        var curPR = 0.0;
536       
537        var peakPR = OnlinePearsonsRCalculator.Calculate(estimatedValuesPerModelPerRowArr[0], realValues, out error);
538        for (int i = 1; i < estimatedValuesPerModelPerRow.Count(); i++) {
539          curPR = OnlinePearsonsRCalculator.Calculate(estimatedValuesPerModelPerRowArr[i], realValues, out error);
540          if (curPR > peakPR && error == OnlineCalculatorError.None) {
541            peakPR = curPR;
542          }
543        }
544        var peakPR2 = peakPR * peakPR;
545
546        // calculate confidence
547        var cm1 = CalulateEnsembleConfidenceCM1(ensemble, estimatedValuesPerModelPerRow, realValues);
548
549        int replayAmount = Datastream.FitnessPartition.End - replayedIndex;
550        int replayCount = estimatedValuesPerRow.Length - replayAmount;
551
552        for (int i = replayedIndex; i < Datastream.FitnessPartition.End; i++) {
553          //ResultsTargets.Rows[ensemble.Name].Values.Add(averageEstimatedValue);
554          ResultsTargets.Rows[ensemble.Name].Values.Add(estimatedValuesPerRow[replayCount]);
555          replayCount++;
556
557          //ResultsQualities.Rows[ensemble.Name + " - " + ResultsQualitiesMSE].Values.Add(mse);
558          ResultsQualities.Rows[ensemble.Name].Values.Add(pR2);
559          ResultsPeakQualities.Rows[ensemble.Name].Values.Add(peakPR2);
560
561          double amp = (pR2 > ensemble.QualityThreshold.Start) ? 1.0 : 0.0;
562          ResultsStateDetection.Rows[ensemble.Name].Values.Add(amp);   
563        }
564        ResultsSWQualitiesBars.Bars[ensemble.Name].Value = pR2;
565        ResultsSonarQualitiesBars.Bars[ensemble.Name].Value = sonarPR2;
566        ResultsSWVotingBars.Bars[ensemble.Name].Value = cm1;
567        ResultsSWPeakQualitiesBars.Bars[ensemble.Name].Value = peakPR2;
568
569        if (pR2 > ensemble.QualityThreshold.Start)
570          curDetectionCount++;
571
572        if (pR2 > winningEnsemblePR2) {
573          winningEnsemblePR2 = pR2;
574          winningEnsembleName = ensemble.Name;
575          winningEnsembleIdx = ec;
576        }
577        ec++;
578      }
579
580      // quality meassures
581      // =================================================
582
583      if (winningEnsemblePR2 > ensembles[winningEnsembleIdx].QualityThreshold.Start) {
584        // Mean PR2
585        pR2Sum += winningEnsemblePR2;
586        detectionCount++;
587        ResultsMeanPR2 = pR2Sum/detectionCount;
588
589        // detection exclusivity --> 1.0 - (x - 1) * (1.0 / n)
590        var fraction = 1.0 / ensembles.Count;
591        var curExclusivity = 1.0 - (curDetectionCount - 1) * fraction;
592        exclusivitySum += curExclusivity;
593        ResultsDetectionExclusivity = exclusivitySum / detectionCount;
594      }
595
596      double replCount = 0.0;
597      double accCount = 0.0;
598      for (int i = replayedIndex; i < Datastream.FitnessPartition.End; i++) {
599        replCount++;
600        curStateValue = problemData.Dataset.GetDoubleValue("h", i);
601        if (curStateValue <= 0.5 && winningEnsembleIdx == 0 && winningEnsemblePR2 > ensembles[winningEnsembleIdx].QualityThreshold.Start) {
602          accCount++;
603        } else if (curStateValue > 0.5 && winningEnsembleIdx == 1 && winningEnsemblePR2 > ensembles[winningEnsembleIdx].QualityThreshold.Start) {
604          accCount++;
605        }
606      }
607      accuracySum += accCount / replCount;
608      ResultsDetectionAccuracy = accuracySum / evaluationCount;
609
610      //if (accCount / replCount > 1.0) {
611      //  Console.WriteLine();
612      //}
613
614      //if(accuracySum / evaluationCount > 1.0) {
615      //  Console.WriteLine();
616      //}
617
618      //if (accCount < replCount && !accDiscount) accDiscount = true;
619      //if (accDiscount && accuracySum/evaluationCount >= 1.0) {
620      //  Console.WriteLine();
621      //}
622
623      lastStateValue = curStateValue;
624
625      // detection of state change
626      //for (int i = replayedIndex; i < Datastream.FitnessPartition.End; i++) {
627      //  curStateValue = problemData.Dataset.GetDoubleValue("h", i);
628      //  if (lastStateValue > curStateValue || lastStateValue < curStateValue) {
629      //    stateChangeInStep = true;
630      //    changeDetectionCount++;
631      //  }
632      //}
633      //lastStateValue = curStateValue;
634
635      // detection accuracy
636      //if (!stateChangeInStep && winningEnsemblePR2 > ensembles[winningEnsembleIdx].QualityThreshold.Start) {
637      //  // (stable) state - detected
638      //  accuracySum++;
639      //} else if(!stateChangeInStep && winningEnsemblePR2 < ensembles[winningEnsembleIdx].QualityThreshold.Start) {
640      //  // (stable) state - not detected
641      //  // no accuracy points (or penalty)
642      //} else if (stateChangeInStep && winningEnsemblePR2 < ensembles[winningEnsembleIdx].QualityThreshold.Start) {
643      //  // change - detected
644      //  accuracySum++;
645      //} else if (stateChangeInStep && winningEnsemblePR2 > ensembles[winningEnsembleIdx].QualityThreshold.Start) {
646      //  // change - not detected
647      //  // no accuracy points (or penalty)
648      //}
649    }
650    private bool accDiscount = false;
651
652    private double CalulateEnsembleConfidenceCM1(RatedEnsembleModel ensemble, IEnumerable<double[]> estimatedValuesPerModelPerRow, IEnumerable<double> realValues) {
653      int noModels = estimatedValuesPerModelPerRow.Count();
654      int votes = 0;
655
656      OnlineCalculatorError error;
657
658      foreach(var model in estimatedValuesPerModelPerRow) {
659        var pR = OnlinePearsonsRCalculator.Calculate(model, realValues, out error);
660        var pR2 = error == OnlineCalculatorError.None ? pR * pR : 0.0;
661        if (pR2 >= ensemble.QualityThreshold.End) {
662          votes++;
663        }
664      }
665     
666
667      return (double)votes/noModels;
668    }
669
670    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
671      System.Timers.Timer timer = (System.Timers.Timer)sender;
672      timer.Enabled = false;
673      DateTime now = DateTime.UtcNow;
674      ExecutionTime += now - lastUpdateTime;
675      lastUpdateTime = now;
676      timer.Enabled = true;
677    }
678
679    public void CollectParameterValues(IDictionary<string, IItem> values) {
680      values.Add("Datastream Analysis Name", new StringValue(Name));
681      if (Datastream != null) {
682        Datastream.CollectParameterValues(values);
683        values.Add("Datastream Name", new StringValue(Datastream.Name));
684      }
685    }
686
687    public void CollectResultValues(IDictionary<string, IItem> values) {
688      values.Add("Execution Time", new TimeSpanValue(ExecutionTime));
689      Results.CollectResultValues(values);
690    }
691    #endregion
692
693    #region events
694
695    #region events registration
696
697    public EventHandler EnsemblesChanged;
698    public EventHandler DatastreamChanged;
699
700    protected virtual void DeregisterRunsEvents() {
701      runs.CollectionReset -= new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
702    }
703
704    protected virtual void RegisterRunsEvents() {
705      runs.CollectionReset += new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
706    }
707
708    protected virtual void RegisterDatastreamEvents() {
709      datastream.Reset += new EventHandler(Datastream_Reset);
710      datastream.ProblemDataChanged += new EventHandler(Datastream_ProblemDataChanged);
711    }
712
713    protected virtual void DeregisterDatastreamEvents() {
714      datastream.Reset -= new EventHandler(Datastream_Reset);
715      datastream.ProblemDataChanged -= new EventHandler(Datastream_ProblemDataChanged);
716    }
717
718    protected virtual void RegisterEnsembleEvents() {
719      ensembles.ItemsAdded += new CollectionItemsChangedEventHandler<IndexedItem<RatedEnsembleModel>>(Ensembles_ItemsChanged);
720      ensembles.ItemsMoved += new CollectionItemsChangedEventHandler<IndexedItem<RatedEnsembleModel>>(Ensembles_ItemsChanged);
721      ensembles.ItemsRemoved += new CollectionItemsChangedEventHandler<IndexedItem<RatedEnsembleModel>>(Ensembles_ItemsChanged);
722      ensembles.ItemsReplaced += new CollectionItemsChangedEventHandler<IndexedItem<RatedEnsembleModel>>(Ensembles_ItemsChanged);
723      ensembles.CollectionReset += new CollectionItemsChangedEventHandler<IndexedItem<RatedEnsembleModel>>(Ensembles_Reset);
724    }
725
726    protected virtual void DeregisterEnsembleEvents() {
727      ensembles.ItemsAdded -= new CollectionItemsChangedEventHandler<IndexedItem<RatedEnsembleModel>>(Ensembles_ItemsChanged);
728      ensembles.ItemsMoved -= new CollectionItemsChangedEventHandler<IndexedItem<RatedEnsembleModel>>(Ensembles_ItemsChanged);
729      ensembles.ItemsRemoved -= new CollectionItemsChangedEventHandler<IndexedItem<RatedEnsembleModel>>(Ensembles_ItemsChanged);
730      ensembles.ItemsReplaced -= new CollectionItemsChangedEventHandler<IndexedItem<RatedEnsembleModel>>(Ensembles_ItemsChanged);
731      ensembles.CollectionReset -= new CollectionItemsChangedEventHandler<IndexedItem<RatedEnsembleModel>>(Ensembles_Reset);
732    }
733    #endregion
734
735    #region event handling
736
737    protected virtual void Runs_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRun> e) {
738      runsCounter = runs.Count;
739    }
740
741    protected virtual void Datastream_Reset(object sender, EventArgs e) {
742      Prepare();
743    }
744
745    protected virtual void Datastream_ProblemDataChanged(object sender, EventArgs e) {
746      Prepare();
747    }
748
749    protected virtual void Ensembles_Reset(object sender, EventArgs e) {
750      Prepare();
751    }
752
753    protected virtual void Ensembles_ItemsChanged(object sender, EventArgs e) {
754      Prepare();
755    }
756
757    private void OnEnsemblesChanged() {
758      var changed = EnsemblesChanged;
759      if (changed != null)
760        changed(this, EventArgs.Empty);
761    }
762
763    private void OnDatastreamChanged() {
764      var changed = DatastreamChanged;
765      if (changed != null)
766        changed(this, EventArgs.Empty);
767    }
768
769    #endregion
770
771    #endregion
772
773    #region NamedItem
774
775    [Storable]
776    protected string name;
777
778    /// <inheritdoc/>
779    /// <remarks>Calls <see cref="OnNameChanging"/> and also <see cref="OnNameChanged"/>
780    /// eventually in the setter.</remarks>
781    public string Name {
782      get { return name; }
783      set {
784        if (!CanChangeName) throw new NotSupportedException("Name cannot be changed.");
785        if (!(name.Equals(value) || (value == null) && (name == string.Empty))) {
786          CancelEventArgs<string> e = value == null
787            ? new CancelEventArgs<string>(string.Empty)
788            : new CancelEventArgs<string>(value);
789          OnNameChanging(e);
790          if (!e.Cancel) {
791            name = value == null ? string.Empty : value;
792            OnNameChanged();
793          }
794        }
795      }
796    }
797
798    public virtual bool CanChangeName {
799      get { return true; }
800    }
801
802    [Storable] protected string description;
803
804    public string Description {
805      get { return description; }
806      set {
807        if (!CanChangeDescription) throw new NotSupportedException("Description cannot be changed.");
808        if (!(description.Equals(value) || (value == null) && (description == string.Empty))) {
809          description = value == null ? string.Empty : value;
810          OnDescriptionChanged();
811        }
812      }
813    }
814
815    public virtual bool CanChangeDescription {
816      get { return true; }
817    }
818
819    /// <summary>
820    /// Gets the string representation of the current instance in the format: <c>Name: [null|Value]</c>.
821    /// </summary>
822    /// <returns>The current instance as a string.</returns>
823    public override string ToString() {
824      return Name;
825    }
826
827    /// <inheritdoc/>
828    public event EventHandler<CancelEventArgs<string>> NameChanging;
829
830    /// <summary>
831    /// Fires a new <c>NameChanging</c> event.
832    /// </summary>
833    /// <param name="e">The event arguments of the changing.</param>
834    protected virtual void OnNameChanging(CancelEventArgs<string> e) {
835      var handler = NameChanging;
836      if (handler != null) handler(this, e);
837    }
838
839    /// <inheritdoc/>
840    public event EventHandler NameChanged;
841
842    /// <summary>
843    /// Fires a new <c>NameChanged</c> event.
844    /// </summary>
845    /// <remarks>Calls <see cref="ItemBase.OnChanged"/>.</remarks>
846    protected virtual void OnNameChanged() {
847      var handler = NameChanged;
848      if (handler != null) handler(this, EventArgs.Empty);
849      OnToStringChanged();
850    }
851
852    /// <inheritdoc/>
853    public event EventHandler DescriptionChanged;
854
855    /// <summary>
856    /// Fires a new <c>DescriptionChanged</c> event.
857    /// </summary>
858    /// <remarks>Calls <see cref="ItemBase.OnChanged"/>.</remarks>
859    protected virtual void OnDescriptionChanged() {
860      var handler = DescriptionChanged;
861      if (handler != null) handler(this, EventArgs.Empty);
862    }
863
864    #endregion nameditem
865  }
866}
Note: See TracBrowser for help on using the repository browser.