Exemplo n.º 1
0
        // Testing basic funcionality of fuzzy sets
        private void runFuzzySetTestButton_Click( object sender, EventArgs e )
        {
            ClearDataSeries( );

            // create 2 fuzzy sets to represent the Cool and Warm temperatures
            TrapezoidalFunction function1 = new TrapezoidalFunction( 13, 18, 23, 28 );
            FuzzySet fsCool = new FuzzySet( "Cool", function1 );
            TrapezoidalFunction function2 = new TrapezoidalFunction( 23, 28, 33, 38 );
            FuzzySet fsWarm = new FuzzySet( "Warm", function2 );

            // get membership of some points to the cool fuzzy set
            double[,] coolValues = new double[20, 2];
            for ( int i = 10; i < 30; i++ )
            {
                coolValues[i - 10, 0] = i;
                coolValues[i - 10, 1] = fsCool.GetMembership( i );
            }

            // getting memberships of some points to the warm fuzzy set
            double[,] warmValues = new double[20, 2];
            for ( int i = 20; i < 40; i++ )
            {
                warmValues[i - 20, 0] = i;
                warmValues[i - 20, 1] = fsWarm.GetMembership( i );
            }

            // plot membership to a chart
            chart.UpdateDataSeries( "COOL", coolValues );
            chart.UpdateDataSeries( "WARM", warmValues );
        }
Exemplo n.º 2
0
        public InferenceSystem SetupInferenceSystem(int width)
        {
            var mp = new TrapezoidalFunction(centerPoint - width/2, centerPoint, centerPoint + width/2);
            var mn = new TrapezoidalFunction(-centerPoint - width/2, -centerPoint, -centerPoint + width/2);
            var sp = new TrapezoidalFunction(-centerPoint/2 + width/4, (double) centerPoint/2, centerPoint/2 + width/3);
            var sn = new TrapezoidalFunction(-centerPoint/2 - width/3, (double) -centerPoint/2, centerPoint/2 - width/4);
            var ze = new TrapezoidalFunction(-(double)centerPoint / 4, 0, (double)centerPoint / 4);

            var mpSet = new FuzzySet("MP", mp);
            var mnSet = new FuzzySet("MN", mn);
            var spSet = new FuzzySet("SP", sp);
            var snSet = new FuzzySet("SN", sn);
            var zeSet = new FuzzySet("ZE", ze);

            var ruleDatabase = new Database();

            for (int i = 0; i < windowSize*windowSize - 1; i++)
            {
                var variable = new LinguisticVariable(String.Format("IN{0}", i), -255, 255);
                variable.AddLabel(mpSet);
                variable.AddLabel(mnSet);
                ruleDatabase.AddVariable(variable);
            }

            var outVariable = new LinguisticVariable("OUT", -centerPoint - width/2, centerPoint + width/2);
            outVariable.AddLabel(spSet);
            outVariable.AddLabel(snSet);
            outVariable.AddLabel(zeSet);
            ruleDatabase.AddVariable(outVariable);
            var inferenceSystem = new InferenceSystem(ruleDatabase, new CentroidDefuzzifier(100));
            string rule1 = "IF ";
            string rule2 = "IF ";
            string rule3 = "IF ";
            for (int i = 0; i < windowSize*windowSize - 1; i++)
            {
                rule1 += String.Format("IN{0} is MP and ", i);
                rule2 += String.Format("IN{0} is MN and ", i);
                rule3 += String.Format("IN{0} is not MP and IN{0} is not MN AND ", i);
            }

            rule1 = rule1.Remove(rule1.Length - 4, 4);
            rule2 = rule2.Remove(rule2.Length - 4, 4);
            rule3 = "IF NOT (" + rule1.Replace("IF", "") + ") AND NOT(" + rule2.Replace("IF", "") + ")";

            rule1 += " then OUT is SN";
            rule2 += " then OUT is SP";
            rule3 += " then OUT is ZE";

            inferenceSystem.NewRule("Rule1", rule1);
            inferenceSystem.NewRule("Rule2", rule2);
            inferenceSystem.NewRule("Rule3", rule3);

            return inferenceSystem;
        }
Exemplo n.º 3
0
        // Testing basic funcionality of linguistic variables
        private void runLingVarTestButton_Click( object sender, EventArgs e )
        {
            ClearDataSeries( );

            // create a linguistic variable to represent temperature
            LinguisticVariable lvTemperature = new LinguisticVariable( "Temperature", 0, 80 );

            // create the linguistic labels (fuzzy sets) that compose the temperature 
            TrapezoidalFunction function1 = new TrapezoidalFunction( 10, 15, TrapezoidalFunction.EdgeType.Right );
            FuzzySet fsCold = new FuzzySet( "Cold", function1 );
            TrapezoidalFunction function2 = new TrapezoidalFunction( 10, 15, 20, 25 );
            FuzzySet fsCool = new FuzzySet( "Cool", function2 );
            TrapezoidalFunction function3 = new TrapezoidalFunction( 20, 25, 30, 35 );
            FuzzySet fsWarm = new FuzzySet( "Warm", function3 );
            TrapezoidalFunction function4 = new TrapezoidalFunction( 30, 35, TrapezoidalFunction.EdgeType.Left );
            FuzzySet fsHot = new FuzzySet( "Hot", function4 );

            // adding labels to the variable
            lvTemperature.AddLabel( fsCold );
            lvTemperature.AddLabel( fsCool );
            lvTemperature.AddLabel( fsWarm );
            lvTemperature.AddLabel( fsHot );

            // get membership of some points to the cool fuzzy set
            double[][,] chartValues = new double[4][,];
            for ( int i = 0; i < 4; i++ )
                chartValues[i] = new double[160, 2];

            // showing the shape of the linguistic variable - the shape of its labels memberships from start to end
            int j = 0;
            for ( float x = 0; x < 80; x += 0.5f, j++ )
            {
                double y1 = lvTemperature.GetLabelMembership( "Cold", x );
                double y2 = lvTemperature.GetLabelMembership( "Cool", x );
                double y3 = lvTemperature.GetLabelMembership( "Warm", x );
                double y4 = lvTemperature.GetLabelMembership( "Hot", x );

                chartValues[0][j, 0] = x;
                chartValues[0][j, 1] = y1;
                chartValues[1][j, 0] = x;
                chartValues[1][j, 1] = y2;
                chartValues[2][j, 0] = x;
                chartValues[2][j, 1] = y3;
                chartValues[3][j, 0] = x;
                chartValues[3][j, 1] = y4;
            }

            // plot membership to a chart
            chart.UpdateDataSeries( "COLD", chartValues[0] );
            chart.UpdateDataSeries( "COOL", chartValues[1] );
            chart.UpdateDataSeries( "WARM", chartValues[2] );
            chart.UpdateDataSeries( "HOT", chartValues[3] );
        }
Exemplo n.º 4
0
        public void SetInput2()
        {
            this.Power = new LinguisticVariable("Moc_samochodu", 20, 180);

            TrapezoidalFunction function1 = new TrapezoidalFunction(40, 100, TrapezoidalFunction.EdgeType.Right);
            FuzzySet            set1      = new FuzzySet("mała", function1);
            TrapezoidalFunction function2 = new TrapezoidalFunction(70, 100, 130);
            FuzzySet            set2      = new FuzzySet("średnia", function2);
            TrapezoidalFunction function3 = new TrapezoidalFunction(100, 160, TrapezoidalFunction.EdgeType.Left);
            FuzzySet            set3      = new FuzzySet("duża", function3);


            Power.AddLabel(set1);
            Power.AddLabel(set2);
            Power.AddLabel(set3);

            database.AddVariable(Power);

            double y1;
            double y2;
            double y3;

            for (float x = 20; x < 180; x += 0.5f)
            {
                if (Power.GetLabelMembership("mała", x + 0.5f) + Power.GetLabelMembership("mała", x) > 0)
                {
                    y1 = Power.GetLabelMembership("mała", x);
                    chart5.Series["Mała"].Points.AddXY(x, y1);
                }

                if (Power.GetLabelMembership("średnia", x + 0.5f) + Power.GetLabelMembership("średnia", x) > 0)
                {
                    y2 = Power.GetLabelMembership("średnia", x);
                    chart5.Series["Średnia"].Points.AddXY(x, y2);
                }
                if (Power.GetLabelMembership("duża", x + 0.5f) + Power.GetLabelMembership("duża", x) > 0)
                {
                    y3 = Power.GetLabelMembership("duża", x);
                    chart5.Series["Duża"].Points.AddXY(x, y3);
                }
            }
        }
        /// <summary>
        /// Adds a linguistic label to the variable.
        /// </summary>
        ///
        /// <param name="label">A <see cref="FuzzySet"/> that will be a linguistic label of the linguistic variable.</param>
        ///
        /// <remarks>Linguistic labels are fuzzy sets (<see cref="FuzzySet"/>). Each
        /// label of the variable must have a unique name. The range of the label
        /// (left and right limits) cannot be greater than
        /// the linguistic variable range (start/end).</remarks>
        ///
        /// <exception cref="NullReferenceException">The fuzzy set was not initialized.</exception>
        /// <exception cref="ArgumentException">The linguistic label name already exists in the linguistic variable.</exception>
        /// <exception cref="ArgumentException">The left limit of the fuzzy set can not be lower than the linguistic variable's starting point.</exception>
        /// <exception cref="ArgumentException">"The right limit of the fuzzy set can not be greater than the linguistic variable's ending point."</exception>
        ///
        public void AddLabel(FuzzySet label)
        {
            // checking for existing name
            if (this.labels.ContainsKey(label.Name))
            {
                throw new ArgumentException("The linguistic label name already exists in the linguistic variable.");
            }

            // checking ranges
            if (label.LeftLimit < this.start)
            {
                throw new ArgumentException("The left limit of the fuzzy set can not be lower than the linguistic variable's starting point.");
            }
            if (label.RightLimit > this.end)
            {
                throw new ArgumentException("The right limit of the fuzzy set can not be greater than the linguistic variable's ending point.");
            }

            // adding label
            this.labels.Add(label.Name, label);
        }
Exemplo n.º 6
0
        public void SetInput1()
        {
            this.Temp_opon = new LinguisticVariable("Temperatura", 0, 180);

            TrapezoidalFunction function1 = new TrapezoidalFunction(30, 90, TrapezoidalFunction.EdgeType.Right);
            FuzzySet            set1      = new FuzzySet("zimne", function1);
            TrapezoidalFunction function2 = new TrapezoidalFunction(70, 90, 110);
            FuzzySet            set2      = new FuzzySet("średnie", function2);
            TrapezoidalFunction function3 = new TrapezoidalFunction(90, 150, TrapezoidalFunction.EdgeType.Left);
            FuzzySet            set3      = new FuzzySet("gorące", function3);

            Temp_opon.AddLabel(set1);
            Temp_opon.AddLabel(set2);
            Temp_opon.AddLabel(set3);

            database.AddVariable(Temp_opon);

            double y1;
            double y2;
            double y3;

            for (float x = 0; x < 180; x += 0.5f)
            {
                if (Temp_opon.GetLabelMembership("zimne", x + 0.5f) + Temp_opon.GetLabelMembership("zimne", x) > 0)
                {
                    y1 = Temp_opon.GetLabelMembership("zimne", x);
                    chart4.Series["Zimne"].Points.AddXY(x, y1);
                }
                if (Temp_opon.GetLabelMembership("średnie", x + 0.5f) + Temp_opon.GetLabelMembership("średnie", x) > 0)
                {
                    y2 = Temp_opon.GetLabelMembership("średnie", x);
                    chart4.Series["Średnie"].Points.AddXY(x, y2);
                }
                if (Temp_opon.GetLabelMembership("gorące", x + 0.5f) + Temp_opon.GetLabelMembership("gorące", x) > 0)
                {
                    y3 = Temp_opon.GetLabelMembership("gorące", x);
                    chart4.Series["Gorące"].Points.AddXY(x, y3);
                }
            }
        }
Exemplo n.º 7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Clause"/> class.
 /// </summary>
 /// 
 /// <param name="variable">Linguistic variable of the clause. </param>
 /// 
 /// <param name="label">Label of the linguistic variable, a fuzzy set used as label into the linguistic variable.</param>
 /// 
 /// <exception cref="KeyNotFoundException">The label indicated was not found in the linguistic variable.</exception>
 /// 
 public Clause( LinguisticVariable variable, FuzzySet label )
 {
     // check if label belongs to var.
     variable.GetLabel( label.Name );
     
     // initializing attributes
     this.label    = label;
     this.variable = variable;
 }
Exemplo n.º 8
0
        // Hardcode initializing the Fuzzy Inference System
        void InitFuzzyEngine( )
        {

            // Linguistic labels (fuzzy sets) that compose the distances
            FuzzySet fsNear = new FuzzySet( "Near", new TrapezoidalFunction( 15, 50, TrapezoidalFunction.EdgeType.Right ) );
            FuzzySet fsMedium = new FuzzySet( "Medium", new TrapezoidalFunction( 15, 50, 60, 100 ) );
            FuzzySet fsFar = new FuzzySet( "Far", new TrapezoidalFunction( 60, 100, TrapezoidalFunction.EdgeType.Left ) );

            // Right Distance (Input)
            LinguisticVariable lvRight = new LinguisticVariable( "RightDistance", 0, 120 );
            lvRight.AddLabel( fsNear );
            lvRight.AddLabel( fsMedium );
            lvRight.AddLabel( fsFar );

            // Left Distance (Input)
            LinguisticVariable lvLeft = new LinguisticVariable( "LeftDistance", 0, 120 );
            lvLeft.AddLabel( fsNear );
            lvLeft.AddLabel( fsMedium );
            lvLeft.AddLabel( fsFar );

            // Front Distance (Input)
            LinguisticVariable lvFront = new LinguisticVariable( "FrontalDistance", 0, 120 );
            lvFront.AddLabel( fsNear );
            lvFront.AddLabel( fsMedium );
            lvFront.AddLabel( fsFar );

            // Linguistic labels (fuzzy sets) that compose the angle
            FuzzySet fsVN = new FuzzySet( "VeryNegative", new TrapezoidalFunction( -40, -35, TrapezoidalFunction.EdgeType.Right ) );
            FuzzySet fsN = new FuzzySet( "Negative", new TrapezoidalFunction( -40, -35, -25, -20 ) );
            FuzzySet fsLN = new FuzzySet( "LittleNegative", new TrapezoidalFunction( -25, -20, -10, -5 ) );
            FuzzySet fsZero = new FuzzySet( "Zero", new TrapezoidalFunction( -10, 5, 5, 10 ) );
            FuzzySet fsLP = new FuzzySet( "LittlePositive", new TrapezoidalFunction( 5, 10, 20, 25 ) );
            FuzzySet fsP = new FuzzySet( "Positive", new TrapezoidalFunction( 20, 25, 35, 40 ) );
            FuzzySet fsVP = new FuzzySet( "VeryPositive", new TrapezoidalFunction( 35, 40, TrapezoidalFunction.EdgeType.Left ) );

            // Angle
            LinguisticVariable lvAngle = new LinguisticVariable( "Angle", -50, 50 );
            lvAngle.AddLabel( fsVN );
            lvAngle.AddLabel( fsN );
            lvAngle.AddLabel( fsLN );
            lvAngle.AddLabel( fsZero );
            lvAngle.AddLabel( fsLP );
            lvAngle.AddLabel( fsP );
            lvAngle.AddLabel( fsVP );

            // The database
            Database fuzzyDB = new Database( );
            fuzzyDB.AddVariable( lvFront );
            fuzzyDB.AddVariable( lvLeft );
            fuzzyDB.AddVariable( lvRight );
            fuzzyDB.AddVariable( lvAngle );

            // Creating the inference system
            IS = new InferenceSystem( fuzzyDB, new CentroidDefuzzifier( 1000 ) );

            // Going Straight
            IS.NewRule( "Rule 1", "IF FrontalDistance IS Far THEN Angle IS Zero" );
            // Going Straight (if can go anywhere)
            IS.NewRule( "Rule 2", "IF FrontalDistance IS Far AND RightDistance IS Far AND LeftDistance IS Far THEN Angle IS Zero" );
            // Near right wall
            IS.NewRule( "Rule 3", "IF RightDistance IS Near AND LeftDistance IS Not Near THEN Angle IS LittleNegative" );
            // Near left wall
            IS.NewRule("Rule 4", "IF RightDistance IS Not Near AND LeftDistance IS Near THEN Angle IS LittlePositive");
            // Near front wall - room at right
            IS.NewRule( "Rule 5", "IF RightDistance IS Far AND FrontalDistance IS Near THEN Angle IS Positive" );
            // Near front wall - room at left
            IS.NewRule( "Rule 6", "IF LeftDistance IS Far AND FrontalDistance IS Near THEN Angle IS Negative" );
            // Near front wall - room at both sides - go right
            IS.NewRule( "Rule 7", "IF RightDistance IS Far AND LeftDistance IS Far AND FrontalDistance IS Near THEN Angle IS Positive" );
        }
        /// <summary>
        /// Calculate the membership of a given value to a given label. Used to evaluate linguistics clauses like
        /// "X IS A", where X is a value and A is a linguistic label.
        /// </summary>
        ///
        /// <param name="labelName">Label (fuzzy set) to evaluate value's membership.</param>
        /// <param name="value">Value which label's membership will to be calculated.</param>
        ///
        /// <returns>Degree of membership [0..1] of the value to the label (fuzzy set).</returns>
        ///
        /// <exception cref="KeyNotFoundException">The label indicated in labelName was not found in the linguistic variable.</exception>
        ///
        public float GetLabelMembership(string labelName, float value)
        {
            FuzzySet fs = labels[labelName];

            return(fs.GetMembership(value));
        }
        /// <summary>
        /// Adds a linguistic label to the variable. 
        /// </summary>
        /// 
        /// <param name="label">A <see cref="FuzzySet"/> that will be a linguistic label of the linguistic variable.</param>
        /// 
        /// <remarks>Linguistic labels are fuzzy sets (<see cref="FuzzySet"/>). Each
        /// label of the variable must have a unique name. The range of the label 
        /// (left and right limits) cannot be greater than 
        /// the linguistic variable range (start/end).</remarks>
        /// 
        /// <exception cref="NullReferenceException">The fuzzy set was not initialized.</exception>
        /// <exception cref="ArgumentException">The linguistic label name already exists in the linguistic variable.</exception>
        /// <exception cref="ArgumentException">The left limit of the fuzzy set can not be lower than the linguistic variable's starting point.</exception>
        /// <exception cref="ArgumentException">"The right limit of the fuzzy set can not be greater than the linguistic variable's ending point."</exception>
        /// 
        public void AddLabel( FuzzySet label )
        {
            // checking for existing name
            if ( this.labels.ContainsKey( label.Name ) )
                throw new ArgumentException( "The linguistic label name already exists in the linguistic variable." );

            // checking ranges
            if ( label.LeftLimit < this.start )
                throw new ArgumentException( "The left limit of the fuzzy set can not be lower than the linguistic variable's starting point." );
            if ( label.RightLimit > this.end )
                throw new ArgumentException( "The right limit of the fuzzy set can not be greater than the linguistic variable's ending point." );

            // adding label
            this.labels.Add( label.Name, label );
        }
        private InferenceSystem SetupInferenceSystem(byte minLuma, byte maxLuma, byte meanLuma)
        {
            var lumaIn = new LinguisticVariable("LumaIn", minLuma, maxLuma);
            var lumaOut = new LinguisticVariable("LumaOut", 0, 255);

            var darkFunction = new TrapezoidalFunction(minLuma, meanLuma, TrapezoidalFunction.EdgeType.Right);
            var darkSet = new FuzzySet("Dark", darkFunction);

            var mediumFunction = new TrapezoidalFunction(minLuma, meanLuma, maxLuma);
            var mediumSet = new FuzzySet("Medium", mediumFunction);

            var lightFunction = new TrapezoidalFunction(meanLuma, maxLuma, TrapezoidalFunction.EdgeType.Left);
            var lightSet = new FuzzySet("Light", lightFunction);

            lumaIn.AddLabel(darkSet);
            lumaIn.AddLabel(mediumSet);
            lumaIn.AddLabel(lightSet);

            var whiteFunction = new SingletonFunction(255);
            var whiteSet = new FuzzySet("White", whiteFunction);

            var blackFunction = new SingletonFunction(0);
            var blackSet = new FuzzySet("Black", blackFunction);

            var grayFunction = new SingletonFunction(128);
            var graySet = new FuzzySet("Gray", grayFunction);

            lumaOut.AddLabel(blackSet);
            lumaOut.AddLabel(graySet);
            lumaOut.AddLabel(whiteSet);

            var database = new Database();
            database.AddVariable(lumaIn);
            database.AddVariable(lumaOut);

            var inferenceSystem = new InferenceSystem(database, new CogDefuzzifier());
            inferenceSystem.NewRule("Rule 1", "IF LumaIn IS Dark THEN LumaOut is Black");
            inferenceSystem.NewRule("Rule 2", "IF LumaIn IS Medium THEN LumaOut is Gray");
            inferenceSystem.NewRule("Rule 3", "IF LumaIn IS Light THEN LumaOut is White");

            return inferenceSystem;
        }
Exemplo n.º 12
0
        /// <summary>
        /// Converts the Fuzzy Rule to RPN (Reverse Polish Notation). For debug proposes, the string representation of the
        /// RPN expression can be acessed by calling <see cref="GetRPNExpression"/> method.
        /// </summary>
        ///
        private void ParseRule( )
        {
            // flag to incicate we are on consequent state
            bool consequent = false;

            // tokens like IF and THEN will be searched always in upper case
            string upRule = rule.ToUpper( );

            // the rule must start with IF, and must have a THEN somewhere
            if (!upRule.StartsWith("IF"))
            {
                throw new ArgumentException("A Fuzzy Rule must start with an IF statement.");
            }
            if (upRule.IndexOf("THEN") < 0)
            {
                throw new ArgumentException("Missing the consequent (THEN) statement.");
            }

            // building a list with all the expression (rule) string tokens
            string spacedRule = rule.Replace("(", " ( ").Replace(")", " ) ");

            // getting the tokens list
            string[] tokensList = GetRuleTokens(spacedRule);

            // stack to convert to RPN
            Stack <string> s = new Stack <string>( );
            // storing the last token
            string lastToken = "IF";
            // linguistic var read, used to build clause
            LinguisticVariable lingVar = null;

            // verifying each token
            for (int i = 0; i < tokensList.Length; i++)
            {
                // removing spaces
                string token = tokensList[i].Trim( );
                // getting upper case
                string upToken = token.ToUpper( );

                // ignoring these tokens
                if (upToken == "" || upToken == "IF")
                {
                    continue;
                }

                // if the THEN is found, the rule is now on consequent
                if (upToken == "THEN")
                {
                    lastToken  = upToken;
                    consequent = true;
                    continue;
                }

                // if we got a linguistic variable, an IS statement and a label is needed
                if (lastToken == "VAR")
                {
                    if (upToken == "IS")
                    {
                        lastToken = upToken;
                    }
                    else
                    {
                        throw new ArgumentException("An IS statement is expected after a linguistic variable.");
                    }
                }
                // if we got an IS statement, a label must follow it
                else if (lastToken == "IS")
                {
                    try
                    {
                        FuzzySet fs = lingVar.GetLabel(token);
                        Clause   c  = new Clause(lingVar, fs);
                        if (consequent)
                        {
                            output = c;
                        }
                        else
                        {
                            rpnTokenList.Add(c);
                        }
                        lastToken = "LAB";
                    }
                    catch (KeyNotFoundException)
                    {
                        throw new ArgumentException("Linguistic label " + token + " was not found on the variable " + lingVar.Name + ".");
                    }
                }
                // not VAR and not IS statement
                else
                {
                    // openning new scope
                    if (upToken == "(")
                    {
                        // if we are on consequent, only variables can be found
                        if (consequent)
                        {
                            throw new ArgumentException("Linguistic variable expected after a THEN statement.");
                        }
                        // if its a (, just push it
                        s.Push(upToken);
                        lastToken = upToken;
                    }
                    // operators
                    else if (upToken == "AND" || upToken == "OR" || unaryOperators.IndexOf(upToken) >= 0)
                    {
                        // if we are on consequent, only variables can be found
                        if (consequent)
                        {
                            throw new ArgumentException("Linguistic variable expected after a THEN statement.");
                        }

                        // pop all the higher priority operators until the stack is empty
                        while ((s.Count > 0) && (Priority(s.Peek( )) > Priority(upToken)))
                        {
                            rpnTokenList.Add(s.Pop( ));
                        }

                        // pushing the operator
                        s.Push(upToken);
                        lastToken = upToken;
                    }
                    // closing the scope
                    else if (upToken == ")")
                    {
                        // if we are on consequent, only variables can be found
                        if (consequent)
                        {
                            throw new ArgumentException("Linguistic variable expected after a THEN statement.");
                        }

                        // if there is nothing on the stack, an oppening parenthesis is missing.
                        if (s.Count == 0)
                        {
                            throw new ArgumentException("Openning parenthesis missing.");
                        }

                        // pop the tokens and copy to output until openning is found
                        while (s.Peek( ) != "(")
                        {
                            rpnTokenList.Add(s.Pop( ));
                            if (s.Count == 0)
                            {
                                throw new ArgumentException("Openning parenthesis missing.");
                            }
                        }
                        s.Pop( );

                        // saving last token...
                        lastToken = upToken;
                    }
                    // finally, the token is a variable
                    else
                    {
                        // find the variable
                        try
                        {
                            lingVar   = database.GetVariable(token);
                            lastToken = "VAR";
                        }
                        catch (KeyNotFoundException)
                        {
                            throw new ArgumentException("Linguistic variable " + token + " was not found on the database.");
                        }
                    }
                }
            }

            // popping all operators left in stack
            while (s.Count > 0)
            {
                rpnTokenList.Add(s.Pop( ));
            }
        }
Exemplo n.º 13
0
        public void SetOutput()
        {
            this.Risk = new LinguisticVariable("Ryzyko", 0, 30);

            TrapezoidalFunction function1 = new TrapezoidalFunction(5, 10, TrapezoidalFunction.EdgeType.Right);
            FuzzySet            set1      = new FuzzySet("niskie", function1);
            TrapezoidalFunction function2 = new TrapezoidalFunction(5, 10, 15);
            FuzzySet            set2      = new FuzzySet("średnio_niskie", function2);
            TrapezoidalFunction function3 = new TrapezoidalFunction(10, 15, 20);
            FuzzySet            set3      = new FuzzySet("średnie", function3);
            TrapezoidalFunction function4 = new TrapezoidalFunction(15, 20, 25);
            FuzzySet            set4      = new FuzzySet("średnio_wysokie", function4);
            TrapezoidalFunction function5 = new TrapezoidalFunction(20, 25, TrapezoidalFunction.EdgeType.Left);
            FuzzySet            set5      = new FuzzySet("wysokie", function5);


            Risk.AddLabel(set1);
            Risk.AddLabel(set2);
            Risk.AddLabel(set3);
            Risk.AddLabel(set4);
            Risk.AddLabel(set5);

            database.AddVariable(Risk);

            double y1;
            double y2;
            double y3;
            double y4;
            double y5;

            for (float x = 0; x < 30; x += 0.05f)
            {
                if (Risk.GetLabelMembership("niskie", x + 0.05f) + Risk.GetLabelMembership("niskie", x) > 0)
                {
                    y1 = Risk.GetLabelMembership("niskie", x);
                    chart6.Series["Niskie"].Points.AddXY(x, y1);
                }
                if (Risk.GetLabelMembership("średnio_niskie", x + 0.05f) + Risk.GetLabelMembership("średnio_niskie", x) > 0)
                {
                    y2 = Risk.GetLabelMembership("średnio_niskie", x);
                    chart6.Series["Śr_nisk"].Points.AddXY(x, y2);
                }

                if (Risk.GetLabelMembership("średnie", x + 0.05f) + Risk.GetLabelMembership("średnie", x) > 0)
                {
                    y3 = Risk.GetLabelMembership("średnie", x);
                    chart6.Series["Średnie"].Points.AddXY(x, y3);
                }

                if (Risk.GetLabelMembership("średnio_wysokie", x + 0.05f) + Risk.GetLabelMembership("średnio_wysokie", x) > 0)
                {
                    y4 = Risk.GetLabelMembership("średnio_wysokie", x);
                    chart6.Series["Śr_wys"].Points.AddXY(x, y4);
                }

                if (Risk.GetLabelMembership("wysokie", x + 0.05f) + Risk.GetLabelMembership("wysokie", x) > 0)
                {
                    y5 = Risk.GetLabelMembership("wysokie", x);
                    chart6.Series["Wysokie"].Points.AddXY(x, y5);
                }
            }
        }
Exemplo n.º 14
0
        public FuzzyEngine()
        {
            // Linguistic labels (fuzzy sets) for Momentum
            FuzzySet momDown = new FuzzySet("Down", new TrapezoidalFunction(-20, 5, 5, 5));
            FuzzySet momNeutral = new FuzzySet("Neutral", new TrapezoidalFunction(-20, 0, 0, 20));
            FuzzySet momUp = new FuzzySet("Up", new TrapezoidalFunction(5, 20, 20, 20));


            // Linguistic labels (fuzzy sets) for RSI
            FuzzySet rsiLow = new FuzzySet("Low", new TrapezoidalFunction(0, 30, 30, 30));
            FuzzySet rsiMedium = new FuzzySet("Medium", new TrapezoidalFunction(0, 50, 50, 100));
            FuzzySet rsiHigh = new FuzzySet("High", new TrapezoidalFunction(70, 100, 100, 100));

            // MOM (Input)
            LinguisticVariable lvMom = new LinguisticVariable("MOM", -20, 20);
            lvMom.AddLabel(momDown);
            lvMom.AddLabel(momNeutral);
            lvMom.AddLabel(momUp);

            // RSI (Input)
            LinguisticVariable lvRsi = new LinguisticVariable("RSI", 0, 100);
            lvRsi.AddLabel(rsiLow);
            lvRsi.AddLabel(rsiMedium);
            lvRsi.AddLabel(rsiHigh);

            // Linguistic labels (fuzzy sets) that compose the Signal
            FuzzySet fsShort = new FuzzySet("Sell", new TrapezoidalFunction(-100, 0, 0, 00));
            FuzzySet fsHold = new FuzzySet("Hold", new TrapezoidalFunction(-50, 0, 0, 50));
            FuzzySet fsLong = new FuzzySet("Buy", new TrapezoidalFunction(0, 100, 100, 100));

            // Output
            LinguisticVariable lvSignal = new LinguisticVariable("Signal", -100, 100);
            lvSignal.AddLabel(fsShort);
            lvSignal.AddLabel(fsHold);
            lvSignal.AddLabel(fsLong);

            // The database
            Database fuzzyDB = new Database();
            fuzzyDB.AddVariable(lvMom);
            fuzzyDB.AddVariable(lvRsi);
            fuzzyDB.AddVariable(lvSignal);

            // Creating the inference system
            IS = new InferenceSystem(fuzzyDB, new CentroidDefuzzifier(1000));

            // Rules
            IS.NewRule("Rule 1", "IF RSI IS Low AND MOM IS Down THEN Signal IS Buy");
            IS.NewRule("Rule 2", "IF RSI IS Medium AND MOM IS Down THEN Signal IS Buy");
            IS.NewRule("Rule 3", "IF RSI IS High AND MOM IS Down THEN Signal IS Hold");

            IS.NewRule("Rule 4", "IF RSI IS Low AND MOM IS Neutral THEN Signal IS Buy");
            IS.NewRule("Rule 5", "IF RSI IS Medium AND MOM IS Neutral THEN Signal IS Hold");
            IS.NewRule("Rule 6", "IF RSI IS High AND MOM IS Neutral THEN Signal IS Sell");

            IS.NewRule("Rule 7", "IF RSI IS Low AND MOM IS Up THEN Signal IS Hold");
            IS.NewRule("Rule 8", "IF RSI IS Medium AND MOM IS Up THEN Signal IS Sell");
            IS.NewRule("Rule 9", "IF RSI IS High AND MOM IS Up THEN Signal IS Sell");



        }