summaryrefslogtreecommitdiff
path: root/fuzzylite/src/imex/FisImporter.cpp
blob: f846469487ed2f5b9a287d089d2e8882a0038c98 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
/*
 fuzzylite (R), a fuzzy logic control library in C++.
 Copyright (C) 2010-2017 FuzzyLite Limited. All rights reserved.
 Author: Juan Rada-Vilela, Ph.D. <jcrada@fuzzylite.com>

 This file is part of fuzzylite.

 fuzzylite is free software: you can redistribute it and/or modify it under
 the terms of the FuzzyLite License included with the software.

 You should have received a copy of the FuzzyLite License along with
 fuzzylite. If not, see <http://www.fuzzylite.com/license/>.

 fuzzylite is a registered trademark of FuzzyLite Limited.
 */

#include "fl/imex/FisImporter.h"

#include "fl/Headers.h"

namespace fl {

    FisImporter::FisImporter() : Importer() { }

    FisImporter::~FisImporter() { }

    std::string FisImporter::name() const {
        return "FisImporter";
    }

    Engine* FisImporter::fromString(const std::string& fis) const {
        FL_unique_ptr<Engine> engine(new Engine);

        std::istringstream fisReader(fis);
        std::string line;
        std::size_t lineNumber = 0;

        std::vector<std::string> sections;
        while (std::getline(fisReader, line)) {
            ++lineNumber;
            //remove comments
            line = Op::split(line, "//", false).front();
            line = Op::split(line, "#", false).front();
            line = Op::trim(line);
            if (line.empty() or line.at(0) == '%') {
                continue;
            }

            line = Op::findReplace(line, "'", "");

            if ("[System]" == line.substr(0, std::string("[System]").size())
                    or "[Input" == line.substr(0, std::string("[Input").size())
                    or "[Output" == line.substr(0, std::string("[Output").size())
                    or "[Rules]" == line.substr(0, std::string("[Rules]").size())) {
                sections.push_back(line);
            } else {
                if (not sections.empty()) {
                    sections.at(sections.size() - 1) += "\n" + line;
                } else {
                    std::ostringstream ss;
                    ss << "[import error] line " << lineNumber << " <" << line << "> "
                            "does not belong to any section";
                    throw Exception(ss.str(), FL_AT);
                }
            }
        }
        std::string andMethod, orMethod, impMethod, aggMethod, defuzzMethod;
        for (std::size_t i = 0; i < sections.size(); ++i) {
            if ("[System]" == sections.at(i).substr(0, std::string("[System]").size()))
                importSystem(sections.at(i), engine.get(),
                    andMethod, orMethod, impMethod, aggMethod, defuzzMethod);
            else if ("[Input" == sections.at(i).substr(0, std::string("[Input").size()))
                importInput(sections.at(i), engine.get());
            else if ("[Output" == sections.at(i).substr(0, std::string("[Output").size()))
                importOutput(sections.at(i), engine.get());
            else if ("[Rules]" == sections.at(i).substr(0, std::string("[Rules]").size()))
                importRules(sections.at(i), engine.get());
            else throw Exception("[import error] section <"
                    + sections.at(i) + "> not recognized", FL_AT);
        }
        engine->configure(translateTNorm(andMethod), translateSNorm(orMethod),
                translateTNorm(impMethod), translateSNorm(aggMethod),
                translateDefuzzifier(defuzzMethod), General().className());
        return engine.release();
    }

    void FisImporter::importSystem(const std::string& section, Engine * engine,
            std::string& andMethod, std::string& orMethod,
            std::string& impMethod, std::string& aggMethod,
            std::string& defuzzMethod) const {
        std::istringstream reader(section);
        std::string line;
        std::getline(reader, line); //ignore first line [System]
        while (std::getline(reader, line)) {
            std::vector<std::string> keyValue = Op::split(line, "=");

            std::string key = Op::trim(keyValue.at(0));
            std::string value;
            for (std::size_t i = 1; i < keyValue.size(); ++i) {
                value += keyValue.at(i);
            }
            value = Op::trim(value);
            if (key == "Name") engine->setName(value);
            else if (key == "AndMethod") andMethod = value;
            else if (key == "OrMethod") orMethod = value;
            else if (key == "ImpMethod") impMethod = value;
            else if (key == "AggMethod") aggMethod = value;
            else if (key == "DefuzzMethod") defuzzMethod = value;
            else if (key == "Type" or key == "Version"
                    or key == "NumInputs" or key == "NumOutputs"
                    or key == "NumRules" or key == "NumMFs") {
                //ignore because are redundant.
            } else throw Exception("[import error] token <" + key + "> not recognized", FL_AT);
        }
    }

    void FisImporter::importInput(const std::string& section, Engine* engine) const {
        std::istringstream reader(section);
        std::string line;
        std::getline(reader, line); //ignore first line [Input#]

        InputVariable* input = new InputVariable;
        engine->addInputVariable(input);

        while (std::getline(reader, line)) {
            std::vector<std::string> keyValue = Op::split(line, "=");
            if (keyValue.size() != 2)
                throw Exception("[syntax error] expected a property of type "
                    "'key=value', but found <" + line + ">", FL_AT);
            std::string key = Op::trim(keyValue.at(0));
            std::string value = Op::trim(keyValue.at(1));

            if (key == "Name") {
                input->setName(Op::validName(value));
            } else if (key == "Enabled") {
                input->setEnabled(Op::isEq(Op::toScalar(value), 1.0));
            } else if (key == "Range") {
                std::pair<scalar, scalar> minmax = parseRange(value);
                input->setMinimum(minmax.first);
                input->setMaximum(minmax.second);
            } else if (key.substr(0, 2) == "MF") {
                input->addTerm(parseTerm(value, engine));
            } else if (key == "NumMFs") {
                //ignore
            } else {
                throw Exception("[import error] token <" + key + "> not recognized", FL_AT);
            }
        }
    }

    void FisImporter::importOutput(const std::string& section, Engine* engine) const {
        std::istringstream reader(section);
        std::string line;
        std::getline(reader, line); //ignore first line [Output#]

        OutputVariable* output = new OutputVariable;
        engine->addOutputVariable(output);


        while (std::getline(reader, line)) {
            std::vector<std::string> keyValue = Op::split(line, "=");
            if (keyValue.size() != 2)
                throw Exception("[syntax error] expected a property of type "
                    "'key=value', but found < " + line + ">", FL_AT);
            std::string key = Op::trim(keyValue.at(0));
            std::string value = Op::trim(keyValue.at(1));

            if (key == "Name") {
                output->setName(Op::validName(value));
            } else if (key == "Enabled") {
                output->setEnabled(Op::isEq(Op::toScalar(value), 1.0));
            } else if (key == "Range") {
                std::pair<scalar, scalar> minmax = parseRange(value);
                output->setMinimum(minmax.first);
                output->setMaximum(minmax.second);
            } else if (key.substr(0, 2) == "MF") {
                output->addTerm(parseTerm(value, engine));
            } else if (key == "Default") {
                output->setDefaultValue(Op::toScalar(value));
            } else if (key == "LockPrevious") {
                output->setLockPreviousValue(Op::isEq(Op::toScalar(value), 1.0));
            } else if (key == "LockRange") {
                output->setLockValueInRange(Op::isEq(Op::toScalar(value), 1.0));
            } else if (key == "NumMFs") {
                //ignore
            } else {
                throw Exception("[import error] token <" + key + "> not recognized", FL_AT);
            }
        }
    }

    void FisImporter::importRules(const std::string& section, Engine* engine) const {
        std::istringstream reader(section);
        std::string line;
        std::getline(reader, line); //ignore first line [Rules]

        RuleBlock* ruleblock = new RuleBlock;
        engine->addRuleBlock(ruleblock);

        while (std::getline(reader, line)) {
            std::vector<std::string> inputsAndRest = Op::split(line, ",");
            if (inputsAndRest.size() != 2)
                throw Exception("[syntax error] expected rule to match pattern "
                    "<'i '+, 'o '+ (w) : '1|2'>, but found instead <" + line + ">", FL_AT);

            std::vector <std::string> outputsAndRest = Op::split(inputsAndRest.at(1), ":");
            if (outputsAndRest.size() != 2)
                throw Exception("[syntax error] expected rule to match pattern "
                    "<'i '+, 'o '+ (w) : '1|2'>, but found instead <" + line + ">", FL_AT);

            std::vector<std::string> inputs = Op::split(inputsAndRest.at(0), " ");
            std::vector<std::string> outputs = Op::split(outputsAndRest.at(0), " ");
            std::string weightInParenthesis = outputs.at(outputs.size() - 1);
            outputs.erase(outputs.begin() + outputs.size() - 1);
            std::string connector = Op::trim(outputsAndRest.at(1));

            if (inputs.size() != engine->numberOfInputVariables()) {
                std::ostringstream ss;
                ss << "[syntax error] expected <" << engine->numberOfInputVariables() << ">"
                        " input variables, but found <" << inputs.size() << ">"
                        " input variables in rule <" << line << ">";
                throw Exception(ss.str(), FL_AT);
            }
            if (outputs.size() != engine->numberOfOutputVariables()) {
                std::ostringstream ss;
                ss << "[syntax error] expected <" << engine->numberOfOutputVariables() << ">"
                        " output variables, but found <" << outputs.size() << ">"
                        " output variables in rule <" << line << ">";
                throw Exception(ss.str(), FL_AT);
            }

            std::vector<std::string> antecedent, consequent;

            for (std::size_t i = 0; i < inputs.size(); ++i) {
                scalar inputCode = Op::toScalar(inputs.at(i));
                if (Op::isEq(inputCode, 0.0)) continue;
                std::ostringstream ss;
                ss << engine->getInputVariable(i)->getName() << " "
                        << Rule::isKeyword() << " "
                        << translateProposition(inputCode, engine->getInputVariable(i));
                antecedent.push_back(ss.str());
            }

            for (std::size_t i = 0; i < outputs.size(); ++i) {
                scalar outputCode = Op::toScalar(outputs.at(i));
                if (Op::isEq(outputCode, 0.0)) continue;
                std::ostringstream ss;
                ss << engine->getOutputVariable(i)->getName() << " "
                        << Rule::isKeyword() << " "
                        << translateProposition(outputCode, engine->getOutputVariable(i));
                consequent.push_back(ss.str());
            }

            std::ostringstream ruleText;

            ruleText << Rule::ifKeyword() << " ";
            for (std::size_t i = 0; i < antecedent.size(); ++i) {
                ruleText << antecedent.at(i);
                if (i + 1 < antecedent.size()) {
                    ruleText << " ";
                    if (connector == "1") ruleText << Rule::andKeyword() << " ";
                    else if (connector == "2") ruleText << Rule::orKeyword() << " ";
                    else throw Exception("[syntax error] connector <"
                            + connector + "> not recognized", FL_AT);
                }
            }

            ruleText << " " << Rule::thenKeyword() << " ";
            for (std::size_t i = 0; i < consequent.size(); ++i) {
                ruleText << consequent.at(i);
                if (i + 1 < consequent.size()) {
                    ruleText << " " << Rule::andKeyword() << " ";
                }
            }

            std::ostringstream ss;
            for (std::size_t i = 0; i < weightInParenthesis.size(); ++i) {
                if (weightInParenthesis.at(i) == '('
                        or weightInParenthesis.at(i) == ')'
                        or weightInParenthesis.at(i) == ' ') continue;
                ss << weightInParenthesis.at(i);
            }

            scalar weight = Op::toScalar(ss.str());
            if (not Op::isEq(weight, 1.0))
                ruleText << " " << Rule::withKeyword() << " " << Op::str(weight);
            Rule* rule = new Rule(ruleText.str());
            try {
                rule->load(engine);
            } catch (...) {
                //ignore
            }
            ruleblock->addRule(rule);
        }
    }

    std::string FisImporter::translateProposition(scalar code, Variable* variable) const {
        int intPart = (int) std::floor(std::abs(code)) - 1;
        scalar fracPart = std::fmod(std::abs(code), scalar(1.0));
        if (intPart >= static_cast<int> (variable->numberOfTerms())) {
            std::ostringstream ex;
            ex << "[syntax error] the code <" << code << "> refers to a term "
                    "out of range from variable <" << variable->getName() << ">";
            throw Exception(ex.str(), FL_AT);
        }

        bool isAny = intPart < 0;
        std::ostringstream ss;
        if (code < 0) ss << Not().name() << " ";
        if (Op::isEq(fracPart, 0.01)) ss << Seldom().name() << " ";
        else if (Op::isEq(fracPart, 0.05)) ss << Somewhat().name() << " ";
        else if (Op::isEq(fracPart, 0.2)) ss << Very().name() << " ";
        else if (Op::isEq(fracPart, 0.3)) ss << Extremely().name() << " ";
        else if (Op::isEq(fracPart, 0.4)) ss << Very().name() << " " << Very().name() << " ";
        else if (Op::isEq(fracPart, 0.99)) ss << Any().name() << " ";
        else if (not Op::isEq(fracPart, 0.0))
            throw Exception("[syntax error] no hedge defined in FIS format for <"
                + Op::str(fracPart) + ">", FL_AT);
        if (not isAny) {
            ss << variable->getTerm(intPart)->getName();
        }
        return ss.str();
    }

    std::string FisImporter::translateTNorm(const std::string& name) const {
        if (name.empty()) return "";
        if (name == "min") return Minimum().className();
        if (name == "prod") return AlgebraicProduct().className();
        if (name == "bounded_difference") return BoundedDifference().className();
        if (name == "drastic_product") return DrasticProduct().className();
        if (name == "einstein_product") return EinsteinProduct().className();
        if (name == "hamacher_product") return HamacherProduct().className();
        if (name == "nilpotent_minimum") return NilpotentMinimum().className();
        return name;
    }

    std::string FisImporter::translateSNorm(const std::string& name) const {
        if (name.empty()) return "";
        if (name == "max") return Maximum().className();
        if (name == "probor") return AlgebraicSum().className();
        if (name == "bounded_sum") return BoundedSum().className();
        if (name == "normalized_sum") return NormalizedSum().className();
        if (name == "drastic_sum") return DrasticSum().className();
        if (name == "einstein_sum") return EinsteinSum().className();
        if (name == "hamacher_sum") return HamacherSum().className();
        if (name == "nilpotent_maximum") return NilpotentMaximum().className();
        if (name == "sum") return UnboundedSum().className();
        return name;
    }

    std::string FisImporter::translateDefuzzifier(const std::string& name) const {
        if (name.empty()) return "";
        if (name == "centroid") return Centroid().className();
        if (name == "bisector") return Bisector().className();
        if (name == "lom") return LargestOfMaximum().className();
        if (name == "mom") return MeanOfMaximum().className();
        if (name == "som") return SmallestOfMaximum().className();
        if (name == "wtaver") return WeightedAverage().className();
        if (name == "wtsum") return WeightedSum().className();
        return name;
    }

    std::pair<scalar, scalar> FisImporter::parseRange(const std::string& range) const {
        std::vector<std::string> parts = Op::split(range, " ");
        if (parts.size() != 2)
            throw Exception("[syntax error] expected range in format '[begin end]',"
                " but found <" + range + ">", FL_AT);
        std::string begin = parts.at(0), end = parts.at(1);
        if (begin.at(0) != '[' or end.at(end.size() - 1) != ']')
            throw Exception("[syntax error] expected range in format '[begin end]',"
                " but found <" + range + ">", FL_AT);
        std::pair<scalar, scalar> result;
        result.first = Op::toScalar(begin.substr(1));
        result.second = Op::toScalar(end.substr(0, end.size() - 1));
        return result;
    }

    Term * FisImporter::parseTerm(const std::string& fis, const Engine* engine) const {
        std::ostringstream ss;
        for (std::size_t i = 0; i < fis.size(); ++i) {
            if (not (fis.at(i) == '[' or fis.at(i) == ']')) {
                ss << fis.at(i);
            }
        }
        std::string line = ss.str();

        std::vector<std::string> nameTerm = Op::split(line, ":");
        if (nameTerm.size() != 2) {
            throw Exception("[syntax error] expected term in format 'name':'class',[params], "
                    "but found <" + line + ">", FL_AT);
        }
        std::vector<std::string> termParams = Op::split(nameTerm.at(1), ",");
        if (termParams.size() != 2) {
            throw Exception("[syntax error] expected term in format 'name':'class',[params], "
                    "but found " + line, FL_AT);
        }

        std::vector<std::string> parameters = Op::split(termParams.at(1), " ");
        for (std::size_t i = 0; i < parameters.size(); ++i) {
            parameters.at(i) = Op::trim(parameters.at(i));
        }
        return createInstance(
                Op::trim(termParams.at(0)),
                Op::trim(nameTerm.at(0)),
                parameters, engine);
    }

    Term* FisImporter::createInstance(const std::string& mClass,
            const std::string& name, const std::vector<std::string>& params,
            const Engine* engine) const {
        std::map<std::string, std::string> mapping;
        mapping["binarymf"] = Binary().className();
        mapping["concavemf"] = Concave().className();
        mapping["constant"] = Constant().className();
        mapping["cosinemf"] = Cosine().className();
        mapping["discretemf"] = Discrete().className();
        mapping["function"] = Function().className();
        mapping["gbellmf"] = Bell().className();
        mapping["gaussmf"] = Gaussian().className();
        mapping["gauss2mf"] = GaussianProduct().className();
        mapping["linear"] = Linear().className();
        mapping["pimf"] = PiShape().className();
        mapping["rampmf"] = Ramp().className();
        mapping["rectmf"] = Rectangle().className();
        mapping["smf"] = SShape().className();
        mapping["sigmf"] = Sigmoid().className();
        mapping["dsigmf"] = SigmoidDifference().className();
        mapping["psigmf"] = SigmoidProduct().className();
        mapping["spikemf"] = Spike().className();
        mapping["trapmf"] = Trapezoid().className();
        mapping["trimf"] = Triangle().className();
        mapping["zmf"] = ZShape().className();

        std::vector<std::string> sortedParams = params;

        if (mClass == "gbellmf" and params.size() >= 3) {
            sortedParams.at(0) = params.at(2);
            sortedParams.at(1) = params.at(0);
            sortedParams.at(2) = params.at(1);
        } else if (mClass == "gaussmf" and params.size() >= 2) {
            sortedParams.at(0) = params.at(1);
            sortedParams.at(1) = params.at(0);
        } else if (mClass == "gauss2mf" and params.size() >= 4) {
            sortedParams.at(0) = params.at(1);
            sortedParams.at(1) = params.at(0);
            sortedParams.at(2) = params.at(3);
            sortedParams.at(3) = params.at(2);
        } else if (mClass == "sigmf" and params.size() >= 2) {
            sortedParams.at(0) = params.at(1);
            sortedParams.at(1) = params.at(0);
        } else if (mClass == "dsigmf" and params.size() >= 4) {
            sortedParams.at(0) = params.at(1);
            sortedParams.at(1) = params.at(0);
            sortedParams.at(2) = params.at(2);
            sortedParams.at(3) = params.at(3);
        } else if (mClass == "psigmf" and params.size() >= 4) {
            sortedParams.at(0) = params.at(1);
            sortedParams.at(1) = params.at(0);
            sortedParams.at(2) = params.at(2);
            sortedParams.at(3) = params.at(3);
        }

        std::string flClass;
        std::map<std::string, std::string>::const_iterator it = mapping.find(mClass);
        if (it != mapping.end()) flClass = it->second;
        else flClass = mClass;

        FL_unique_ptr<Term> term;
        term.reset(FactoryManager::instance()->term()->constructObject(flClass));
        term->updateReference(engine);
        term->setName(Op::validName(name));
        std::string separator;
        if (not dynamic_cast<Function*> (term.get())) {
            separator = " ";
        }
        term->configure(Op::join(sortedParams, separator));
        return term.release();
    }

    FisImporter* FisImporter::clone() const {
        return new FisImporter(*this);
    }

}