FuzzyRule.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using FuzzyLogicPCL.FuzzySets;
  2. using System;
  3. using System.Collections.Generic;
  4. namespace FuzzyLogicPCL
  5. {
  6. public class FuzzyRule
  7. {
  8. List<FuzzyExpression> Premises;
  9. FuzzyExpression Conclusion;
  10. public FuzzyRule(List<FuzzyExpression> _prem, FuzzyExpression _concl)
  11. {
  12. Premises = _prem;
  13. Conclusion = _concl;
  14. }
  15. public FuzzyRule(string ruleStr, FuzzySystem fuzzySystem)
  16. {
  17. // To Uppercase
  18. ruleStr = ruleStr.ToUpper();
  19. // Split premises and conclusion
  20. String[] rule = ruleStr.Split(new String[]{" THEN "}, StringSplitOptions.RemoveEmptyEntries);
  21. if (rule.Length == 2)
  22. {
  23. // Compute and add premises
  24. rule[0] = rule[0].Remove(0, 2); // On enlève "IF"
  25. String[] prem = rule[0].Trim().Split(new String[] {" AND "}, StringSplitOptions.RemoveEmptyEntries);
  26. Premises = new List<FuzzyExpression>();
  27. foreach (String exp in prem)
  28. {
  29. String[] res = exp.Split(new String[] { " IS " }, StringSplitOptions.RemoveEmptyEntries);
  30. if (res.Length == 2)
  31. {
  32. FuzzyExpression fexp = new FuzzyExpression(fuzzySystem.LinguisticVariableByName(res[0]), res[1]);
  33. Premises.Add(fexp);
  34. }
  35. }
  36. // Add conclusion
  37. String[] conclu = rule[1].Split(new String[] {" IS "}, StringSplitOptions.RemoveEmptyEntries);
  38. if (conclu.Length == 2)
  39. {
  40. Conclusion = new FuzzyExpression(fuzzySystem.LinguisticVariableByName(conclu[0]), conclu[1]);
  41. }
  42. }
  43. }
  44. internal FuzzySet Apply(List<FuzzyValue> Problem)
  45. {
  46. // Compute degree (for the whole rule) : min(degree for each premise)
  47. double degree = 1;
  48. foreach (FuzzyExpression premise in Premises)
  49. {
  50. double localDegree = 0;
  51. LinguisticValue val = null;
  52. // Search premise in problem : is there a value in the problem ? (officially : yes but...)
  53. foreach (FuzzyValue pb in Problem)
  54. {
  55. if (premise.Lv == pb.Lv)
  56. {
  57. // We have found the Linguistic Variable, we search for the Linguistic Value and stop
  58. val = premise.Lv.LinguisticValueByName(premise.LinguisticValueName);
  59. if (val != null)
  60. {
  61. localDegree = val.DegreeAtValue(pb.Value); // this is fuzzyfication here
  62. break;
  63. }
  64. }
  65. }
  66. if (val == null)
  67. {
  68. return null; // problem here : we don't have the information in the problem
  69. }
  70. // Change overall degree and go on for the next premise
  71. degree = Math.Min(degree, localDegree);
  72. }
  73. // We know how much the rule is true, so we compute the resulting fuzzy set * degree
  74. return Conclusion.Lv.LinguisticValueByName(Conclusion.LinguisticValueName).Fs * degree;
  75. }
  76. }
  77. }