Esempio n. 1
0
        private void ShowLinearRegressionModel()
        {
            tabControlMain.SelectedIndex = 0;
            string qualityParam = XMLWork.FindNameWithID(_linearEquation.OutputParameter.Id.Value,
                                                         Properties.Settings.Default.Languages);

            double[] coefficients =
                _linearEquation.InputParameters.Select(item => item.Coefficient).ToArray();
            string inputParam = XMLWork.FindNameWithID(_linearEquation.InputParameters[1].Id.Value,
                                                       Properties.Settings.Default.Languages);

            for (int i = 0; i < comboBoxInputParams.Items.Count; i++)
            {
                if (comboBoxInputParams.Items[i].Equals(inputParam))
                {
                    comboBoxInputParams.SelectedIndex = i;
                    break;
                }
            }
            for (int i = 0; i < comboBoxQualityParams.Items.Count; i++)
            {
                if (comboBoxQualityParams.Items[i].Equals(qualityParam))
                {
                    comboBoxQualityParams.SelectedIndex = i;
                    break;
                }
            }
            labelRMSE.Text = _linearEquation.RMSEString;
            checkBoxNormalizeValuesPage1.Checked = _linearEquation.NormalizeValues;
            GetLinearRegressionModel(qualityParam, inputParam, false);
        }
Esempio n. 2
0
        bool GetLinearRegressionModel(string qualityParam, string inputParam, bool writeModel = true)
        {
            int inputParameterID   = XMLWork.FindIDWithName(inputParam, Properties.Settings.Default.Languages);
            int qualityParameterID = XMLWork.FindIDWithName(qualityParam, Properties.Settings.Default.Languages);

            try
            {
                var generalData = (from row in TrainData.Train
                                   select new PointD {
                    X = (double)row.Input[inputParameterID], Y = (double)row.Output[qualityParameterID]
                }).ToList();
                if (!generalData.Any(item => Math.Abs(item.X) > DataSensitivityThreshhold && Math.Abs(item.Y) > DataSensitivityThreshhold))
                {
                    throw new Exception("Incorrect input data");
                }
                DrawMainChart(generalData, writeModel);
                DrawErrorsChart(generalData);
                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error parsing data: \"{ex.Message}\"", "Exception", MessageBoxButtons.OK);
                return(false);
            }
        }
Esempio n. 3
0
        private void ShowMultipleRegressionModel()
        {
            tabControlMain.SelectedIndex = 2;
            string qualityParam = XMLWork.FindNameWithID(_multipleRegressionEquation.OutputParameter.Id.Value,
                                                         Properties.Settings.Default.Languages);

            double[] coefficients =
                _multipleRegressionEquation.InputParameters.Select(item => item.Coefficient).ToArray();
            string[] inputParametersToCheck = _multipleRegressionEquation.InputParameters.Skip(1)
                                              .Select(item => XMLWork.FindNameWithID(item.Id.Value, Properties.Settings.Default.Languages)).ToArray();

            for (int i = 0; i < comboBoxQualityParametersPage3.Items.Count; i++)
            {
                if (comboBoxQualityParametersPage3.Items[i].Equals(qualityParam))
                {
                    comboBoxQualityParametersPage3.SelectedIndex = i;
                    break;
                }
            }
            for (int i = 0; i < checkedListBoxInputParametersToCheckPage3.Items.Count; i++)
            {
                checkedListBoxInputParametersToCheckPage3.SetItemCheckState(i,
                                                                            inputParametersToCheck.Contains(checkedListBoxInputParametersToCheckPage3.Items[i])
                        ? CheckState.Checked
                        : CheckState.Unchecked);
            }
            labelRMSEPage3.Text = _multipleRegressionEquation.RMSEString;
            checkBoxNormalizeValuesPage3.Checked = _multipleRegressionEquation.NormalizeValues;
            ShowRegressionEquasion(qualityParam, coefficients);
            ShowRegressionEquasionHelp(inputParametersToCheck);
        }
Esempio n. 4
0
        private void TrafficLight_Shown(object sender, EventArgs e)
        {
            var parameters = TrainData.nameParameter.Values.Where(o => o.StartsWith("Def")).ToArray();

            foreach (var parameter in parameters)
            {
                parameterCondition.Items.Add(XMLWork.FindNameWithScada(parameter, Properties.Settings.Default.Languages));
            }
            if (parameterCondition.Items.Count == 0)
            {
                MessageBox.Show(Localization.MyStrings.WithoutDefect);
            }
            if (parameterCondition.Items.Count != 0)
            {
                parameterCondition.SelectedIndex = 0;
            }
            if (ListAdd.Items.Count != 0)
            {
                ListAdd.SelectedIndex = 0;
            }
            if (ListDelete.Items.Count != 0)
            {
                ListDelete.SelectedIndex = 0;
            }
            if (ListAddError.Items.Count != 0)
            {
                ListAddError.SelectedIndex = 0;
            }
            if (ListDeleteError.Items.Count != 0)
            {
                ListDeleteError.SelectedIndex = 0;
            }
        }
Esempio n. 5
0
        private void PreprocessToWorkTree()
        {
            var c45         = new DecisionTreeC45();
            int parameterID = XMLWork.FindIDWithName(parameterCondition.SelectedItem.ToString(), Properties.Settings.Default.Languages);

            _root = c45.MountTree(TrainData.Train, TrainData.nameParameter, parameterID, Convert.ToInt32(textEdit1.Value) + 1);
            MessageBox.Show(Localization.MyStrings.Over);
        }
Esempio n. 6
0
 private void NormalDistribution_Shown(object sender, EventArgs e)
 {
     name_parametrs = TrainData.nameParameter.Values.Where(o => o.StartsWith("Def")).ToList();// || o.StartsWith("OPC")).ToList();
     ListParam.Items.Clear();
     foreach (var item in name_parametrs)
     {
         ListParam.Items.Add(XMLWork.FindNameWithScada(item, Properties.Settings.Default.Languages));
     }
 }
Esempio n. 7
0
 private void simpleButton1_Click_1(object sender, EventArgs e)
 {
     foreach (OneRow row in TrainData.Train)
     {
         var point = CalculateShrinkageValue(row.Temperatures.Values.ToArray(), row.Velocities.Values.ToArray());
         XMLWork.addShrinkageFile(row.Date, point);
     }
     MessageBox.Show("Данные об усадке собраны");
 }
Esempio n. 8
0
 private void GetPoints(ref decimal pointX, OneRow data, ref decimal pointY)
 {
     foreach (var item in ListDelete.Items)
     {
         int parameterID = XMLWork.FindIDWithName(item.ToString(), Properties.Settings.Default.Languages);
         pointX = pointX * data.Input[parameterID]; //234 232
     }
     foreach (var item in ListDeleteError.Items)
     {
         int parameterID = XMLWork.FindIDWithName(item.ToString(), Properties.Settings.Default.Languages);
         pointY = pointY * data.Input[parameterID]; //234 232
     }
 }
Esempio n. 9
0
        void ShowProcessParameters()
        {
            string[] input, quality;
            input   = _inputParams.Select(item => XMLWork.FindNameWithScada(item, Properties.Settings.Default.Languages)).ToArray();
            quality = _qualityParams.Select(item => XMLWork.FindNameWithScada(item, Properties.Settings.Default.Languages)).ToArray();

            comboBoxInputParams.Items.Clear();
            comboBoxInputParams.Items.AddRange(input);
            comboBoxInputParams.SelectedIndex = 0;
            comboBoxQualityParams.Items.Clear();
            comboBoxQualityParams.Items.AddRange(quality);
            comboBoxQualityParams.SelectedIndex = 0;
        }
Esempio n. 10
0
        public Kohonen()
        {
            if (!string.IsNullOrEmpty(Properties.Settings.Default.Languages))
            {
                System.Threading.Thread.CurrentThread.CurrentUICulture =
                    System.Globalization.CultureInfo.GetCultureInfo(Properties.Settings.Default.Languages);
                System.Threading.Thread.CurrentThread.CurrentCulture =
                    System.Globalization.CultureInfo.GetCultureInfo(Properties.Settings.Default.Languages);
            }
            InitializeComponent();
            ListAdd.Items.Clear();
            ListDelete.Items.Clear();
            List <int> keys = new List <int>();
            Dictionary <int, decimal> firstRow = TrainData.Train.First().Input;

            foreach (OneRow data in TrainData.Train)
            {
                foreach (var item in data.Input)
                {
                    if (keys.Contains(item.Key))
                    {
                        continue;
                    }
                    if (item.Key != firstRow[item.Key])
                    {
                        keys.Add(item.Key);
                    }
                }
                break;
            }
            var parameters = TrainData.nameParameter.Values.Where(o => o.StartsWith("Def")).ToArray();

            foreach (var parameter1 in parameters)
            {
                ListAdd.Items.Add(XMLWork.FindNameWithScada(parameter1, Properties.Settings.Default.Languages));
            }
            foreach (int key in keys)
            {
                ListAdd.Items.Add(XMLWork.FindNameWithID(key, Properties.Settings.Default.Languages));
            }
            if (ListAdd.Items.Count != 0)
            {
                ListAdd.SelectedIndex = 0;
            }
            if (ListDelete.Items.Count != 0)
            {
                ListDelete.SelectedIndex = 0;
            }
        }
Esempio n. 11
0
 void ShowParametersOnPage3()
 {
     if (checkedListBoxInputParametersToCheckPage3.SelectedItems.Count != 0)
     {
         return;
     }
     string[] input, quality;
     input   = _inputParams.Select(item => XMLWork.FindNameWithScada(item, Properties.Settings.Default.Languages)).ToArray();
     quality = _qualityParams.Select(item => XMLWork.FindNameWithScada(item, Properties.Settings.Default.Languages)).ToArray();
     comboBoxQualityParametersPage3.Items.Clear();
     comboBoxQualityParametersPage3.Items.AddRange(quality);
     comboBoxQualityParametersPage3.SelectedIndex = 0;
     checkedListBoxInputParametersToCheckPage3.Items.Clear();
     checkedListBoxInputParametersToCheckPage3.Items.AddRange(input);
 }
Esempio n. 12
0
        private void GetBooleanForOutput(List <OneRow> trainData, decimal criterion)
        {
            int parameterID = XMLWork.FindIDWithName(parameterCondition.SelectedItem.ToString(), Properties.Settings.Default.Languages);

            foreach (OneRow oneRow in trainData)
            {
                if (oneRow.Output[parameterID] >= criterion)
                {
                    oneRow.OutputBool[parameterID] = true;
                }
                else
                {
                    oneRow.OutputBool[parameterID] = false;
                }
            }
        }
Esempio n. 13
0
        private void PreprocessToWorkTreeRandomForest(TrainData trainedData, TrainData checkData,
                                                      Dictionary <int, string> analysParameter)
        {
            int numberOfForest = Convert.ToInt32(numberOfForests.Value);

            RandForests = new List <DM.DecisionTree.TreeNode>();
            //double accuracy = 0.0;
            //do
            //{
            //Random rand = new Random((int) (DateTime.Now.Ticks));
            //DivideSet(rand, trainData, trainedData, checkData);
            List <DM.DecisionTree.TreeNode> rndForests = new List <DM.DecisionTree.TreeNode>();
            int parameterID = XMLWork.FindIDWithName(parameterCondition.SelectedItem.ToString(), Properties.Settings.Default.Languages);
            int restrictCountOfParameters          = Convert.ToInt32(Math.Sqrt(analysParameter.Count)) + 1;
            Dictionary <int, string> newParameters = new Dictionary <int, string>();


            for (int forestsCount = 0; forestsCount < numberOfForest;)
            {
                DM.DecisionTree.RandomForest random = new RandomForest();
                List <int> parametersName           = new List <int>();
                foreach (KeyValuePair <int, string> keyValuePair in analysParameter)
                {
                    if (!keyValuePair.Value.StartsWith("Def"))
                    {
                        parametersName.Add(keyValuePair.Key);
                    }
                }
                for (int i = 0; i < restrictCountOfParameters; i++)
                {
                    int j = rand.Next(0, analysParameter.Count);
                    if (!newParameters.ContainsKey(parametersName[j]))
                    {
                        newParameters.Add(parametersName[j], analysParameter[parametersName[j]]);
                    }
                }
                List <OneRow> trainData = new List <OneRow>();
                trainData = GetRandomData(TrainData.Train, newParameters, parameterID);
                _root     = random.MountTree(trainData, newParameters, parameterID, Convert.ToInt32(textEdit1.Value) + 1);
                if (_root.attributeName != "False")
                {
                    RandForests.Add(_root);
                    forestsCount++;
                }
                newParameters.Clear();
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Calculate Dispersion all parameters
        /// </summary>
        private void CalculateDispersion()
        {
            int countElements = 10;
            Dictionary <int, decimal> mathematicalExpectation = new Dictionary <int, decimal>();
            Dictionary <int, decimal> dispersion = new Dictionary <int, decimal>();
            Dictionary <int, decimal> bestValues = new Dictionary <int, decimal>();

            ProcessingData.MathematicalExpectation(TrainData.Train, mathematicalExpectation);
            ProcessingData.Dispersion(TrainData.Train, mathematicalExpectation, dispersion);
            List <FisherCritery> elements = new List <FisherCritery>();

            foreach (var @decimal in dispersion)
            {
                elements.Add(new FisherCritery(@decimal.Key, @decimal.Value));
            }
            ListOfElements dispoersionElements = new ListOfElements(elements);

            dispoersionElements.InsertionSort();
            for (int i = 0; i < countElements; i++)
            {
                bestValues.Add(dispoersionElements.Fisher[i].Key, dispoersionElements.Fisher[i].Value);
            }

            this.chart2.Series.Clear();
            this.chart2.Titles.Clear();
            this.chart2.ChartAreas[0].AxisY.Maximum = Math.Round(Convert.ToDouble(bestValues.First().Value), 0) + 25;
            this.chart2.ChartAreas[0].AxisY.Minimum = Math.Round(Convert.ToDouble(bestValues.Last().Value), 0) - 25;

            // Set palette.
            this.chart2.Palette = ChartColorPalette.SeaGreen;

            // Set title.
            this.chart2.Titles.Add("Deviation");
            double numberOfParameters = 1.0;

            foreach (var item in bestValues)
            {
                // Add series.
                Series series = this.chart2.Series.Add(XMLWork.FindNameWithID(item.Key, Properties.Settings.Default.Languages));
                // Add point.
                //series.Points.Add(Convert.ToDouble(item.Value));
                series.Points.AddXY(numberOfParameters, item.Value);
                numberOfParameters += 0.1;
            }
            // Add series.
        }
Esempio n. 15
0
        private void RegressionAnalysisNew_Shown(object sender, EventArgs e)
        {
            _qualityParams = TrainData.nameParameter.Values.Where(o => o.StartsWith("Def")).ToArray();
            _inputParams   = TrainData.nameParameter.Values.Where(o => o.StartsWith("OPC")).ToArray();

            comboBoxInputParams.Items.Clear();
            comboBoxQualityParams.Items.Clear();
            foreach (var qualityParam in _qualityParams)
            {
                comboBoxQualityParams.Items.Add(XMLWork.FindNameWithScada(qualityParam, Properties.Settings.Default.Languages));
            }
            foreach (var inputParam in _inputParams)
            {
                comboBoxInputParams.Items.Add(XMLWork.FindNameWithScada(inputParam, Properties.Settings.Default.Languages));
            }
            comboBoxInputParams.SelectedIndex = comboBoxQualityParams.SelectedIndex = 0;
        }
Esempio n. 16
0
        /// <summary>
        /// Main method
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DictionaryMeasurement_Shown(object sender, EventArgs e)
        {
            int       columns = TrainData.Train[0].Input.Count;
            int       i;
            DataTable sourceTable = new DataTable();

            sourceTable.Columns.Add("Date");
            foreach (KeyValuePair <int, decimal> keyValuePair in TrainData.Train[0].Input)
            {
                String parName = XMLWork.FindNameWithID(keyValuePair.Key, Properties.Settings.Default.Languages);
                sourceTable.Columns.Add(parName);
            }
            foreach (KeyValuePair <int, decimal> keyValuePair in TrainData.Train[0].Output)
            {
                String parName = XMLWork.FindNameWithID(keyValuePair.Key, Properties.Settings.Default.Languages);
                sourceTable.Columns.Add(parName);
            }
            foreach (OneRow oneRow in TrainData.Train)
            {
                DataRow row = sourceTable.NewRow();
                i = 1;
                foreach (KeyValuePair <int, decimal> valuePair in oneRow.Input.OrderBy(o => o.Key))
                {
                    row[0] = oneRow.Date;
                    row[i] = valuePair.Value;
                    i++;
                }
                foreach (KeyValuePair <int, decimal> valuePair in oneRow.Output.OrderBy(o => o.Key))
                {
                    row[i] = valuePair.Value;
                    i++;
                }
                sourceTable.Rows.Add(row);
            }
            gridMeasurements.DataSource = sourceTable;
            EnableDoubleBuffering();
        }
Esempio n. 17
0
        bool GetDataForRSquaredGraph(string qualityParam)
        {
            var allData = new Dictionary <string, KeyValuePair <double, double> >();
            var inputParametersToCheck = checkedListBoxInputParametersToCheck.CheckedItems.Cast <string>();

            int qualityParameterID = XMLWork.FindIDWithName(qualityParam, Properties.Settings.Default.Languages);

            try
            {
                foreach (var inputParam in inputParametersToCheck)
                {
                    int inputParameterID = XMLWork.FindIDWithName(inputParam, Properties.Settings.Default.Languages);

                    double rSquared, Fisher;
                    var    generalData = (from row in TrainData.Train
                                          select new PointD {
                        X = (double)row.Input[inputParameterID], Y = (double)row.Output[qualityParameterID]
                    }).ToList();
                    if (!generalData.Any(item => Math.Abs(item.X) > DataSensitivityThreshhold && Math.Abs(item.Y) > DataSensitivityThreshhold))
                    {
                        throw new Exception("Incorrect input data");
                    }

                    Regression.Correlation(generalData, checkBoxNormalizeValuesPage2.Checked, out rSquared, out Fisher);
                    allData.Add(inputParam, new KeyValuePair <double, double>(rSquared, Fisher));
                }
                allData = allData.Where(item => !IsNanOrInfinity(item.Value)).OrderByDescending(item => item.Value.Key)
                          .Take(BestSimpleRegressionsShowingCount).ToDictionary(item => item.Key, item => item.Value);
                ShowRSquaredGraph(allData);
                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error processing data: \"{ex.Message}\"", "Exception", MessageBoxButtons.OK);
                return(false);
            }
        }
Esempio n. 18
0
        private void parameterCondition_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListAdd.Items.Clear();
            ListDelete.Items.Clear();
            List <int> keys                    = new List <int>();
            int        parameterID             = XMLWork.FindIDWithName(parameterCondition.SelectedItem.ToString(), Properties.Settings.Default.Languages);
            Dictionary <int, decimal> firstRow = TrainData.Train.First().Input;

            foreach (OneRow data in TrainData.Train)
            {
                foreach (var item in data.Input)
                {
                    if (keys.Contains(item.Key))
                    {
                        continue;
                    }
                    if (item.Key != firstRow[item.Key])
                    {
                        keys.Add(item.Key);
                    }
                }
                break;
            }
            foreach (int key in keys)
            {
                ListAdd.Items.Add(XMLWork.FindNameWithID(key, Properties.Settings.Default.Languages));
            }
            if (ListAdd.Items.Count != 0)
            {
                ListAdd.SelectedIndex = 0;
            }
            if (ListDelete.Items.Count != 0)
            {
                ListDelete.SelectedIndex = 0;
            }
        }
Esempio n. 19
0
        //Сбор данных
        private void dataAcq_Click(object sender, EventArgs e)
        {
            if (ListDelete.Items.Count != 0)
            {
                Stopwatch sw = new Stopwatch();
                sw.Start();
                TrainData.Train.Clear();
                measurementses.Clear();
                Dictionary <string, int> newElements = new Dictionary <string, int>();
                if (ListDelete.Items.Count != 0)
                {
                    //Сохранения имен параметров и их ID в справочник newElements
                    foreach (var item in ListDelete.Items)
                    {
                        string t = item.ToString();
                        int    j = elements.Where(s => s.Key == t).Single().Value;
                        newElements.Add(t, j);
                        //Работа с локальной базой данных(сохранения данных туда)
                        XMLWork.AddRow(j, t);
                    }
                }
                var  stream  = File.Open(path.Text, FileMode.Open, FileAccess.Read);
                var  eReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
                bool check   = true;
                try
                {
                    _counter = 0;
                    while (eReader.Read()) // Одну строку пропускаем с общей информацией
                    {
                        ++_counter;
                        break;
                    }
                    DateTime lastTime = new DateTime();
                    while (eReader.Read()) // Считывание информации с EXCEL файла
                    {
                        var      date = eReader.GetDateTime(0);
                        var      time = eReader.GetDateTime(1);
                        TimeSpan ts   = new TimeSpan(time.Hour, time.Minute, time.Second);
                        date = date + ts;
                        if (_counter == 1)
                        {
                            lastTime = date;
                        }
                        else
                        {
                            if (lastTime == date)
                            {
                                continue;
                            }
                            lastTime = date;
                        }
                        Measurements measurements;
                        foreach (var value in newElements)
                        {
                            Decimal parValue;
                            var     val = Convert.ToString(eReader.GetValue(value.Value));
                            val = val.Trim();
                            if (val == "")
                            {
                                parValue = -1;
                            }
                            else
                            {
                                var extA = Convert.ToString(eReader.GetValue(value.Value)).Replace(",", ".");
                                try
                                {
                                    parValue = Decimal.Parse(extA, NumberStyles.Float, _formatProvider);
                                }
                                catch (Exception exe)
                                {
                                    throw new Exception("Invalid value format in row " + _counter, exe);
                                }
                                measurements = new Measurements(parValue, date, value.Key, value.Value); // созеания измерения

                                measurementses.Add(measurements);                                        // и добавление его в коллекцию
                            }
                        }

                        ++_counter;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                finally
                {
                    eReader.Close();
                }
                try
                {
                    List <OneRow> dataSet         = new List <OneRow>();
                    var           uniqueTimestamp = measurementses.OrderBy(o => o.TimeStamp).Select(o => o.TimeStamp).Distinct();
                    OneRow        lastRow         = new OneRow();

                    // Отделение технологических параметров от показателей качество.
                    //TODO: сделать отдельную колонку в бд, в которой хранить краткую информацию о расположении датчика относительно производственной линии
                    foreach (DateTime dateTime in uniqueTimestamp)
                    {
                        var moveData =
                            measurementses.Where(
                                o => ((dateTime == o.TimeStamp) && (!o.ParameterName.StartsWith("Def"))))
                            .ToDictionary(o => o.ParID, s => s.Value);     // Добавление технологических параметров в дикшионари
                        //температуры для усадки
                        var temperatureData = measurementses.Where(o => ((dateTime == o.TimeStamp) && (o.ParameterName.Contains("XT"))))
                                              .ToDictionary(o => o.ParameterName, s => s.Value);
                        //скорости для усадки
                        var velocityData = measurementses.Where(o => ((dateTime == o.TimeStamp) && (o.ParameterName.Contains("XV"))))
                                           .ToDictionary(o => o.ParameterName, s => s.Value);
                        OneRow row = new OneRow();
                        row.Input        = moveData;
                        row.Temperatures = temperatureData;
                        row.Velocities   = velocityData;
                        if (row.Input.Count >= 1)
                        {
                            row.Date = dateTime;
                            var dataOutput =
                                measurementses.Where(
                                    o => ((dateTime == o.TimeStamp) && (o.ParameterName.StartsWith("Def"))))
                                .ToDictionary(o => o.ParID, s => s.Value);
                            row.Output = dataOutput;
                            dataSet.Add(row); // Добавление показателя качества в ОЗУ
                        }
                        lastRow = row;
                    }

                    var datas =
                        measurementses.Where(o => dataSet.First().Date == o.TimeStamp)
                        .ToDictionary(o => o.ParID, s => s.ParameterName);
                    TrainData.GetData();
                    foreach (KeyValuePair <int, string> keyValuePair in datas)
                    {
                        if (!TrainData.Pairs.ContainsKey(keyValuePair.Value))
                        {
                            TrainData.Pairs.Add(keyValuePair.Value, keyValuePair.Value);
                        }
                    }
                    TrainData.nameParameter = datas;
                    TrainData.Train         = dataSet; // Присвоение статической переменной данных
                }
                catch (InvalidOperationException iex)
                {
                    var parameters = measurementses.Where(o => !o.ParameterName.StartsWith("Def")).ToArray();
                    if (parameters.Count() == 0)
                    {
                        MessageBox.Show(
                            Localization.MyStrings.QualityParameters);
                    }
                    else
                    {
                        MessageBox.Show(iex.ToString());
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }

                sw.Stop();
                var parametersInput = measurementses.Where(o => o.ParameterName.StartsWith("Def")).ToArray();
                if (parametersInput.Count() == 0)
                {
                    MessageBox.Show(
                        Localization.MyStrings.RegimeParameters, Localization.MyStrings.Warning);
                }
                MessageBox.Show(Localization.MyStrings.TimeParameters + sw.Elapsed);
                string pathToShrinkage = System.AppDomain.CurrentDomain.BaseDirectory + "\\Shrinkage.xml";
                if (File.Exists(pathToShrinkage))
                {
                    File.Delete(pathToShrinkage);
                }
            }
            else
            {
                MessageBox.Show(Localization.MyStrings.SelectedParameters);
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Implement FisherCritery
        /// </summary>
        private void FisherCritery()
        {
            if (parameterCondition.Items.Count != 0)
            {
                int                       countElements = 10;
                List <OneRow>             trainData     = TrainData.Train;
                Dictionary <int, decimal> bestValues    = new Dictionary <int, decimal>();
                List <FisherCritery>      fishers       = new List <FisherCritery>();
                try
                {
                    int     parameterID = XMLWork.FindIDWithName((string)parameterCondition.SelectedItem, Properties.Settings.Default.Languages);
                    decimal averageY    = AverageOutput(trainData, parameterID);

                    //Fisher Critery
                    foreach (var item in trainData[0].Input)
                    {
                        Fisher fisher = new Fisher(trainData, item.Key, parameterID, averageY);
                        fisher.CalculateFisher();
                        fishers.Add(new FisherCritery(item.Key, fisher.Critery));
                    }

                    //Sort of data
                    ListOfElements fisherElements = new ListOfElements(fishers);
                    fisherElements.InsertionSort();
                    //Give Best Value
                    for (int i = 0; i < countElements; i++)
                    {
                        bestValues.Add(fisherElements.Fisher[i].Key, fisherElements.Fisher[i].Value);
                    }

                    //Clear Palette
                    this.chart1.Series.Clear();
                    this.chart1.Titles.Clear();
                    this.chart1.ChartAreas[0].AxisY.Maximum = Math.Round(Convert.ToDouble(bestValues.First().Value), 0) + 25;
                    this.chart1.ChartAreas[0].AxisY.Minimum = Math.Round(Convert.ToDouble(bestValues.Last().Value), 0) - 25;

                    // Set palette.
                    this.chart1.Palette = ChartColorPalette.SeaGreen;

                    // Set title.
                    this.chart1.Titles.Add("Critery F-Test");
                    double numberOfParameters = 1.0;

                    foreach (var item in bestValues)
                    {
                        // Add series.
                        Series series = this.chart1.Series.Add(XMLWork.FindNameWithID(item.Key, Properties.Settings.Default.Languages));
                        // Add point.
                        //series.Points.Add(Convert.ToDouble(item.Value));
                        series.Points.AddXY(numberOfParameters, item.Value);
                        numberOfParameters += 0.1;
                    }
                }
                catch (InvalidOperationException ex)
                {
                    MessageBox.Show(Localization.MyStrings.SelectCriterion);
                }
                catch (Exception excep)
                {
                    MessageBox.Show(excep.ToString());
                }
            }
            else
            {
                MessageBox.Show(Localization.MyStrings.WithoutDefect);
            }
            // Add series.
        }
Esempio n. 21
0
        public void LoadFromDB()
        {
            values          = null;
            normalise       = null;
            weights         = null;
            normaliseRandom = null;
            listParameter.Clear();

            values                 = new decimal[ListDelete.Items.Count, TrainData.Train.Count];
            normalise              = new decimal[ListDelete.Items.Count, TrainData.Train.Count];
            normaliseRandom        = new decimal[ListDelete.Items.Count, TrainData.Train.Count];
            weights                = new decimal[ListDelete.Items.Count, Convert.ToInt32(numberOfNeurons.Text)];
            dimensionOfVector.Text = Convert.ToString(ListDelete.Items.Count);

            int count = 0;

            foreach (var item in ListDelete.Items)
            {
                int     parameterID = XMLWork.FindIDWithName(item.ToString(), Properties.Settings.Default.Languages);
                OneRow  row         = TrainData.Train.First();
                decimal value       = 0.0M;
                if (row.Input.ContainsKey(parameterID))
                {
                    value = row.Input[parameterID];
                }
                else if (row.Output.ContainsKey(parameterID))
                {
                    value = row.Output[parameterID];
                }
                listParameter.Add(count, new ParameterCharacteristics(item.ToString(), value, value, value, 0.0M, 0.0M));
                count++;
            }
            if (TrainData.Train.Count > 0)
            {
                int j = 0;
                //Вычисление среднего значения каждого атрибута выборки + сумма, минимум и максимум также вычисляются
                foreach (OneRow row in TrainData.Train)
                {
                    for (int i = 0; i < listParameter.Count; i++)
                    {
                        try
                        {
                            int parameterID = XMLWork.FindIDWithName(listParameter[i].ParameterName, Properties.Settings.Default.Languages);
                            if (row.Input.ContainsKey(parameterID))
                            {
                                values[i, j] = row.Input[parameterID];
                            }
                            else if (row.Output.ContainsKey(parameterID))
                            {
                                values[i, j] = row.Output[parameterID];
                            }
                            if (values[i, j] < listParameter[i].Min)
                            {
                                listParameter[i].Min = values[i, j];
                            }
                            if (values[i, j] > listParameter[i].Max)
                            {
                                listParameter[i].Max = values[i, j];
                            }
                            listParameter[i].Sum += values[i, j];
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                    }
                    j++;
                }
                //Поиск среднего значения по выборке
                for (int i = 0; i < listParameter.Count; i++)
                {
                    listParameter[i].Mean = listParameter[i].Sum / Convert.ToDecimal(TrainData.Train.Count);
                    j = 0;
                    decimal differenceSquares = 0.0M;
                    foreach (OneRow row in TrainData.Train)
                    {
                        differenceSquares += ((values[i, j] - listParameter[i].Mean) * (values[i, j] - listParameter[i].Mean));
                        j++;
                    }
                    listParameter[i].Deviation = differenceSquares / (decimal)(TrainData.Train.Count - 1);
                }



                //Нормализация данных
                for (int i = 0; i < listParameter.Count; i++)
                {
                    for (int k = 0; k < TrainData.Train.Count; k++)
                    {
                        if (listParameter[i].Max - listParameter[i].Min != 0)
                        {
                            normalise[i, k] = Normalisation.NormaliseWithDeviation(values[i, k], listParameter[i].Mean, listParameter[i].Deviation);
                        }
                        else
                        {
                            normalise[i, k] = 0.0M;
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show(Localization.MyStrings.Absent, Localization.MyStrings.Warning);
            }


            //
            int step = TrainData.Train.Count / Convert.ToInt32(numberOfNeurons.Text);

            //Здесь задаются начальные значения весов

            /*
             * for (int j = 0, n = 0; j < TrainData.Train.Count; j = j + step, n++)
             *  {
             *      if (n < Convert.ToInt32(numberOfNeurons.Text))
             *      {
             *          for (int i = 0; i < listParameter.Count; i++)
             *              weights[i,n] = normalise[i,j];
             *      }
             *  }*/
            Random rand = new Random((int)(DateTime.Now.Ticks));

            for (int j = 0; j < Convert.ToInt32(numberOfNeurons.Text); j++)
            {
                for (int k = 0; k < listParameter.Count; k++)
                {
                    weights[k, j] = Randomise.RandomDecimal(rand);
                }
            }
        }
Esempio n. 22
0
        private void ShowThrend(object sender)
        {
            FormsPlot chartControl = chartControl1;

            try
            {
                List <double> xs = new List <double>();
                List <double> ys = new List <double>();
                // Процедура поиска текущего контрола для отрисовки трендов
                if (extruderTabPage.Visible)
                {
                    chartControl = chartTrends;
                }
                if (calenderRollTabPage.Visible)
                {
                    chartControl = chartCalenderRoll;
                }
                if (takeoffRollTabPage.Visible)
                {
                    chartControl = chartTakeOffRoll;
                }
                if (temperingRollTabPage.Visible)
                {
                    chartControl = chartTemperingRoll;
                }
                if (winderTabPage.Visible)
                {
                    chartControl = chartWinder;
                }
                if (qualityTabPage.Visible) // Ситуация когда мы находимся на вкладке показателей качества является нетривиальной
                {
                    chartControl = chartControl1;
                    if (sender is TextBox)
                    {
                        //Поиск текстбокса и указание ограничений по времени
                        TextBox  edit       = sender as TextBox;
                        DateTime timeBefore = TrainData.Train.OrderBy(o => o.Date).First().Date;
                        DateTime timeAfter  = TrainData.Train.OrderByDescending(o => o.Date).First().Date;
                        chartControl.plt.Clear();
                        if (edit.Name.Contains("Shrinkage")) //если выбрана усадка
                        {
                            TimeSpan ts = new TimeSpan(ProductionTime.TakeOffTime);
                            foreach (OneRow row in TrainData.Train)
                            {
                                DataSet AuthorsDataSet = new DataSet();
                                AuthorsDataSet.ReadXml(XMLWork.PathShrinkage);
                                string shrinkageValues = XMLWork.FindShrinkageWithTimestamp(row.Date);
                                if ((row.Date >= timeBefore) && (row.Date <= timeAfter))
                                {
                                    xs.Add((row.Date - ts).ToOADate());
                                    ys.Add(Convert.ToDouble(shrinkageValues.Replace(".", ",")));
                                }
                            }
                            chartControl.plt.PlotScatter(xs.ToArray(), ys.ToArray(), lineWidth: 2, markerShape: MarkerShape.none, label: "Shrinkage value");
                        }
                        else
                        {
                            //Отрисовка
                            int parameterID = XMLWork.FindID(edit.Name.Replace("_", "."));
                            foreach (OneRow row in TrainData.Train)
                            {
                                if ((row.Date >= timeBefore) && (row.Date <= timeAfter))
                                {
                                    xs.Add(row.Date.ToOADate());
                                    ys.Add(Convert.ToDouble(row.Output[parameterID]));
                                }
                            }
                            chartControl.plt.PlotScatter(xs.ToArray(), ys.ToArray(), lineWidth: 2, markerShape: MarkerShape.none, label: XMLWork.FindNameWithID(parameterID, Properties.Settings.Default.Languages));
                        }
                    }
                    chartControl.plt.Ticks(dateTimeX: true);
                    chartControl.plt.Legend(location: legendLocation.upperRight, shadowDirection: shadowDirection.none);
                    chartControl.plt.AxisAuto();
                    double xDelta = Math.Abs(xs.Max() - xs.Min());
                    double yDelta = Math.Abs(ys.Max() - ys.Min());
                    chartControl.plt.Axis(xs.Min() - xDelta * 0.05, xs.Max() + xDelta * 0.05, ys.Min() - yDelta * 0.05, ys.Max() + yDelta * 0.05); chartControl.Render();
                    return;
                }
                if (sender is TextBox)
                {
                    //Поиск текстбокса и указание ограничений по времени
                    TextBox  edit       = sender as TextBox;
                    DateTime timeBefore = TrainData.Train.OrderBy(o => o.Date).First().Date;
                    DateTime timeAfter  = TrainData.Train.OrderByDescending(o => o.Date).First().Date;
                    chartControl.plt.Clear();
                    //Отрисовка
                    int parameterID = XMLWork.FindID(edit.Name);
                    foreach (OneRow row in TrainData.Train)
                    {
                        if ((row.Date >= timeBefore) && (row.Date <= timeAfter) && (!qualityTabPage.Visible))
                        {
                            xs.Add(row.Date.ToOADate());
                            ys.Add(Convert.ToDouble(row.Input[parameterID]));
                        }
                    }
                    chartControl.plt.PlotScatter(xs.ToArray(), ys.ToArray(), lineWidth: 2, markerShape: MarkerShape.none, label: XMLWork.FindNameWithID(parameterID, Properties.Settings.Default.Languages));
                    chartControl.plt.Ticks(dateTimeX: true);
                    chartControl.plt.Legend(location: legendLocation.upperRight, shadowDirection: shadowDirection.none);
                    chartControl.plt.AxisAuto();
                    double xDelta = Math.Abs(xs.Max() - xs.Min());
                    double yDelta = Math.Abs(ys.Max() - ys.Min());
                    chartControl.plt.Axis(xs.Min() - xDelta * 0.05, xs.Max() + xDelta * 0.05, ys.Min() - yDelta * 0.05, ys.Max() + yDelta * 0.05);
                    chartControl.Render();
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(Localization.MyStrings.SomethingWrong + exception.ToString());
            }
        }
Esempio n. 23
0
        bool GetMultipleRegressionModel(string qualityParam)
        {
            double[,] processParametersData;
            double[] qualityParameterData;

            var inputParametersToCheck = checkedListBoxInputParametersToCheckPage3.CheckedItems.Cast <string>().ToList();
            int qualityParameterID     = XMLWork.FindIDWithName(qualityParam, Properties.Settings.Default.Languages);

            processParametersData = new double[TrainData.Train.Count, inputParametersToCheck.Count + 1];
            qualityParameterData  = new double[TrainData.Train.Count];
            //Setting first column of input values of regression matrix X with "1" values
            for (int i = 0; i < processParametersData.GetLength(0); i++)
            {
                processParametersData[i, 0] = 1;
            }

            List <double> parametersLowerBounds = new List <double>(), parametersUpperBounds = new List <double>();

            //Setting all input data
            for (int paramNumber = 0; paramNumber < inputParametersToCheck.Count; paramNumber++)
            {
                double minValue = double.MaxValue, maxValue = double.MinValue;
                int    inputParameterID = XMLWork.FindIDWithName(inputParametersToCheck[paramNumber], Properties.Settings.Default.Languages);
                for (int rowNumber = 0; rowNumber < TrainData.Train.Count; rowNumber++)
                {
                    processParametersData[rowNumber, paramNumber + 1] =
                        (double)TrainData.Train[rowNumber].Input[inputParameterID];
                    if (processParametersData[rowNumber, paramNumber + 1] < minValue)
                    {
                        minValue = processParametersData[rowNumber, paramNumber + 1];
                    }
                    if (processParametersData[rowNumber, paramNumber + 1] > maxValue)
                    {
                        maxValue = processParametersData[rowNumber, paramNumber + 1];
                    }
                }
                parametersLowerBounds.Add(minValue);
                parametersUpperBounds.Add(maxValue);
            }

            //Setting output data
            for (int i = 0; i < TrainData.Train.Count; i++)
            {
                qualityParameterData[i] = (double)TrainData.Train[i].Output[qualityParameterID];
            }

            //Call for multiple regression calculation method
            try
            {
                for (int j = 1; j < processParametersData.GetLength(1); j++)
                {
                    bool throwData = true;
                    for (int i = 0; i < processParametersData.GetLength(0); i++)
                    {
                        if (Math.Abs(processParametersData[i, j]) > DataSensitivityThreshhold)
                        {
                            throwData = false;
                            break;
                        }
                    }
                    if (throwData)
                    {
                        throw new Exception("Incorrect input data");
                    }
                }
                if (!qualityParameterData.Any(item => Math.Abs(item) > DataSensitivityThreshhold))
                {
                    throw new Exception("Incorrect input data");
                }
                var coefficients = Regression.MultipleRegression(processParametersData, qualityParameterData, checkBoxNormalizeValuesPage3.Checked);

                double rmse = Regression.MultipleRMSE(processParametersData, qualityParameterData, coefficients);
                labelRMSEPage3.Text = $"RMSE = {Math.Round(rmse, RMSESignificantDigitsCount)}";

                _multipleRegressionEquation = new RegressionModelEquation("DefaultName", qualityParam,
                                                                          inputParametersToCheck, rmse, coefficients,
                                                                          inputParametersToCheck.ToArray(), parametersLowerBounds.ToArray(), parametersUpperBounds.ToArray(), checkBoxNormalizeValuesPage3.Checked);

                ShowRegressionEquasion(qualityParam, coefficients);
                ShowRegressionEquasionHelp(inputParametersToCheck.ToArray());
                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Exception thrown in multiple regression calculation: \"{ex.Message}\"!");
                return(false);
            }
        }
Esempio n. 24
0
        /// <summary>
        /// Selects parameters in orange
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        /*private void DrawItem(object sender, ListBoxDrawItemEventArgs e)
         * {
         *  ListBoxControl control = (ListBoxControl)sender;
         *  if (e.Index == (control.SelectedIndex))
         *  {
         *      e.Appearance.BackColor = Color.Orange;
         *  }
         * }*/

        #endregion


        private void parameterCondition_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListAdd.Items.Clear();
            ListDelete.Items.Clear();
            ListAddError.Items.Clear();
            ListDeleteError.Items.Clear();
            List <int> keys                    = new List <int>();
            int        parameterID             = XMLWork.FindIDWithName(parameterCondition.SelectedItem.ToString(), Properties.Settings.Default.Languages);
            Dictionary <int, decimal> firstRow = TrainData.Train.First(o => o.Output[parameterID] > (Convert.ToDecimal(uppLimit.Value) * 0.9M)).Input;

            foreach (OneRow data in TrainData.Train)
            {
                if (data.Output[parameterID] > 1.0M)
                {
                    foreach (var item in data.Input)
                    {
                        if (keys.Contains(item.Key))
                        {
                            continue;
                        }
                        if (item.Key != firstRow[item.Key])
                        {
                            keys.Add(item.Key);
                        }
                    }
                }
            }
            foreach (int key in keys)
            {
                ListAdd.Items.Add(XMLWork.FindNameWithID(key, Properties.Settings.Default.Languages));
                ListAddError.Items.Add(XMLWork.FindNameWithID(key, Properties.Settings.Default.Languages));
            }
            addAllToFirstCoordinate.Enabled     = true;
            addAllToSecondCoordinate.Enabled    = true;
            addOneCoordinate.Enabled            = true;
            addOneToSecondCoordinate.Enabled    = true;
            deleteAllToFirstCoordinate.Enabled  = true;
            deleteAllToSecondCoordinate.Enabled = true;
            deleteOneToSecondCoordinate.Enabled = true;
            deleteToFirstCoordinate.Enabled     = true;
            if (parameterCondition.SelectedIndex != -1)
            {
                parameterCondition.BackColor = Color.White;
            }

            if (ListAdd.Items.Count != 0)
            {
                ListAdd.SelectedIndex = 0;
            }
            if (ListDelete.Items.Count != 0)
            {
                ListDelete.SelectedIndex = 0;
            }
            if (ListAddError.Items.Count != 0)
            {
                ListAddError.SelectedIndex = 0;
            }
            if (ListDeleteError.Items.Count != 0)
            {
                ListDeleteError.SelectedIndex = 0;
            }
        }
Esempio n. 25
0
        public Diagramm(List <DM.DecisionTree.TreeNode> rndForests)
        {
            if (!string.IsNullOrEmpty(Properties.Settings.Default.Languages))
            {
                System.Threading.Thread.CurrentThread.CurrentUICulture =
                    System.Globalization.CultureInfo.GetCultureInfo(Properties.Settings.Default.Languages);
                System.Threading.Thread.CurrentThread.CurrentCulture =
                    System.Globalization.CultureInfo.GetCultureInfo(Properties.Settings.Default.Languages);
            }
            InitializeComponent();
            TrainData.GetData();
            List <string>            dictForestsSort = new List <string>();
            List <string>            secForestsSort  = new List <string>();
            Dictionary <string, int> dictForests     = new Dictionary <string, int>();
            Dictionary <string, int> secondForests   = new Dictionary <string, int>();

            foreach (DM.DecisionTree.TreeNode rndForest in rndForests)
            {
                if (!dictForests.ContainsKey(rndForest.attributeName))
                {
                    dictForests.Add(rndForest.attributeName, 1);
                }
                else
                {
                    dictForests[rndForest.attributeName]++;
                }
            }
            dictForestsSort = dictForests.Keys.ToList();

            InsertionSort(dictForestsSort, dictForests);


            this.chart1.Series.Clear();
            this.chart1.Titles.Clear();


            // Set palette.
            this.chart1.Palette = ChartColorPalette.SeaGreen;

            // Set title.
            this.chart1.Titles.Add("1st Node");
            double numberOfParameters = 1.0;

            foreach (var item in dictForestsSort)
            {
                //TODO Russian name
                if ((item != "False") && (item != "True"))
                {
                    var name = TrainData.nameParameter.SingleOrDefault(parameter => parameter.Value == item).Value;
                    // Add series.

                    Series series = this.chart1.Series.Add(XMLWork.FindNameWithScada(item, Properties.Settings.Default.Languages));
                    // Add point.
                    //series.Points.Add(Convert.ToDouble(item.Value));
                    series.Points.Add(dictForests[item]);
                }
            }

            foreach (var rndForest in rndForests)
            {
                foreach (var treeNode in rndForest.MChilds)
                {
                    if ((treeNode != null) && (treeNode.attributeName != "False") && ((treeNode.attributeName != "True")))
                    {
                        if (!secondForests.ContainsKey(treeNode.attributeName))
                        {
                            secondForests.Add(treeNode.attributeName, 1);
                        }
                        else
                        {
                            secondForests[treeNode.attributeName]++;
                        }
                    }
                }
            }

            secForestsSort = secondForests.Keys.ToList();
            InsertionSort(secForestsSort, secondForests);
            this.chart2.Series.Clear();
            this.chart2.Titles.Clear();


            // Set palette.
            this.chart2.Palette = ChartColorPalette.SeaGreen;

            // Set title.
            this.chart2.Titles.Add("2nd Node");

            foreach (var item in secForestsSort)
            {
                //TODO Russian name
                var name = TrainData.nameParameter.Single(parameter => parameter.Value == item).Value;
                // Add series.
                Series series = this.chart2.Series.Add(XMLWork.FindNameWithScada(item, Properties.Settings.Default.Languages));
                // Add point.
                series.Points.Add(secondForests[item]);
            }
        }
Esempio n. 26
0
        void ShowThrends2()
        {
            if ((ListDelete.Items.Count > 10) || (ListDeleteError.Items.Count > 10))
            {
                MessageBox.Show(
                    Localization.MyStrings.ParametersSelected);
                return;
            }
            if (parameterCondition.SelectedIndex == -1)
            {
                MessageBox.Show(Localization.MyStrings.SelectCriterion);
                parameterCondition.BackColor = Color.Red;
                return;
            }
            int parameterID = XMLWork.FindIDWithName(parameterCondition.SelectedItem.ToString(), Properties.Settings.Default.Languages);

            Chart.plt.Clear();
            List <OneRow> trainData = TrainData.Train;
            List <double> xs1 = new List <double>(), ys1 = new List <double>(), xs2 = new List <double>(), ys2 = new List <double>();
            decimal       minX = 0.0M;
            decimal       maxX = 0.0M;
            decimal       minY = 0.0M;
            decimal       maxY = 0.0M;

            foreach (OneRow data in trainData)
            {
                decimal pointX = 1.0M;
                decimal pointY = 1.0M;
                if (data.Output[parameterID] > (Convert.ToDecimal(uppLimit.Value) * 0.9M))
                {
                    GetPoints(ref pointX, data, ref pointY);
                    maxX = pointX;
                    maxY = pointY;
                    minX = pointX;
                    minY = pointY;
                }
                else
                {
                    GetPoints(ref pointX, data, ref pointY);
                    maxX = pointX;
                    maxY = pointY;
                    minX = pointX;
                    minY = pointY;
                }
                break;
            }
            foreach (OneRow data in trainData)
            {
                decimal pointX = 1.0M;
                decimal pointY = 1.0M;
                if (data.Output[parameterID] > (Convert.ToDecimal(uppLimit.Value) * 0.9M))
                {
                    GetPoints(ref pointX, data, ref pointY);
                    if (pointX > maxX)
                    {
                        maxX = pointX;
                    }
                    if (pointY > maxY)
                    {
                        maxY = pointY;
                    }
                    if (pointX < minX)
                    {
                        minX = pointX;
                    }
                    if (pointY < minY)
                    {
                        minY = pointY;
                    }
                    xs1.Add(Convert.ToDouble(pointX));
                    ys1.Add(Convert.ToDouble(pointY));
                }
                else
                {
                    GetPoints(ref pointX, data, ref pointY);
                    if (pointX > maxX)
                    {
                        maxX = pointX;
                    }
                    if (pointY > maxY)
                    {
                        maxY = pointY;
                    }
                    if (pointX < minX)
                    {
                        minX = pointX;
                    }
                    if (pointY < minY)
                    {
                        minY = pointY;
                    }
                    xs2.Add(Convert.ToDouble(pointX));
                    ys2.Add(Convert.ToDouble(pointY));
                }
            }
            Chart.plt.PlotScatter(xs1.ToArray(), ys1.ToArray(), lineWidth: 0, markerShape: MarkerShape.filledCircle, label: Localization.MyStrings.WithD);
            Chart.plt.PlotScatter(xs2.ToArray(), ys2.ToArray(), lineWidth: 0, markerShape: MarkerShape.filledCircle, label: Localization.MyStrings.WithoutD);
            Chart.plt.Legend(location: legendLocation.upperRight, shadowDirection: shadowDirection.none);
            Chart.plt.AxisAuto();
            decimal deltaX = Math.Abs(maxX - minX);
            decimal deltaY = Math.Abs(maxY - minY);

            Chart.plt.Axis(Convert.ToDouble(minX - deltaX * 0.05m), Convert.ToDouble(maxX + deltaX * 0.05m),
                           Convert.ToDouble(minY - deltaY * 0.05m), Convert.ToDouble(maxY + deltaY * 0.05m));
            Chart.Render();
        }
Esempio n. 27
0
        private void trainButton_Click(object sender, EventArgs e)
        {
            if ((parameterCondition.Items.Count != 0) && (ListDelete.Items.Count != 0) && (parameterCondition.SelectedIndex != -1))
            {
                try
                {
                    GetBooleanForOutput(TrainData.Train, criterion.Value);
                    bool falseData   = false;
                    bool trueData    = false;
                    int  parameterID = XMLWork.FindIDWithName(parameterCondition.SelectedItem.ToString(), Properties.Settings.Default.Languages);
                    foreach (OneRow oneRow in TrainData.Train)
                    {
                        if ((oneRow.OutputBool[parameterID] == true) && (trueData == false))
                        {
                            trueData = true;
                        }
                        else if ((oneRow.OutputBool[parameterID] == false) && (falseData == false))
                        {
                            falseData = true;
                        }
                    }

                    if ((falseData) && (trueData))
                    {
                        PreprocessToWorkTree();
                    }
                    else
                    {
                        MessageBox.Show(Localization.MyStrings.AnotherCriterion);
                    }
                }
                catch
                (InvalidOperationException ex)
                {
                    MessageBox.Show(Localization.MyStrings.SelectCriterion);
                    criterion.BackColor          = Color.White;
                    ListDelete.BackColor         = Color.White;
                    parameterCondition.BackColor = Color.Red;
                }
                catch
                (Exception excep)
                {
                    if (criterion.Text.Trim() == "")
                    {
                        MessageBox.Show(Localization.MyStrings.SelectPartitioninCriterion);
                        criterion.BackColor          = Color.Red;
                        ListDelete.BackColor         = Color.White;
                        parameterCondition.BackColor = Color.White;
                    }
                    else if (ListDelete.Items.Count == 0)
                    {
                        MessageBox.Show(Localization.MyStrings.AddParameter);
                        criterion.BackColor          = Color.White;
                        ListDelete.BackColor         = Color.Red;
                        parameterCondition.BackColor = Color.White;
                    }
                    else
                    {
                        MessageBox.Show(excep.ToString());
                        criterion.BackColor          = Color.White;
                        ListDelete.BackColor         = Color.White;
                        parameterCondition.BackColor = Color.White;
                    }
                }
            }
            else
            {
                if (parameterCondition.Items.Count == 0)
                {
                    MessageBox.Show(Localization.MyStrings.WithoutDefect);
                }
                else if ((parameterCondition.SelectedIndex == -1))
                {
                    MessageBox.Show(Localization.MyStrings.SelectCriterion);
                    criterion.BackColor          = Color.White;
                    ListDelete.BackColor         = Color.White;
                    parameterCondition.BackColor = Color.Red;
                }
                if (ListDelete.Items.Count == 0)
                {
                    MessageBox.Show(Localization.MyStrings.AddParameter);
                    criterion.BackColor          = Color.White;
                    ListDelete.BackColor         = Color.Red;
                    parameterCondition.BackColor = Color.White;
                }
            }
            // Add series.
        }
Esempio n. 28
0
        private void DecisionTreeRandomForest()
        {
            var checkData       = new TrainData();
            var analysParameter = new Dictionary <int, string>();
            var trainData       = new TrainData();
            var trainedData     = new TrainData();

            if ((parameterCondition.Items.Count != 0) && (ListDelete.Items.Count != 0) &&
                (parameterCondition.SelectedIndex != -1))
            {
                try
                {
                    GetBooleanForOutput(TrainData.Train, Convert.ToDecimal(criterion.Text));
                    analysParameter = TrainData.nameParameter.Where(o => !o.Value.StartsWith("Def"))
                                      .ToDictionary(o => o.Key, o => o.Value);
                    bool falseData   = false;
                    bool trueData    = false;
                    int  parameterID = XMLWork.FindIDWithName(parameterCondition.SelectedItem.ToString(), Properties.Settings.Default.Languages);
                    foreach (OneRow oneRow in TrainData.Train)
                    {
                        if ((oneRow.OutputBool[parameterID] == true) && (trueData == false))
                        {
                            trueData = true;
                        }
                        else if ((oneRow.OutputBool[parameterID] == false) && (falseData == false))
                        {
                            falseData = true;
                        }
                    }
                    if ((falseData) && (trueData))
                    {
                        PreprocessToWorkTreeRandomForest(trainedData, checkData, analysParameter);
                        System.Windows.Forms.MessageBox.Show(Localization.MyStrings.Over);
                    }
                    else
                    {
                        MessageBox.Show(Localization.MyStrings.AnotherCriterion);
                    }
                }
                catch (FormatException formatException)
                {
                    MessageBox.Show(Localization.MyStrings.SelectPartitioninCriterion);
                    criterion.BackColor          = Color.Red;
                    ListDelete.BackColor         = Color.White;
                    parameterCondition.BackColor = Color.White;
                }
                catch
                (InvalidOperationException ex)
                {
                    MessageBox.Show(Localization.MyStrings.SelectCriterion);
                    criterion.BackColor          = Color.White;
                    ListDelete.BackColor         = Color.White;
                    parameterCondition.BackColor = Color.Red;
                }
                catch (Exception excep)
                {
                    if (ListDelete.Items.Count == 0)
                    {
                        MessageBox.Show(Localization.MyStrings.AddParameter);
                        criterion.BackColor          = Color.White;
                        ListDelete.BackColor         = Color.Red;
                        parameterCondition.BackColor = Color.White;
                    }
                    else
                    {
                        MessageBox.Show(excep.ToString());
                        criterion.BackColor          = Color.White;
                        ListDelete.BackColor         = Color.White;
                        parameterCondition.BackColor = Color.White;
                    }
                }
            }
            else
            {
                if (parameterCondition.Items.Count == 0)
                {
                    MessageBox.Show(Localization.MyStrings.WithoutDefect);
                }
                else if ((parameterCondition.SelectedIndex == -1))
                {
                    MessageBox.Show(Localization.MyStrings.SelectCriterion);
                    criterion.BackColor          = Color.White;
                    ListDelete.BackColor         = Color.White;
                    parameterCondition.BackColor = Color.Red;
                }
                if (ListDelete.Items.Count == 0)
                {
                    MessageBox.Show(Localization.MyStrings.AddParameter);
                    criterion.BackColor          = Color.White;
                    ListDelete.BackColor         = Color.Red;
                    parameterCondition.BackColor = Color.White;
                }
            }
        }
Esempio n. 29
0
        void ShowParameterData(string parameterName)
        {
            if (Calculation.stringName != parameterName)
            {
                Calculation.stringName  = parameterName;
                TextBoxColumnCount.Text = "";
                TextBoxMax.Text         = "";
                TextBoxMin.Text         = "";
            }
            List <KeyValuePair <DateTime, double> > data;

            int parameterID = XMLWork.FindIDWithName(parameterName, Properties.Settings.Default.Languages);
            var scadaName   = XMLWork.FindScadaNameWithID(parameterID);

            if (scadaName.StartsWith("Def"))
            {
                data = (from row in TrainData.Train
                        select new KeyValuePair <DateTime, double>(row.Date, (double)row.Output[parameterID])).ToList();
            }
            else
            {
                data = (from row in TrainData.Train
                        select new KeyValuePair <DateTime, double>(row.Date, (double)row.Input[parameterID])).ToList();
            }

            /* double min, max;
             * min = String.IsNullOrWhiteSpace(TextBoxMin.Text) ? data.Min(item => item.Value) : double.Parse(TextBoxMin.Text);
             * TextBoxMin.Text = min.ToString();
             * max = String.IsNullOrWhiteSpace(TextBoxMax.Text) ? data.Max(item => item.Value) : double.Parse(TextBoxMax.Text);
             * TextBoxMax.Text = max.ToString();*/

            if (options.log)
            {
                data = data.Where(item => item.Value != 0).ToList();
                List <KeyValuePair <DateTime, double> > keyValuePairs = new List <KeyValuePair <DateTime, double> >();
                foreach (var d in data)
                {
                    keyValuePairs.Add(new KeyValuePair <DateTime, double>(d.Key, Math.Round(Math.Log(d.Value), 2)));
                }
                data = keyValuePairs;
                if (!String.IsNullOrWhiteSpace(TextBoxMin.Text) || !String.IsNullOrWhiteSpace(TextBoxMin.Text))
                {
                    if (data.Max(n => n.Value) < Convert.ToDouble(TextBoxMax.Text) || data.Min(n => n.Value) > Convert.ToDouble(TextBoxMin.Text))
                    {
                        TextBoxMin.Text = "";
                        TextBoxMax.Text = "";
                    }
                }
            }
            if (options.unlog)
            {
                List <KeyValuePair <DateTime, double> > keyValuePairs = new List <KeyValuePair <DateTime, double> >();
                foreach (var d in data)
                {
                    keyValuePairs.Add(new KeyValuePair <DateTime, double>(d.Key, Math.Round(Math.Exp(d.Value), 2)));
                }
                data            = keyValuePairs;
                TextBoxMin.Text = "";
                TextBoxMax.Text = "";
            }
            if (options.sigma)
            {
                List <KeyValuePair <DateTime, double> > dataControl;
                double expectedValue     = data.Sum(item => item.Value) / data.Count;
                double standartDeviation = Math.Sqrt(data.Sum(item => Math.Pow(item.Value - expectedValue, 2)) / (data.Count - 1));
                do
                {
                    data              = data.Where(item => item.Value > (expectedValue - 3 * standartDeviation) && item.Value < (expectedValue + 3 * standartDeviation)).ToList();
                    expectedValue     = data.Sum(item => item.Value) / data.Count;
                    standartDeviation = Math.Sqrt(data.Sum(item => Math.Pow(item.Value - expectedValue, 2)) / (data.Count - 1));
                    double a = expectedValue - 3 * standartDeviation;
                    double b = expectedValue + 3 * standartDeviation;
                    dataControl = data.Where(item => item.Value <= a || item.Value >= b).ToList();
                } while (dataControl.Count() > 0);
            }
            double min, max;

            if (options.language)
            {
                TextBoxMin.Text = TextBoxMin.Text.Replace(".", ",");
                TextBoxMax.Text = TextBoxMax.Text.Replace(".", ",");
            }
            else
            {
                TextBoxMin.Text = TextBoxMin.Text.Replace(",", ".");
                TextBoxMax.Text = TextBoxMax.Text.Replace(",", ".");
            }
            min             = String.IsNullOrWhiteSpace(TextBoxMin.Text) ? data.Min(item => item.Value) : double.Parse(TextBoxMin.Text);
            TextBoxMin.Text = min.ToString();
            max             = String.IsNullOrWhiteSpace(TextBoxMax.Text) ? data.Max(item => item.Value) : double.Parse(TextBoxMax.Text);
            TextBoxMax.Text = max.ToString();

            if (options.minmax)
            {
                data = data.Where(item => item.Value >= min && item.Value <= max).ToList();
            }
            dataResult = data;
            ShowChart1(data, parameterName);
            ShowChart2(data, parameterName);
        }