Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2913_MatlabScriptProblemInstanceProvider/HeuristicLab.Problems.Instances.DataAnalysis.Views/3.3/Regression/Matlab/RegressionMatlabImportDialog.cs @ 15926

Last change on this file since 15926 was 15926, checked in by rhanghof, 6 years ago

#2913:

  • Added the support for importing different Matlab datatypes.
  • Added some classes and changed the import dialog for importing double arrays.
File size: 7.7 KB
Line 
1using System;
2using System.Collections;
3using System.Collections.Generic;
4using System.ComponentModel;
5using System.Data;
6using System.Drawing;
7using System.IO;
8using System.Linq;
9using System.Text;
10using System.Threading.Tasks;
11using System.Threading;
12using System.Windows.Forms;
13using HeuristicLab.Common;
14using HeuristicLab.Problems.DataAnalysis;
15using HeuristicLab.Problems.Instances.DataAnalysis.Regression.Matlab;
16using HeuristicLab.Problems.Instances.DataAnalysis.Regression.Matlab.Api;
17using HeuristicLab.Problems.Instances.DataAnalysis.Regression.Matlab.Api.Types;
18
19namespace HeuristicLab.Problems.Instances.DataAnalysis.Views.Regression.Matlab {
20  public partial class RegressionMatlabImportDialog : Form {
21    private const int TAB_INDEX_TIMESERIES = 0;
22    private const int TAB_INDEX_DOUBLE_ARRAYS = 1;
23
24    private IMatlabConnector _mlConnector;
25
26    private IMLVariablesLoader _variablesLoader;
27    private IMLVariablesLoader _timeseriesLoader;
28    private IMLVariablesLoader _doubleArraysLoader;
29
30    private CancellationTokenSource _cts = new CancellationTokenSource();
31
32    public event EventHandler<EventArgs<string>> StatusChangedEvent;
33    public event EventHandler<EventArgs<string>> ErrorOccuredEvent;
34
35    /// <summary>
36    /// Path to the Matlab file
37    /// </summary>
38    public string Path {
39      get { return ProblemTextBox.Text; }
40    }
41
42    /// <summary>
43    /// As loading the data can take much time, loaded values will be stored.
44    /// So they have not have to be loaded a secound time.
45    /// </summary>
46    private Dataset _values;
47
48    public RegressionMatlabImportType ImportType {
49      get {
50        return new RegressionMatlabImportType() {
51          Shuffle = false,
52          TrainingPercentage = TrainingTestTrackBar.Value,
53          TargetVariable = (String)TargetVariableComboBox.SelectedValue,
54          Values = _values
55        };
56      }
57    }
58
59    private IList<MLVariableInfo> _selectedTimeseries;
60    private IList<MLVariableInfo> _selectedDoubleArrays;
61
62    public IEnumerable<MLVariableInfo> SelectedVariables {
63      get {
64        return _variablesLoader.SelectedVariables;
65      }
66    }
67
68    public RegressionMatlabImportDialog() {
69      InitializeComponent();
70
71      _selectedTimeseries = new List<MLVariableInfo>();
72      _selectedDoubleArrays = new List<MLVariableInfo>();
73      _values = new Dataset();
74
75      this.FormClosed += (s, e) => DisposeMatlabConnector();
76      OpenFileButton.Click += OpenFileButtonClick;
77
78      DatatypeSelectorTabControl.SelectedIndexChanged += (s, e) => BeginInvoke((MethodInvoker)(() => DatatypeSelectorTabControlTabIndexChanged(s, e)));
79
80      LoadValuesButton.Click += LoadValuesButtonClick;
81      TrainingTestTrackBar.ValueChanged += TrainingTestTrackBarValueChanged;
82
83      StatusChangedEvent += (s, e) => BeginInvoke((MethodInvoker)(() => StatusLabel.Text = e.Value));
84      ErrorOccuredEvent += (s, e) => BeginInvoke((MethodInvoker)(() => {
85        OkButton.Enabled = false;
86        ErrorTextBox.Text = e.Value;
87        ErrorTextBox.Visible = true;
88      }));
89
90      _timeseriesLoader = new MLTimeseriesLoader(this, TimeseriesListBox);
91      _timeseriesLoader.NumberOfSelectedVariablesChanged += NumberOfSelectedVariablesChanged;
92      _doubleArraysLoader = new MLDoubleArrayLoader(this, DoubleArraysListBox);
93      _doubleArraysLoader.NumberOfSelectedVariablesChanged += NumberOfSelectedVariablesChanged;
94
95      _variablesLoader = _timeseriesLoader;
96
97    }
98
99    #region Methods for Events
100
101    private void NumberOfSelectedVariablesChanged(object s, EventArgs<int> e) {
102      LoadValuesButton.Enabled = e.Value > 0;
103    }
104
105    private void DatatypeSelectorTabControlTabIndexChanged(object s, EventArgs e) {
106      switch (DatatypeSelectorTabControl.SelectedIndex) {
107        case TAB_INDEX_TIMESERIES:
108          _variablesLoader = _timeseriesLoader;
109          break;
110        case TAB_INDEX_DOUBLE_ARRAYS:
111          _variablesLoader = _doubleArraysLoader;
112          break;
113      }
114
115      LoadValuesButton.Enabled = _variablesLoader.SelectedVariables.Count() > 0;
116    }
117
118    private void LoadValuesButtonClick(object sender, EventArgs e) {
119      _cts.Cancel();
120      _cts = new CancellationTokenSource();
121      LoadValuesAsync();
122    }
123
124    private void OpenFileButtonClick(object sender, EventArgs e) {
125      if (openFileDialog.ShowDialog(this) != DialogResult.OK) {
126        return;
127      }
128      GetVariableNamesAsync();
129      ErrorTextBox.Visible = false;
130    }
131
132    private void TrainingTestTrackBarValueChanged(object sender, System.EventArgs e) {
133      TrainingLabel.Text = "Training: " + TrainingTestTrackBar.Value + " %";
134      TestLabel.Text = "Test: " + (TrainingTestTrackBar.Maximum - TrainingTestTrackBar.Value) + " %";
135    }
136    #endregion
137
138    /// <summary>
139    /// Fires the ErrorOccuredEvent with the given text message.
140    /// </summary>
141    /// <param name="message"></param>
142    private void ErrorOccured(string message) {
143      ErrorOccuredEvent?.Invoke(this, new EventArgs<string>(message));
144    }
145
146    /// <summary>
147    /// Fires the StatusChangedEvent.
148    /// </summary>
149    /// <param name="text"></param>
150    private void UpdateStatus(string text) {
151      StatusChangedEvent?.Invoke(this, new EventArgs<string>(text));
152    }
153
154    #region Opening and disposing of the Matlab connector
155    private void OpenMatlabConnector() {
156      if (_mlConnector == null) {
157        _mlConnector = MatlabApiFactory.CreateMatlabConnector();
158        _mlConnector.ErrorOccuredEvent += ErrorOccured;
159      }
160    }
161
162    private async void DisposeMatlabConnector() {
163      UpdateStatus("Closing Matlab");
164      await Task.Run(() => {
165        if (_mlConnector != null) {
166          _mlConnector.Dispose();
167        }
168      });
169    }
170    #endregion
171
172
173    /// <summary>
174    /// This method reads all available variables form the selected matlab scirpt and puts them into the list view.
175    /// </summary>
176    private async void GetVariableNamesAsync() {
177      UpdateStatus("Opening Matlab");
178      var path = openFileDialog.FileName;
179      ProblemTextBox.Text = path;
180      var variables = await Task.Run(() => {
181        OpenMatlabConnector();
182        return _mlConnector.GetVariablesFromScript(path);
183      });
184
185      UpdateStatus("Loading variable names");
186      _timeseriesLoader.DisplayVariables(variables);
187      _doubleArraysLoader.DisplayVariables(variables);
188      UpdateStatus("Done");
189    }
190
191    private async void LoadValuesAsync() {
192      UpdateStatus("Loading values from Matlab");
193      try {
194        // As there can be a huge amount of data, it should be freed before reallocating it.
195        OkButton.Enabled = false;
196        _values = new Dataset();
197        PreviewDatasetMatrix.Content = _values;
198        TargetVariableComboBox.DataSource = new List<string>();
199        TargetVariableComboBox.SelectedText = "";
200        GC.Collect();
201        var token = _cts.Token;
202        var ds = await Task.Run<Dataset>(() => _variablesLoader.GetPreviewDataset(_mlConnector, token), token);
203        GC.Collect();
204
205        if (ds != null) {
206          _values = ds;
207          PreviewDatasetMatrix.Content = _values;
208          TargetVariableComboBox.DataSource = _values.VariableNames;
209
210          ErrorTextBox.Text = String.Empty;
211          ErrorTextBox.Visible = false;
212          OkButton.Enabled = true;
213        }       
214      } catch (Exception ex) {
215        if (ex is IOException || ex is InvalidOperationException || ex is ArgumentException) {
216          ErrorOccured(ex.Message);
217        } else if (ex is OutOfMemoryException) {
218          ErrorOccured(ex.Message + " Amount of the given data is too big.");
219        } else {
220          throw;
221        }
222      }
223      UpdateStatus("Done");
224    }
225  }
226}
227
Note: See TracBrowser for help on using the repository browser.