Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OKB (trunk integration)/HeuristicLab.Clients.OKB/3.3/Query/Views/QueryView.cs @ 7589

Last change on this file since 7589 was 7589, checked in by ascheibe, 13 years ago

#1174 values of returned runs can now be limited

File size: 9.6 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;
24using System.Collections.Generic;
25using System.IO;
26using System.Linq;
27using System.Threading;
28using System.Threading.Tasks;
29using System.Windows.Forms;
30using HeuristicLab.Core;
31using HeuristicLab.MainForm;
32using HeuristicLab.MainForm.WindowsForms;
33using HeuristicLab.Optimization;
34using HeuristicLab.Persistence.Default.Xml;
35using HeuristicLab.PluginInfrastructure;
36
37namespace HeuristicLab.Clients.OKB.Query {
38  [View("OKB Query")]
39  [Content(typeof(QueryClient), true)]
40  public sealed partial class QueryView : AsynchronousContentView {
41    private CancellationTokenSource cancellationTokenSource;
42    private CombinedFilterView combinedFilterView;
43
44    public new QueryClient Content {
45      get { return (QueryClient)base.Content; }
46      set { base.Content = value; }
47    }
48
49    public QueryView() {
50      InitializeComponent();
51    }
52
53    protected override void DeregisterContentEvents() {
54      Content.Refreshing -= new EventHandler(Content_Refreshing);
55      Content.Refreshed -= new EventHandler(Content_Refreshed);
56      base.DeregisterContentEvents();
57    }
58
59    protected override void RegisterContentEvents() {
60      base.RegisterContentEvents();
61      Content.Refreshing += new EventHandler(Content_Refreshing);
62      Content.Refreshed += new EventHandler(Content_Refreshed);
63    }
64
65    protected override void OnContentChanged() {
66      base.OnContentChanged();
67      CreateFilterView();
68      runCollectionView.Content = null;
69    }
70
71    protected override void SetEnabledStateOfControls() {
72      base.SetEnabledStateOfControls();
73      resultsGroupBox.Enabled = combinedFilterView != null;
74    }
75
76    #region Load Results
77    private void LoadResultsAsync(int batchSize) {
78      bool includeBinaryValues = includeBinaryValuesCheckBox.Checked;
79      IEnumerable<ValueName> valueNames = constraintsCheckedListBox.CheckedItems.Cast<ValueName>();
80
81      Cursor = Cursors.AppStarting;
82      resultsInfoLabel.Text = "Loading Results ...";
83      resultsProgressBar.Value = 0;
84      resultsProgressBar.Step = batchSize;
85      abortButton.Enabled = true;
86      resultsInfoPanel.Visible = true;
87      splitContainer.Enabled = false;
88      cancellationTokenSource = new CancellationTokenSource();
89      CancellationToken cancellationToken = cancellationTokenSource.Token;
90
91      Task task = Task.Factory.StartNew(() => {
92        var ids = QueryClient.Instance.GetRunIds(combinedFilterView.Content);
93        int idsCount = ids.Count();
94
95        Invoke(new Action(() => {
96          resultsInfoLabel.Text = "Loaded 0 of " + idsCount.ToString() + " Results ...";
97          resultsProgressBar.Maximum = idsCount;
98        }));
99
100        RunCollection runs = new RunCollection();
101        runCollectionView.Content = runs;
102        while (ids.Count() > 0) {
103          cancellationToken.ThrowIfCancellationRequested();
104          if (AllValueNamesChecked()) {
105            runs.AddRange(QueryClient.Instance.GetRuns(ids.Take(batchSize), includeBinaryValues).Select(x => ConvertToOptimizationRun(x)));
106          } else {
107            runs.AddRange(QueryClient.Instance.GetRunsWithValues(ids.Take(batchSize), includeBinaryValues, valueNames).Select(x => ConvertToOptimizationRun(x)));
108          }
109          ids = ids.Skip(batchSize);
110          Invoke(new Action(() => {
111            resultsInfoLabel.Text = "Loaded " + runs.Count + " of " + idsCount.ToString() + " Results ...";
112            resultsProgressBar.PerformStep();
113          }));
114        }
115      }, cancellationToken);
116      task.ContinueWith(t => {
117        Invoke(new Action(() => {
118          cancellationTokenSource.Dispose();
119          cancellationTokenSource = null;
120          resultsInfoPanel.Visible = false;
121          splitContainer.Enabled = true;
122          this.Cursor = Cursors.Default;
123          SetEnabledStateOfControls();
124          try {
125            t.Wait();
126          }
127          catch (AggregateException ex) {
128            try {
129              ex.Flatten().Handle(x => x is OperationCanceledException);
130            }
131            catch (AggregateException remaining) {
132              if (remaining.InnerExceptions.Count == 1) ErrorHandling.ShowErrorDialog(this, "Refresh results failed.", remaining.InnerExceptions[0]);
133              else ErrorHandling.ShowErrorDialog(this, "Refresh results failed.", remaining);
134            }
135          }
136        }));
137      });
138    }
139    #endregion
140
141    private void Content_Refreshing(object sender, EventArgs e) {
142      if (InvokeRequired) {
143        Invoke(new EventHandler(Content_Refreshing), sender, e);
144      } else {
145        Cursor = Cursors.AppStarting;
146        filtersInfoPanel.Visible = true;
147        splitContainer.Enabled = false;
148      }
149    }
150    private void Content_Refreshed(object sender, EventArgs e) {
151      if (InvokeRequired) {
152        Invoke(new EventHandler(Content_Refreshed), sender, e);
153      } else {
154        CreateFilterView();
155        CreateConstraintsView();
156        filtersInfoPanel.Visible = false;
157        splitContainer.Enabled = true;
158        Cursor = Cursors.Default;
159        SetEnabledStateOfControls();
160      }
161    }
162
163    private void refreshFiltersButton_Click(object sender, EventArgs e) {
164      Content.RefreshAsync(new Action<Exception>((Exception ex) => ErrorHandling.ShowErrorDialog(this, "Refresh failed.", ex)));
165    }
166
167    private void refreshResultsButton_Click(object sender, EventArgs e) {
168      LoadResultsAsync(10);
169    }
170
171    private void abortButton_Click(object sender, EventArgs e) {
172      if (cancellationTokenSource != null) cancellationTokenSource.Cancel();
173      abortButton.Enabled = false;
174    }
175
176    private void CreateFilterView() {
177      combinedFilterView = null;
178      filterPanel.Controls.Clear();
179      if ((Content != null) && (Content.Filters != null)) {
180        CombinedFilter filter = Content.Filters.OfType<CombinedFilter>().Where(x => x.Operation == BooleanOperation.And).FirstOrDefault();
181        if (filter != null) {
182          combinedFilterView = (CombinedFilterView)MainFormManager.CreateView(typeof(CombinedFilterView));
183          combinedFilterView.Content = (CombinedFilter)filter.Clone();
184          Control control = (Control)combinedFilterView;
185          control.Dock = DockStyle.Fill;
186          filterPanel.Controls.Add(control);
187        }
188      }
189    }
190
191    private void CreateConstraintsView() {
192      constraintsCheckedListBox.Items.Clear();
193      constraintsCheckedListBox.Items.AddRange(QueryClient.Instance.ValueNames.ToArray());
194      SetCheckedState(true);
195    }
196
197    private Optimization.IRun ConvertToOptimizationRun(Run run) {
198      Optimization.Run optRun = new Optimization.Run();
199      foreach (Value value in run.ParameterValues)
200        optRun.Parameters.Add(value.Name, ConvertToItem(value));
201      foreach (Value value in run.ResultValues)
202        optRun.Results.Add(value.Name, ConvertToItem(value));
203      return optRun;
204    }
205
206    private IItem ConvertToItem(Value value) {
207      if (value is BinaryValue) {
208        IItem item = null;
209        BinaryValue binaryValue = (BinaryValue)value;
210        if (binaryValue.Value != null) {
211          using (MemoryStream stream = new MemoryStream(binaryValue.Value)) {
212            try {
213              item = XmlParser.Deserialize<IItem>(stream);
214            }
215            catch (Exception) { }
216            stream.Close();
217          }
218        }
219        return item != null ? item : new Data.StringValue(value.DataType.Name);
220      } else if (value is BoolValue) {
221        return new Data.BoolValue(((BoolValue)value).Value);
222      } else if (value is FloatValue) {
223        return new Data.DoubleValue(((FloatValue)value).Value);
224      } else if (value is PercentValue) {
225        return new Data.PercentValue(((PercentValue)value).Value);
226      } else if (value is DoubleValue) {
227        return new Data.DoubleValue(((DoubleValue)value).Value);
228      } else if (value is IntValue) {
229        return new Data.IntValue((int)((IntValue)value).Value);
230      } else if (value is LongValue) {
231        return new Data.IntValue((int)((LongValue)value).Value);
232      } else if (value is StringValue) {
233        return new Data.StringValue(((StringValue)value).Value);
234      }
235      return null;
236    }
237
238    private void SetCheckedState(bool val) {
239      for (int i = 0; i < constraintsCheckedListBox.Items.Count; i++) {
240        constraintsCheckedListBox.SetItemChecked(i, val);
241      }
242    }
243
244    private bool AllValueNamesChecked() {
245      return constraintsCheckedListBox.Items.Count == constraintsCheckedListBox.CheckedItems.Count;
246    }
247
248    private void selectAllButton_Click(object sender, EventArgs e) {
249      SetCheckedState(true);
250    }
251
252    private void deselectAllButton_Click(object sender, EventArgs e) {
253      SetCheckedState(false);
254    }
255  }
256}
Note: See TracBrowser for help on using the repository browser.