/// <summary> /// Генерация нечетких тенденций /// </summary> /// <param name="seriesId"></param> public static void GenerateFuzzyTrends(int seriesId) { using (var _context = new DissertationDbContext()) using (var transaction = _context.Database.BeginTransaction()) { try { foreach (FuzzyTrendLabel elem in Enum.GetValues(typeof(FuzzyTrendLabel))) { _context.FuzzyTrends.Add(ModelConvector.ToFuzzyTrend(new FuzzyTrendBindingModel { SeriesId = seriesId, TrendName = elem, Weight = Converter.ToFuzzyTrendLabelWeight(elem) })); _context.SaveChanges(); } transaction.Commit(); } catch (Exception) { transaction.Rollback(); throw; } } }
/// <summary> /// Вычисление значения энтропии по нечеткой тенденции /// </summary> /// <param name="point"></param> /// <returns></returns> public static double CalcEntropyByFT(FuzzyTrendLabel lastPointFTN, FuzzyTrendLabel beforeLastPointFTN, FuzzyTrendLabel beforeBeforeLastPointFTN, int seriesId, out int pointNext) { var xNow = Converter.ToFuzzyTrendLabelWeight(lastPointFTN); if (xNow == Converter.TrendWeightNotFound) { throw new Exception(string.Format("Не найден вес для тенденции {0}", lastPointFTN)); } var xLast = Converter.ToFuzzyTrendLabelWeight(beforeLastPointFTN); if (xLast == Converter.TrendWeightNotFound) { throw new Exception(string.Format("Не найден вес для тенденции {0}", beforeLastPointFTN)); } var xLastLast = Converter.ToFuzzyTrendLabelWeight(beforeBeforeLastPointFTN); if (xLastLast == Converter.TrendWeightNotFound) { throw new Exception(string.Format("Не найден вес для тенденции {0}", beforeBeforeLastPointFTN)); } // точка на фазовой полскости для предыдущей точки ряда var beforePoint = CalcPointOnPhasePlane(beforeLastPointFTN, xLastLast - xLast); // точка на фазовой плоскости для текущей точки ряда var nextPoint = CalcPointOnPhasePlane(lastPointFTN, xLast - xNow); pointNext = nextPoint; // получаем энтропию using (var _context = new DissertationDbContext()) { var point = _context.PointTrends.FirstOrDefault(rec => rec.StartPoint == beforePoint && rec.FinishPoint == nextPoint && rec.SeriesDiscriptionId == seriesId); if (point == null) { return(1); } else { point.Count++; _context.SaveChanges(); return(1.0 - point.Weight); } } }
public static void GenerateSituationsByEntropy(int seriesId) { using (var _context = new DissertationDbContext()) using (var transaction = _context.Database.BeginTransaction()) { try { var needForecast = _context.SeriesDescriptions.SingleOrDefault(sd => sd.Id == seriesId).NeedForecast; var labels = EntropyByFT.Entropyes; var trends = (needForecast) ? EntropyByUX.Entropyes4Forecast : EntropyByUX.EntropyesNot4Forecast; int counter = 0; for (int i = 0; i < labels.Count; ++i) { for (int j = 0; j < trends.Count; ++j) { for (int t = 0; t < labels.Count; ++t) { for (int r = 0; r < trends.Count; ++r) { _context.StatisticsByEntropys.Add(new StatisticsByEntropy { NumberSituation = counter++, SeriesDiscriptionId = seriesId, StartStateLingvistUX = trends[j], StartStateLingvistFT = labels[i], EndStateLingvistUX = trends[r], EndStateLingvistFT = labels[t], CountMeet = 0 }); _context.SaveChanges(); } } } } transaction.Commit(); } catch (Exception) { transaction.Rollback(); throw; } } }
public static void GenerateSituationsByFuzzy(int seriesId) { using (var _context = new DissertationDbContext()) using (var transaction = _context.Database.BeginTransaction()) { try { var labels = _context.FuzzyLabels.Where(fl => fl.SeriesDiscriptionId == seriesId).ToList(); var trends = _context.FuzzyTrends.Where(ft => ft.SeriesDiscriptionId == seriesId).ToList(); int counter = 0; for (int i = 0; i < labels.Count; ++i) { for (int j = 0; j < trends.Count; ++j) { for (int t = 0; t < labels.Count; ++t) { for (int r = 0; r < trends.Count; ++r) { _context.StatisticsByFuzzys.Add(new StatisticsByFuzzy { NumberSituation = counter++, SeriesDiscriptionId = seriesId, StartStateFuzzyLabelId = labels[i].Id, StartStateFuzzyTrendId = trends[j].Id, EndStateFuzzyLabelId = labels[t].Id, EndStateFuzzyTrendId = trends[r].Id, CountMeet = 0 }); _context.SaveChanges(); } } } } transaction.Commit(); } catch (Exception) { transaction.Rollback(); throw; } } }
/// <summary> /// Определение ситуации по энтропиям, увеличение статистики по этой ситуации /// </summary> /// <param name="point"></param> /// <returns></returns> private StatisticsByEntropy GetStateEntropy(PointInfo point) { using (var _context = new DissertationDbContext()) { var startEntropyUX = Converter.ToLingvistUX(_points[_points.Count - 1].EntropuUX, _points[_points.Count - 1].PositionFUX); var startEntropyFT = Converter.ToLingvistFT(_points[_points.Count - 1].EntropyFT); var endEntropyUX = Converter.ToLingvistUX(point.EntropuUX, point.PositionFUX); var endEntropyFT = Converter.ToLingvistFT(point.EntropyFT); var stateEntropy = _context.StatisticsByEntropys.SingleOrDefault(r => r.StartStateLingvistUX == startEntropyUX && r.StartStateLingvistFT == startEntropyFT && r.EndStateLingvistUX == endEntropyUX && r.EndStateLingvistFT == endEntropyFT && r.SeriesDiscriptionId == point.SeriesDiscriptionId); if (stateEntropy == null) { var number = _context.StatisticsByEntropys .Where(sbf => sbf.SeriesDiscriptionId == point.SeriesDiscriptionId) .Select(sbf => sbf.NumberSituation) .DefaultIfEmpty() .Max() + 1; stateEntropy = new StatisticsByEntropy { SeriesDiscriptionId = point.SeriesDiscriptionId, StartStateLingvistUX = startEntropyUX, StartStateLingvistFT = startEntropyFT, EndStateLingvistUX = endEntropyUX, EndStateLingvistFT = endEntropyFT, NumberSituation = number, CountMeet = 1 }; _context.StatisticsByEntropys.Add(stateEntropy); } else { stateEntropy.CountMeet++; } _context.SaveChanges(); return(stateEntropy); } }
/// <summary> /// Определение ситуации по нечеткости, увеличение статистики по этой ситуации /// </summary> /// <param name="point"></param> /// <returns></returns> private StatisticsByFuzzy GetStateFuzzy(PointInfo point) { using (var _context = new DissertationDbContext()) { var startLabelId = _points[_points.Count - 1].FuzzyLabelId; var startTrendId = _points[_points.Count - 1].FuzzyTrendId; var stateFuzzy = _context.StatisticsByFuzzys.SingleOrDefault(r => r.StartStateFuzzyLabelId == startLabelId && r.StartStateFuzzyTrendId == startTrendId && r.EndStateFuzzyLabelId == point.FuzzyLabelId && r.EndStateFuzzyTrendId == point.FuzzyTrendId && r.SeriesDiscriptionId == point.SeriesDiscriptionId); if (stateFuzzy == null) { var number = _context.StatisticsByFuzzys .Where(sbf => sbf.SeriesDiscriptionId == point.SeriesDiscriptionId) .Select(sbf => sbf.NumberSituation) .DefaultIfEmpty() .Max() + 1; stateFuzzy = new StatisticsByFuzzy { SeriesDiscriptionId = point.SeriesDiscriptionId, StartStateFuzzyLabelId = startLabelId.Value, StartStateFuzzyTrendId = startTrendId.Value, EndStateFuzzyLabelId = point.FuzzyLabelId.Value, EndStateFuzzyTrendId = point.FuzzyTrendId.Value, NumberSituation = number, CountMeet = 1 }; _context.StatisticsByFuzzys.Add(stateFuzzy); } else { stateFuzzy.CountMeet++; } _context.SaveChanges(); return(stateFuzzy); } }
private bool MakeTest(FileInfo file) { using (var _context = new DissertationDbContext()) { try { var entity = ModelConvector.ToSeriesDescription(new SeriesDescriptionBindingModel { SeriesName = file.Name, NeedForecast = true }); _context.SeriesDescriptions.Add(entity); _context.SaveChanges(); #region Временной ряд var res = CreateFuzzyLabel(file.FullName, entity.Id); if (!res) { return(false); } _context.LogDatas.Add(new LogData { DateLog = DateTime.Now, MessageLogType = "Info", MessageLogTitle = file.Name, MessageLog = string.Format("{0} нечеткие метки получены", file.Name) }); res = CreateFuzzyTrend(file.FullName, entity.Id); if (!res) { return(false); } _context.LogDatas.Add(new LogData { DateLog = DateTime.Now, MessageLogType = "Info", MessageLogTitle = file.Name, MessageLog = string.Format("{0} нечеткие тенденции получены", file.Name) }); res = CreateRuleTrend(file.FullName, entity.Id); if (!res) { return(false); } _context.LogDatas.Add(new LogData { DateLog = DateTime.Now, MessageLogType = "Info", MessageLogTitle = file.Name, MessageLog = string.Format("{0} правила для тенденций получены", file.Name) }); res = CreatePointTrend(file.FullName, entity.Id); if (!res) { return(false); } _context.LogDatas.Add(new LogData { DateLog = DateTime.Now, MessageLogType = "Info", MessageLogTitle = file.Name, MessageLog = string.Format("{0} точки для тенденций получены", file.Name) }); res = GenerateSituationsByEntropy(file.FullName, entity.Id); if (!res) { return(false); } _context.LogDatas.Add(new LogData { DateLog = DateTime.Now, MessageLogType = "Info", MessageLogTitle = file.Name, MessageLog = string.Format("{0} ситуации по энтропии получены", file.Name) }); res = GenerateSituationsByFuzzy(file.FullName, entity.Id); if (!res) { return(false); } _context.LogDatas.Add(new LogData { DateLog = DateTime.Now, MessageLogType = "Info", MessageLogTitle = file.Name, MessageLog = string.Format("{0} ситуации по нечеткости получены", file.Name) }); #endregion lock (runForecast) { _countPoints = 0; _points = new List <PointInfo>(); var test = ModelConvector.ToDiagnosticTest(new DiagnosticTestBindingModel { TestNumber = "1", FileName = file.FullName, TypeFile = TypeFile.Текстовый, DatasInFile = new List <TypeDataInFile> { TypeDataInFile.ЧисловоеЗначение }, SeriesDiscriptionId = entity.Id, CountPointsForMemmory = 5 }); test.DateTest = DateTime.Now; test.Count = 0; _context.DiagnosticTests.Add(test); _context.SaveChanges(); _context.LogDatas.Add(new LogData { DateLog = DateTime.Now, MessageLogType = "Info", MessageLogTitle = file.Name, MessageLog = string.Format("{0} создали тест", file.Name) }); var values = LoadFromTxt(file.FullName); if (values != null && values.Count > 1) { _context.LogDatas.Add(new LogData { DateLog = DateTime.Now, MessageLogType = "Info", MessageLogTitle = file.Name, MessageLog = string.Format("{0} загрузили данные", file.Name) }); for (int i = 0; i < values.Count - 1; ++i) { AddNewPoint(new PointInfo { SeriesDiscriptionId = entity.Id, DiagnosticTestId = test.Id, Value = values[i] }, entity.Id); } _context.LogDatas.Add(new LogData { DateLog = DateTime.Now, MessageLogType = "Info", MessageLogTitle = file.Name, MessageLog = string.Format("{0} обработали данные", file.Name) }); test.Count = _countPoints; var lastPoint = _points[_points.Count - 1]; lastPoint.IsLast = true; ClearPoint(lastPoint); _context.PointInfos.Add(lastPoint); _context.SaveChanges(); var preLastPoint = _points[_points.Count - 2]; ClearPoint(preLastPoint); _context.PointInfos.Add(preLastPoint); _context.SaveChanges(); _context.LogDatas.Add(new LogData { DateLog = DateTime.Now, MessageLogType = "Info", MessageLogTitle = file.Name, MessageLog = string.Format("{0} сохранили последние точки", file.Name) }); _context.SaveChanges(); var forecast = mdt.GetForecast(test.Id); var forecasts = string.Join(";", mdt.GetForecastByPointTrend(test.Id)); _context.LogDatas.Add(new LogData { DateLog = DateTime.Now, MessageLogType = "Info", MessageLogTitle = file.Name, MessageLog = string.Format("{0} получили прогноз", file.Name) }); var realValue = values[values.Count - 1]; _context.ExperimentFileResults.Add(new ExperimentFileResult { DateExperiment = DateTime.Now, Forecast = forecast, ForecastsByPoint = forecasts, RealValue = realValue, FileName = file.Name }); _context.SaveChanges(); _context.LogDatas.Add(new LogData { DateLog = DateTime.Now, MessageLogType = "Info", MessageLogTitle = file.Name, MessageLog = string.Format("{0} сохранили прогноз", file.FullName) }); _context.SaveChanges(); } else { _context.SaveChanges(); _context.LogDatas.Add(new LogData { DateLog = DateTime.Now, MessageLogType = "Error", MessageLogTitle = file.Name, MessageLog = string.Format("{0} не получили точек", file.FullName) }); _context.SaveChanges(); } } return(true); } catch (Exception ex) { _context.LogDatas.Add(new LogData { DateLog = DateTime.Now, MessageLog = string.Format("MakeTest {0}: {1}", file.FullName, ex.Message), MessageLogType = "Error" }); _context.SaveChanges(); return(false); } } }
/// <summary> /// Настройка весов для созданныых точек /// </summary> /// <param name="seriesId"></param> /// <returns></returns> private static bool SetWeightForPoint(int seriesId) { using (var _context = new DissertationDbContext()) { try { var groupPoints = _context.PointTrends.Where(pt => pt.SeriesDiscriptionId == seriesId).GroupBy(pt => pt.StartPoint).ToList(); foreach (var groupPoint in groupPoints) { var points = groupPoint.OrderByDescending(pt => pt.Count).ToList(); List <int> deltas = new List <int>(); if (points.Count == 0) { } else if (points.Count == 1) { points[0].Weight = 1; _context.SaveChanges(); continue; } else if (points.Count == 2) { var delta = Math.Abs(points[0].Count - points[1].Count); if (delta < 5) { points[0].Weight = 0.5; points[1].Weight = 0.5; } else { points[0].Weight = 1; points[1].Weight = 0.5; } } else if (points.Count == 3) { var delta1 = Math.Abs(points[0].Count - points[1].Count); var delta2 = Math.Abs(points[1].Count - points[2].Count); if (delta1 < delta2) { points[0].Weight = 0.5; points[1].Weight = 0.5; } else { points[0].Weight = 1; points[1].Weight = 0.5; points[2].Weight = 0.5; } } else { points[0].Weight = 1; for (int i = 1; i < points.Count; ++i) { points[i].Weight = 0.5; } } _context.SaveChanges(); } return(true); } catch (Exception) { throw; } } }
/// <summary> /// Обработка новой точки /// </summary> /// <param name="point"></param> /// <param name="seriesId"></param> /// <returns></returns> private static bool AddNewPoint(PointInfo point, int seriesId) { using (var _context = new DissertationDbContext()) { try { if (_points.Count > 0) {//если уже есть точки, получить тенденцию point = ModelCalculator.CalcFUX(point, seriesId); var fuzzyLabelId = _points[_points.Count - 1].FuzzyLabelId; var rule = _context.RuleTrends.SingleOrDefault(r => r.FuzzyLabelFromId == fuzzyLabelId && r.FuzzyLabelToId == point.FuzzyLabelId); if (rule == null) { throw new Exception(string.Format("Нет правила для такого сочитания нечетких меток: {0} и {1}", _points[_points.Count - 1].FuzzyLabel.FuzzyLabelName, point.FuzzyLabel.FuzzyLabelName)); } point.FuzzyTrendId = rule.FuzzyTrendId; point.FuzzyTrend = _context.FuzzyTrends.Single(ft => ft.Id == rule.FuzzyTrendId); if (_points.Count > 2) {//если есть возможность, получить энтропию по тенденции var xNow = Converter.ToFuzzyTrendLabelWeight(point.FuzzyTrend.TrendName); if (xNow == Converter.TrendWeightNotFound) { throw new Exception(string.Format("Не найден вес для тенденции {0}", point.FuzzyTrend.TrendName)); } var xLast = Converter.ToFuzzyTrendLabelWeight(_points[_points.Count - 1].FuzzyTrend.TrendName); if (xLast == Converter.TrendWeightNotFound) { throw new Exception(string.Format("Не найден вес для тенденции {0}", _points[_points.Count - 1].FuzzyTrend.TrendName)); } var xLastLast = Converter.ToFuzzyTrendLabelWeight(_points[_points.Count - 2].FuzzyTrend.TrendName); if (xLastLast == Converter.TrendWeightNotFound) { throw new Exception(string.Format("Не найден вес для тенденции {0}", _points[_points.Count - 2].FuzzyTrend.TrendName)); } // скорость преращения тенденции в предыдущей точке var speedTrendLast = xLastLast - xLast; // скорость преращения тенденции в ткущей точке var speedTrend = xLast - xNow; int beforePoint = ModelCalculator.CalcPointOnPhasePlane(_points[_points.Count - 1].FuzzyTrend.TrendName, speedTrendLast); int nextPoint = ModelCalculator.CalcPointOnPhasePlane(point.FuzzyTrend.TrendName, speedTrend); var pointTrend = _context.PointTrends.FirstOrDefault(p => p.StartPoint == beforePoint && p.FinishPoint == nextPoint && p.SeriesDiscriptionId == seriesId); if (pointTrend == null) { pointTrend = new PointTrend { StartPoint = beforePoint, FinishPoint = nextPoint, Count = 1, Weight = 0, SeriesDiscriptionId = seriesId, Trends = point.FuzzyTrend.TrendName.ToString() }; _context.PointTrends.Add(pointTrend); } else { if (!pointTrend.Trends.Contains(point.FuzzyTrend.TrendName.ToString())) { pointTrend.Trends += string.Format(", {0}", point.FuzzyTrend.TrendName); } pointTrend.Count++; } _context.SaveChanges(); } } else { point = ModelCalculator.CalcFUX(point, seriesId); } if (_points.Count == 5) { _points.RemoveAt(0); } _points.Add(point);//занести точку return(true); } catch (Exception) { throw; } } }