aGrUM 3.1.1
a C++ library for (probabilistic) graphical models
formula.cpp
Go to the documentation of this file.
1/****************************************************************************
2 * This file is part of the aGrUM/pyAgrum library. *
3 * *
4 * Copyright (c) 2005-2026 by *
5 * - Pierre-Henri WUILLEMIN(_at_LIP6) *
6 * - Christophe GONZALES(_at_AMU) *
7 * *
8 * The aGrUM/pyAgrum library is free software; you can redistribute it *
9 * and/or modify it under the terms of either : *
10 * *
11 * - the GNU Lesser General Public License as published by *
12 * the Free Software Foundation, either version 3 of the License, *
13 * or (at your option) any later version, *
14 * - the MIT license (MIT), *
15 * - or both in dual license, as here. *
16 * *
17 * (see https://agrum.gitlab.io/articles/dual-licenses-lgplv3mit.html) *
18 * *
19 * This aGrUM/pyAgrum library is distributed in the hope that it will be *
20 * useful, but WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
21 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES MERCHANTABILITY or FITNESS *
22 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
23 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
24 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, *
25 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR *
26 * OTHER DEALINGS IN THE SOFTWARE. *
27 * *
28 * See LICENCES for more details. *
29 * *
30 * SPDX-FileCopyrightText: Copyright 2005-2026 *
31 * - Pierre-Henri WUILLEMIN(_at_LIP6) *
32 * - Christophe GONZALES(_at_AMU) *
33 * SPDX-License-Identifier: LGPL-3.0-or-later OR MIT *
34 * *
35 * Contact : info_at_agrum_dot_org *
36 * homepage : http://agrum.gitlab.io *
37 * gitlab : https://gitlab.com/agrumery/agrum *
38 * *
39 ****************************************************************************/
40
41
43
44// Keep this here because of cyclic dependencies
45#include <agrum/base/core/math/cocoR/Parser.h>
46#include <agrum/base/core/math/cocoR/Scanner.h>
47
48namespace gum {
49
50 // ==========================================================================
51 // === Class FormulaPart ===
52 // ==========================================================================
53
54 // Helper function for debuging
55 void print_stack(std::stack< FormulaPart > s) {
56 std::cout << std::endl;
57 std::list< FormulaPart > l;
58 while (!s.empty()) {
59 l.push_front(s.top());
60 s.pop();
61 }
62
63 std::cout << "Stack: ";
64 for (const auto& elt: l) {
65 std::cout << elt.str() << " ";
66 }
67 std::cout << std::endl;
68 }
69
70 // Helper function for debuging
71 void print_output(std::vector< FormulaPart > v) {
72 std::cout << "Output: ";
73 for (const auto& elt: v) {
74 std::cout << elt.str() << " ";
75 }
76 std::cout << std::endl;
77 }
78
80 switch (func) {
82 return "exp";
83 }
85 return "log";
86 }
88 return "ln";
89 }
91 return "pow";
92 }
94 return "sqrt";
95 }
97 return "nil";
98 }
99 default : {
100 GUM_ERROR(OperationNotAllowed, "unknown function")
101 }
102 }
103 }
104
106 GUM_CONSTRUCTOR(FormulaPart);
107 }
108
110 type(t), number(n), character('\0'), function(nil) {
111 GUM_CONSTRUCTOR(FormulaPart);
112 }
113
115 type(t), number(NAN), character(c), function(nil) {
116 GUM_CONSTRUCTOR(FormulaPart);
117 }
118
120 type(t), number(NAN), character('\0'), function(func) {
121 GUM_CONSTRUCTOR(FormulaPart);
122 }
123
125 type(source.type), number(source.number), character(source.character),
126 function(source.function) {
127 GUM_CONS_CPY(FormulaPart);
128 }
129
131 type(std::move(source.type)), number(std::move(source.number)),
132 character(std::move(source.character)), function(std::move(source.function)) {
133 GUM_CONS_MOV(FormulaPart);
134 }
135
137 GUM_DESTRUCTOR(FormulaPart);
138 ;
139 }
140
142 if (this == &source) { return *this; }
143
144 type = source.type;
145 number = source.number;
146 character = source.character;
147 function = source.function;
148
149 return *this;
150 }
151
153 if (this == &source) { return *this; }
154
155 type = std::move(source.type);
156 number = std::move(source.number);
157 character = std::move(source.character);
158 function = std::move(source.function);
159
160 return *this;
161 }
162
163 std::string FormulaPart::str() const {
164 switch (type) {
165 case token_type::NUMBER : {
166 return std::format("{}", number);
167 }
168
170 case token_type::OPERATOR : {
171 return (character == '\0') ? "\\0" : std::string(1, character);
172 }
173
174 case token_type::FUNCTION : {
175 return func2str(function);
176 }
177
178 default : {
179 GUM_ERROR(OperationNotAllowed, "unknown type")
180 }
181 }
182 }
183
184 // ==========================================================================
185 // === Class Formula ===
186 // ==========================================================================
187
189 auto c_str = (unsigned char*)_formula_.c_str();
190 auto scanner = new gum::formula::Scanner(c_str, (int)_formula_.size());
191 _scanner_ = std::unique_ptr< gum::formula::Scanner >(scanner);
192
193 auto parser = new gum::formula::Parser(scanner);
194 _parser_ = std::unique_ptr< gum::formula::Parser >(parser);
195 _parser_->formula(this);
196 }
197
199 GUM_CONSTRUCTOR(Formula);
200 _initialise_();
201 }
202
204 GUM_CONSTRUCTOR(Formula);
205 _initialise_();
206 }
207
209 GUM_CONSTRUCTOR(Formula);
210 _initialise_();
211 }
212
214 GUM_CONSTRUCTOR(Formula);
215 _initialise_();
216 }
217
219 GUM_CONSTRUCTOR(Formula);
220 _initialise_();
221 }
222
224 GUM_CONSTRUCTOR(Formula);
225 _initialise_();
226 }
227
229 GUM_CONSTRUCTOR(Formula);
230 _initialise_();
231 }
232
233 Formula::Formula(unsigned long long ul) :
235 GUM_CONSTRUCTOR(Formula);
236 _initialise_();
237 }
238
240 GUM_CONSTRUCTOR(Formula);
241 _initialise_();
242 }
243
245 GUM_CONSTRUCTOR(Formula);
246 _initialise_();
247 }
248
249 Formula::Formula(const std::string& f) : _formula_(f), _last_token_(FormulaPart()) {
250 GUM_CONSTRUCTOR(Formula);
251
252 _initialise_();
253 }
254
255 Formula::Formula(const Formula& source) :
257 _stack_(source._stack_) {
258 GUM_CONS_CPY(Formula);
259
260 _initialise_();
261 }
262
264 _formula_(std::move(source._formula_)), _scanner_(std::move(source._scanner_)),
265 _parser_(std::move(source._parser_)), _last_token_(std::move(source._last_token_)),
266 _output_(std::move(source._output_)), _stack_(std::move(source._stack_)) {
267 GUM_CONS_CPY(Formula);
268
269 _parser_->formula(this);
270 }
271
273 GUM_DESTRUCTOR(Formula);
274 ;
275 }
276
278 if (this == &source) { return *this; }
279
280 _formula_ = source._formula_;
281 _last_token_ = source._last_token_;
282 _output_ = source._output_;
283 _stack_ = source._stack_;
284
285 _initialise_();
286
287 return *this;
288 }
289
291 if (this == &source) { return *this; }
292
293 _formula_ = std::move(source._formula_);
294 _scanner_ = std::move(source._scanner_);
295 _parser_ = std::move(source._parser_);
296 _parser_->formula(this);
297 _last_token_ = std::move(source._last_token_);
298 _output_ = std::move(source._output_);
299 _stack_ = std::move(source._stack_);
300
301 return *this;
302 }
303
304 double Formula::result() const {
305 _parser_->Parse();
306
307 std::stack< FormulaPart > stack;
308 if (_output_.empty()) { GUM_ERROR(OperationNotAllowed, "no output found") }
309
310 for (auto item: _output_) {
311 switch (item.type) {
313 stack.push(item);
314 break;
315 }
316
319 _reduceOperatorOrFunction_(item, stack);
320 break;
321 }
322
323 default : {
324 GUM_ERROR(OperationNotAllowed, "expecting numbers, operators or functions")
325 }
326 }
327 }
328
329 if (stack.size() != 1) {
330 GUM_ERROR(OperationNotAllowed, "too many inputs")
331
332 } else if (stack.top().type != FormulaPart::token_type::NUMBER) {
333 GUM_ERROR(OperationNotAllowed, "too many inputs")
334 }
335 return stack.top().number;
336 }
337
339 switch (character) {
340 case '+' :
341 case '-' :
342 case '*' :
343 case '/' : {
344 return true;
345 }
346
347 case '_' : {
348 return false;
349 }
350 case '^' : {
351 return false;
352 }
353
354 default : {
355 GUM_ERROR(OperationNotAllowed, "A - not an operator")
356 }
357 }
358 }
359
361 switch (character) {
362 case '+' :
363 case '-' : {
364 return 2;
365 }
366
367 case '*' :
368 case '/' : {
369 return 3;
370 }
371
372 case '^' : {
373 return 4;
374 }
375
376 case '_' : {
377 return 5;
378 }
379
380 default : {
381 GUM_ERROR(OperationNotAllowed, "B - not an operator")
382 }
383 }
384 }
385
386 size_t FormulaPart::argc() const {
387 switch (type) {
388 case OPERATOR : {
389 return _operator_argc_();
390 }
391
392 case FUNCTION : {
393 return _function_argc_();
394 }
395
396 default : {
397 GUM_ERROR(OperationNotAllowed, "expecting a function or an operator")
398 }
399 }
400 }
401
403 switch (character) {
404 case '_' : {
405 return (size_t)1;
406 }
407 case '+' :
408 case '-' :
409 case '*' :
410 case '/' :
411 case '^' : {
412 return (size_t)2;
413 }
414
415 default : {
416 GUM_ERROR(OperationNotAllowed, "C - not an operator")
417 }
418 }
419 }
420
422 switch (function) {
424 return 1;
425 }
427 return 1;
428 }
430 return 1;
431 }
433 return 2;
434 }
436 return 1;
437 }
438 // case FormulaPart::token_function::nil: { return "nil"; }
439 default : {
440 GUM_ERROR(OperationNotAllowed, "unknown function")
441 }
442 }
443 }
444
445 double FormulaPart::_operator_eval_(const std::vector< FormulaPart >& args) const {
446 switch (character) {
447 case '+' : {
448 return args[1].number + args[0].number;
449 }
450
451 case '-' : {
452 return args[1].number - args[0].number;
453 }
454
455 case '*' : {
456 return args[1].number * args[0].number;
457 }
458
459 case '/' : {
460 return args[1].number / args[0].number;
461 }
462
463 case '^' : {
464 return std::pow(args[1].number, args[0].number);
465 }
466
467 case '_' : {
468 return 0 - args[0].number;
469 }
470
471 default : {
472 GUM_ERROR(OperationNotAllowed, "D - not an operator")
473 }
474 }
475 }
476
477 double FormulaPart::_function_eval_(const std::vector< FormulaPart >& args) const {
478 switch (function) {
480 return std::exp(args[0].number);
481 }
483 return std::log(args[0].number);
484 }
486 return std::log(args[0].number);
487 }
489 return std::pow(args[1].number, args[0].number);
490 }
492 return std::sqrt(args[0].number);
493 }
494 // case FormulaPart::token_function::nil: { return "nil"; }
495 default : {
496 GUM_ERROR(OperationNotAllowed, "unknown function")
497 }
498 }
499 }
500
501 FormulaPart FormulaPart::eval(const std::vector< FormulaPart >& args) const {
502 switch (type) {
503 case OPERATOR : {
504 return {token_type::NUMBER, _operator_eval_(args)};
505 }
506
507 case FUNCTION : {
508 return {token_type::NUMBER, _function_eval_(args)};
509 }
510
511 default : {
512 GUM_ERROR(OperationNotAllowed, "cannot evaluate expression")
513 }
514 }
515 }
516
518 while (!_stack_.empty()) {
519 if (_stack_.top().character == '(') { GUM_ERROR(OperationNotAllowed, "expecting ')'") }
520
521 _push_output_(_stack_.top());
522 _stack_.pop();
523 }
524 }
525
526 void Formula::_push_function_(std::string_view func) {
527 if (func == "exp") {
529 _push_stack_(t);
530
531 } else if (func == "log") {
533 _push_stack_(t);
534
535 } else if (func == "ln") {
537 _push_stack_(t);
538
539 } else if (func == "pow") {
541 _push_stack_(t);
542
543 } else if (func == "sqrt") {
545 _push_stack_(t);
546
547 } else {
548 GUM_ERROR(OperationNotAllowed, "unknown function")
549 }
550 }
551
552 void Formula::_push_identifier_(std::string_view ident) {
553 try {
554 _push_function_(ident);
555
556 } catch (OperationNotAllowed const&) {
557 try {
558 _push_variable_(ident);
559
560 } catch (OperationNotAllowed const&) { GUM_ERROR(OperationNotAllowed, "unknown identifier") }
561 }
562 }
563} // namespace gum
564
565#ifdef GUM_NO_INLINE
567#endif // GUM_NO_INLINE
Represents part of a formula.
Definition formula.h:79
double _operator_eval_(const std::vector< FormulaPart > &args) const
Returns the evaluation of the vector of gum::FormulaPart as arguments of the value stored in this gum...
Definition formula.cpp:445
size_t argc() const
Returns the number of argument of the function stored in this gum::FormulaPart.
Definition formula.cpp:386
double _function_eval_(const std::vector< FormulaPart > &args) const
Returns the evaluation of the vector of gum::FormulaPart as arguments of the value stored in this gum...
Definition formula.cpp:477
std::string str() const
Returns a string representation of this gum::FormulaPart value.
Definition formula.cpp:163
token_function function
The value stored by this gum::FormulaPart.
Definition formula.h:99
FormulaPart()
Class constructor.
Definition formula.cpp:105
size_t _function_argc_() const
Returns the number of arguments expected by the function stored in this gum::FormulaPart.
Definition formula.cpp:421
size_t _operator_argc_() const
Returns the number of arguments expected by the operator stored in this gum::FormulaPart.
Definition formula.cpp:402
FormulaPart & operator=(const FormulaPart &source)
Definition formula.cpp:141
bool isLeftAssociative() const
Returns true if this gum::FormulaPart is left associative.
Definition formula.cpp:338
~FormulaPart()
Class destuctor.
Definition formula.cpp:136
double number
The value stored by this gum::FormulaPart.
Definition formula.h:97
token_function
The functions allowed in a formula.
Definition formula.h:85
FormulaPart eval(const std::vector< FormulaPart > &args) const
Returns the evaluation of the vector of gum::FormulaPart as arguments of the value stored in this gum...
Definition formula.cpp:501
char character
The value stored by this gum::FormulaPart.
Definition formula.h:98
int precedence() const
Returns the precedence priority of the value stored in this gum::FormulaPart.
Definition formula.cpp:360
token_type type
The token_type stored by this gum::FormulaPart.
Definition formula.h:88
token_type
The tokens constituting a formula.
Definition formula.h:82
void _push_output_(FormulaPart t)
Push the gum::FormulaPart in the output vector.
~Formula()
Class destructor.
Definition formula.cpp:272
friend class gum::formula::Parser
Definition formula.h:294
std::unique_ptr< gum::formula::Parser > _parser_
The parser used by the formula.
Definition formula.h:467
void _push_stack_(FormulaPart t)
Push the gum::FormulaPart in the stack.
void _push_function_(std::string_view func)
Push a function in the formula.
Definition formula.cpp:526
std::unique_ptr< gum::formula::Scanner > _scanner_
The scanner used by the formula.
Definition formula.h:464
Formula & operator=(const Formula &source)
Copy operator.
Definition formula.cpp:277
void _initialise_()
Initialise the formula scanner and parser.
Definition formula.cpp:188
std::string _formula_
The formula to evaluate.
Definition formula.h:461
void _push_identifier_(std::string_view ident)
Use this if you don't know if ident is a function or a variable.
Definition formula.cpp:552
void _reduceOperatorOrFunction_(FormulaPart item, std::stack< FormulaPart > &stack) const
Evaluate an operator or function and push its result.
Formula(short s)
Constructor.
Definition formula.cpp:198
double result() const
Returns the result of this gum::Formula.
Definition formula.cpp:304
std::vector< FormulaPart > _output_
The output stack, will contain one value after evaluation.
Definition formula.h:473
void _finalize_()
Finalize the formula and prepare it for evaluation.
Definition formula.cpp:517
void _push_variable_(std::string_view var)
Push a variable in the formula.
FormulaPart _last_token_
The last token added to the formula.
Definition formula.h:470
std::stack< FormulaPart > _stack_
A stack used during evaluation.
Definition formula.h:476
Exception : operation not allowed.
#define GUM_ERROR(type, msg)
Definition exceptions.h:76
Headers files for the gum::FormulaPart and gum::Formula classes.
gum is the global namespace for all aGrUM entities
Definition agrum.h:46
void print_stack(std::stack< FormulaPart > s)
Definition formula.cpp:55
std::string func2str(FormulaPart::token_function func)
Definition formula.cpp:79
std::string to_string(const Formula &f)
void print_output(std::vector< FormulaPart > v)
Definition formula.cpp:71
STL namespace.