Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
11/28/12 01:59:10 (12 years ago)
Author:
abeham
Message:

#1985:

  • Removed .resx file
  • Fixed bugs
File:
1 edited

Legend:

Unmodified
Added
Removed
  • branches/RuntimeOptimizer/HeuristicLab.Optimization/3.3/MetaOptimizers/TimeLimitRun.cs

    r8955 r8956  
    2626using System.Linq;
    2727using System.Threading;
     28using System.Threading.Tasks;
    2829using System.Timers;
    2930using HeuristicLab.Collections;
     
    5556    #endregion
    5657
    57     private readonly Timer snapTimer;
    58     private readonly Timer runTimer;
     58    private Timer snapTimer, runTimer;
     59    private readonly ManualResetEvent algorithmStarted = new ManualResetEvent(false);
    5960    private readonly ManualResetEvent algorithmPaused = new ManualResetEvent(false);
    6061    private readonly ManualResetEvent algorithmStopped = new ManualResetEvent(false);
     62    [Storable]
     63    private bool snapshotTimesDirty;
    6164
    6265    [Storable]
     
    8184        if (snapshotTimes == value) return;
    8285        snapshotTimes = value;
    83         snapshotTimesIndex = 0;
     86        snapshotTimesDirty = true;
    8487        OnPropertyChanged("SnapshotTimes");
    8588      }
     
    124127      set {
    125128        if (algorithm == value) return;
    126         if (algorithm != null) {
    127           DeregisterAlgorithmEvents();
    128           var runs = algorithm.Runs;
    129           algorithm = null; //necessary to avoid removing the runs from the old algorithm
    130           Runs.RemoveRange(runs);
    131         }
     129        if (algorithm != null) DeregisterAlgorithmEvents();
    132130        algorithm = value;
    133131        if (algorithm != null) {
    134132          RegisterAlgorithmEvents();
    135           Runs.AddRange(algorithm.Runs);
     133          if (algorithm.ExecutionState == ExecutionState.Started) algorithmStarted.Set();
     134          else algorithmStarted.Reset();
    136135          if (algorithm.ExecutionState == ExecutionState.Paused) algorithmPaused.Set();
    137136          else algorithmPaused.Reset();
     
    167166
    168167    [StorableConstructor]
    169     private TimeLimitRun(bool deserializing)
    170       : base(deserializing) {
    171       // the timer will not be serialized
    172       snapTimer = new Timer() {
    173         AutoReset = false,
    174         Enabled = false,
    175         Interval = double.MaxValue
    176       };
    177       runTimer = new Timer() {
    178         AutoReset = false,
    179         Enabled = false,
    180         Interval = double.MaxValue
    181       };
    182     }
     168    private TimeLimitRun(bool deserializing) : base(deserializing) { }
    183169    private TimeLimitRun(TimeLimitRun original, Cloner cloner)
    184170      : base(original, cloner) {
     
    186172      snapshotTimes = new ObservableList<double>(original.snapshotTimes);
    187173      snapshotTimesIndex = original.snapshotTimesIndex;
    188       snapTimer = new Timer() {
    189         AutoReset = original.snapTimer.AutoReset,
    190         Enabled = original.snapTimer.Enabled,
    191         Interval = original.snapTimer.Interval
    192       };
    193       runTimer = new Timer() {
    194         AutoReset = original.runTimer.AutoReset,
    195         Enabled = original.runTimer.Enabled,
    196         Interval = original.runTimer.Interval
    197       };
    198174      snapshots = cloner.Clone(original.snapshots);
     175      snapshotTimesDirty = original.snapshotTimesDirty;
    199176      storeAlgorithmInEachSnapshot = original.storeAlgorithmInEachSnapshot;
    200177      algorithm = cloner.Clone(original.algorithm);
    201178      runs = cloner.Clone(original.runs);
     179
     180      snapTimer = new Timer() {
     181        AutoReset = original.snapTimer.AutoReset,
     182        Interval = original.snapTimer.Interval
     183      };
     184      runTimer = new Timer() {
     185        AutoReset = original.runTimer.AutoReset,
     186        Interval = original.runTimer.Interval
     187      };
     188      if (original.algorithm != null && original.algorithm.ExecutionState == ExecutionState.Started)
     189        algorithmStarted.Set();
     190      if (original.algorithm != null && original.algorithm.ExecutionState == ExecutionState.Paused)
     191        algorithmPaused.Set();
     192      if (original.algorithm != null && original.algorithm.ExecutionState == ExecutionState.Stopped)
     193        algorithmStopped.Set();
     194
    202195      Initialize();
    203196    }
     
    215208        AutoReset = false,
    216209        Enabled = false,
    217         Interval = snapshotTimes[snapshotTimesIndex]
     210        Interval = 100
    218211      };
    219212      runTimer = new Timer() {
     
    224217      snapshots = new RunCollection();
    225218      Runs = new RunCollection { AlgorithmName = Name };
     219      Initialize();
    226220    }
    227221    public TimeLimitRun(string name)
     
    237231        AutoReset = false,
    238232        Enabled = false,
    239         Interval = snapshotTimes[snapshotTimesIndex]
     233        Interval = 100
    240234      };
    241235      snapshots = new RunCollection();
     
    246240      };
    247241      Runs = new RunCollection { AlgorithmName = Name };
     242      Initialize();
    248243    }
    249244    public TimeLimitRun(string name, string description)
     
    258253        AutoReset = false,
    259254        Enabled = false,
    260         Interval = snapshotTimes[snapshotTimesIndex]
     255        Interval = 100
    261256      };
    262257      snapshots = new RunCollection();
     
    267262      };
    268263      Runs = new RunCollection { AlgorithmName = Name };
     264      Initialize();
    269265    }
    270266
     
    276272    [StorableHook(HookType.AfterDeserialization)]
    277273    private void AfterDeserialization() {
     274      // the timers will not be serialized
     275      snapTimer = new Timer() {
     276        AutoReset = false,
     277        Enabled = false,
     278        Interval = 100
     279      };
     280      runTimer = new Timer() {
     281        AutoReset = false,
     282        Enabled = false,
     283        Interval = double.MaxValue
     284      };
     285      if (Algorithm != null && Algorithm.ExecutionState == ExecutionState.Started)
     286        algorithmStarted.Set();
     287      else algorithmStarted.Reset();
     288      if (Algorithm != null && Algorithm.ExecutionState == ExecutionState.Paused)
     289        algorithmPaused.Set();
     290      else algorithmPaused.Reset();
     291      if (Algorithm != null && Algorithm.ExecutionState == ExecutionState.Stopped)
     292        algorithmStopped.Set();
     293      else algorithmStopped.Reset();
    278294      Initialize();
    279295    }
     
    281297    private void Initialize() {
    282298      if (algorithm != null) RegisterAlgorithmEvents();
     299      snapshotTimes.ItemsAdded += snapshotTimes_Changed;
     300      snapshotTimes.ItemsMoved += snapshotTimes_Changed;
     301      snapshotTimes.ItemsRemoved += snapshotTimes_Changed;
     302      snapshotTimes.ItemsReplaced += snapshotTimes_Changed;
     303      snapshotTimes.CollectionReset += snapshotTimes_Changed;
    283304      snapTimer.Elapsed += snapshotTimer_Elapsed;
    284305      runTimer.Elapsed += runTimer_Elapsed;
    285306    }
    286307
    287     private readonly object timerLock = new object();
     308    private void snapshotTimes_Changed(object sender, EventArgs e) {
     309      snapshotTimesDirty = true;
     310    }
     311
     312    private readonly object snapshotLock = new object();
    288313    private void snapshotTimer_Elapsed(object sender, ElapsedEventArgs e) {
    289       lock (timerLock) {
    290         runTimer.Stop();
    291         if (Algorithm == null) return;
    292         if (ExecutionState != ExecutionState.Started) return;
     314      snapTimer.Stop();
     315      lock (snapshotLock) {
     316        try {
     317          if (Algorithm == null) return;
     318          if (ExecutionState != ExecutionState.Started) return;
     319
     320          var execTime = ExecutionTime;
     321          if (snapshotTimesIndex < SnapshotTimes.Count &&
     322              SnapshotTimes[snapshotTimesIndex] <= execTime.TotalMilliseconds) {
     323            DoSnapshot();
     324            snapshotTimesIndex++;
     325            try {
     326              Algorithm.Start();
     327              algorithmStarted.WaitOne();
     328            } catch (InvalidOperationException) { }
     329          }
     330        } catch { }
     331        snapTimer.Start();
     332      }
     333    }
     334
     335    private void runTimer_Elapsed(object sender, ElapsedEventArgs e) {
     336      snapTimer.Stop();
     337      lock (snapshotLock) {
     338        try {
     339          Algorithm.Stop();
     340          algorithmStopped.WaitOne();
     341        } catch (InvalidOperationException) { }
     342      }
     343    }
     344
     345    private void FindNextSnapshotTimeIndex(TimeSpan reference) {
     346      var index = 0;
     347      while (index < snapshotTimes.Count && (snapshotTimes[index] - reference.TotalMilliseconds) <= 0) {
     348        index++;
     349      };
     350      snapshotTimesIndex = index;
     351    }
     352
     353    private void DoSnapshot() {
     354      lock (snapshotLock) {
     355        var wasPaused = Algorithm.ExecutionState == ExecutionState.Paused;
    293356        var error = false;
    294         try { Algorithm.Pause(); } catch (InvalidOperationException) { error = true; }
     357        try {
     358          Algorithm.Pause();
     359          algorithmPaused.WaitOne();
     360        } catch (InvalidOperationException) {
     361          error = true;
     362        }
    295363        if (error && ExecutionState != ExecutionState.Paused) return; // Algorithm is either stopped or prepared
    296364
    297         algorithmPaused.WaitOne();
    298365        MakeSnapshot();
    299         try { Algorithm.Start(); } catch (InvalidOperationException) { }
    300       }
    301     }
    302 
    303     private void runTimer_Elapsed(object sender, ElapsedEventArgs e) {
    304       lock (timerLock) {
    305         runTimer.Stop();
    306         snapTimer.Stop();
    307         try { Algorithm.Stop(); } catch (InvalidOperationException) { }
    308       }
    309     }
    310 
    311     private double? GetNextInterval(TimeSpan reference) {
    312       double interval;
    313       while ((interval = snapshotTimes[snapshotTimesIndex] - reference.TotalMilliseconds) <= 0) {
    314         snapshotTimesIndex++;
    315         if (snapshotTimesIndex >= snapshotTimes.Count) return null;
    316       };
    317       return interval;
     366        if (!wasPaused) {
     367          try {
     368            Algorithm.Start();
     369            algorithmStarted.WaitOne();
     370          } catch (InvalidOperationException) { }
     371        }
     372      }
    318373    }
    319374
    320375    private void MakeSnapshot() {
    321       string runName = ExecutionTime.ToString() + " " + algorithm.Name + " Snapshot";
     376      string time = Math.Round(ExecutionTime.TotalSeconds, 1).ToString("0.0");
     377      string runName = "Snapshot " + time + "s " + algorithm.Name;
    322378      Run run;
    323379      if (StoreAlgorithmInEachSnapshot) {
    324         run = new Run(runName, algorithm);
     380        var temporarilySetStoreFlag = !Algorithm.StoreAlgorithmInEachRun;
     381        if (temporarilySetStoreFlag) Algorithm.StoreAlgorithmInEachRun = true;
     382        run = new Run(runName, Algorithm);
     383        if (temporarilySetStoreFlag) Algorithm.StoreAlgorithmInEachRun = false;
    325384      } else {
    326385        // duplicate code of Run.Initialize - necessary, because Algorithm property doesn't have a setter
     
    339398    }
    340399
     400    public void Snapshot() {
     401      Task.Factory.StartNew(DoSnapshot);
     402    }
     403
    341404    public void Prepare() {
    342405      Prepare(false);
     
    434497    }
    435498    private void Algorithm_Paused(object sender, EventArgs e) {
     499      algorithmStarted.Reset();
    436500      algorithmPaused.Set();
    437501      algorithmStopped.Reset();
     
    439503    }
    440504    private void Algorithm_Prepared(object sender, EventArgs e) {
     505      algorithmStarted.Reset();
    441506      algorithmPaused.Reset();
    442507      algorithmStopped.Reset();
     
    448513    }
    449514    private void Algorithm_Started(object sender, EventArgs e) {
     515      algorithmStarted.Set();
    450516      algorithmPaused.Reset();
    451517      algorithmStopped.Reset();
    452518      var execTime = ExecutionTime;
    453       var interval = GetNextInterval(execTime);
    454       if (interval.HasValue) {
    455         snapTimer.Interval = interval.Value;
    456         snapTimer.Start();
     519      if (snapshotTimesDirty) {
     520        SnapshotTimes.Sort();
     521        snapshotTimesDirty = false; // sort will mark it dirty again
     522        FindNextSnapshotTimeIndex(execTime);
    457523      }
    458524      runTimer.Interval = (MaximumExecutionTime - execTime).TotalMilliseconds;
     525      snapTimer.Start();
    459526      runTimer.Start();
    460527      OnStarted();
    461528    }
    462529    private void Algorithm_Stopped(object sender, EventArgs e) {
     530      algorithmStarted.Reset();
    463531      algorithmPaused.Reset();
    464532      algorithmStopped.Set();
    465       snapTimer.Stop();
    466       runTimer.Stop();
    467       MakeSnapshot();
    468       var snapshotsRun = new Run() { Name = algorithm.Runs.Last().Name };
    469       foreach (var s in snapshots)
    470         snapshotsRun.Parameters.Add(s.Name, s);
    471       Runs.Add(snapshotsRun);
     533      lock (snapshotLock) {
     534        snapTimer.Stop();
     535        runTimer.Stop();
     536        MakeSnapshot();
     537      }
     538      var cloner = new Cloner();
     539      var algRun = cloner.Clone(Algorithm.Runs.Last());
     540      var clonedSnapshots = cloner.Clone(snapshots);
     541      try {
     542        algRun.Results.Add("Snapshots", clonedSnapshots);
     543      } catch (ArgumentException ex) {
     544        // TODO strategy?
     545      }
     546      Runs.Add(algRun);
     547      Algorithm.Runs.Clear();
    472548      OnStopped();
    473549    }
Note: See TracChangeset for help on using the changeset viewer.