Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
05/02/18 13:14:16 (6 years ago)
Author:
rhanghof
Message:

#2913:

  • Added the support for importing different Matlab datatypes.
  • Added some classes and changed the import dialog for importing double arrays.
File:
1 edited

Legend:

Unmodified
Added
Removed
  • branches/2913_MatlabScriptProblemInstanceProvider/HeuristicLab.Problems.Instances.DataAnalysis.Views/3.3/Regression/Matlab/RegressionMatlabImportDialog.cs

    r15919 r15926  
    1919namespace HeuristicLab.Problems.Instances.DataAnalysis.Views.Regression.Matlab {
    2020  public partial class RegressionMatlabImportDialog : Form {
     21    private const int TAB_INDEX_TIMESERIES = 0;
     22    private const int TAB_INDEX_DOUBLE_ARRAYS = 1;
     23
    2124    private IMatlabConnector _mlConnector;
     25
     26    private IMLVariablesLoader _variablesLoader;
     27    private IMLVariablesLoader _timeseriesLoader;
     28    private IMLVariablesLoader _doubleArraysLoader;
     29
     30    private CancellationTokenSource _cts = new CancellationTokenSource();
     31
    2232    public event EventHandler<EventArgs<string>> StatusChangedEvent;
    2333    public event EventHandler<EventArgs<string>> ErrorOccuredEvent;
    24 
    25 
    2634
    2735    /// <summary>
     
    4957    }
    5058
    51     private IList<KeyValuePair<string, MLDatatype>> _selectedVariables;
    52 
    53     public IEnumerable<KeyValuePair<string, MLDatatype>> SelectedVariables {
     59    private IList<MLVariableInfo> _selectedTimeseries;
     60    private IList<MLVariableInfo> _selectedDoubleArrays;
     61
     62    public IEnumerable<MLVariableInfo> SelectedVariables {
    5463      get {
    55         return _selectedVariables;
     64        return _variablesLoader.SelectedVariables;
    5665      }
    5766    }
     
    6069      InitializeComponent();
    6170
    62       _selectedVariables = new List<KeyValuePair<string, MLDatatype>>();
     71      _selectedTimeseries = new List<MLVariableInfo>();
     72      _selectedDoubleArrays = new List<MLVariableInfo>();
    6373      _values = new Dataset();
    6474
    6575      this.FormClosed += (s, e) => DisposeMatlabConnector();
    6676      OpenFileButton.Click += OpenFileButtonClick;
    67       VariablesListBox.ItemCheck += (s, e) => BeginInvoke((MethodInvoker)(() => CheckedItemsChanged(s, e)));
     77
     78      DatatypeSelectorTabControl.SelectedIndexChanged += (s, e) => BeginInvoke((MethodInvoker)(() => DatatypeSelectorTabControlTabIndexChanged(s, e)));
     79
    6880      LoadValuesButton.Click += LoadValuesButtonClick;
    6981      TrainingTestTrackBar.ValueChanged += TrainingTestTrackBarValueChanged;
     82
    7083      StatusChangedEvent += (s, e) => BeginInvoke((MethodInvoker)(() => StatusLabel.Text = e.Value));
    7184      ErrorOccuredEvent += (s, e) => BeginInvoke((MethodInvoker)(() => {
     
    7487        ErrorTextBox.Visible = true;
    7588      }));
    76     }
    77 
    78     private void CheckedItemsChanged(object sender, ItemCheckEventArgs e) {
    79       _selectedVariables.Clear();
    80       foreach (KeyValuePair<string, MLDatatype> item in VariablesListBox.CheckedItems) {
    81         if (item.Value == MLDatatype.Timeseries) {
    82           _selectedVariables.Add(item);
    83         }
    84       }
    85       LoadValuesButton.Enabled = VariablesListBox.CheckedIndices.Count > 0;
    86     }
    87 
    88     #region Events
    89 
     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    }
    90117
    91118    private void LoadValuesButtonClick(object sender, EventArgs e) {
     119      _cts.Cancel();
     120      _cts = new CancellationTokenSource();
    92121      LoadValuesAsync();
    93122    }
     
    106135    }
    107136    #endregion
    108    
     137
    109138    /// <summary>
    110139    /// Fires the ErrorOccuredEvent with the given text message.
     
    127156      if (_mlConnector == null) {
    128157        _mlConnector = MatlabApiFactory.CreateMatlabConnector();
     158        _mlConnector.ErrorOccuredEvent += ErrorOccured;
    129159      }
    130160    }
     
    141171
    142172
    143 
    144173    /// <summary>
    145174    /// This method reads all available variables form the selected matlab scirpt and puts them into the list view.
     
    147176    private async void GetVariableNamesAsync() {
    148177      UpdateStatus("Opening Matlab");
    149 
    150178      var path = openFileDialog.FileName;
    151179      ProblemTextBox.Text = path;
     
    156184
    157185      UpdateStatus("Loading variable names");
    158       var variablesListBoxItems = VariablesListBox.Items;
    159       variablesListBoxItems.Clear();
    160       foreach (var item in variables) {
    161         variablesListBoxItems.Add(item, false);
    162       }
     186      _timeseriesLoader.DisplayVariables(variables);
     187      _doubleArraysLoader.DisplayVariables(variables);
    163188      UpdateStatus("Done");
    164189    }
    165190
    166     /// <summary>
    167     /// Loads the values of the selected timeseries values and displays them at the preview control.
    168     /// </summary>
    169191    private async void LoadValuesAsync() {
     192      UpdateStatus("Loading values from Matlab");
    170193      try {
    171         PreviewDatasetMatrix.Content = new Dataset();
    172 
    173         UpdateStatus("Loading values from Matlab");
    174         var vals = await Task.Run<List<MLTimeseries>>(() => {
    175           var values = new List<MLTimeseries>();
    176           foreach (KeyValuePair<string, MLDatatype> item in VariablesListBox.CheckedItems) {
    177             if (item.Value == MLDatatype.Timeseries) {
    178               var val = _mlConnector.GetTimeseries(item.Key);
    179               if (val != null) {
    180                 values.Add(val);
    181               }
    182             }
    183           }
    184           return values;
    185         });
    186 
    187         UpdateStatus("Converting values");
    188         DisplayLoadedValuesAsync(await Task.Run<MLTimeseries>(() => new MLTimeseries(vals)));
    189         ErrorTextBox.Text = String.Empty;
    190         ErrorTextBox.Visible = false;
    191         OkButton.Enabled = true;
     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        }       
    192214      } catch (Exception ex) {
    193215        if (ex is IOException || ex is InvalidOperationException || ex is ArgumentException) {
    194216          ErrorOccured(ex.Message);
     217        } else if (ex is OutOfMemoryException) {
     218          ErrorOccured(ex.Message + " Amount of the given data is too big.");
    195219        } else {
    196220          throw;
     
    199223      UpdateStatus("Done");
    200224    }
    201 
    202     /// <summary>
    203     /// Displays the values of a given timeseries at the preview dataset matrix.
    204     /// </summary>
    205     /// <param name="timeseries"></param>
    206     private async void DisplayLoadedValuesAsync(MLTimeseries timeseries) {
    207       PreviewDatasetMatrix.Content = null;
    208       IEnumerable<string> variableNamesWithType = GetVariableNamesWithType(timeseries);
    209       var values = await Task.Run<double[,]>(() => GetValuesForDataset(timeseries));
    210       _values = new Dataset(variableNamesWithType, values);
    211       PreviewDatasetMatrix.Content = _values;
    212       SetPossibleTargetVariables(timeseries);
    213     }
    214 
    215     /// <summary>
    216     /// Sets the entries of the combobox for the target variable.
    217     /// </summary>
    218     /// <param name="timeseries"></param>
    219     protected void SetPossibleTargetVariables(MLTimeseries timeseries) {
    220       if (timeseries != null) {
    221         TargetVariableComboBox.DataSource = timeseries.DataHeader;
    222       }
    223     }
    224 
    225     /// <summary>
    226     /// Returns a list with all selected variable names for the preview dataset.
    227     /// </summary>
    228     /// <param name="timeseries"></param>
    229     /// <returns></returns>
    230     private IEnumerable<string> GetVariableNamesWithType(MLTimeseries timeseries) {
    231       IList<string> variableNamesWithType = timeseries.DataHeader.ToList();
    232       variableNamesWithType.Insert(0, "time");
    233       return variableNamesWithType;
    234     }
    235 
    236     /// <summary>
    237     /// Returns a two dimensional double array which contains the values including the timestamps of the given timeseries.
    238     /// Array[value, variable]
    239     /// If the amount of the data is too big, a OutOfMemoryException exception is being thrown.
    240     /// This exception is being cought and a message will be shown at the error message box.
    241     /// </summary>
    242     /// <param name="timeseries"></param>
    243     /// <returns></returns>
    244     private double[,] GetValuesForDataset(MLTimeseries timeseries) {
    245       try {
    246         double[,] datasetValues = new double[timeseries.Count, timeseries.DataHeader.Length + 1];
    247 
    248         int i = 0;
    249         foreach (var item in timeseries.Data) {
    250           datasetValues[i, 0] = item.Key;
    251           for (int j = 1; j < datasetValues.GetLength(1); j++) {
    252             datasetValues[i, j] = item.Value[j - 1];
    253           }
    254           i++;
    255         }
    256         return datasetValues;
    257       } catch (OutOfMemoryException ex) {
    258         ErrorOccured(ex.Message + " Amount of the given data is too big.");
    259       }
    260       return new double[0, timeseries.DataHeader.Length + 1];
    261     }
    262225  }
    263226}
Note: See TracChangeset for help on using the changeset viewer.