Click here to Skip to main content
15,881,248 members
Articles / Programming Languages / C#

C# Fuzzy Logic API

Rate me:
Please Sign up or sign in to vote.
4.73/5 (29 votes)
5 Aug 2020MIT3 min read 55.9K   340   44   21
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 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 purpose. The new version update of this API using iteractions with Parallelism or Yield in some portions of code to increase performance; another advance are bug 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 any developer project.

2) Fuzzy Logic Concepts

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

From: https://www.tutorialspoint.com/fuzzy_logic/fuzzy_logic_introduction.htm

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 built on Fuzzy Logic Engine (view figure below, from Wikepdia reference):

From: https://es.wikipedia.org/wiki/Defuzzificaci%C3%B3n

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 Honest character like integrity, truth and justice sense percentage assessment for all and a boolean expression object that identifies the Honesty Profile, considering the minimal percentage to be an 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 assessment:
h.IntegrityPercentage > 75;
h.JusticeSensePercentage > 75;
h.TruthPercentage > 75;

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

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

//Last group of assessment:
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 four  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 image below:

From: https://github.com/antonio-leonardo/FuzzyLogicApi

C#
HonestAssesment profile4 = new HonestAssesment()
{
    IntegrityPercentage = 91,
    JusticeSensePercentage = 83,
    TruthPercentage = 81
};
List<HonestAssesment> allProfiles = new List<HonestAssesment>();
allProfiles.Add(profile1);
allProfiles.Add(profile2);
allProfiles.Add(profile3);
allProfiles.Add(profile4);
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>
    <ID>8d79084c-9402-4683-833d-437cad86ef4a</ID>
    <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, which has 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 an 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) Dependencies

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.

This article was originally posted at https://github.com/antonio-leonardo/FuzzyLogicApi

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Architect
Brazil 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:
Master in Business Administration (MBA)

Comments and Discussions

 
QuestionFuzzy Logic can be used to judge outputs of multiple neural networks Pin
Matt W. Allen2-Nov-20 11:49
Matt W. Allen2-Nov-20 11:49 
AnswerRe: Fuzzy Logic can be used to judge outputs of multiple neural networks Pin
AntonioLeonardo4-Nov-20 1:57
professionalAntonioLeonardo4-Nov-20 1:57 
QuestionMembership functions? Pin
Member 1019550514-Sep-20 2:49
professionalMember 1019550514-Sep-20 2:49 
AnswerRe: Membership functions? Pin
AntonioLeonardo17-Sep-20 5:41
professionalAntonioLeonardo17-Sep-20 5:41 
QuestionNot able to download a copy Pin
Member 1049523619-Dec-19 5:21
Member 1049523619-Dec-19 5:21 
AnswerRe: Not able to download a copy Pin
AntonioLeonardo19-Dec-19 9:03
professionalAntonioLeonardo19-Dec-19 9:03 
Questiongood example for Fuzzy logic Pin
Mou_kol8-Aug-19 20:47
Mou_kol8-Aug-19 20:47 
AnswerRe: good example for Fuzzy logic Pin
AntonioLeonardo9-Aug-19 2:39
professionalAntonioLeonardo9-Aug-19 2:39 
GeneralMy vote of 5 Pin
Thiago Moreira7-Jul-19 16:17
professionalThiago Moreira7-Jul-19 16:17 
GeneralRe: My vote of 5 Pin
AntonioLeonardo16-Jul-19 4:23
professionalAntonioLeonardo16-Jul-19 4:23 
GeneralPlease do not use percentages in fuzzy logic Pin
Emile van Gerwen17-Jun-19 3:24
Emile van Gerwen17-Jun-19 3:24 
GeneralRe: Please do not use percentages in fuzzy logic Pin
AntonioLeonardo18-Jun-19 12:24
professionalAntonioLeonardo18-Jun-19 12:24 
GeneralRe: Please do not use percentages in fuzzy logic Pin
Nelek4-Jul-19 19:09
protectorNelek4-Jul-19 19:09 
GeneralRe: Please do not use percentages in fuzzy logic Pin
AntonioLeonardo5-Jul-19 15:41
professionalAntonioLeonardo5-Jul-19 15:41 
GeneralRe: Please do not use percentages in fuzzy logic Pin
MKJCP15-Jul-19 6:53
MKJCP15-Jul-19 6:53 
GeneralRe: Please do not use percentages in fuzzy logic Pin
AntonioLeonardo16-Jul-19 4:23
professionalAntonioLeonardo16-Jul-19 4:23 
Questionnice Pin
Member 1449972013-Jun-19 18:51
Member 1449972013-Jun-19 18:51 
AnswerRe: nice Pin
AntonioLeonardo18-Jun-19 12:24
professionalAntonioLeonardo18-Jun-19 12:24 
Questiontypo ? Pin
Member 1411878512-Jun-19 5:23
Member 1411878512-Jun-19 5:23 
AnswerRe: typo ? Pin
AntonioLeonardo12-Jun-19 13:10
professionalAntonioLeonardo12-Jun-19 13:10 

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

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