source: cpp/frams/neuro/impl/neuroimpl-fuzzy.cpp @ 1130

Last change on this file since 1130 was 1130, checked in by Maciej Komosinski, 6 months ago

Used std::min(), std::max() explicitly to avoid compiler confusion. Used std::size() explicitly instead of the equivalent macro

  • Property svn:eol-style set to native
File size: 7.9 KB
Line 
1// This file is a part of Framsticks SDK.  http://www.framsticks.com/
2// Copyright (C) 1999-2021  Maciej Komosinski and Szymon Ulatowski.
3// See LICENSE.txt for details.
4
5#include "neuroimpl-fuzzy.h"
6#include "neuroimpl-fuzzy-f0.h"
7
8int NI_FuzzyNeuro::countOuts(const Model *m, const Neuro *fuzzy)
9{
10        int outputs = 0;
11        for (int i = 0; i < m->getNeuroCount(); i++)
12                for (int in = 0; in < m->getNeuro(i)->getInputCount(); in++)
13                        if (m->getNeuro(i)->getInput(in) == fuzzy) outputs++;
14        return outputs;
15}
16
17int NI_FuzzyNeuro::lateinit()
18{
19        int i, maxOutputNr;
20
21        //check correctness of given parameters: string must not be null, sets&rules number > 0
22        if ((fuzzySetsNr < 1) || (rulesNr < 1) || (fuzzySetString.length() == 0) || (fuzzyRulesString.length() == 0))
23                return 0; //error
24
25        // this part contains transformation of fuzzy sets
26        fuzzySets = new double[4 * fuzzySetsNr]; //because every fuzzy set consist of 4 numbers
27        // converts fuzzy string from f0 to table of fuzzy numbers type 'double'
28        // (fill created space with numbers taken from string)
29        // also checks whether number of fuzzy sets in the string equals declared in the definition
30        if (FuzzyF0String::convertStrToSets(fuzzySetString, fuzzySets, fuzzySetsNr) != 0)
31                return 0; //error
32
33        // this part contains transformation of fuzzy rules and defuzzyfication parameters
34        rulesDef = new int[2 * rulesNr];    //for each rule remembers number of inputs and outputs
35        //check correctness of string and fill in the rulesDef
36        if (FuzzyF0String::countInputsOutputs(fuzzyRulesString.c_str(), rulesDef, rulesNr) == 0)
37        {
38                defuzzParam = new double[rulesNr]; // parameters used in defuzyfication process
39                // create space for rules according to rulesDef
40                rules = new int*[rulesNr];   //list of rules...
41                for (i = 0; i < rulesNr; i++)    //...that contains rules body
42                {
43                        rules[i] = new int[2 * (rulesDef[2 * i] + rulesDef[2 * i + 1])];  //each rule can have different number of inputs and outputs
44                        defuzzParam[i] = 0; //should be done a little bit earlier, but why do not use this loop?
45                }
46                // fill created space with numbers taken from string
47                if (FuzzyF0String::convertStrToRules(fuzzyRulesString, rulesDef, rules, fuzzySetsNr, rulesNr, maxOutputNr) != 0)
48                        return 0; //error
49        }
50        else
51                return 0; //error
52
53        setChannelCount(countOuts(neuro->owner, neuro));
54        return 1; //success
55}
56
57NI_FuzzyNeuro::~NI_FuzzyNeuro()
58{
59        if (rules) //delete rows and columns of **rules
60        {
61                for (int i = 0; i < rulesNr; i++) SAFEDELETEARRAY(rules[i])
62                        SAFEDELETEARRAY(rules)
63        }
64        SAFEDELETEARRAY(defuzzParam)
65                SAFEDELETEARRAY(rulesDef)
66                SAFEDELETEARRAY(fuzzySets)
67}
68
69int NI_FuzzyNeuro::GetFuzzySetParam(int set_nr, double &left, double &midleft, double &midright, double &right)
70{
71        if ((set_nr >= 0) && (set_nr < fuzzySetsNr))
72        {
73                left = fuzzySets[4 * set_nr];
74                midleft = fuzzySets[4 * set_nr + 1];
75                midright = fuzzySets[4 * set_nr + 2];
76                right = fuzzySets[4 * set_nr + 3];
77                return 0;
78        }
79        else
80                return 1;
81}
82
83/** Function conduct fuzzyfication of inputs and calculates - according to rules - crisp multi-channel output */
84void NI_FuzzyNeuro::go()
85{
86        if (Fuzzyfication() != 0)
87                return;
88        if (Defuzzyfication() != 0)
89                return;
90}
91
92/**
93* Function conduct fuzzyfication process - calculates minimum membership function (of every input) for each rule,
94* and writes results into defuzzParam - variable that contains data necessary for defuzzyfication
95*/
96int NI_FuzzyNeuro::Fuzzyfication()
97{
98        int i, j, nrIn, inputNr, nrFuzzySet;
99        double minimumCut; // actual minimal level of cut (= min. membership function)
100
101        // sets defuzzyfication parameters for each rule:
102        for (i = 0; i < rulesNr; i++)
103        {
104                nrIn = rulesDef[2 * i]; // nr of inputs in rule #i
105                minimumCut = 2; // the highest value of membership function is 1.0, so this value will definitely change
106                for (j = 0; (j < nrIn) && (minimumCut > 0); j++) //minimumCut can not be <0, so if =0 then stop calculations
107                {
108                        nrFuzzySet = rules[i][j * 2 + 1]; // j*2 moves pointer through each output, +1 moves to nr of fuzzy set
109                        inputNr = rules[i][j * 2]; // as above but gives input number
110                        minimumCut = std::min(minimumCut, TrapeziumFuzz(nrFuzzySet, getWeightedInputState(inputNr))); // value of membership function for this input and given fuzzy set
111                }
112                if ((minimumCut > 1) || (minimumCut < 0))
113                        return 1;
114                defuzzParam[i] = minimumCut;
115        }
116        return 0;
117}
118
119/**
120* Function calculates value of the membership function of the set given by wchich_fuzzy_set for given crisp value input_val
121* In other words, this function fuzzyficates given crisp value with given fuzzy set, returning it's membership function
122* @param which_fuzzy_set - 0 < number of set < fuzzySetsNr
123* @param input_val - crisp value of input in range <-1; 1>
124* @return value of membership function (of given input for given set) in range <0;1> or, if error occur, negative value
125*/
126double NI_FuzzyNeuro::TrapeziumFuzz(int which_fuzzy_set, double input_val)
127{
128        double range = 0, left = 0, midleft = 0, midright = 0, right = 0;
129
130        if ((which_fuzzy_set < 0) || (which_fuzzy_set > fuzzySetsNr))
131                return -2;
132        if ((input_val < -1) || (input_val > 1))
133                return -3;
134
135        if (GetFuzzySetParam(which_fuzzy_set, left, midleft, midright, right) != 0)
136                return -4;
137
138        if ((input_val < left) || (input_val > right)) // greather than right value
139                return 0;
140        else if ((input_val >= midleft) && (input_val <= midright)) // in the core of fuzzy set
141                return 1;
142        else if ((input_val >= left) && (input_val < midleft)) // at the left side of trapezium
143        {
144                range = fabs(midleft - left);
145                return fabs(input_val - left) / ((range > 0) ? range : 1); // quotient of distance between input and extreme left point of trapezium and range of rising side, or 1
146        }
147        else if ((input_val > midright) && (input_val <= right)) // at the right side of trapezium
148        {
149                range = fabs(right - midright);
150                return fabs(right - input_val) / ((range > 0) ? range : 1); // quotient of distance between input and extreme right point of trapezium and range of falling side, or 1
151        };
152
153        // should not occur
154        return 0;
155
156}
157
158/**
159* Function conducts defuzzyfication process: multi-channel output values are calculates with singleton method (method of high).
160* For each rules, all outputs fuzzy sets are taken and cut at 'cut-level', that is at minumum membership function (of current rule).
161* For all neuro pseudo-outputs, answer is calculated according to prior computations.
162* In fact, there is one output with multi-channel answer and appropriate values are given to right channels.
163*/
164int NI_FuzzyNeuro::Defuzzyfication()
165{
166        int i, j, nrIn, nrOut, out, set, outputsNr;
167        double *numerators, *denominators, midleft, midright, unimp;
168
169        outputsNr = getChannelCount();
170
171        numerators = new double[outputsNr];
172        denominators = new double[outputsNr];
173
174        for (i = 0; i < outputsNr; i++) numerators[i] = denominators[i] = 0;
175
176        // for each rule...
177        for (i = 0; i < rulesNr; i++)
178        {
179                nrIn = rulesDef[2 * i]; // number of inputs in rule #i
180                nrOut = rulesDef[2 * i + 1]; // number of outputs in rule #i
181                // ...calculate each output's product of middle fuzzy set value and minimum membership function (numerator) and sum of minimum membership function (denominator)
182                for (j = 0; j < nrOut; j++)
183                {
184                        out = rules[i][2 * nrIn + 2 * j]; //number of j-output
185                        set = rules[i][2 * nrIn + 2 * j + 1]; //number of fuzzy set attributed to j-output
186                        if (GetFuzzySetParam(set, unimp, midleft, midright, unimp) != 0) // gets range of core of given fuzzy set
187                        {
188                                SAFEDELETEARRAY(denominators) SAFEDELETEARRAY(numerators) return 1;
189                        }
190                        //defuzzParam[i] = minimum membership function for rule #i - calculated in fuzzyfication block
191                        // defuzzyfication method of singletons (high): (fuzzy set modal value) * (minimum membership value)
192                        numerators[out] += ((midleft + midright) / 2.0) * defuzzParam[i];
193                        denominators[out] += defuzzParam[i];
194                }
195        }
196
197        for (i = 0; i < outputsNr; i++)
198        {
199                if (denominators[i] == 0)
200                        setState(0, i);
201                else
202                        setState(numerators[i] / denominators[i], i);
203        }
204
205        SAFEDELETEARRAY(denominators)
206                SAFEDELETEARRAY(numerators)
207
208                return 0;
209}
Note: See TracBrowser for help on using the repository browser.