15,610,841 members
Articles / Artificial Intelligence

50.8K views
42 bookmarked

# C# Fuzzy Logic API

Rate me:
How to execute inferences by fuzzy logic concept on Plain Old CLR Object
This API executes inferences by fuzzy logic concept on plain old CLR Object associating a predicate defined in .NET native object called 'Expression'. In this post, we will go through Abstraction, Fuzzy Logic Concepts and then see how to use the API.

This Api executes inferences by fuzzy logic concept on C# Plain Old CLR Object associating an Expression object defined in native .NET Framework.

## 1) Before you begin: Abstraction

If do you want to delve into Fuzzy Logic theory (such as mathematical theorems, postulates, and Morgan's law) it's strongly recommended to look for other references to satisfy your curiosity and / or your research need. Through here this git post, you'll access only a practical example to execute the Fuzzy Logic in real world applications; then, the focus in this article is not diving on philosophical dialogue with only a pratical porpuse. The new version update of this API using iteractions with Parallelism or Yield in some portions of code to increase performance; another advance are bugs fixes such like: lack of properties in XML output, output of inference in decimal numbers (following the most diffuse logical theory), and calibration of output values for greater accuracy. Important note: All constructors stay the same, with no impact to the any developer project.

## 2) Fuzzy Logic Concepts

This figure from tutorialspoint site resumes the real concept of Fuzzy Logic: Nothing is absolutily true or false (for Fuzzy Logic); between 0 and 1 you have a interval from these extremes, beyond the limits of the boolean logic.

## 3) Using the API

### 3.1) Core flow

The core concept had the first requirement: Defuzzyfication. In other words, generate a Fuzzy Logic results by Crisp Input expression builded on Fuzzy Logic Engine (view figure bellow, from Wikepdia reference):

The rule of Fuzzy Logic Engine is: break apart any complex boolean expression (crisp input) that resolves a logical boolean problem in minor boolean parts rule (about the theory used of this complex boolean expression, view articles like Many-Valued Logic or /Classical Logic).

Based on illustrative example above, let's create a Model class that represents the Honest charater like integrity, truth and justice sense percentage assesment for all and a boolean expression object that identifies the Honesty Profile, considering the minimal percentage to be a honest person:

C#
```[Serializable, XmlRoot]
public class HonestAssesment
{
[XmlElement]
public double Integrity { get; set; }

[XmlElement]
public double Truth { get; set; }

[XmlElement]
public double JusticeSense { get; set; }

[XmlElement]
public double MistakesAVG
{
get
{
return (Integrity + Truth - JusticeSense) / 3;
}
}
}

//Crisp Logic expression that represents Honesty Profiles:
static Expression<Func<HonestAssesment, bool>> _honestyProfile = (h) =>
(h.IntegrityPercentage > 75 && h.JusticeSensePercentage > 75 && h.TruthPercentage > 75) || //First group
(h.IntegrityPercentage > 90 && h.JusticeSensePercentage > 60 && h.TruthPercentage > 50) || //Second group
(h.IntegrityPercentage > 70 && h.JusticeSensePercentage > 90 && h.TruthPercentage > 80) || //Third group
(h.IntegrityPercentage > 65 && h.JusticeSensePercentage == 100 && h.TruthPercentage > 95); //Last group```

The boolean expression broken is one capacity derived from System.Linq.Expressions.Expression class, converting any block of code to representational string; the derived class who will auxiliate with this job is BinaryExpression: the boolean expression will be sliced in binary tree of smaller boolean expression, whose rule will prioritize the slice where the conditional expression is contained 'OR', then sliced by 'AND' conditional expression.

C#
```//First group of assesment:
h.IntegrityPercentage > 75;
h.JusticeSensePercentage > 75;
h.TruthPercentage > 75;

//Second group of assesment:
h.IntegrityPercentage > 90;
h.JusticeSensePercentage > 60;
h.TruthPercentage > 50;

//Third group of assesment:
h.IntegrityPercentage > 70;
h.JusticeSensePercentage > 90;
h.TruthPercentage > 80;

//Last group of assesment:
h.IntegrityPercentage > 65;
h.JusticeSensePercentage == 100;
h.TruthPercentage > 95;```

This functionality contained in the .NET Framework is the trump card to mitigate the appraisal value that the evaluated profiles have conquered or how close they have come to reach any of the 4 defined valuation groups, for example:

C#
```HonestAssesment profile1 = new HonestAssesment()
{
IntegrityPercentage = 90,
JusticeSensePercentage = 80,
TruthPercentage = 70
};
string inference_p1 = FuzzyLogic<HonestAssesment>.GetInference(_honestyProfile, ResponseType.Json, profile1);```

Look at "HitsPercentage" and "InferenceResult" properties. The inference on Profile 1, with 0.67 of Honest (1 is Extremely Honest). -Result of "inference_p1" string variable (JSON):

JavaScript
```{
"ID":"72da723b-b879-474c-b2cc-6a11c5965b25",
"InferenceResult":"0.67",
"Data":
{
"IntegrityPercentage":90,
"TruthPercentage":70,
"JusticeSensePercentage":80,
"MistakesPercentage":20
},
"PropertiesNeedToChange":["IntegrityPercentage"],
"ErrorsQuantity":1
}```
C#
```HonestAssesment profile2 = new HonestAssesment()
{
IntegrityPercentage = 50,
JusticeSensePercentage = 63,
TruthPercentage = 30
};
string inference_p2 = FuzzyLogic<HonestAssesment>.GetInference(_honestyProfile, ResponseType.Xml, profile2);```

The inference on Profile 2, with 33% of Honest, that is "Sometimes honest", like a tutorialspoint figure. --Result of "inference_p2" string variable (XML):

XML
```<?xml version="1.0" encoding="utf-8"?>
<InferenceOfHonestAssesment>
<PropertiesNeedToChange>IntegrityPercentage</PropertiesNeedToChange>
<PropertiesNeedToChange>TruthPercentage</PropertiesNeedToChange>
<ErrorsQuantity>2</ErrorsQuantity>
<ID>efb7249e-568f-44d4-a8b3-ce728a243273</ID>
<InferenceResult>0.33</InferenceResult>
<Data>
<IntegrityPercentage>50</IntegrityPercentage>
<TruthPercentage>30</TruthPercentage>
<JusticeSensePercentage>63</JusticeSensePercentage>
</Data>
</InferenceOfHonestAssesment>```
C#
```HonestAssesment profile3 = new HonestAssesment()
{
IntegrityPercentage = 46,
JusticeSensePercentage = 48,
TruthPercentage = 30
};
var inference_p3 = FuzzyLogic<HonestAssesment>.GetInference(_honestyProfile, profile3);```

The inference on Profile 3, with 0% of Honest, that is "Extremely dishonest", like a figure above. --Result of "inference_p3" Api Model variable (like "Inference<HonestAssesment" object) in imagem bellow:

C#
```HonestAssesment profile4 = new HonestAssesment()
{
IntegrityPercentage = 91,
JusticeSensePercentage = 83,
TruthPercentage = 81
};
List<HonestAssesment> allProfiles = new List<HonestAssesment>();
string inferenceAllProfiles = FuzzyLogic<HonestAssesment>.GetInference(_honestyProfile, ResponseType.Xml, allProfiles);```

Inferences with all Profiles, in XML:

XML
```<?xml version="1.0" encoding="utf-8"?>
<InferenceResultOfHonestAssesment>
<Inferences>
<PropertiesNeedToChange>IntegrityPercentage</PropertiesNeedToChange>
<ErrorsQuantity>1</ErrorsQuantity>
<InferenceResult>0.67</InferenceResult>
<Data>
<IntegrityPercentage>90</IntegrityPercentage>
<TruthPercentage>70</TruthPercentage>
<JusticeSensePercentage>80</JusticeSensePercentage>
</Data>
</Inferences>
<Inferences>
<PropertiesNeedToChange>IntegrityPercentage</PropertiesNeedToChange>
<PropertiesNeedToChange>TruthPercentage</PropertiesNeedToChange>
<ErrorsQuantity>2</ErrorsQuantity>
<ID>979d4ebe-6210-46f4-a492-00df88591d17</ID>
<InferenceResult>0.33</InferenceResult>
<Data>
<IntegrityPercentage>50</IntegrityPercentage>
<TruthPercentage>30</TruthPercentage>
<JusticeSensePercentage>63</JusticeSensePercentage>
</Data>
</Inferences>
<Inferences>
<PropertiesNeedToChange>IntegrityPercentage</PropertiesNeedToChange>
<PropertiesNeedToChange>JusticeSensePercentage</PropertiesNeedToChange>
<PropertiesNeedToChange>TruthPercentage</PropertiesNeedToChange>
<ErrorsQuantity>3</ErrorsQuantity>
<ID>9004cb7a-b75d-4452-9d9a-c8836a5531eb</ID>
<InferenceResult>0</InferenceResult>
<Data>
<IntegrityPercentage>46</IntegrityPercentage>
<TruthPercentage>30</TruthPercentage>
<JusticeSensePercentage>48</JusticeSensePercentage>
</Data>
</Inferences>
<Inferences>
<ErrorsQuantity>0</ErrorsQuantity>
<ID>36545dae-1dde-4bfd-a528-ae42a7a0748f</ID>
<InferenceResult>1.00</InferenceResult>
<Data>
<IntegrityPercentage>91</IntegrityPercentage>
<TruthPercentage>81</TruthPercentage>
<JusticeSensePercentage>83</JusticeSensePercentage>
</Data>
</Inferences>
</InferenceResultOfHonestAssesment>```

### 3.2) Design Pattern

The 'Fuzzy Logic API' developed with Singleton Design Pattern, structured with one private constructor, where have two arguments parameter: one Expression object and one POCO object (defined in Generic parameter); but the developer will get the inference result by one line of code

C#
```//Like a inference object...
Inference<ModelToInfere> inferObj = FuzzyLogic<ModelToInfere>.GetInference(_honestyProfileArg, modelObj);

//... get as xml string...
string inferXml = FuzzyLogic<ModelToInfere>.GetInference(_honestyProfileArg, ResponseType.Xml, modelObj);

//...or json string.
string inferJson = FuzzyLogic<ModelToInfere>.GetInference(_honestyProfileArg, ResponseType.Json, modelObj);```

### 3.3) Dependecies

To add Fuzzy Logic Api as an Assembly or like classes inner in your Visual Studio project, you'll need to install System.Linq.Dynamic dll, that can be installed by nuget reference or execute command on Nuget Package Console (Install-Package System.Linq.Dynamic).

## Award

Voted the Best Article of June/2019 by Code Project

Written By
Architect
Brazil
15 years experience in Software Development, Architecting Solutions focused on Microsoft Ecosystems; and work on Critical Mission Projects.

Certifications:
Microsoft Certified professional (MCP), Microsoft Certified technology specialist (MCTS)
Acknowledgement:

 First Prev Next
 Fuzzy Logic can be used to judge outputs of multiple neural networks Matt W. Allen2-Nov-20 11:49 Matt W. Allen 2-Nov-20 11:49
 Re: Fuzzy Logic can be used to judge outputs of multiple neural networks AntonioLeonardo4-Nov-20 1:57 AntonioLeonardo 4-Nov-20 1:57
 Membership functions? Member 1019550514-Sep-20 2:49 Member 10195505 14-Sep-20 2:49
 Hi, I read many articles about Fuzzy Logic and they all mentioned about the membership functions in FIS. I do not see you mentioned membership functions in your API. Am I missing something or already handle internally? Thanks
 Re: Membership functions? AntonioLeonardo17-Sep-20 5:41 AntonioLeonardo 17-Sep-20 5:41
 Not able to download a copy Member 1049523619-Dec-19 5:21 Member 10495236 19-Dec-19 5:21
 Re: Not able to download a copy AntonioLeonardo19-Dec-19 9:03 AntonioLeonardo 19-Dec-19 9:03
 good example for Fuzzy logic Mou_kol8-Aug-19 20:47 Mou_kol 8-Aug-19 20:47
 Re: good example for Fuzzy logic AntonioLeonardo9-Aug-19 2:39 AntonioLeonardo 9-Aug-19 2:39
 My vote of 5 Thiago Moreira7-Jul-19 16:17 Thiago Moreira 7-Jul-19 16:17
 Re: My vote of 5 AntonioLeonardo16-Jul-19 4:23 AntonioLeonardo 16-Jul-19 4:23
 Please do not use percentages in fuzzy logic Emile van Gerwen17-Jun-19 3:24 Emile van Gerwen 17-Jun-19 3:24
 Re: Please do not use percentages in fuzzy logic AntonioLeonardo18-Jun-19 12:24 AntonioLeonardo 18-Jun-19 12:24
 Re: Please do not use percentages in fuzzy logic Nelek4-Jul-19 19:09 Nelek 4-Jul-19 19:09
 Re: Please do not use percentages in fuzzy logic AntonioLeonardo5-Jul-19 15:41 AntonioLeonardo 5-Jul-19 15:41
 Re: Please do not use percentages in fuzzy logic MKJCP15-Jul-19 6:53 MKJCP 15-Jul-19 6:53
 Re: Please do not use percentages in fuzzy logic AntonioLeonardo16-Jul-19 4:23 AntonioLeonardo 16-Jul-19 4:23
 nice Member 1449972013-Jun-19 18:51 Member 14499720 13-Jun-19 18:51
 Re: nice AntonioLeonardo18-Jun-19 12:24 AntonioLeonardo 18-Jun-19 12:24
 typo ? Member 1411878512-Jun-19 5:23 Member 14118785 12-Jun-19 5:23
 Re: typo ? AntonioLeonardo12-Jun-19 13:10 AntonioLeonardo 12-Jun-19 13:10
 Last Visit: 31-Dec-99 18:00     Last Update: 25-Mar-23 2:17 Refresh 1