Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.TimeSeries/HeuristicLab.Clients.Hive/3.3/HiveJobs/OptimizerHiveTask.cs @ 7213

Last change on this file since 7213 was 7213, checked in by gkronber, 12 years ago

#1081 merged r7103:7209 from trunk into time series branch

File size: 17.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Clients.Hive.Jobs;
26using HeuristicLab.Collections;
27using HeuristicLab.Common;
28using HeuristicLab.Optimization;
29using HeuristicLab.PluginInfrastructure;
30
31namespace HeuristicLab.Clients.Hive {
32  public class OptimizerHiveTask : HiveTask<OptimizerTask> {
33
34    #region Constructors and Cloning
35    public OptimizerHiveTask() { }
36    public OptimizerHiveTask(IOptimizer optimizer)
37      : this() {
38      this.ItemTask = new OptimizerTask(optimizer);
39    }
40    public OptimizerHiveTask(OptimizerTask optimizerJob)
41      : this() {
42      this.ItemTask = optimizerJob;
43    }
44    protected OptimizerHiveTask(OptimizerHiveTask original, Cloner cloner)
45      : base(original, cloner) {
46    }
47    public override IDeepCloneable Clone(Cloner cloner) {
48      return new OptimizerHiveTask(this, cloner);
49    }
50    #endregion
51
52    /// <summary>
53    /// if this.Optimizer is an experiment
54    ///   Uses the child-optimizers of this.HiveTask and creates HiveTask-childs
55    /// if this.Optimizer is a batchrun
56    ///   Creates a number of child-jobs according to repetitions
57    /// </summary>
58    protected override void UpdateChildHiveTasks() {
59      base.UpdateChildHiveTasks();
60      if (Task != null && syncTasksWithOptimizers) {
61        if (!ItemTask.ComputeInParallel) {
62          this.childHiveTasks.Clear();
63        } else {
64          if (ItemTask.Item is Optimization.Experiment) {
65            Optimization.Experiment experiment = (Optimization.Experiment)ItemTask.Item;
66            foreach (IOptimizer childOpt in experiment.Optimizers) {
67              var optimizerHiveTask = new OptimizerHiveTask(childOpt);
68              optimizerHiveTask.Task.Priority = Task.Priority; //inherit priority from parent
69              this.childHiveTasks.Add(optimizerHiveTask);
70            }
71          } else if (ItemTask.Item is Optimization.BatchRun) {
72            Optimization.BatchRun batchRun = ItemTask.OptimizerAsBatchRun;
73            if (batchRun.Optimizer != null) {
74              while (this.childHiveTasks.Count < batchRun.Repetitions) {
75                var optimizerHiveTask = new OptimizerHiveTask(batchRun.Optimizer);
76                optimizerHiveTask.Task.Priority = Task.Priority;
77                this.childHiveTasks.Add(optimizerHiveTask);
78              }
79              while (this.childHiveTasks.Count > batchRun.Repetitions) {
80                this.childHiveTasks.Remove(this.childHiveTasks.Last());
81              }
82            }
83          }
84        }
85      }
86    }
87
88    protected override void RegisterItemTaskEvents() {
89      base.RegisterItemTaskEvents();
90      if (ItemTask != null) {
91        if (ItemTask.Item is Optimization.Experiment) {
92          Optimization.Experiment experiment = ItemTask.OptimizerAsExperiment;
93          experiment.Optimizers.ItemsAdded += new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_ItemsAdded);
94          experiment.Optimizers.ItemsReplaced += new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_ItemsReplaced);
95          experiment.Optimizers.ItemsRemoved += new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_ItemsRemoved);
96          experiment.Optimizers.CollectionReset += new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_CollectionReset);
97        } else if (ItemTask.Item is Optimization.BatchRun) {
98          Optimization.BatchRun batchRun = ItemTask.OptimizerAsBatchRun;
99          batchRun.RepetitionsChanged += new EventHandler(batchRun_RepetitionsChanged);
100          batchRun.OptimizerChanged += new EventHandler(batchRun_OptimizerChanged);
101        }
102      }
103    }
104    protected override void DergisterItemTaskEvents() {
105      base.DergisterItemTaskEvents();
106      if (ItemTask != null) {
107        if (ItemTask.Item is Optimization.Experiment) {
108          Optimization.Experiment experiment = ItemTask.OptimizerAsExperiment;
109          experiment.Optimizers.ItemsAdded -= new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_ItemsAdded);
110          experiment.Optimizers.ItemsReplaced -= new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_ItemsReplaced);
111          experiment.Optimizers.ItemsRemoved -= new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_ItemsRemoved);
112          experiment.Optimizers.CollectionReset -= new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_CollectionReset);
113        } else if (ItemTask.Item is Optimization.BatchRun) {
114          Optimization.BatchRun batchRun = ItemTask.OptimizerAsBatchRun;
115          batchRun.RepetitionsChanged -= new EventHandler(batchRun_RepetitionsChanged);
116          batchRun.OptimizerChanged -= new EventHandler(batchRun_OptimizerChanged);
117        }
118      }
119    }
120
121    private void batchRun_OptimizerChanged(object sender, EventArgs e) {
122      if (syncTasksWithOptimizers) {
123        UpdateChildHiveTasks();
124      }
125    }
126
127    private void batchRun_RepetitionsChanged(object sender, EventArgs e) {
128      if (syncTasksWithOptimizers) {
129        UpdateChildHiveTasks();
130      }
131    }
132
133    private void Optimizers_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<IOptimizer>> e) {
134      if (syncTasksWithOptimizers && this.ItemTask.ComputeInParallel) {
135        childHiveTasksLock.EnterWriteLock();
136        try {
137          foreach (var item in e.Items) {
138            if (GetChildByOptimizer(item.Value) == null && item.Value.Name != "Placeholder") {
139              this.childHiveTasks.Add(new OptimizerHiveTask(item.Value));
140            }
141          }
142        } finally { childHiveTasksLock.ExitWriteLock(); }
143      }
144    }
145    private void Optimizers_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<IndexedItem<IOptimizer>> e) {
146      if (syncTasksWithOptimizers && this.ItemTask.ComputeInParallel) {
147        childHiveTasksLock.EnterWriteLock();
148        try {
149          foreach (var item in e.OldItems) {
150            this.childHiveTasks.Remove(this.GetChildByOptimizer(item.Value));
151          }
152          foreach (var item in e.Items) {
153            if (GetChildByOptimizer(item.Value) == null && item.Value.Name != "Placeholder") {
154              this.childHiveTasks.Add(new OptimizerHiveTask(item.Value));
155            }
156          }
157        } finally { childHiveTasksLock.ExitWriteLock(); }
158      }
159    }
160    private void Optimizers_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<IOptimizer>> e) {
161      if (syncTasksWithOptimizers && this.ItemTask.ComputeInParallel) {
162        childHiveTasksLock.EnterWriteLock();
163        try {
164          foreach (var item in e.Items) {
165            this.childHiveTasks.Remove(this.GetChildByOptimizer(item.Value));
166          }
167        } finally { childHiveTasksLock.ExitWriteLock(); }
168      }
169    }
170    private void Optimizers_CollectionReset(object sender, CollectionItemsChangedEventArgs<IndexedItem<IOptimizer>> e) {
171      if (syncTasksWithOptimizers && this.ItemTask.ComputeInParallel) {
172        childHiveTasksLock.EnterWriteLock();
173        try {
174          foreach (var item in e.Items) {
175            this.childHiveTasks.Remove(this.GetChildByOptimizer(item.Value));
176          }
177        } finally { childHiveTasksLock.ExitWriteLock(); }
178      }
179    }
180
181    /// <summary>
182    /// if this.Optimizer is Experiment
183    ///   replace the child-optimizer in the experiment
184    /// if this.Optimizer is BatchRun
185    ///   add the runs from the optimizerTask to the batchrun and replace the Optimizer
186    /// </summary>
187    public override void IntegrateChild(ItemTask task, Guid childJobId) {
188      var optimizerTask = (OptimizerTask)task;
189      syncTasksWithOptimizers = false; // don't sync with optimizers during this method
190
191      if (this.ItemTask != null && this.ItemTask.Item != null) {
192        if (this.ItemTask.Item is Optimization.Experiment) {
193          UpdateOptimizerInExperiment(this.ItemTask.OptimizerAsExperiment, optimizerTask);
194        } else if (this.ItemTask.Item is Optimization.BatchRun) {
195          UpdateOptimizerInBatchRun(this.ItemTask.OptimizerAsBatchRun, optimizerTask);
196        }
197      }
198
199      childHiveTasksLock.EnterReadLock();
200      OptimizerHiveTask child = (OptimizerHiveTask)this.ChildHiveTasks.Single(j => j.Task.Id == childJobId);
201      try {
202        if (!optimizerTask.ComputeInParallel) {
203          child.syncTasksWithOptimizers = false;
204          child.ItemTask = optimizerTask;
205          child.syncTasksWithOptimizers = true;
206        }
207      } finally { childHiveTasksLock.ExitReadLock(); }
208      syncTasksWithOptimizers = true;
209    }
210
211    /// <summary>
212    /// Adds the runs from the optimizerTask to the batchrun and replaces the Optimizer
213    /// Sideeffect: the optimizerTask.Optimizer will be prepared (scopes are deleted and executionstate will be reset)
214    /// </summary>
215    private void UpdateOptimizerInBatchRun(BatchRun batchRun, OptimizerTask optimizerTask) {
216      if (batchRun.Optimizer == null) {
217        batchRun.Optimizer = (IOptimizer)optimizerTask.Item; // only set the first optimizer as Optimizer. if every time the Optimizer would be set, the runs would be cleared each time
218      }
219      foreach (IRun run in optimizerTask.Item.Runs) {
220        if (!batchRun.Runs.Contains(run)) {
221          run.Name = GetNewRunName(run, batchRun.Runs);
222          batchRun.Runs.Add(run);
223        }
224      }
225    }
226
227    /// <summary>
228    /// replace the child-optimizer in the experiment
229    /// Sideeffect: the optimizerTask.Optimizer will be prepared (scopes are deleted and executionstate will be reset)
230    /// </summary>
231    private void UpdateOptimizerInExperiment(Optimization.Experiment experiment, OptimizerTask optimizerTask) {
232      if (optimizerTask.IndexInParentOptimizerList < 0)
233        throw new IndexOutOfRangeException("IndexInParentOptimizerList must be equal or greater than zero! The Task is invalid and the optimizer-tree cannot be reassembled.");
234
235      while (experiment.Optimizers.Count < optimizerTask.IndexInParentOptimizerList) {
236        experiment.Optimizers.Add(new UserDefinedAlgorithm("Placeholder")); // add dummy-entries to Optimizers so that its possible to insert the optimizerTask at the correct position
237      }
238      if (experiment.Optimizers.Count < optimizerTask.IndexInParentOptimizerList + 1) {
239        experiment.Optimizers.Add(optimizerTask.Item);
240      } else {
241        // if ComputeInParallel==true, don't replace the optimizer (except it is still a Placeholder)
242        // this is because Jobs with ComputeInParallel get submitted to hive with their child-optimizers deleted
243        if (!optimizerTask.ComputeInParallel || experiment.Optimizers[optimizerTask.IndexInParentOptimizerList].Name == "Placeholder") {
244          experiment.Optimizers[optimizerTask.IndexInParentOptimizerList] = optimizerTask.Item;
245        }
246      }
247    }
248
249    /// <summary>
250    /// Sets the IndexInParentOptimizerList property of the OptimizerJob
251    /// according to the position in the OptimizerList of the parentHiveTask.Task
252    /// Recursively updates all the child-jobs as well
253    /// </summary>
254    internal void SetIndexInParentOptimizerList(OptimizerHiveTask parentHiveTask) {
255      if (parentHiveTask != null) {
256        if (parentHiveTask.ItemTask.Item is Optimization.Experiment) {
257          this.ItemTask.IndexInParentOptimizerList = parentHiveTask.ItemTask.OptimizerAsExperiment.Optimizers.IndexOf(this.ItemTask.Item);
258        } else if (parentHiveTask.ItemTask.Item is Optimization.BatchRun) {
259          this.ItemTask.IndexInParentOptimizerList = 0;
260        } else {
261          throw new NotSupportedException("Only Experiment and BatchRuns are supported");
262        }
263      }
264      childHiveTasksLock.EnterReadLock();
265      try {
266        foreach (OptimizerHiveTask child in childHiveTasks) {
267          child.SetIndexInParentOptimizerList(this);
268        }
269      } finally { childHiveTasksLock.ExitReadLock(); }
270    }
271
272    public override void AddChildHiveTask(HiveTask hiveTask) {
273      base.AddChildHiveTask(hiveTask);
274      var optimizerHiveJob = (OptimizerHiveTask)hiveTask;
275      syncTasksWithOptimizers = false;
276      if (this.ItemTask != null && optimizerHiveJob.ItemTask != null) {
277        // if task is in state Paused, it has to preserve its ResultCollection, which is cleared when a optimizer is added to an experiment
278        OptimizerTask optimizerJobClone = null;
279        if (optimizerHiveJob.Task.State == TaskState.Paused) {
280          optimizerJobClone = (OptimizerTask)optimizerHiveJob.ItemTask.Clone();
281        }
282
283        if (this.ItemTask.Item is Optimization.Experiment) {
284          if (!this.ItemTask.OptimizerAsExperiment.Optimizers.Contains(optimizerHiveJob.ItemTask.Item)) {
285            UpdateOptimizerInExperiment(this.ItemTask.OptimizerAsExperiment, optimizerHiveJob.ItemTask);
286          }
287        } else if (this.ItemTask.Item is Optimization.BatchRun) {
288          UpdateOptimizerInBatchRun(this.ItemTask.OptimizerAsBatchRun, optimizerHiveJob.ItemTask);
289        }
290
291        if (optimizerHiveJob.Task.State == TaskState.Paused) {
292          optimizerHiveJob.ItemTask = optimizerJobClone;
293        }
294      }
295      syncTasksWithOptimizers = true;
296    }
297
298    /// <summary>
299    /// Creates a TaskData object containing the Task and the IJob-Object as byte[]
300    /// </summary>
301    /// <param name="withoutChildOptimizers">
302    ///   if true the Child-Optimizers will not be serialized (if the task contains an Experiment)
303    /// </param>
304    public override TaskData GetAsTaskData(bool withoutChildOptimizers, out List<IPluginDescription> plugins) {
305      plugins = new List<IPluginDescription>();
306      if (this.itemTask == null) // || this.jobItem.Optimizer == null
307        return null;
308
309      IEnumerable<Type> usedTypes;
310      byte[] jobByteArray;
311      if (withoutChildOptimizers && this.ItemTask.Item is Optimization.Experiment) {
312        OptimizerTask clonedJob = (OptimizerTask)this.ItemTask.Clone(); // use a cloned task, so that the childHiveJob don't get confused
313        clonedJob.OptimizerAsExperiment.Optimizers.Clear();
314        jobByteArray = PersistenceUtil.Serialize(clonedJob, out usedTypes);
315      } else if (withoutChildOptimizers && this.ItemTask.Item is Optimization.BatchRun) {
316        OptimizerTask clonedJob = (OptimizerTask)this.ItemTask.Clone();
317        clonedJob.OptimizerAsBatchRun.Optimizer = null;
318        jobByteArray = PersistenceUtil.Serialize(clonedJob, out usedTypes);
319      } else if (this.ItemTask.Item is IAlgorithm) {
320        ((IAlgorithm)this.ItemTask.Item).StoreAlgorithmInEachRun = false; // avoid storing the algorithm in runs to reduce size
321        jobByteArray = PersistenceUtil.Serialize(this.ItemTask, out usedTypes);
322      } else {
323        jobByteArray = PersistenceUtil.Serialize(this.ItemTask, out usedTypes);
324      }
325
326      TaskData jobData = new TaskData() { TaskId = task.Id, Data = jobByteArray };
327      PluginUtil.CollectDeclaringPlugins(plugins, usedTypes);
328      return jobData;
329    }
330
331    public OptimizerHiveTask GetChildByOptimizerJob(OptimizerTask optimizerJob) {
332      childHiveTasksLock.EnterReadLock();
333      try {
334        foreach (OptimizerHiveTask child in childHiveTasks) {
335          if (child.ItemTask == optimizerJob)
336            return child;
337        }
338        return null;
339      } finally { childHiveTasksLock.ExitReadLock(); }
340    }
341
342    public HiveTask<OptimizerTask> GetChildByOptimizer(IOptimizer optimizer) {
343      childHiveTasksLock.EnterReadLock();
344      try {
345        foreach (OptimizerHiveTask child in childHiveTasks) {
346          if (child.ItemTask.Item == optimizer)
347            return child;
348        }
349        return null;
350      } finally { childHiveTasksLock.ExitReadLock(); }
351    }
352
353    #region Helpers
354    /// <summary>
355    /// Parses the run numbers out of runs and renames the run to the next number
356    /// </summary>
357    private static string GetNewRunName(IRun run, RunCollection runs) {
358      int idx = run.Name.IndexOf("Run ") + 4;
359
360      if (idx == 3 || runs.Count == 0)
361        return run.Name;
362
363      int maxRunNumber = int.MinValue;
364      foreach (IRun r in runs) {
365        int number = GetRunNumber(r.Name);
366        maxRunNumber = Math.Max(maxRunNumber, number);
367      }
368
369      return run.Name.Substring(0, idx) + (maxRunNumber + 1).ToString();
370    }
371
372    /// <summary>
373    /// Parses the number of a Run out of its name. Example "Genetic Algorithm Run 3" -> 3
374    /// </summary>
375    private static int GetRunNumber(string runName) {
376      int idx = runName.IndexOf("Run ") + 4;
377      if (idx == 3) {
378        return 0;
379      } else {
380        return int.Parse(runName.Substring(idx, runName.Length - idx));
381      }
382    }
383    #endregion
384  }
385}
Note: See TracBrowser for help on using the repository browser.