Click here to Skip to main content
Click here to Skip to main content

FuzzScript - A Fuzzy Logic Control Language

By , 16 Dec 2009
Rate this:
Please Sign up or sign in to vote.


This article presents a Fuzzy Logic scripting language, FuzzScript, which can be used to include fuzzy controllers in C# applications. One interesting aspect is the possibility to generate an optimized version (hardcoded) of the controller under examination at runtime. I thank the user patsissons for his article: Compiling and Executing Code at Runtime that was of great help.

Fuzzy Logic and Fuzzy Control

Fuzzy Set theory was introduced in 1965 by Lotfi Zadeh’s seminal paper on fuzzy sets. It defines a generalization of classical set theory, making it possible to represent concepts that do not have a precise boundary like ‘tall’ or ‘heavy’. This is achieved by allowing items to belong to a given variable to a certain degree, where a degree of membership of a variable is a real number in [0, 1]. Formally, a fuzzy set F over universe of discourse X is defined by its membership function which maps elements to a number between 0 and 1.

Hence, for any , represents the degree by which x belongs to X, for example:

If is continuous, can be given by:

Since for our applications the universe of discourse is discrete, so that it can be processed by a computer, is represented by:

Consider fuzzy sets A and B defined over a universe of discourse X, their degree of membership at is:

A and B are equal if:

The complement of a fuzzy set is defined as:

Before examining fuzzy relation operators, it is useful to define a family of operators known as triangular norms (t-norm) and their conorm (s-norm).

Well known examples of t-norms, represented by include:

Well known examples of conorm (s-norm), represented by include:


min(x+y, 1)

The union of two fuzzy sets, A and B, at a given point in the domain of discourse X is:

The intersection of two fuzzy sets, A and B, at a given point in the domain of discourse X is:

Fuzzy Control and Fuzzy Systems

The figure below shows the familiar closed loop system controller which has been the topic of intensive research in control theory and control engineering:

Closed Loop Control System

Many control tasks are apparently simple for humans, but they create a continuous challenge for machines. Examples of such systems include walking through a cluttered environment, lifting fragile objects, or parking a car. The ability of humans to deal with vague and imprecise data makes such tasks easy for us. Therefore, if our aim is to replicate the control actions of a human operator, we must be able to model the actions of the operator and not of the plant itself. Our model must be built so that it is capable to deal with vague information.

A fuzzy system is a repository of fuzzy expert knowledge that can reason about data in vague terms instead of precise Boolean logic. Expert knowledge is a collection of fuzzy membership functions and a set of fuzzy rules, known as the rule-base, of the form:

IF (conditions are fulfilled) THEN (consequences are inferred)

The basic configuration of a fuzzy system is shown below:

Fuzzy Logic Controller

A typical fuzzy system can be split up into four main parts, namely a fuzzifier, a knowledge base, an inference engine, and a defuzzifier.

The fuzzifier maps a real crisp input to a fuzzy function, therefore determining the ‘degree of membership’ of the input to a vague concept. In a number of controllers, the values of the input variables are mapped to the range of values of the corresponding universe of discourse. The range and resolution of input fuzzy sets and their effect on the fuzzification process is considered as a factor affecting the overall performance of the controller.

The knowledge base comprises the knowledge of the application domain and the attendant control goals. It can be split in a database of definitions used to express linguistic control rules in the controller, and a rule base that describes the knowledge held by the experts of the domain. Intuitively, the knowledge base is the core element of a fuzzy controller as it will contain all the information necessary to accomplish its execution tasks. Extensive research has been carried out in order to fine tune a fuzzy controller’s knowledge base, many using other AI disciplines such Genetic Algorithms or neural networks.

The Inference Engine provides the decision making logic of the controller. It deduces the fuzzy control actions by employing fuzzy implication and fuzzy rules of inference. In many aspects, it can be viewed as an emulation of human decision making.

The defuzzification process converts fuzzy control values into crisp quantities; that is, it links a single point to a fuzzy set, given that the point belongs to the support of the fuzzy set. There are many defuzzification processes, the most famous being:

Centre of Area (Centre of Gravity)


In Mamdani systems, the antecedents and consequents of a fuzzy rule are fuzzy sets. Inferences are based on Generalized Modus Ponens, which states that the degree of truth of the consequent of a fuzzy rule is the degree of truth of the antecedent. In the case where more than one antecedent clause is present, the individual degrees of membership are joined using a min t-norm operator. If the fuzzy set contains several rules, their output is combined using a max s-norm operator. Defuzzification is necessary so that the consequent action can be expressed in terms of a crisp value.

Mamdani Fuzzy Controller

Overview of FuzzScript

FuzzScript is divided into three sections: a Knowledge base definition section, a Predicates definition section, and the Rule base definition section.

Knowledge Base

The knowledge base contains the definitions of all the variables used in the system, and the fuzzy sets for that variable. It is enclosed within the KnowledgeBase keyword:

    //variable definitions

Each variable is identified by its type (input or output variable), its name, and its limits; hence, an input variable called temperature having a lower limit of 0 degrees and higher limit of 100 degrees, is defined as follows:

InputVariable TEMPERATURE [0, 100]
      // fuzzy set definitions

Similarly, the output variable MotorSpeed can be defined as:

OutputVariable MOTORSPEED [0, 3000]
      // fuzzy set definitions

Currently, three types of fuzzy sets can be defined in FuzzScript:

Fuzzy Set Type Illustration FuzzScript Syntax Example

Triangular (NAME, a, b, c)

Triangular (warm, 10, 30, 50)


LShoulder (NAME, a, b)

LShoulder(cold, 20, 40)


RShoulder (NAME, a, b)

RShoulder(hot,40, 80)


The predicates section holds a number of named fuzzy clauses that will be used in the antecedent parts of the fuzzy rules. They isolate the rules from the specifics of the sensors used, thus making the rule-base more descriptive. As an example, consider a system where a temperature sensor and a humidity sensor are used to control a fan. A fuzzy rule in this scenario might be:

If temperature is very hot and humidity is very high then speed is high

Obviously, all the rules will require considerable changes if the sensors are changed. If we define a fuzzy predicate that will have a value in the [0, 1] range, that will indicate a high effective temperate, such that:

Predicate EffectiveTemperatureHigh
  temperature is very hot and humidity is very high

the predicate can then be used in the antecedent part of the fuzzy rules instead of the clause. If the sensors are changed, it is necessary to modify the predicates without touching the rules.

In FuzzScript, the predicates contained in the Predicates section:

    // Predicates definitions

Each predicate is identified by a the Predicate keyword and the predicate name, as was illustrated in the EffectiveTemperatureHigh predicate above.

The actual clauses can contain any combination of conjunctive or disjunctive operators; hence, clauses of the following form are possible:

(A is a  and B is b) or
(A is c  and B is d ) or
(A is e  and B is f )

Fuzzy hedges or negation can also be implemented in clauses. In this version the hedge very and the negation operator not can be used so that the following statement can be formed:

(not A is a  and B is b) or
(A is c  and very B is d )

Rule Base

The rule base contains a collection of If – Then fuzzy rules that are executed so that the output values can be deduced. It is identified by the RuleBase keyword:

      // Rules definitions

The antecedent part can contain the names of fuzzy predicates that were defined in the predicates section, or fuzzy clauses, or a mixture of the two connected by ‘and’ or ‘or’ operators. If fuzzy predicates are used, they should be enclosed in a set of < > braces.

The consequent part can contain fuzzy clauses of the type:


or assignments such as:


Assignments are very handy whenever a specific output value must be used. It is also important to note that fuzzy hedges can be applied to predicates and clauses in the antecedent parts of fuzzy rules as well. An example of a fuzzy rule is:

If very <far> Then VELOCITYANGULAR = 0 and VELOCITYLINEAR is medium

Implementation of FuzzScript

FuzzScript was described in a coco/r definition that generated the C# parser and scanner code. The parser actually builds a tree structure that makes up the system, where each node implements the INode interface.

Four methods are defined in this interface:

  • AddSibling – Adds a child node.
  • Initialize – Initializes the node.
  • Execute – Is called during the execution of the system.
  • Generate – Returns the equivalent c# code string for the node.

The system root node class, FuzzySystem, contains two additional methods that provide an input and output interface to the fuzzy system: UpdateSystemInputs and UpdateSystemOutputs. Both methods operate on a collection of named doubles that contain the input and output values of the system.

The interface to the fuzzy system is provided via the FuzzyEngine class that implements the IControlEngine interface. This interface specifies a single method:

Control(Dictionary<string, double> p_InternalState, 
        Dictionary<string, double> p_ControlValues);

In essence, references to the input and output values are passed to the system. At the end of each control cycle, the output values will be contained in the ControlValues dictionary.

The FuzzyEngine constructor requires a parameter that contains the path to a fuzzy system definition file.

The other method in FuzzyEngine is Generate that returns an IControlEngine object. This method will return a ‘hardcoded’ system as explained in the following section.

Optimizing the Fuzzy Engine

Clearly, one of the goals of the system described above is performance. In order to maximize this parameter, a mechanism was created whereby each node returns its C# string equivalent. At the root node level, a string containing the definition of a single class that implements a hardcoded version of the system will be contained. The FuzzyEngine Generate method compiles this code at runtime, and returns an IControlEngine object defined by the hardcoded class.

Two versions of the Generate method are implemented in FuzzyEngine so that it is possible to store the hardcoded class code in a file.

Using FuzzScript

The following code snippet illustrates the use of the unoptimized fuzzy engine. The following steps are required:

  • The engine is created, given a valid definition file.
  • The input and output dictionaries are created and the input values submitted.
  • The Control method is called, and the output values are collected from the output dictionary.
FuzzyEngine engine = new FuzzyEngine("..\\..\\System1.txt");
// Create Internal state
Dictionary<string, double> internalStates = new Dictionary<string, double>();
internalStates.Add("SENSORRIGHT", 10);
internalStates.Add("SENSORMIDDLE", 200);
internalStates.Add("SENSORLEFT", 200);
// Create control values - initialize all to zero
Dictionary<string, double> controlActions = new Dictionary<string, double>();
controlActions.Add("VELOCITYLINEAR", 0.0);
controlActions.Add("VELOCITYANGULAR", 0.0);
engine.Control( internalStates, controlActions);

In order to use an optimized engine, the Generate method must be called so that the new engine is created and can be used. In both cases, the input and output dictionaries must be created and the Control method called:

FuzzyEngine engine = new FuzzyEngine("..\\..\\System1.txt");

IControlEngine optimizedEngine = engine.Generate();
// Create Internal state
Dictionary<string, double> internalStates = new Dictionary<string, double>();
internalStates.Add("SENSORRIGHT", 10);
internalStates.Add("SENSORMIDDLE", 200);
internalStates.Add("SENSORLEFT", 200);
// Create control values - initialize all to zero
Dictionary<string, double> controlActions = new Dictionary<string, double>();
controlActions.Add("VELOCITYLINEAR", 0.0);
controlActions.Add("VELOCITYANGULAR", 0.0);
optimizedEngine.Control( internalStates, controlActions);


In most cases, the optimized engines were about 30% faster than their non-optimized counterparts. Although by no means perfect and substantial polishing work is required, encouraging results were obtained when the engine was tested in various scenarios.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Carmel Gafa
Team Leader Crimsonwing (Malta) Ltd
Malta Malta
No Biography provided

Comments and Discussions

GeneralMy vote of 5 PinmemberShayan Ali Bhatti6-Mar-13 0:29 
GeneralMy vote of 5 PinmvpKanasz Robert5-Nov-12 23:59 
GeneralWhy not use XML or a Config file? [modified] Pinmemberponki.d.monkey14-Apr-10 3:45 
GeneralRe: Why not use XML or a Config file? PinmemberCarmel Gafa15-Jun-10 23:48 
GeneralYou get my 5! PinmemberColin Vella22-Dec-09 10:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140415.2 | Last Updated 16 Dec 2009
Article Copyright 2009 by Carmel Gafa
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid