public FuzzySet(string label, IMembershipFunction membershipFunction, double xmin, double xmax) { Label = label ?? throw new ArgumentNullException(nameof(label)); MembershipFunction = membershipFunction ?? throw new ArgumentNullException(nameof(membershipFunction)); Xmin = xmin; Xmax = xmax; }
public CompositeMembershipFunction(String name, IMembershipFunction leftFunction, IMembershipFunction rightFunction, double midPoint) : base(name) { _leftFunction = leftFunction; _rightFunction = rightFunction; _midPoint = midPoint; }
public FuzzySet(string description, IMembershipFunction membershipFunction, double minValueOfColumn, double maxValueOfColumn) { Description = description; MembershipFunction = membershipFunction; MinValueOfColumn = minValueOfColumn; MaxValueOfColumn = maxValueOfColumn; }
/// <summary> /// Constructor /// </summary> /// <param name="composType">Membership functions composition type</param> /// <param name="mf1">Membership function 1</param> /// <param name="mf2">Membership function 2</param> public CompositeMembershipFunction( MfCompositionType composType, IMembershipFunction mf1, IMembershipFunction mf2) : this(composType) { _mfs.Add(mf1); _mfs.Add(mf2); }
/// <summary> /// Initializes a new instance of the <see cref="FuzzySet"/> class. /// </summary> /// <param name="state"> /// The state. /// </param> /// <param name="function"> /// The membership function. /// </param> public FuzzySet(string state, IMembershipFunction function) { Validate.NotNull(state, nameof(state)); Validate.NotNull(function, nameof(function)); this.State = FuzzyState.Create(state); this.function = function; }
public static string GetMembershipString(IMembershipFunction memFun) { var memFunName = memFun.Name; memFunName = memFunName.Replace("triangular", "tri"); memFunName = memFunName.Replace("trapezoidal", "trap"); return(memFunName); }
private FuzzySet(List <Tuple <Double, Double> > set) { mSet.Clear(); foreach (var el in set) { mSet.Add(new Tuple <double, double>(el.Item1, el.Item2)); } fun = null; }
public FuzzySet(double[] input, double[] value, IMembershipFunction memberShipFunction) { mSet.Clear(); for (int i = 0; i < input.Length; i++) { mSet.Add(new Tuple <double, double>(input[i], memberShipFunction.Calc(value[i]))); } fun = memberShipFunction; }
public AverageSalary() { Input = new LinguisticVariable("averageSalary"); Low = Input.MembershipFunctions.AddTrapezoid("Low", 0, 13000, 16000, 19000); Medium = Input.MembershipFunctions.AddTrapezoid("Medium", 19000, 26000, 32000, 35000); High = Input.MembershipFunctions.AddTrapezoid("High", 35000, 38000, 42000, 45000); VeryHigh = Input.MembershipFunctions.AddGaussian("VeryHigh", 100000, 55000); }
public NonWhiteBritishEthnicityPercentage() { Input = new LinguisticVariable("nonWhiteBritishEthnicityPercentage"); Low = Input.MembershipFunctions.AddGaussian("Low", 0, 8.25); Medium = Input.MembershipFunctions.AddGaussian("Medium", 18, 4.25); High = Input.MembershipFunctions.AddGaussian("High", 49.5, 8.25); VeryHigh = Input.MembershipFunctions.AddGaussian("VeryHigh", 100, 17.5); }
public NumberOfUniversities() { Input = new LinguisticVariable("numberOfUniversities"); Low = Input.MembershipFunctions.AddTriangle("Low", -4, 0, 4); Medium = Input.MembershipFunctions.AddGaussian("Medium", 8, 4); High = Input.MembershipFunctions.AddGaussian("High", 20, 4); VeryHigh = Input.MembershipFunctions.AddGaussian("VeryHigh", 40, 12); }
public PopulationDensity() { Input = new LinguisticVariable("populationDensity"); VeryLow = Input.MembershipFunctions.AddTrapezoid("VeryLow", 0, 40, 80, 120); Low = Input.MembershipFunctions.AddTrapezoid("Low", 100, 300, 650, 1000); Medium = Input.MembershipFunctions.AddTriangle("Medium", 100, 3000, 9000); High = Input.MembershipFunctions.AddGaussian("High", 11000, 2000); VeryHigh = Input.MembershipFunctions.AddGaussian("VeryHigh", 17000, 4000); }
public PoliticalLeaning() { Output = new LinguisticVariable("politicalLeaning"); HardLeft = Output.MembershipFunctions.AddGaussian("HardLeft", 0, 10); Left = Output.MembershipFunctions.AddGaussian("Left", 20, 8); CentreLeft = Output.MembershipFunctions.AddGaussian("CentreLeft", 40, 8); Centre = Output.MembershipFunctions.AddTriangle("Centre", 40, 50, 60); CentreRight = Output.MembershipFunctions.AddGaussian("CentreRight", 60, 8); Right = Output.MembershipFunctions.AddGaussian("Right", 80, 8); HardRight = Output.MembershipFunctions.AddGaussian("HardRight", 100, 10); }
private List <Player> Support(List <Player> entries, IMembershipFunction function) { List <Player> result = new List <Player>(); entries.ForEach((e) => { if (function.GetMembership(FieldExtractor(e)) > 0) { result.Add(e); } }); return(result); }
public static FuzzyRuleCondition IsNot(this LinguisticVariable value, IMembershipFunction function) { if (null == function) { throw new ArgumentNullException("function"); } var @operator = new FuzzyRuleToken("NOT", FuzzyRuleTokenType.Not); var clause = new FuzzyRuleCondition(value, @operator, function); return(clause); }
public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { base.OnStateEnter(animator, stateInfo, layerIndex); _currentInterval = 0; _currentMaxInterval = interval; _enemyCount = new LinguisticVariable("_enemyCount"); _few = _enemyCount.MembershipFunctions.AddTrapezoid("_few", 0, 0, 5, 12.5); _some = _enemyCount.MembershipFunctions.AddTriangle("_some", 5, 12.5, 21.25); _many = _enemyCount.MembershipFunctions.AddTrapezoid("_many", 12.5, 21.25, 25, 25); _enemyDistance = new LinguisticVariable("_enemyDistance"); _close = _enemyDistance.MembershipFunctions.AddTrapezoid("_close", 0, 0, 1, 10); _med = _enemyDistance.MembershipFunctions.AddTriangle("_med", 1, 10, 17); _far = _enemyDistance.MembershipFunctions.AddTrapezoid("_far", 10, 17, 20, 20); _power = new LinguisticVariable("_power"); _light = _power.MembershipFunctions.AddTrapezoid("_light", 0, 0, 2, 5); _norm = _power.MembershipFunctions.AddTriangle("_norm", 2, 5, 7.6); _heavy = _power.MembershipFunctions.AddTrapezoid("_heavy", 5, 7.6, 10, 10); _fuzzyEngine = new FuzzyEngineFactory().Default(); var rule1 = Rule.If(_enemyDistance.Is(_close).And(_enemyCount.Is(_few))).Then(_power.Is(_norm)); var rule2 = Rule.If(_enemyDistance.Is(_close).And(_enemyCount.Is(_some))).Then(_power.Is(_heavy)); var rule3 = Rule.If(_enemyDistance.Is(_close).And(_enemyCount.Is(_many))).Then(_power.Is(_heavy)); var rule4 = Rule.If(_enemyDistance.Is(_med).And(_enemyCount.Is(_few))).Then(_power.Is(_light)); var rule5 = Rule.If(_enemyDistance.Is(_med).And(_enemyCount.Is(_some))).Then(_power.Is(_norm)); var rule6 = Rule.If(_enemyDistance.Is(_med).And(_enemyCount.Is(_many))).Then(_power.Is(_heavy)); var rule7 = Rule.If(_enemyDistance.Is(_far).And(_enemyCount.Is(_few))).Then(_power.Is(_light)); var rule8 = Rule.If(_enemyDistance.Is(_far).And(_enemyCount.Is(_some))).Then(_power.Is(_light)); var rule9 = Rule.If(_enemyDistance.Is(_far).And(_enemyCount.Is(_many))).Then(_power.Is(_norm)); _fuzzyEngine.Rules.Add( rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8, rule9 ); }
/// <summary> /// Handles the Click event of the ButtonAddTerm control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private void ButtonAddTerm_Click(object sender, EventArgs e) { var term = new TermModel(this.textBoxTermName.Text.ToString()); if (this.comboBoxVariableForm.SelectedItem == null || string.IsNullOrEmpty(term.Name)) { return; } IMembershipFunction function = null; if (this.comboBoxVariableForm.SelectedItem.Equals("Triangle")) { // TODO: Make validation for entered values. function = new TriangleMembershipFunction { Left = Int32.Parse(this.textBoxTriangleLeft.Text), Middle = Int32.Parse(this.textBoxTriangleMiddle.Text), Right = Int32.Parse(this.textBoxTriangleRight.Text) }; } else if (this.comboBoxVariableForm.SelectedItem.Equals("Gauss")) { // TODO: Make validation function = new GaussMembershipFunction { B = Int32.Parse(this.textBoxGaussB.Text), C = Int32.Parse(this.textBoxGaussC.Text) }; } term.Function = function; /// Checks if term was edited or created new one. if (this.newFuzzyVariable.Terms.Any(t => t.Name.Equals(this.textBoxTermName.Text.ToString()))) { int termIndex = this.newFuzzyVariable.Terms.FindIndex(t => t.Name.Equals(this.textBoxTermName.Text)); this.newFuzzyVariable.Terms[termIndex] = term; } else { this.newFuzzyVariable.Terms.Add(term); } this.ClearTermField(); this.UpdateListBox(); this.UpdateChart(term); }
private void CoG_Defuzzify(IMembershipFunction memFunc, Double expectedResult) { //Arrange LinguisticVariable temp = new LinguisticVariable("v"); temp.MembershipFunctions.Add(memFunc); memFunc.PremiseModifier = 1; var defuzz = new CoGDefuzzification(); //Act var result = defuzz._Defuzzify(temp.MembershipFunctions.ToList()); //Assert Assert.That(Math.Floor(result), Is.EqualTo(expectedResult)); }
public LinguisticVariable(string text, string attributeName, bool quantifierAbsolute, IMembershipFunction membershipFunction) { Text = text; AttributeName = attributeName; if (attributeName == "Quantifier") { Type = ""; } else if (attributeName == "Age" || attributeName == "Height" || attributeName == "Weight" || attributeName == "Sprint") { Type = "are"; } else { Type = "have"; } QuantifierAbsolute = quantifierAbsolute; MembershipFunction = membershipFunction; }
public Variable(VariableConfig config, Chart chart) { _chart = chart; _range = config.Range; Name = config.Name; Type = config.Type; _sets = new List <FuzzySet>(); ResultValue = null; foreach (SetConfig setConfig in config.sets) { IMembershipFunction membershipFunction = null; switch (setConfig.Type) { case SetType.TrapezoidalFunctionCenter: membershipFunction = new TrapezoidalFunction(setConfig.Values[0], setConfig.Values[1], setConfig.Values[2], setConfig.Values[3]); break; case SetType.TrapezoidalFunctionLeft: membershipFunction = new TrapezoidalFunction(setConfig.Values[0], setConfig.Values[1], TrapezoidalFunction.EdgeType.Right); break; case SetType.TrapezoidalFunctionRight: membershipFunction = new TrapezoidalFunction(setConfig.Values[0], setConfig.Values[1], TrapezoidalFunction.EdgeType.Left); break; default: break; } FuzzySet newSet = new FuzzySet(setConfig.Name, membershipFunction); _sets.Add(newSet); } Initialize(); }
/// <summary> /// Initializes a new instance of the <see cref="FuzzySet"/> class. /// </summary> /// <param name="labelEnum"> /// The label enumeration. /// </param> /// <param name="function"> /// The membership function. /// </param> public FuzzySet(Enum labelEnum, IMembershipFunction function) : this(labelEnum.ToString(), function) { }
public Quantifier(string label, IMembershipFunction membership, QuantifierType type, double xmin, double xmax) : base(label, membership, xmin, xmax) { Type = type; }
/// <summary> /// Constructor /// </summary> /// <param name="name">Term name</param> /// <param name="upperMF">Membership function initially associated with the term</param> public Type2FuzzyTerm(string name, IMembershipFunction upperMF, IMembershipFunction lowerMF) : base(name) { this.upperMF = upperMF; this.lowerMF = lowerMF; }
double Defuzzify(IMembershipFunction mf, double min, double max) { if (_defuzzMethod == DefuzzificationMethod.Centroid) { int k = 50; double step = (max - min) / k; // // Calculate a center of gravity as integral // double ptLeft = 0.0; double ptCenter = 0.0; double ptRight = 0.0; double valLeft = 0.0; double valCenter = 0.0; double valRight = 0.0; double val2Left = 0.0; double val2Center = 0.0; double val2Right = 0.0; double numerator = 0.0; double denominator = 0.0; for (int i = 0; i < k; i++) { if (i == 0) { ptRight = min; valRight = mf.GetValue(ptRight); val2Right = ptRight * valRight; } ptLeft = ptRight; ptCenter = min + step * ((double)i + 0.5); ptRight = min + step * (i + 1); valLeft = valRight; valCenter = mf.GetValue(ptCenter); valRight = mf.GetValue(ptRight); val2Left = val2Right; val2Center = ptCenter * valCenter; val2Right = ptRight * valRight; numerator += step * (val2Left + 4 * val2Center + val2Right) / 3.0; denominator += step * (valLeft + 4 * valCenter + valRight) / 3.0; } return(numerator / denominator); } else if (_defuzzMethod == DefuzzificationMethod.Bisector) { // TODO: throw new NotSupportedException(); } else if (_defuzzMethod == DefuzzificationMethod.AverageMaximum) { // TODO: throw new NotSupportedException(); } else { throw new Exception("Internal exception."); } }
/// <summary> /// Initializes a new instance of the <see cref="FuzzySet"/> class. /// </summary> /// /// <param name="name">Name of the fuzzy set.</param> /// <param name="function">Membership function that will define the shape of the fuzzy set. </param> /// public FuzzySet( string name, IMembershipFunction function ) { this.name = name; this.function = function; }
double Defuzzify(IMembershipFunction mf, double min, double max) { if (_defuzzMethod == DefuzzificationMethod.Centroid) { int k = 50; double step = (max - min) / k; // // Calculate a center of gravity as integral // double ptLeft = 0.0; double ptCenter = 0.0; double ptRight = 0.0; double valLeft = 0.0; double valCenter = 0.0; double valRight = 0.0; double val2Left = 0.0; double val2Center = 0.0; double val2Right = 0.0; double numerator = 0.0; double denominator = 0.0; for (int i = 0; i < k; i++) { if (i == 0) { ptRight = min; valRight = mf.GetValue(ptRight); val2Right = ptRight * valRight; } ptLeft = ptRight; ptCenter = min + step * ((double)i + 0.5); ptRight = min + step * (i + 1); valLeft = valRight; valCenter = mf.GetValue(ptCenter); valRight = mf.GetValue(ptRight); val2Left = val2Right; val2Center = ptCenter * valCenter; val2Right = ptRight * valRight; numerator += step * (val2Left + 4 * val2Center + val2Right) / 3.0; denominator += step * (valLeft + 4 * valCenter + valRight) / 3.0; } return numerator / denominator; } else if (_defuzzMethod == DefuzzificationMethod.Bisector) { // TODO: throw new NotSupportedException(); } else if (_defuzzMethod == DefuzzificationMethod.AverageMaximum) { // TODO: throw new NotSupportedException(); } else { throw new Exception("Internal exception."); } }
public Conclusion(LinguisticVariable variable, IFuzzyRuleToken @operator, IMembershipFunction function) : base(variable, @operator, function) { }
/// <summary> /// Constructor /// </summary> /// <param name="name">Term name</param> /// <param name="mf">Membership function initially associated with the term</param> public FuzzyTerm(string name, IMembershipFunction mf) : base(name) { _mf = mf; }
/// <summary> /// Initializes a new instance of the <see cref="FuzzySet"/> class. /// </summary> /// /// <param name="name">Name of the fuzzy set.</param> /// <param name="function">Membership function that will define the shape of the fuzzy set. </param> /// public FuzzySet(string name, IMembershipFunction function) { this.name = name; this.function = function; }
public Summarizator(string description, string attributeName, IMembershipFunction membershipFunction, double minValueOfColumn, double maxValueOfColumn) : base(description, membershipFunction, minValueOfColumn, maxValueOfColumn) { AttributeName = attributeName; }
/// <summary> /// Обучение Fis /// </summary> /// <param name="anfisTrain">Функция обучения</param> public void Train(anfisTrain anfisTrain = null) { // // Генерация Fis // Genfis(); // // Обучение Fis // int epoch = 1; double epochError; if (Rules.Count == 0) { throw new Exception("Должно быть хотя бы одно правило."); } int k = xout.Length; // Количество параметров обучающей выборки int l = (xin.Length + 1) * Rules.Count; // (m+1)n - m - количество входных переменных n - количество правил Matrix C = new Matrix(l, 1); // Столбец весовых коэффициентов Matrix Y = new Matrix(k, 1); // Вектор столбец выходных данных for (int i = 0; i < k; i++) { Y[i, 0] = xout[i]; } errorTrain = new double[Epochs]; while (epoch <= Epochs) { epochError = 0.0; // Ошибка на i эпохе // // Формирование матрицы коэффициентов // Matrix W = new Matrix(k, l); Matrix ew = new Matrix(k, Rules.Count); for (int i = 0; i < k; i++) { Dictionary <FuzzyVariable, double> inputValues = new Dictionary <FuzzyVariable, double>(); // По количеству переменных for (int j = 0; j < xin.Length; j++) { inputValues.Add(InputByName(NameInput + (j + 1).ToString()), xin[j][i]); } // Посылки правил Dictionary <FuzzyVariable, Dictionary <FuzzyTerm, double> > fuzzyInput = Fuzzify(inputValues); // Агрегирование подусловий Dictionary <SugenoFuzzyRule, double> rulesWeight = EvaluateConditions(fuzzyInput); // Заключение правил double Stau = 0.0; List <double> tau = new List <double>(); foreach (double _tau in rulesWeight.Values) { Stau += _tau; tau.Add(_tau); } double[] b = new double[tau.Count]; for (int j = 0; j < b.Length; j++) { b[j] = tau[j] / Stau; ew[i, j] = tau[j]; } // Формирование входных переменных double[] x = new double[xin.Length + 1]; // +1, т.к. x0 = 1 x[0] = 1; // x0 = 1 for (int j = 1; j < x.Length; j++) { x[j] = xin[j - 1][i]; // заполняем x1, x2,...,x3 } int columnW = 0; for (int g = 0; g < b.Length; g++) // перебираем по заключениям { for (int d = 0; d < x.Length; d++) // перебираем по входным данным { W[i, columnW] = b[g] * x[d]; // переменожаем коэффициенты на переменные columnW++; // увеличиваем строку на 1 } } } Matrix Winverse = W.PInverse(); // W+ псевдоинверстная матрица // // Если псевдоинверстная матрица не найдена // bool breakTrain = false; for (int i = 0; i < Winverse.N; i++) { for (int j = 0; j < Winverse.M; j++) { if (double.IsNaN(Winverse[i, j])) { breakTrain = true; break; } } if (breakTrain) { break; } } if (breakTrain) { break; // Прерываем обучение } C = Winverse * Y; // Находим коэффициенты // // Нахождение вектора фактического выхода сети // Matrix Ystrich = W * C; // // Правим коэффициенты // for (int i = 0; i < Input.Count; i++) { FuzzyVariable fv = Input[i]; // Забираем переменную for (int j = 0; j < fv.Terms.Count; j++) { FuzzyTerm term = fv.Terms[j]; // Выбираем j терм i входной переменной // // Меняем в случае если функция принадлежности колоколообразная // IMembershipFunction mf = term.MembershipFunction; if (mf is NormalMembershipFunction) { NormalMembershipFunction mfterm = (NormalMembershipFunction)mf; // Приводим тип // // Перебираем все переменные k - количество выходных параметров // for (int g = 0; g < k; g++) { double b = mfterm.B; double sigma = mfterm.Sigma; double xa = xin[i][g] - b; // xin - b double yyStrih = Ystrich[g, 0] - xout[g]; // y' - y double p = ew[g, j]; double sp = 0.0; for (int q = 0; q < Rules.Count; q++) { sp += ew[g, q]; } double pb = p / (sp / Math.Pow(sigma, 2)); // (t/summt) / sigma^2 // // Инициализируем матрицы для нахождения c // Matrix x = new Matrix(1, xin.Length + 1); Matrix c = new Matrix(xin.Length + 1, 1); x[0, 0] = 1; //x0 = 1 for (int q = 1; q < x.M; q++) { x[0, q] = xin[q - 1][g]; } // Заполняем коэффициенты int start = j * x.M; for (int q = start; q < start + x.M; q++) { c[q - start, 0] = C[q, 0]; } // Перемножаем матрици double cy = ((x * c)[0] - Ystrich[g, 0]); // // Корректируем B // b -= 2 * Nu * xa * yyStrih * cy * pb; // // Корректируем Sigma // sigma -= 2 * Nu * Math.Pow(xa, 2) * yyStrih * cy * pb; // // Условия переобучения и недопустимости применения условий // if (double.IsNaN(mfterm.Sigma) || double.IsNaN(mfterm.B)) { continue; // Идем на следующую итерацию } else { mfterm.B = b; mfterm.Sigma = sigma; } } // // Загоняем терм обратно // fv.Terms[j].MembershipFunction = mfterm; } // // TODO: Настройка остальных функций принадлежности не реализовано // } Input[i] = fv; // Загоняем переменную обратно } // // Находим ошибку выхода // epochError = 0.0; for (int i = 0; i < Ystrich.N; i++) { epochError += 0.5 * Math.Pow(Ystrich[i, 0] - xout[i], 2); } errorTrain[epoch - 1] = epochError; anfisTrain?.Invoke(epoch, Epochs, nu, epochError); Nu *= NuStep; epoch++; } // Конец эпох обучения // // Применяем параметры коэффициентов y = c0 + c1 * x1 + c2 * x2 + ... + ci * xi // SetCoefficient(C); // // Перезаписываем правила в силу архитектуры сети // Rules.Clear(); for (int i = 0; i < rulesText.Length; i++) { Rules.Add(ParseRule(rulesText[i])); } Console.WriteLine(Rules[0].ToString()); }
string DefuzzifyToClosestTerm(FuzzyVariable outputVariable, IMembershipFunction compositeMF, double min, double max) { int k = 50; double step = (max - min) / k; double maxArea = 0; string matchingTerm = outputVariable.Terms[0].Name; foreach (var term in outputVariable.Terms) { double coverageArea = 0; double leftX = min; double rightX = leftX + step; while (rightX <= max) { coverageArea += step * (Math.Min(term.MembershipFunction.GetValue(leftX), compositeMF.GetValue(leftX))); leftX += step; rightX += step; } if (coverageArea > maxArea) { maxArea = coverageArea; matchingTerm = term.Name; } } return matchingTerm; }
public Qualifier(string label, string column, IMembershipFunction membershipFunction, double xmin, double xmax) : base(label, membershipFunction, xmin, xmax) { Column = column ?? throw new ArgumentNullException(nameof(column)); }
public VeryHedge(IMembershipFunction membershipFunction) { this.membershipFunction = membershipFunction; }