public UpdateDataSeries ( string name, double data ) : void | ||
name | string | Data series name to update. |
data | double | Data series values. |
return | void |
// Load data private void loadDataButton_Click(object sender, System.EventArgs e) { // show file selection dialog if (openFileDialog.ShowDialog() == DialogResult.OK) { StreamReader reader = null; // read maximum 50 points double[] tempData = new double[50]; try { // open selected file reader = File.OpenText(openFileDialog.FileName); string str = null; int i = 0; // read the data while ((i < 50) && ((str = reader.ReadLine()) != null)) { // parse the value tempData[i] = double.Parse(str); i++; } // allocate and set data data = new double[i]; dataToShow = new double[i, 2]; Array.Copy(tempData, 0, data, 0, i); for (int j = 0; j < i; j++) { dataToShow[j, 0] = j; dataToShow[j, 1] = data[j]; } } catch (Exception) { MessageBox.Show("Failed reading the file", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } finally { // close file if (reader != null) { reader.Close(); } } // update list and chart UpdateDataListView(); chart.RangeX = new Range(0, data.Length - 1); chart.UpdateDataSeries("data", dataToShow); chart.UpdateDataSeries("solution", null); // set delimiters UpdateDelimiters(); // enable "Start" button startButton.Enabled = true; } }
// Update chart private void UpdateChart() { // update chart range chart.RangeX = userFunction.Range; double[,] data = null; if (chart.RangeX.Length > 0) { // prepare data data = new double[501, 2]; double minX = userFunction.Range.Min; double length = userFunction.Range.Length; for (int i = 0; i <= 500; i++) { data[i, 0] = minX + length * i / 500; data[i, 1] = userFunction.OptimizationFunction(data[i, 0]); } } // update chart series chart.UpdateDataSeries("function", data); }
// Clear current solution private void ClearSolution( ) { errorChart.UpdateDataSeries("error", null); weightsList.Items.Clear( ); currentIterationBox.Text = string.Empty; currentErrorBox.Text = string.Empty; }
// On "Generate Map" button click - generate map private void generateMapButton_Click(object sender, System.EventArgs e) { if (GA_Thread == null) //Executar apenas se o algoritmo não estiver sendo executado { Map.Clear(); //Limpa a lista mapa Path.Clear(); //Limpa a lista de caminho Population.Clear(); //Limpa a lista de população // get cities count: try //Tentar Executar o seguinte: { //Obtém o número de cidades da TextBox, limitando entre um máximo e mínimo NCities = Math.Max(5, Math.Min(199, int.Parse(citiesCountBox.Text))); } catch //Em caso de uma exceção (erro): { //Definir o número de cidades como uma constante (20) NCities = 20; } //Atualizar o texto da TextBox com o número de cidades citiesCountBox.Text = NCities.ToString(); //------------------------------------------------------------------------------- // Generate new map for the Traveling Salesman problem: Random rand = new Random((int)DateTime.Now.Ticks); //Gera as cidades: for (int i = 0; i < NCities; i++) //Enquanto i estiver entre 0 e N Cidades { int x = rand.Next(1001); //Gera um número aleatório para a coordenada X int y = rand.Next(1001); City city = new City(x, y); //Cria nova cidade nas coordenadas X e Y Map.Add(city); //Adiciona a cidade recém criada ao mapa } double[,] map = new double[NCities, 2]; //Gera a matriz do mapa com tamanho igual ao número de cidades map = ListToMatrix(Map); //Converte a lista Mapa para uma matriz e a armazena // set the map mapControl.UpdateDataSeries("map", map); //Utiliza a matriz para preencher o gráfico com os pontos das cidades // erase path if it is "null" mapControl.UpdateDataSeries("path", null); //Se o caminho não tiver sido gerado ainda, apagá-lo mapControl.UpdateDataSeries("start_end", null); //Se o ponto de início/fim não tiver sido gerado ainda, apagá-lo } else //Se o algoritmo estiver em andamento, impedir geração de novo mapa { MessageBox.Show("O algoritmo está em execução, aguarde o término."); } }
// Show training data on chart private void ShowTrainingData() { var class1Size = 0; var class2Size = 0; // calculate number of samples in each class for (int i = 0, n = samples; i < n; i++) { if (classes[i] == 0) { class1Size++; } else { class2Size++; } } // allocate classes arrays var class1 = new double[class1Size, 2]; var class2 = new double[class2Size, 2]; // fill classes arrays for (int i = 0, c1 = 0, c2 = 0; i < samples; i++) { if (classes[i] == 0) { // class 1 class1[c1, 0] = data[i, 0]; class1[c1, 1] = data[i, 1]; c1++; } else { // class 2 class2[c2, 0] = data[i, 0]; class2[c2, 1] = data[i, 1]; c2++; } } // updata chart control chart.UpdateDataSeries("class1", class1); chart.UpdateDataSeries("class2", class2); }
// Generate new map for the Traivaling Salesman problem private void GenerateMap() { var rand = new Random((int)DateTime.Now.Ticks); // create coordinates array map = new double[citiesCount, 2]; for (var i = 0; i < citiesCount; i++) { map[i, 0] = rand.Next(1001); map[i, 1] = rand.Next(1001); } // set the map chart.UpdateDataSeries("cities", map); // erase path if it is chart.UpdateDataSeries("path", null); }
// Load data private void loadDataButton_Click(object sender, System.EventArgs e) { // show file selection dialog if (openFileDialog.ShowDialog() == DialogResult.OK) { data = null; try { // open selected file using (TextReader stream = new StreamReader(openFileDialog.FileName)) using (CsvReader reader = new CsvReader(stream, false)) { data = reader.ToTable().ToMatrix(CultureInfo.InvariantCulture); } } catch (Exception) { MessageBox.Show("Failed reading the file", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } DoubleRange[] ranges = data.Range(dimension: 0); xRange = ranges[0]; yRange = ranges[1]; // update list and chart UpdateDataListView(); chart.RangeX = new Range((float)xRange.Min, (float)xRange.Max); chart.UpdateDataSeries("data", data); chart.UpdateDataSeries("solution", null); // enable "Start" button startButton.Enabled = true; } }
// Show training data on chart private void ShowTrainingData( ) { double[][,] dataSeries = new double[classesCount][, ]; int[] indexes = new int[classesCount]; // allocate data arrays for (int i = 0; i < classesCount; i++) { dataSeries[i] = new double[samplesPerClass[i], 2]; } // fill data arrays for (int i = 0; i < samples; i++) { // get sample's class int dataClass = classes[i]; // copy data into appropriate array dataSeries[dataClass][indexes[dataClass], 0] = data[i, 0]; dataSeries[dataClass][indexes[dataClass], 1] = data[i, 1]; indexes[dataClass]++; } // remove all previous data series from chart control chart.RemoveAllDataSeries( ); // add new data series for (int i = 0; i < classesCount; i++) { string className = string.Format("class" + i); // add data series chart.AddDataSeries(className, dataSereisColors[i], Chart.SeriesType.Dots, 5); chart.UpdateDataSeries(className, dataSeries[i]); // add classifier chart.AddDataSeries(string.Format("classifier" + i), Color.Gray, Chart.SeriesType.Line, 1, false); } }
// Load data private void loadDataButton_Click(object sender, System.EventArgs e) { // show file selection dialog if (openFileDialog.ShowDialog() == DialogResult.OK) { data = null; try { // open selected file using (TextReader stream = new StreamReader(openFileDialog.FileName)) using (CsvReader reader = new CsvReader(stream, false)) { data = reader.ToTable().ToMatrix(CultureInfo.InvariantCulture).GetColumn(0); } } catch (Exception) { MessageBox.Show("Failed reading the file", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } dataToShow = Matrix.Stack(Matrix.Indices(0, data.Length).ToDouble(), data).Transpose(); // update list and chart UpdateDataListView(); chart.RangeX = new Range(0, data.Length - 1); chart.UpdateDataSeries("data", dataToShow); chart.UpdateDataSeries("solution", null); // set delimiters UpdateDelimiters(); // enable "Start" button startButton.Enabled = true; } }
// Update delimiters on the chart private void UpdateDelimiters( ) { // window delimiter windowDelimiter[0, 0] = windowDelimiter[1, 0] = windowSize; windowDelimiter[0, 1] = chart.RangeY.Min; windowDelimiter[1, 1] = chart.RangeY.Max; chart.UpdateDataSeries("window", windowDelimiter); // prediction delimiter predictionDelimiter[0, 0] = predictionDelimiter[1, 0] = data.Length - 1 - predictionSize; predictionDelimiter[0, 1] = chart.RangeY.Min; predictionDelimiter[1, 1] = chart.RangeY.Max; chart.UpdateDataSeries("prediction", predictionDelimiter); }
// Load data private void loadDataButton_Click(object sender, System.EventArgs e) { // show file selection dialog if (openFileDialog.ShowDialog() == DialogResult.OK) { StreamReader reader = null; // read maximum 50 points double[,] tempData = new double[50, 2]; double minX = double.MaxValue; double maxX = double.MinValue; try { // open selected file reader = File.OpenText(openFileDialog.FileName); string str = null; int i = 0; // read the data while ((i < 50) && ((str = reader.ReadLine()) != null)) { string[] strs = str.Split(';'); if (strs.Length == 1) { strs = str.Split(','); } // parse X tempData[i, 0] = double.Parse(strs[0]); tempData[i, 1] = double.Parse(strs[1]); // search for min value if (tempData[i, 0] < minX) { minX = tempData[i, 0]; } // search for max value if (tempData[i, 0] > maxX) { maxX = tempData[i, 0]; } i++; } // allocate and set data data = new double[i, 2]; Array.Copy(tempData, 0, data, 0, i * 2); } catch (Exception) { MessageBox.Show("Failed reading the file", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } finally { // close file if (reader != null) { reader.Close(); } } // update list and chart UpdateDataListView(); chart.RangeX = new Range((float)minX, (float)maxX); chart.UpdateDataSeries("data", data); chart.UpdateDataSeries("solution", null); // enable "Start" button startButton.Enabled = true; } }
// Clear current solution private void ClearCurrentSolution( ) { chart.UpdateDataSeries("classifier", null); errorChart.UpdateDataSeries("error", null); weightsList.Items.Clear( ); }
// Worker thread void SearchSolution( ) { // initialize input and output values double[][] input = null; double[][] output = null; if (sigmoidType == 0) { // unipolar data input = new double[4][] { new double[] { 0, 0 }, new double[] { 0, 1 }, new double[] { 1, 0 }, new double[] { 1, 1 } }; output = new double[4][] { new double[] { 0 }, new double[] { 1 }, new double[] { 1 }, new double[] { 0 } }; } else { // biipolar data input = new double[4][] { new double[] { -1, -1 }, new double[] { -1, 1 }, new double[] { 1, -1 }, new double[] { 1, 1 } }; output = new double[4][] { new double[] { -1 }, new double[] { 1 }, new double[] { 1 }, new double[] { -1 } }; } // create perceptron ActivationNetwork network = new ActivationNetwork( (sigmoidType == 0) ? (IActivationFunction) new SigmoidFunction(sigmoidAlphaValue) : (IActivationFunction) new BipolarSigmoidFunction(sigmoidAlphaValue), 2, 2, 1); // create teacher BackPropagationLearning teacher = new BackPropagationLearning(network); // set learning rate and momentum teacher.LearningRate = learningRate; teacher.Momentum = momentum; // iterations int iteration = 1; // statistic files StreamWriter errorsFile = null; try { // check if we need to save statistics to files if (saveStatisticsToFiles) { // open files errorsFile = File.CreateText("errors.csv"); } // erros list ArrayList errorsList = new ArrayList( ); // loop while (!needToStop) { // run epoch of learning procedure double error = teacher.RunEpoch(input, output); errorsList.Add(error); // save current error if (errorsFile != null) { errorsFile.WriteLine(error); } // show current iteration & error currentIterationBox.Text = iteration.ToString( ); currentErrorBox.Text = error.ToString( ); iteration++; // check if we need to stop if (error <= learningErrorLimit) { break; } } // show error's dynamics double[,] errors = new double[errorsList.Count, 2]; for (int i = 0, n = errorsList.Count; i < n; i++) { errors[i, 0] = i; errors[i, 1] = (double)errorsList[i]; } errorChart.RangeX = new DoubleRange(0, errorsList.Count - 1); errorChart.UpdateDataSeries("error", errors); } catch (IOException) { MessageBox.Show("Failed writing file", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { // close files if (errorsFile != null) { errorsFile.Close( ); } } // enable settings controls EnableControls(true); }
// Load input data private void loadButton_Click(object sender, System.EventArgs e) { // data file format: // X1, X2, class // load maximum 10 classes ! // show file selection dialog if (openFileDialog.ShowDialog( ) == DialogResult.OK) { StreamReader reader = null; // temp buffers (for 200 samples only) float[,] tempData = new float[200, 2]; int[] tempClasses = new int[200]; // min and max X values float minX = float.MaxValue; float maxX = float.MinValue; // samples count samples = 0; // classes count classesCount = 0; samplesPerClass = new int[10]; try { string str = null; // open selected file reader = File.OpenText(openFileDialog.FileName); // read the data while ((samples < 200) && ((str = reader.ReadLine( )) != null)) { // split the string string[] strs = str.Split(';'); if (strs.Length == 1) { strs = str.Split(','); } // check tokens count if (strs.Length != 3) { throw new ApplicationException("Invalid file format"); } // parse tokens tempData[samples, 0] = float.Parse(strs[0]); tempData[samples, 1] = float.Parse(strs[1]); tempClasses[samples] = int.Parse(strs[2]); // skip classes over 10, except only first 10 classes if (tempClasses[samples] >= 10) { continue; } // count the amount of different classes if (tempClasses[samples] >= classesCount) { classesCount = tempClasses[samples] + 1; } // count samples per class samplesPerClass[tempClasses[samples]]++; // search for min value if (tempData[samples, 0] < minX) { minX = tempData[samples, 0]; } // search for max value if (tempData[samples, 0] > maxX) { maxX = tempData[samples, 0]; } samples++; } // allocate and set data data = new double[samples, 2]; Array.Copy(tempData, 0, data, 0, samples * 2); classes = new int[samples]; Array.Copy(tempClasses, 0, classes, 0, samples); // clear current result weightsList.Items.Clear( ); errorChart.UpdateDataSeries("error", null); } catch (Exception) { MessageBox.Show("Failed reading the file", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } finally { // close file if (reader != null) { reader.Close( ); } } // update chart chart.RangeX = new Range(minX, maxX); ShowTrainingData( ); // enable start button startButton.Enabled = true; } }