summaryrefslogtreecommitdiff
path: root/fuzzylite/src/term/Function.cpp
blob: c0f54b8beffbe8e48c1bbe88e94d857a962b5326 (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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
/*
 Author: Juan Rada-Vilela, Ph.D.
 Copyright (C) 2010-2014 FuzzyLite Limited
 All rights reserved

 This file is part of fuzzylite.

 fuzzylite is free software: you can redistribute it and/or modify it under
 the terms of the GNU Lesser General Public License as published by the Free
 Software Foundation, either version 3 of the License, or (at your option)
 any later version.

 fuzzylite is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
 for more details.

 You should have received a copy of the GNU Lesser General Public License
 along with fuzzylite.  If not, see <http://www.gnu.org/licenses/>.

 fuzzylite™ is a trademark of FuzzyLite Limited.

 */

#include "fl/term/Function.h"

#include "fl/Engine.h"
#include "fl/factory/FactoryManager.h"
#include "fl/factory/FunctionFactory.h"
#include "fl/rule/Rule.h"
#include "fl/variable/InputVariable.h"
#include "fl/variable/OutputVariable.h"

#include <cctype>
#include <functional>
#include <queue>
#include <signal.h>
#include <stack>


namespace fl {

    /**
     * Parsing elements
     */


    Function::Element::Element(const std::string& name, const std::string& description, Type type)
    : name(name), description(description), type(type), unary(fl::null), binary(fl::null), arity(0),
    precedence(0), associativity(-1) {

    }

    Function::Element::Element(const std::string& name, const std::string& description,
            Type type, Unary unary, int precedence, int associativity)
    : name(name), description(description), type(type), unary(unary), binary(fl::null), arity(1),
    precedence(precedence), associativity(associativity) {
    }

    Function::Element::Element(const std::string& name, const std::string& description,
            Type type, Binary binary, int precedence, int associativity)
    : name(name), description(description), type(type), unary(fl::null), binary(binary), arity(2),
    precedence(precedence), associativity(associativity) {
    }

    Function::Element::~Element() {

    }

    bool Function::Element::isOperator() const {
        return type == OPERATOR;
    }

    bool Function::Element::isFunction() const {
        return type == FUNCTION;
    }

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

    std::string Function::Element::toString() const {
        std::ostringstream ss;

        if (type == OPERATOR) {
            ss << "Operator (name=" << name << ", "
                    << "description=" << description << ", "
                    << "precedence=" << precedence << ", "
                    << "arity=" << arity << ", "
                    << "associativity=" << associativity << ", ";
            if (arity == 1) ss << "pointer=" << unary;
            else if (arity == 2) ss << "pointer=" << binary;
            else ss << "pointer=error";
            ss << ")";
        } else if (type == FUNCTION) {
            ss << "Function (name=" << name << ", "
                    << "description=" << description << ", "
                    << "arity=" << arity << ", "
                    << "associativity=" << associativity << ", ";
            if (arity == 1) ss << "pointer=" << unary;
            else if (arity == 2) ss << "pointer=" << binary;
            else ss << "pointer=error";
            ss << ")";
        }
        return ss.str();
    }

    /******************************
     * Tree Node Elements
     ******************************/

    Function::Node::Node(Element* element, Node* left, Node* right)
    : element(element), left(left), right(right), variable(""), value(fl::nan) {
    }

    Function::Node::Node(const std::string& variable)
    : element(fl::null), left(fl::null), right(fl::null), variable(variable), value(fl::nan) {
    }

    Function::Node::Node(scalar value)
    : element(fl::null), left(fl::null), right(fl::null), variable(""), value(value) {
    }

    Function::Node::Node(const Node& other)
    : element(fl::null), left(fl::null), right(fl::null), variable(""), value(fl::nan) {
        copyFrom(other);
    }

    Function::Node& Function::Node::operator=(const Node& other) {
        if (this != &other) {
            element.reset(fl::null);
            left.reset(fl::null);
            right.reset(fl::null);

            copyFrom(other);
        }
        return *this;
    }

    void Function::Node::copyFrom(const Node& other) {
        if (other.element.get()) element.reset(other.element->clone());
        if (other.left.get()) left.reset(other.left->clone());
        if (other.right.get()) right.reset(other.right->clone());
        variable = other.variable;
        value = other.value;
    }

    Function::Node::~Node() {
    }

    scalar Function::Node::evaluate(const std::map<std::string, scalar>* variables) const {
        scalar result = fl::nan;
        if (element.get()) {
            if (element->unary) {
                result = element->unary(left->evaluate(variables));
            } else if (element->binary) {
                result = element->binary(right->evaluate(variables), left->evaluate(variables));
            } else {
                std::ostringstream ex;
                ex << "[function error] arity <" << element->arity << "> of "
                        << (element->isOperator() ? "operator" : "function") <<
                        " <" << element->name << "> is fl::null";
                throw fl::Exception(ex.str(), FL_AT);
            }

        } else if (not variable.empty()) {
            if (not variables) {
                throw fl::Exception("[function error] "
                        "expected a map of variables, but none was provided", FL_AT);
            }
            std::map<std::string, scalar>::const_iterator it = variables->find(variable);
            if (it != variables->end()) result = it->second;
            else throw fl::Exception("[function error] "
                    "unknown variable <" + variable + ">", FL_AT);
        } else {
            result = value;
        }
        return result;
    }

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

    std::string Function::Node::toString() const {
        std::ostringstream ss;
        if (element.get()) ss << element->name;
        else if (not variable.empty()) ss << variable;
        else ss << fl::Op::str(value);
        return ss.str();
    }

    std::string Function::Node::toPrefix(const Node* node) const {
        if (not node) node = this;
        if (not fl::Op::isNaN(node->value)) { //is terminal
            return fl::Op::str(node->value);
        }
        if (not node->variable.empty()) {
            return node->variable;
        }

        std::ostringstream ss;
        ss << node->toString();
        if (node->left.get())
            ss << " " << this->toPrefix(node->left.get());
        if (node->right.get())
            ss << " " << this->toPrefix(node->right.get());
        return ss.str();
    }

    std::string Function::Node::toInfix(const Node* node) const {
        if (not node) node = this;
        if (not fl::Op::isNaN(node->value)) { //is proposition
            return fl::Op::str(node->value);
        }
        if (not node->variable.empty()) {
            return node->variable;
        }

        std::ostringstream ss;
        if (node->left.get())
            ss << this->toInfix(node->left.get()) << " ";
        ss << node->toString();
        if (node->right.get())
            ss << " " << this->toInfix(node->right.get());
        return ss.str();
    }

    std::string Function::Node::toPostfix(const Node* node) const {
        if (not node) node = this;
        if (not fl::Op::isNaN(node->value)) { //is proposition
            return fl::Op::str(node->value);
        }
        if (not node->variable.empty()) {
            return node->variable;
        }

        std::ostringstream ss;
        if (node->left.get())
            ss << this->toPostfix(node->left.get()) << " ";
        if (node->right.get())
            ss << this->toPostfix(node->right.get()) << " ";
        ss << node->toString();
        return ss.str();
    }

    /**********************************
     * Function class.
     **********************************/
    Function::Function(const std::string& name,
            const std::string& formula, const Engine* engine)
    : Term(name), _root(fl::null), _formula(formula), _engine(engine) {
    }

    Function::Function(const Function& other) : Term(other),
    _root(fl::null), _formula(other._formula), _engine(other._engine) {
        if (other._root.get()) _root.reset(other._root->clone());
        variables = other.variables;
    }

    Function& Function::operator=(const Function& other) {
        if (this != &other) {
            _root.reset(fl::null);

            Term::operator=(other);
            _formula = other._formula;
            _engine = other._engine;
            if (other._root.get()) _root.reset(other._root->clone());
            variables = other.variables;
        }
        return *this;
    }

    Function::~Function() {
    }

    std::string Function::className() const {
        return "Function";
    }

    scalar Function::membership(scalar x) const {
        if (not this->_root.get()) {
            throw fl::Exception("[function error] function <" + _formula + "> not loaded.", FL_AT);
        }
        if (this->_engine) {
            for (int i = 0; i < this->_engine->numberOfInputVariables(); ++i) {
                InputVariable* input = this->_engine->getInputVariable(i);
                this->variables[input->getName()] = input->getInputValue();
            }
            for (int i = 0; i < this->_engine->numberOfOutputVariables(); ++i) {
                OutputVariable* output = this->_engine->getOutputVariable(i);
                this->variables[output->getName()] = output->getOutputValue();
            }
        }
        this->variables["x"] = x;
        return this->evaluate(&this->variables);
    }

    scalar Function::evaluate(const std::map<std::string, scalar>* localVariables) const {
        if (not this->_root.get())
            throw fl::Exception("[function error] evaluation failed because the function is not loaded", FL_AT);
        if (localVariables)
            return this->_root->evaluate(localVariables);
        return this->_root->evaluate(&this->variables);
    }

    std::string Function::parameters() const {
        return _formula;
    }

    void Function::configure(const std::string& parameters) {
        load(parameters);
    }

    Function* Function::create(const std::string& name,
            const std::string& infix, const Engine* engine) {
        FL_unique_ptr<Function> result(new Function(name));
        result->load(infix, engine);
        return result.release();
    }

    bool Function::isLoaded() const {
        return this->_root.get() != fl::null;
    }

    void Function::unload() {
        this->_root.reset(fl::null);
        this->variables.clear();
    }

    void Function::load() {
        load(this->_formula);
    }

    void Function::load(const std::string& formula) {
        load(formula, this->_engine);
    }

    void Function::load(const std::string& formula,
            const Engine* engine) {
        unload();
        this->_formula = formula;
        this->_engine = engine;
        this->_root.reset(parse(formula));
        membership(0.0); //make sure function evaluates without throwing exception.
    }

    void Function::setFormula(const std::string& formula) {
        this->_formula = formula;
    }

    std::string Function::getFormula() const {
        return this->_formula;
    }

    void Function::setEngine(const Engine* engine) {
        this->_engine = engine;
    }

    const Engine* Function::getEngine() const {
        return this->_engine;
    }

    Function::Node* Function::root() const {
        return this->_root.get();
    }

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

    Term* Function::constructor() {
        return new Function;
    }

    std::string Function::space(const std::string& formula) const {
        std::vector<std::string> chars;
        chars.push_back("(");
        chars.push_back(")");
        chars.push_back(",");

        std::vector<std::string> operators = fl::FactoryManager::instance()->function()->availableOperators();
        for (std::size_t i = 0; i < operators.size(); ++i) {
            if (not (operators.at(i) == fl::Rule::andKeyword() or
                    operators.at(i) == fl::Rule::orKeyword())) {
                chars.push_back(operators.at(i));
            }
        }

        std::string result = formula;
        for (std::size_t i = 0; i < chars.size(); ++i) {
            result = fl::Op::findReplace(result, chars.at(i), " " + chars.at(i) + " ");
        }
        return result;
    }

    /****************************************
     * The Glorious Parser
     * Shunting-yard algorithm
     * TODO: Maybe change it for http://en.wikipedia.org/wiki/Operator-precedence_parser
     ***************************************/

    std::string Function::toPostfix(const std::string& formula) const {
        std::string spacedFormula = space(formula);

        std::queue<std::string> queue;
        std::stack<std::string> stack;

        std::stringstream tokenizer(spacedFormula);
        std::string token;
        FunctionFactory* factory = fl::FactoryManager::instance()->function();
        while (tokenizer >> token) {
            Element* element = factory->getObject(token);
            bool isOperand = not element and token != "(" and token != ")" and token != ",";

            if (isOperand) {
                queue.push(token);

            } else if (element and element->isFunction()) {
                stack.push(token);

            } else if (token == ",") {
                while (not stack.empty() and stack.top() != "(") {
                    queue.push(stack.top());
                    stack.pop();
                }
                if (stack.empty() or stack.top() != "(") {
                    std::ostringstream ex;
                    ex << "[parsing error] mismatching parentheses in: " << formula;
                    throw fl::Exception(ex.str(), FL_AT);
                }

            } else if (element and element->isOperator()) {
                Element* op1 = element;
                for (;;) {
                    Element* op2 = fl::null;
                    if (not stack.empty()) op2 = factory->getObject(stack.top());
                    if (not op2) break;

                    if ((op1->associativity < 0 and op1->precedence == op2->precedence)
                            or op1->precedence < op2->precedence) {
                        queue.push(stack.top());
                        stack.pop();
                    } else
                        break;
                }
                stack.push(token);

            } else if (token == "(") {
                stack.push(token);

            } else if (token == ")") {
                while (not stack.empty() and stack.top() != "(") {
                    queue.push(stack.top());
                    stack.pop();
                }
                if (stack.empty() or stack.top() != "(") {
                    std::ostringstream ex;
                    ex << "[parsing error] mismatching parentheses in: " << formula;
                    throw fl::Exception(ex.str(), FL_AT);
                }
                stack.pop(); //get rid of "("

                Element* top = fl::null;
                if (not stack.empty()) top = factory->getObject(stack.top());
                if (top and top->isFunction()) {
                    queue.push(stack.top());
                    stack.pop();
                }
            } else {
                std::ostringstream ex;
                ex << "[parsing error] unexpected error with token <" << token << ">";
                throw fl::Exception(ex.str(), FL_AT);
            }
        }

        while (not stack.empty()) {
            if (stack.top() == "(" or stack.top() == ")") {
                std::ostringstream ex;
                ex << "[parsing error] mismatching parentheses in: " << formula;
                throw fl::Exception(ex.str(), FL_AT);
            }
            queue.push(stack.top());
            stack.pop();
        }

        std::stringstream ssPostfix;
        while (not queue.empty()) {
            ssPostfix << queue.front();
            queue.pop();
            if (not queue.empty()) ssPostfix << " ";
        }
        //        FL_DBG("postfix=" << ssPostfix.str());
        return ssPostfix.str();
    }

    //    bool FunctionFactory::isOperand(const std::string& name) const {
    //        //An operand is not a parenthesis...
    //        if (name == "(" or name == ")" or name == ",") return false;
    //        //nor an operator...
    //        if (isOperator(name)) return false;
    //        //nor a function...
    //        if (isFunction(name)) return false;
    //        //...it is everything else :)
    //        return true;
    //    }

    Function::Node* Function::parse(const std::string& formula) {
        if (formula.empty())
            throw fl::Exception("[function error] formula is empty", FL_AT);
        std::string postfix = toPostfix(formula);

        std::stack<Node*> stack;

        std::istringstream tokenizer(postfix);
        std::string token;
        FunctionFactory* factory = fl::FactoryManager::instance()->function();
        while (tokenizer >> token) {
            Element* element = factory->getObject(token);
            bool isOperand = not element and token != "(" and token != ")" and token != ",";

            if (element) {
                if (element->arity > (int) stack.size()) {
                    std::ostringstream ss;
                    ss << "[function error] " << (element->isOperator() ? "operator" : "function") <<
                            " <" << element->name << "> has arity <" << element->arity << ">, "
                            "but found <" << stack.size() << "> element" <<
                            (stack.size() == 1 ? "" : "s");
                    throw fl::Exception(ss.str(), FL_AT);
                }

                Node* node = new Node(element->clone());
                node->left.reset(stack.top());
                stack.pop();
                if (element->arity == 2) {
                    node->right.reset(stack.top());
                    stack.pop();
                }
                stack.push(node);

            } else if (isOperand) {
                Node* node;
                try {
                    scalar value = fl::Op::toScalar(token);
                    node = new Node(value);
                } catch (std::exception& ex) {
                    (void) ex;
                    node = new Node(token);
                }
                stack.push(node);
            }
        }

        if (stack.size() != 1)
            throw fl::Exception("[function error] ill-formed formula <" + formula + ">", FL_AT);

        return stack.top();
    }

    void Function::main() {
        Function f;
        std::string text = "3+4*2/(1-5)^2^3";
        FL_LOG(f.toPostfix(text));
        FL_LOG("P: " << f.parse(text)->toInfix());
        FL_LOG(">" << f.parse(text)->evaluate());
        //3 4 2 * 1 5 - 2 3 ^ ^ / +

        f.variables["y"] = 1.0;
        text = "sin(y*x)^2/x";
        FL_LOG("pre: " << f.parse(text)->toPrefix());
        FL_LOG("in: " << f.parse(text)->toInfix());
        FL_LOG("pos: " << f.parse(text)->toPostfix());
        f.load(text);
        FL_LOG("Result: " << f.membership(1));
        //y x * sin 2 ^ x /


        text = "(Temperature is High and Oxygen is Low) or "
                "(Temperature is Low and (Oxygen is Low or Oxygen is High))";
        FL_LOG(f.toPostfix(text));

        f.variables["pi"] = 3.14;
        text = "-5 *4/sin(-pi/2)";
        FL_LOG(f.toPostfix(text));
        try {
            FL_LOG(f.parse(text)->evaluate());
        } catch (std::exception& e) {
            FL_LOG(e.what());
        }
        f.variables["pi"] = 3.14;
        text = "~5 *4/sin(~pi/2)";
        FL_LOG(f.toPostfix(text));
        try {
            FL_LOG(f.parse(text)->evaluate(&f.variables));
        } catch (std::exception& e) {
            FL_LOG(e.what());
        }
    }

}