Advertisement
Guest User

Untitled

a guest
Aug 19th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 13.72 KB | None | 0 0
  1.  
  2. /****************************************************************************/
  3. /*************************  Routine **********************/
  4. /****************************************************************************/
  5.  
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Text;
  9. using System.Xml;
  10.  
  11. namespace DotFuzzy
  12. {
  13.     /// <summary>
  14.     /// Represents the inferential engine.
  15.     /// </summary>
  16.     public class FuzzyEngine
  17.     {
  18.         #region Private Properties
  19.  
  20.         private LinguisticVariableCollection linguisticVariableCollection = new LinguisticVariableCollection();
  21.         private string consequent = String.Empty;
  22.         private FuzzyRuleCollection fuzzyRuleCollection = new FuzzyRuleCollection();
  23.         private string filePath = String.Empty;
  24.  
  25.         #endregion
  26.  
  27.         #region Private Methods
  28.  
  29.         private LinguisticVariable GetConsequent()
  30.         {
  31.             return this.linguisticVariableCollection.Find(this.consequent);
  32.         }
  33.  
  34.         private double Parse(string text)
  35.         {
  36.             Console.WriteLine(text);
  37.            
  38.             int counter = 0;
  39.             int firstMatch = 0;
  40.  
  41.             if (!text.StartsWith("("))
  42.             {
  43.                 string[] tokens = text.Split();
  44.                 return this.linguisticVariableCollection.Find(tokens[0]).Fuzzify(tokens[2]);
  45.             }
  46.  
  47.             for (int i = 0; i < text.Length; i++)
  48.             {
  49.                 switch (text[i])
  50.                 {
  51.                     case '(':
  52.                         counter++;
  53.                         if (counter == 1)
  54.                             firstMatch = i;
  55.                         break;
  56.  
  57.                     case ')':
  58.                         counter--;
  59.                         if ((counter == 0) && (i > 0))
  60.                         {
  61.                             string substring = text.Substring(firstMatch + 1, i - firstMatch - 1);
  62.                             string substringBrackets = text.Substring(firstMatch, i - firstMatch + 1);
  63.                             int length = substringBrackets.Length;
  64.                             text = text.Replace(substringBrackets, Parse(substring).ToString());
  65.                             i = i - (length - 1);
  66.                         }
  67.                         break;
  68.  
  69.                     default:
  70.                         break;
  71.                 }
  72.             }
  73.  
  74.             return Evaluate(text);
  75.         }
  76.  
  77.         private double Evaluate(string text)
  78.         {
  79.             string[] tokens = text.Split();
  80.             string connective = "";
  81.             double value = 0;
  82.  
  83.             for (int i = 0; i <= ((tokens.Length / 2) + 1); i = i + 2)
  84.             {
  85.                 double tokenValue = Convert.ToDouble(tokens[i]);
  86.  
  87.                 switch (connective)
  88.                 {
  89.                     case "AND":
  90.                         if (tokenValue < value)
  91.                             value = tokenValue;
  92.                         break;
  93.  
  94.                     case "OR":
  95.                         if (tokenValue > value)
  96.                             value = tokenValue;
  97.                         break;
  98.  
  99.                     default:
  100.                         value = tokenValue;
  101.                         break;
  102.                 }
  103.  
  104.                 if ((i + 1) < tokens.Length)
  105.                     connective = tokens[i + 1];
  106.             }
  107.  
  108.             return value;
  109.         }
  110.  
  111.         void ReadVariable(XmlNode xmlNode)
  112.         {
  113.             LinguisticVariable linguisticVariable = this.linguisticVariableCollection.Find(xmlNode.Attributes["NAME"].InnerText);
  114.  
  115.             foreach (XmlNode termNode in xmlNode.ChildNodes)
  116.             {
  117.                 string[] points = termNode.Attributes["POINTS"].InnerText.Split();
  118.                 linguisticVariable.MembershipFunctionCollection.Add(new MembershipFunction(
  119.                     termNode.Attributes["NAME"].InnerText,
  120.                     Convert.ToDouble(points[0]),
  121.                     Convert.ToDouble(points[1]),
  122.                     Convert.ToDouble(points[2]),
  123.                     Convert.ToDouble(points[3])));
  124.             }
  125.         }
  126.  
  127.         #endregion
  128.  
  129.         #region Public Properties
  130.  
  131.         /// <summary>
  132.         /// A collection of linguistic variables.
  133.         /// </summary>
  134.         public LinguisticVariableCollection LinguisticVariableCollection
  135.         {
  136.             get { return linguisticVariableCollection; }
  137.             set { linguisticVariableCollection = value; }
  138.         }
  139.  
  140.         /// <summary>
  141.         /// The consequent variable name.
  142.         /// </summary>
  143.         public string Consequent
  144.         {
  145.             get { return consequent; }
  146.             set { consequent = value; }
  147.         }
  148.  
  149.         /// <summary>
  150.         /// A collection of rules.
  151.         /// </summary>
  152.         public FuzzyRuleCollection FuzzyRuleCollection
  153.         {
  154.             get { return fuzzyRuleCollection; }
  155.             set { fuzzyRuleCollection = value; }
  156.         }
  157.  
  158.         /// <summary>
  159.         /// The path of the FCL-like XML file in which save the project.
  160.         /// </summary>
  161.         public string FilePath
  162.         {
  163.             get { return filePath; }
  164.             set { filePath = value; }
  165.         }
  166.  
  167.         #endregion
  168.  
  169.         #region Public Methods
  170.  
  171.         /// <summary>
  172.         /// Calculates the defuzzification value with the CoG (Center of Gravity) technique.
  173.         /// </summary>
  174.         /// <returns>The defuzzification value.</returns>
  175.         public double Defuzzify()
  176.         {
  177.             double numerator = 0;
  178.             double denominator = 0;
  179.  
  180.             // Reset values
  181.             foreach (MembershipFunction membershipFunction in this.GetConsequent().MembershipFunctionCollection)
  182.             {
  183.                 membershipFunction.Value = 0;
  184.             }
  185.  
  186.             foreach (FuzzyRule fuzzyRule in this.fuzzyRuleCollection)
  187.             {
  188.                 fuzzyRule.Value = Parse(fuzzyRule.Conditions());
  189.  
  190.                 string[] tokens = fuzzyRule.Text.Split();
  191.                 MembershipFunction membershipFunction = this.GetConsequent().MembershipFunctionCollection.Find(tokens[tokens.Length - 1]);
  192.                
  193.                 if (fuzzyRule.Value > membershipFunction.Value)
  194.                     membershipFunction.Value = fuzzyRule.Value;
  195.             }
  196.  
  197.             foreach (MembershipFunction membershipFunction in this.GetConsequent().MembershipFunctionCollection)
  198.             {
  199.                 numerator += membershipFunction.Centorid() * membershipFunction.Area();
  200.                 denominator += membershipFunction.Area();
  201.             }
  202.  
  203.             return numerator / denominator;
  204.         }
  205.  
  206.         /// <summary>
  207.         /// Sets the FilePath property and saves the project into a FCL-like XML file.
  208.         /// </summary>
  209.         /// <param name="path">Path of the destination document.</param>
  210.         public void Save(string path)
  211.         {
  212.             this.FilePath = path;
  213.             this.Save();
  214.         }
  215.  
  216.         /// <summary>
  217.         /// Saves the project into a FCL-like XML file.
  218.         /// </summary>
  219.         public void Save()
  220.         {
  221.             if (this.filePath == String.Empty)
  222.                 throw new Exception("FilePath not set");
  223.  
  224.             int i = 0;
  225.             XmlTextWriter xmlTextWriter = new XmlTextWriter(this.filePath, Encoding.UTF8);
  226.             xmlTextWriter.Formatting = Formatting.Indented;
  227.             xmlTextWriter.WriteStartDocument(true);
  228.             xmlTextWriter.WriteStartElement("FUNCTION_BLOCK");
  229.  
  230.             foreach (LinguisticVariable linguisticVariable in this.linguisticVariableCollection)
  231.             {
  232.                 if (linguisticVariable.Name == this.consequent)
  233.                     xmlTextWriter.WriteStartElement("VAR_OUTPUT");
  234.                 else
  235.                     xmlTextWriter.WriteStartElement("VAR_INPUT");
  236.  
  237.                 xmlTextWriter.WriteAttributeString("NAME", linguisticVariable.Name);
  238.                 xmlTextWriter.WriteAttributeString("TYPE", "REAL");
  239.                 xmlTextWriter.WriteAttributeString("RANGE",
  240.                     linguisticVariable.MinValue().ToString() + " " +
  241.                     linguisticVariable.MaxValue().ToString());
  242.                 xmlTextWriter.WriteEndElement();
  243.             }
  244.  
  245.             foreach (LinguisticVariable linguisticVariable in this.linguisticVariableCollection)
  246.             {
  247.                 if (linguisticVariable.Name == this.consequent)
  248.                 {
  249.                     xmlTextWriter.WriteStartElement("DEFUZZIFY");
  250.                     xmlTextWriter.WriteAttributeString("METHOD", "CoG");
  251.                     xmlTextWriter.WriteAttributeString("ACCU", "MAX");
  252.                 }
  253.                 else
  254.                     xmlTextWriter.WriteStartElement("FUZZIFY");
  255.                
  256.                 xmlTextWriter.WriteAttributeString("NAME", linguisticVariable.Name);
  257.  
  258.                 foreach (MembershipFunction membershipFunction in linguisticVariable.MembershipFunctionCollection)
  259.                 {
  260.                     xmlTextWriter.WriteStartElement("TERM");
  261.                     xmlTextWriter.WriteAttributeString("NAME", membershipFunction.Name);
  262.                     xmlTextWriter.WriteAttributeString("POINTS",
  263.                         membershipFunction.X0 + " " +
  264.                         membershipFunction.X1 + " " +
  265.                         membershipFunction.X2 + " " +
  266.                         membershipFunction.X3);
  267.                     xmlTextWriter.WriteEndElement();
  268.                 }
  269.  
  270.                 xmlTextWriter.WriteEndElement();
  271.             }
  272.  
  273.             xmlTextWriter.WriteStartElement("RULEBLOCK");
  274.             xmlTextWriter.WriteAttributeString("AND", "MIN");
  275.             xmlTextWriter.WriteAttributeString("OR", "MAX");
  276.  
  277.             foreach (FuzzyRule fuzzyRule in this.fuzzyRuleCollection)
  278.             {
  279.                 i++;
  280.                 xmlTextWriter.WriteStartElement("RULE");
  281.                 xmlTextWriter.WriteAttributeString("NUMBER", i.ToString());
  282.                 xmlTextWriter.WriteAttributeString("TEXT", fuzzyRule.Text);
  283.                 xmlTextWriter.WriteEndElement();
  284.             }
  285.            
  286.             xmlTextWriter.WriteEndElement();
  287.  
  288.             xmlTextWriter.WriteEndElement();
  289.             xmlTextWriter.WriteEndDocument();
  290.             xmlTextWriter.Close();
  291.         }
  292.  
  293.         /// <summary>
  294.         /// Sets the FilePath property and loads a project from a FCL-like XML file.
  295.         /// </summary>
  296.         /// <param name="path">Path of the source file.</param>
  297.         public void Load(string path)
  298.         {
  299.             this.FilePath = path;
  300.             this.Load();
  301.         }
  302.  
  303.         /// <summary>
  304.         /// Loads a project from a FCL-like XML file.
  305.         /// </summary>
  306.         public void Load()
  307.         {
  308.             if (this.filePath == String.Empty)
  309.                 throw new Exception("FilePath not set");
  310.  
  311.             XmlDocument xmlDocument = new XmlDocument();
  312.             xmlDocument.Load(this.filePath);
  313.  
  314.             foreach (XmlNode xmlNode in xmlDocument.GetElementsByTagName("VAR_INPUT"))
  315.             {
  316.                 this.LinguisticVariableCollection.Add(new LinguisticVariable(xmlNode.Attributes["NAME"].InnerText));
  317.             }
  318.  
  319.             this.consequent = xmlDocument.GetElementsByTagName("VAR_OUTPUT")[0].Attributes["NAME"].InnerText;
  320.             this.LinguisticVariableCollection.Add(new LinguisticVariable(this.consequent));
  321.  
  322.             foreach (XmlNode xmlNode in xmlDocument.GetElementsByTagName("FUZZIFY"))
  323.             {
  324.                 ReadVariable(xmlNode);
  325.             }
  326.  
  327.             ReadVariable(xmlDocument.GetElementsByTagName("DEFUZZIFY")[0]);
  328.  
  329.             foreach (XmlNode xmlNode in xmlDocument.GetElementsByTagName("RULE"))
  330.             {
  331.                 this.fuzzyRuleCollection.Add(new FuzzyRule(xmlNode.Attributes["TEXT"].InnerText));
  332.             }
  333.         }
  334.  
  335.         #endregion
  336.     }
  337. }
  338.  
  339.  
  340. /****************************************************************************/
  341. /*************************  MAIN **********************/
  342. /****************************************************************************/
  343.  
  344. using System.Text;
  345.  
  346. namespace DotFuzzy
  347. {
  348.     class Program
  349.     {
  350.         static void Main(string[] args)
  351.         {
  352.             LinguisticVariable water = new LinguisticVariable("Water");
  353.             water.MembershipFunctionCollection.Add(new MembershipFunction("Cold", 0, 0, 20, 40));
  354.             water.MembershipFunctionCollection.Add(new MembershipFunction("Tepid", 30, 50, 50, 70));
  355.             water.MembershipFunctionCollection.Add(new MembershipFunction("Hot", 50, 80, 100, 100));
  356.  
  357.             LinguisticVariable power = new LinguisticVariable("Power");
  358.             power.MembershipFunctionCollection.Add(new MembershipFunction("Low", 0, 25, 25, 50));
  359.             power.MembershipFunctionCollection.Add(new MembershipFunction("High", 25, 50, 50, 75));
  360.  
  361.             FuzzyEngine fuzzyEngine = new FuzzyEngine();
  362.             fuzzyEngine.LinguisticVariableCollection.Add(water);
  363.             fuzzyEngine.LinguisticVariableCollection.Add(power);
  364.             fuzzyEngine.Consequent = "Power";
  365.             fuzzyEngine.FuzzyRuleCollection.Add(new FuzzyRule("IF (Water IS Cold) OR (Water IS Tepid) THEN Power IS High"));
  366.             fuzzyEngine.FuzzyRuleCollection.Add(new FuzzyRule("IF (Water IS Hot) THEN Power IS Low"));
  367.  
  368.             water.InputValue = 60;
  369.  
  370.             try
  371.             {
  372.                 //MessageBox.Show(fuzzyEngine.Defuzzify().ToString());
  373.                 Console.WriteLine(fuzzyEngine.Defuzzify().ToString());
  374.             }
  375.             catch (Exception e)
  376.             {
  377.                 //MessageBox.Show(e.Message);
  378.                 Console.WriteLine(e.Message);
  379.             }
  380.             Console.ReadLine();
  381.         }
  382.     }
  383. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement