Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ScatterSearch (trunk integration)/HeuristicLab.Clients.Hive.JobManager/3.3/Views/HiveResourceSelector.cs @ 8086

Last change on this file since 8086 was 8086, checked in by jkarder, 12 years ago

#1331:

  • synced branch with trunk
  • added custom interface (ISimilarityBasedOperator) to mark operators that conduct similarity calculation
  • similarity calculators are now parameterized by the algorithm
  • deleted SolutionPool2TierUpdateMethod
  • deleted KnapsackMultipleGuidesPathRelinker
  • moved IImprovementOperator, IPathRelinker and ISimilarityCalculator to HeuristicLab.Optimization
  • added parameter descriptions
  • fixed plugin references
  • fixed count of EvaluatedSolutions
  • fixed check for duplicate solutions
  • minor code improvements
File size: 13.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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.Drawing;
25using System.Linq;
26using System.Text;
27using System.Windows.Forms;
28using HeuristicLab.Clients.Hive.JobManager.ExtensionMethods;
29using HeuristicLab.Core;
30using HeuristicLab.Core.Views;
31using HeuristicLab.MainForm;
32using HeuristicLab.MainForm.WindowsForms;
33
34namespace HeuristicLab.Clients.Hive.JobManager.Views {
35  [View("Hive Resource Selector View")]
36  [Content(typeof(IItemList<Resource>), true)]
37  public partial class HiveResourceSelector : ItemView, IDisposable {
38    private const int slaveImageIndex = 0;
39    private const int slaveGroupImageIndex = 1;
40    private string currentSearchString;
41    private ISet<TreeNode> mainTreeNodes;
42    private ISet<TreeNode> filteredTreeNodes;
43    private ISet<TreeNode> nodeStore;
44
45    private ISet<Resource> selectedResources;
46    public ISet<Resource> SelectedResources {
47      get { return selectedResources; }
48      set { selectedResources = value; }
49    }
50
51    private ProgressView progressView;
52    public ProgressView ProgressView {
53      get { return progressView; }
54      set { progressView = value; }
55    }
56
57    public new IItemList<Resource> Content {
58      get { return (IItemList<Resource>)base.Content; }
59      set { base.Content = value; }
60    }
61
62    public HiveResourceSelector() {
63      InitializeComponent();
64      mainTreeNodes = new HashSet<TreeNode>();
65      filteredTreeNodes = new HashSet<TreeNode>();
66      nodeStore = new HashSet<TreeNode>();
67      selectedResources = new HashSet<Resource>();
68      imageList.Images.Add(HeuristicLab.Common.Resources.VSImageLibrary.MonitorLarge);
69      imageList.Images.Add(HeuristicLab.Common.Resources.VSImageLibrary.NetworkCenterLarge);
70    }
71
72    public void StartProgressView() {
73      if (InvokeRequired) {
74        Invoke(new Action(StartProgressView));
75      } else {
76        if (progressView == null) {
77          IProgress prog = new Progress();
78          prog.Status = "Downloading resources. Please be patient.";
79          progressView = new ProgressView(this, prog);
80        }
81      }
82    }
83
84    public void FinishProgressView() {
85      if (InvokeRequired) {
86        Invoke(new Action(FinishProgressView));
87      } else {
88        if (progressView != null) {
89          progressView.Finish();
90          progressView = null;
91          SetEnabledStateOfControls();
92        }
93      }
94    }
95
96    protected override void OnContentChanged() {
97      base.OnContentChanged();
98
99      if (Content != null) {
100        selectedResources = new HashSet<Resource>(Content.Where(x => selectedResources.Any(y => x.Id == y.Id)));
101        UpdateMainTree();
102        ExtractStatistics();
103      } else {
104        mainTreeNodes.Clear();
105        UpdateFilteredTree();
106      }
107    }
108
109    #region MainTree Methods
110    private void UpdateMainTree() {
111      mainTreeNodes.Clear();
112
113      foreach (Resource g in Content) {
114        if (g.GetType() == typeof(SlaveGroup)) {
115          //root node
116          if (g.ParentResourceId == null) {
117            TreeNode tn = new TreeNode();
118            tn.ImageIndex = slaveGroupImageIndex;
119            tn.SelectedImageIndex = tn.ImageIndex;
120
121            tn.Tag = g;
122            tn.Text = g.Name;
123            tn.Checked = selectedResources.Any(x => x.Id == g.Id);
124
125            BuildMainTree(tn);
126            mainTreeNodes.Add(tn);
127          }
128        }
129      }
130      UpdateFilteredTree();
131    }
132
133    private void BuildMainTree(TreeNode tn) {
134      foreach (Resource r in Content.Where(s => s.ParentResourceId != null && s.ParentResourceId == ((Resource)tn.Tag).Id)) {
135        TreeNode stn = new TreeNode(r.Name);
136        if (r is Slave) stn.ImageIndex = slaveImageIndex;
137        else if (r is SlaveGroup) stn.ImageIndex = slaveGroupImageIndex;
138        stn.SelectedImageIndex = stn.ImageIndex;
139        stn.Tag = r;
140        stn.Checked = selectedResources.Any(x => x.Id == r.Id);
141        tn.Nodes.Add(stn);
142        mainTreeNodes.Add(stn);
143
144        BuildMainTree(stn);
145      }
146    }
147    #endregion
148
149    #region FilteredTree Methods
150    private void UpdateFilteredTree() {
151      filteredTreeNodes.Clear();
152      foreach (TreeNode n in mainTreeNodes) {
153        n.BackColor = SystemColors.Window;
154        if (currentSearchString == null || ((Resource)n.Tag).Name.ToLower().Contains(currentSearchString)) {
155          n.BackColor = string.IsNullOrEmpty(currentSearchString) ? SystemColors.Window : Color.LightBlue;
156          filteredTreeNodes.Add(n);
157          TraverseParentNodes(n);
158        }
159      }
160      UpdateResourceTree();
161    }
162
163    private void TraverseParentNodes(TreeNode node) {
164      if (node != null) {
165        for (TreeNode parent = node.Parent; parent != null; parent = parent.Parent)
166          filteredTreeNodes.Add(parent);
167      }
168    }
169    #endregion
170
171    #region ResourceTree Methods
172    private void UpdateResourceTree() {
173      resourcesTreeView.Nodes.Clear();
174      nodeStore.Clear();
175
176      foreach (TreeNode node in filteredTreeNodes) {
177        var clone = nodeStore.SingleOrDefault(x => ((Resource)x.Tag).Id == ((Resource)node.Tag).Id);
178        if (clone == null) {
179          clone = (TreeNode)node.Clone();
180          nodeStore.Add(clone);
181          clone.Nodes.Clear();
182        }
183        foreach (TreeNode child in node.Nodes)
184          if (filteredTreeNodes.Any(x => ((Resource)x.Tag).Id == ((Resource)child.Tag).Id)) {
185            var childClone = nodeStore.SingleOrDefault(x => ((Resource)x.Tag).Id == ((Resource)child.Tag).Id);
186            if (childClone == null) {
187              childClone = (TreeNode)child.Clone();
188              nodeStore.Add(childClone);
189              childClone.Nodes.Clear();
190            }
191            clone.Nodes.Add(childClone);
192          }
193      }
194      resourcesTreeView.Nodes.AddRange(nodeStore.Where(x => ((Resource)x.Tag).ParentResourceId == null).ToArray());
195      if (string.IsNullOrEmpty(currentSearchString)) ExpandSlaveGroupNodes();
196      else resourcesTreeView.ExpandAll();
197    }
198    #endregion
199
200    #region Events
201    private void resourcesTreeView_AfterCheck(object sender, TreeViewEventArgs e) {
202      if (e.Action != TreeViewAction.Unknown) {
203        if (e.Node.Checked) {
204          IncludeChildNodes(mainTreeNodes.SingleOrDefault(x => ((Resource)x.Tag).Id == ((Resource)e.Node.Tag).Id));
205          IncludeParentNodes(mainTreeNodes.SingleOrDefault(x => ((Resource)x.Tag).Id == ((Resource)e.Node.Tag).Id));
206        } else {
207          ExcludeChildNodes(mainTreeNodes.SingleOrDefault(x => ((Resource)x.Tag).Id == ((Resource)e.Node.Tag).Id));
208          ExcludeParentNodes(mainTreeNodes.SingleOrDefault(x => ((Resource)x.Tag).Id == ((Resource)e.Node.Tag).Id));
209        }
210        ExtractStatistics();
211      }
212    }
213
214    private void resourcesTreeView_AfterSelect(object sender, TreeViewEventArgs e) {
215      if (e.Action != TreeViewAction.Unknown) {
216        ExtractStatistics(e.Node);
217      }
218    }
219
220    private void searchTextBox_TextChanged(object sender, System.EventArgs e) {
221      currentSearchString = searchTextBox.Text.ToLower();
222      UpdateFilteredTree();
223    }
224    #endregion
225
226    #region Helpers
227    private void IncludeChildNodes(TreeNode node) {
228      if (node != null) {
229        node.Checked = true;
230        selectedResources.Add((Resource)node.Tag);
231        AdjustNodeCheckedState(node);
232        foreach (TreeNode n in node.Nodes) IncludeChildNodes(n);
233      }
234    }
235
236    private void IncludeParentNodes(TreeNode node) {
237      if (node != null && node.Parent != null) {
238        TreeNode parent = node.Parent;
239        if (parent.Nodes.OfType<TreeNode>().All(x => x.Checked)) {
240          parent.Checked = true;
241          selectedResources.Add((Resource)parent.Tag);
242          AdjustNodeCheckedState(parent);
243          IncludeParentNodes(parent);
244        }
245      }
246    }
247
248    private void ExcludeChildNodes(TreeNode node) {
249      if (node != null) {
250        node.Checked = false;
251        selectedResources.Remove((Resource)node.Tag);
252        AdjustNodeCheckedState(node);
253        foreach (TreeNode n in node.Nodes) ExcludeChildNodes(n);
254      }
255    }
256
257    private void ExcludeParentNodes(TreeNode node) {
258      if (node != null) {
259        node.Checked = false;
260        selectedResources.Remove((Resource)node.Tag);
261        AdjustNodeCheckedState(node);
262        ExcludeParentNodes(node.Parent);
263      }
264    }
265
266    private void AdjustNodeCheckedState(TreeNode node) {
267      var filterdNode = filteredTreeNodes.SingleOrDefault(x => ((Resource)x.Tag).Id == ((Resource)node.Tag).Id);
268      var storedNode = nodeStore.SingleOrDefault(x => ((Resource)x.Tag).Id == ((Resource)node.Tag).Id);
269      if (filterdNode != null) filterdNode.Checked = node.Checked;
270      if (storedNode != null) storedNode.Checked = node.Checked;
271    }
272
273    private void ExpandSlaveGroupNodes() {
274      foreach (TreeNode n in nodeStore.Where(x => x.Tag is SlaveGroup)) {
275        TreeNode[] children = new TreeNode[n.Nodes.Count];
276        n.Nodes.CopyTo(children, 0);
277        if (children.Any(x => x.Tag is SlaveGroup)) n.Expand();
278      }
279    }
280
281    private void ExtractStatistics(TreeNode treeNode = null) {
282      StringBuilder sb = new StringBuilder();
283      Resource resource = treeNode == null ? null : treeNode.Tag as Resource;
284      ISet<Resource> resources = treeNode == null ? selectedResources : new HashSet<Resource>(treeNode.DescendantNodes().Select(x => x.Tag as Resource)); ;
285      IEnumerable<SlaveGroup> slaveGroups = resources.OfType<SlaveGroup>();
286      IEnumerable<Slave> slaves = resources.OfType<Slave>();
287      int cpuSpeed = 0, cores = 0, freeCores = 0, memory = 0, freeMemory = 0;
288      string contextString = treeNode == null ? "Selected" : "Included";
289
290      if (resources.Any() || resource != null) {
291        foreach (Slave s in slaves) {
292          cpuSpeed += s.CpuSpeed.GetValueOrDefault();
293          cores += s.Cores.GetValueOrDefault();
294          freeCores += s.FreeCores.GetValueOrDefault();
295          memory += s.Memory.GetValueOrDefault();
296          freeMemory += s.FreeMemory.GetValueOrDefault();
297        }
298        if (resource != null) {
299          if (resource is SlaveGroup) sb.Append("Slave group: ");
300          else if (resource is Slave) {
301            sb.Append("Slave: ");
302            if (!resources.Any()) {
303              Slave s = resource as Slave;
304              cpuSpeed = s.CpuSpeed.GetValueOrDefault();
305              cores = s.Cores.GetValueOrDefault();
306              freeCores = s.FreeCores.GetValueOrDefault();
307              memory = s.Memory.GetValueOrDefault();
308              freeMemory = s.FreeMemory.GetValueOrDefault();
309            }
310          }
311          sb.AppendLine(string.Format("{0}", resource.Name));
312        }
313        if (resource == null || resource is SlaveGroup) {
314          if (resources.Any()) {
315            sb.AppendFormat("{0} slave groups ({1}): ", contextString, slaveGroups.Count());
316            foreach (SlaveGroup sg in slaveGroups) sb.AppendFormat("{0}; ", sg.Name);
317            sb.AppendLine();
318            sb.AppendFormat("{0} slaves ({1}): ", contextString, slaves.Count());
319            foreach (Slave s in slaves) sb.AppendFormat("{0}; ", s.Name);
320            sb.AppendLine();
321          } else {
322            sb.Append("The selection does not inlcude any further resources.");
323          }
324        }
325        sb.AppendLine();
326        sb.AppendLine(string.Format("CPU speed: {0} MHz", cpuSpeed));
327        if (resources.Any()) sb.AppendLine(string.Format("Avg. CPU speed: {0:0.00} MHz", (double)cpuSpeed / resources.Count()));
328        sb.AppendLine(string.Format("Cores: {0}", cores));
329        sb.AppendLine(string.Format("Free cores: {0}", freeCores));
330        if (resources.Any()) sb.AppendLine(string.Format("Avg. free cores: {0:0.00}", (double)freeCores / resources.Count()));
331        sb.AppendLine(string.Format("Memory: {0} MB", memory));
332        sb.AppendFormat("Free memory: {0} MB", freeMemory);
333        if (resources.Any()) sb.Append(string.Format("{0}Avg. free memory: {1:0.00} MB", Environment.NewLine, (double)freeMemory / resources.Count()));
334      } else {
335        sb.Append("No resources selected.");
336      }
337
338      descriptionTextBox.Text = sb.ToString();
339    }
340    #endregion
341  }
342}
Note: See TracBrowser for help on using the repository browser.