aGrUM 3.2.0
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; GUM_COCOR_PUBLIC is locally
45// forced to BASE's own export macro so the grammar is tagged correctly
46// regardless of which translation unit includes it.
47#pragma push_macro("GUM_COCOR_PUBLIC")
48#undef GUM_COCOR_PUBLIC
49#define GUM_COCOR_PUBLIC GUM_SHARED_PUBLIC
50#include <agrum/base/core/math/cocoR/Parser.h>
51#include <agrum/base/core/math/cocoR/Scanner.h>
52#pragma pop_macro("GUM_COCOR_PUBLIC")
53
54namespace gum {
55
56 // ==========================================================================
57 // === Class FormulaPart ===
58 // ==========================================================================
59
60 // Helper function for debuging
61 void print_stack(std::stack< FormulaPart > s) {
62 std::cout << std::endl;
63 std::list< FormulaPart > l;
64 while (!s.empty()) {
65 l.push_front(s.top());
66 s.pop();
67 }
68
69 std::cout << "Stack: ";
70 for (const auto& elt: l) {
71 std::cout << elt.str() << " ";
72 }
73 std::cout << std::endl;
74 }
75
76 // Helper function for debuging
77 void print_output(std::vector< FormulaPart > v) {
78 std::cout << "Output: ";
79 for (const auto& elt: v) {
80 std::cout << elt.str() << " ";
81 }
82 std::cout << std::endl;
83 }
84
86 switch (func) {
88 return "exp";
89 }
91 return "log";
92 }
94 return "ln";
95 }
97 return "pow";
98 }
100 return "sqrt";
101 }
103 return "nil";
104 }
105 default : {
106 GUM_ERROR(OperationNotAllowed, "unknown function")
107 }
108 }
109 }
110
112 GUM_CONSTRUCTOR(FormulaPart);
113 }
114
116 type(t), number(n), character('\0'), function(nil) {
117 GUM_CONSTRUCTOR(FormulaPart);
118 }
119
121 type(t), number(NAN), character(c), function(nil) {
122 GUM_CONSTRUCTOR(FormulaPart);
123 }
124
126 type(t), number(NAN), character('\0'), function(func) {
127 GUM_CONSTRUCTOR(FormulaPart);
128 }
129
131 type(source.type), number(source.number), character(source.character),
132 function(source.function) {
133 GUM_CONS_CPY(FormulaPart);
134 }
135
137 type(std::move(source.type)), number(std::move(source.number)),
138 character(std::move(source.character)), function(std::move(source.function)) {
139 GUM_CONS_MOV(FormulaPart);
140 }
141
143 GUM_DESTRUCTOR(FormulaPart);
144 ;
145 }
146
148 if (this == &source) { return *this; }
149
150 type = source.type;
151 number = source.number;
152 character = source.character;
153 function = source.function;
154
155 return *this;
156 }
157
159 if (this == &source) { return *this; }
160
161 type = std::move(source.type);
162 number = std::move(source.number);
163 character = std::move(source.character);
164 function = std::move(source.function);
165
166 return *this;
167 }
168
169 std::string FormulaPart::str() const {
170 switch (type) {
171 case token_type::NUMBER : {
172 return std::format("{}", number);
173 }
174
176 case token_type::OPERATOR : {
177 return (character == '\0') ? "\\0" : std::string(1, character);
178 }
179
180 case token_type::FUNCTION : {
181 return func2str(function);
182 }
183
184 default : {
185 GUM_ERROR(OperationNotAllowed, "unknown type")
186 }
187 }
188 }
189
190 // ==========================================================================
191 // === Class Formula ===
192 // ==========================================================================
193
195 auto c_str = (unsigned char*)_formula_.c_str();
196 auto scanner = new gum::formula::Scanner(c_str, (int)_formula_.size());
197 _scanner_ = std::unique_ptr< gum::formula::Scanner >(scanner);
198
199 auto parser = new gum::formula::Parser(scanner);
200 _parser_ = std::unique_ptr< gum::formula::Parser >(parser);
201 _parser_->formula(this);
202 }
203
205 GUM_CONSTRUCTOR(Formula);
206 _initialise_();
207 }
208
210 GUM_CONSTRUCTOR(Formula);
211 _initialise_();
212 }
213
215 GUM_CONSTRUCTOR(Formula);
216 _initialise_();
217 }
218
220 GUM_CONSTRUCTOR(Formula);
221 _initialise_();
222 }
223
225 GUM_CONSTRUCTOR(Formula);
226 _initialise_();
227 }
228
230 GUM_CONSTRUCTOR(Formula);
231 _initialise_();
232 }
233
235 GUM_CONSTRUCTOR(Formula);
236 _initialise_();
237 }
238
239 Formula::Formula(unsigned long long ul) :
241 GUM_CONSTRUCTOR(Formula);
242 _initialise_();
243 }
244
246 GUM_CONSTRUCTOR(Formula);
247 _initialise_();
248 }
249
251 GUM_CONSTRUCTOR(Formula);
252 _initialise_();
253 }
254
255 Formula::Formula(const std::string& f) : _formula_(f), _last_token_(FormulaPart()) {
256 GUM_CONSTRUCTOR(Formula);
257
258 _initialise_();
259 }
260
261 Formula::Formula(const Formula& source) :
263 _stack_(source._stack_) {
264 GUM_CONS_CPY(Formula);
265
266 _initialise_();
267 }
268
270 _formula_(std::move(source._formula_)), _scanner_(std::move(source._scanner_)),
271 _parser_(std::move(source._parser_)), _last_token_(std::move(source._last_token_)),
272 _output_(std::move(source._output_)), _stack_(std::move(source._stack_)) {
273 GUM_CONS_CPY(Formula);
274
275 _parser_->formula(this);
276 }
277
279 GUM_DESTRUCTOR(Formula);
280 ;
281 }
282
284 if (this == &source) { return *this; }
285
286 _formula_ = source._formula_;
287 _last_token_ = source._last_token_;
288 _output_ = source._output_;
289 _stack_ = source._stack_;
290
291 _initialise_();
292
293 return *this;
294 }
295
297 if (this == &source) { return *this; }
298
299 _formula_ = std::move(source._formula_);
300 _scanner_ = std::move(source._scanner_);
301 _parser_ = std::move(source._parser_);
302 _parser_->formula(this);
303 _last_token_ = std::move(source._last_token_);
304 _output_ = std::move(source._output_);
305 _stack_ = std::move(source._stack_);
306
307 return *this;
308 }
309
310 double Formula::result() const {
311 _parser_->Parse();
312
313 std::stack< FormulaPart > stack;
314 if (_output_.empty()) { GUM_ERROR(OperationNotAllowed, "no output found") }
315
316 for (auto item: _output_) {
317 switch (item.type) {
319 stack.push(item);
320 break;
321 }
322
325 _reduceOperatorOrFunction_(item, stack);
326 break;
327 }
328
329 default : {
330 GUM_ERROR(OperationNotAllowed, "expecting numbers, operators or functions")
331 }
332 }
333 }
334
335 if (stack.size() != 1) {
336 GUM_ERROR(OperationNotAllowed, "too many inputs")
337
338 } else if (stack.top().type != FormulaPart::token_type::NUMBER) {
339 GUM_ERROR(OperationNotAllowed, "too many inputs")
340 }
341 return stack.top().number;
342 }
343
345 switch (character) {
346 case '+' :
347 case '-' :
348 case '*' :
349 case '/' : {
350 return true;
351 }
352
353 case '_' : {
354 return false;
355 }
356 case '^' : {
357 return false;
358 }
359
360 default : {
361 GUM_ERROR(OperationNotAllowed, "A - not an operator")
362 }
363 }
364 }
365
367 switch (character) {
368 case '+' :
369 case '-' : {
370 return 2;
371 }
372
373 case '*' :
374 case '/' : {
375 return 3;
376 }
377
378 case '^' : {
379 return 4;
380 }
381
382 case '_' : {
383 return 5;
384 }
385
386 default : {
387 GUM_ERROR(OperationNotAllowed, "B - not an operator")
388 }
389 }
390 }
391
392 size_t FormulaPart::argc() const {
393 switch (type) {
394 case OPERATOR : {
395 return _operator_argc_();
396 }
397
398 case FUNCTION : {
399 return _function_argc_();
400 }
401
402 default : {
403 GUM_ERROR(OperationNotAllowed, "expecting a function or an operator")
404 }
405 }
406 }
407
409 switch (character) {
410 case '_' : {
411 return (size_t)1;
412 }
413 case '+' :
414 case '-' :
415 case '*' :
416 case '/' :
417 case '^' : {
418 return (size_t)2;
419 }
420
421 default : {
422 GUM_ERROR(OperationNotAllowed, "C - not an operator")
423 }
424 }
425 }
426
428 switch (function) {
430 return 1;
431 }
433 return 1;
434 }
436 return 1;
437 }
439 return 2;
440 }
442 return 1;
443 }
444 // case FormulaPart::token_function::nil: { return "nil"; }
445 default : {
446 GUM_ERROR(OperationNotAllowed, "unknown function")
447 }
448 }
449 }
450
451 double FormulaPart::_operator_eval_(const std::vector< FormulaPart >& args) const {
452 switch (character) {
453 case '+' : {
454 return args[1].number + args[0].number;
455 }
456
457 case '-' : {
458 return args[1].number - args[0].number;
459 }
460
461 case '*' : {
462 return args[1].number * args[0].number;
463 }
464
465 case '/' : {
466 return args[1].number / args[0].number;
467 }
468
469 case '^' : {
470 return std::pow(args[1].number, args[0].number);
471 }
472
473 case '_' : {
474 return 0 - args[0].number;
475 }
476
477 default : {
478 GUM_ERROR(OperationNotAllowed, "D - not an operator")
479 }
480 }
481 }
482
483 double FormulaPart::_function_eval_(const std::vector< FormulaPart >& args) const {
484 switch (function) {
486 return std::exp(args[0].number);
487 }
489 return std::log(args[0].number);
490 }
492 return std::log(args[0].number);
493 }
495 return std::pow(args[1].number, args[0].number);
496 }
498 return std::sqrt(args[0].number);
499 }
500 // case FormulaPart::token_function::nil: { return "nil"; }
501 default : {
502 GUM_ERROR(OperationNotAllowed, "unknown function")
503 }
504 }
505 }
506
507 FormulaPart FormulaPart::eval(const std::vector< FormulaPart >& args) const {
508 switch (type) {
509 case OPERATOR : {
510 return {token_type::NUMBER, _operator_eval_(args)};
511 }
512
513 case FUNCTION : {
514 return {token_type::NUMBER, _function_eval_(args)};
515 }
516
517 default : {
518 GUM_ERROR(OperationNotAllowed, "cannot evaluate expression")
519 }
520 }
521 }
522
524 while (!_stack_.empty()) {
525 if (_stack_.top().character == '(') { GUM_ERROR(OperationNotAllowed, "expecting ')'") }
526
527 _push_output_(_stack_.top());
528 _stack_.pop();
529 }
530 }
531
532 void Formula::_push_function_(std::string_view func) {
533 if (func == "exp") {
535 _push_stack_(t);
536
537 } else if (func == "log") {
539 _push_stack_(t);
540
541 } else if (func == "ln") {
543 _push_stack_(t);
544
545 } else if (func == "pow") {
547 _push_stack_(t);
548
549 } else if (func == "sqrt") {
551 _push_stack_(t);
552
553 } else {
554 GUM_ERROR(OperationNotAllowed, "unknown function")
555 }
556 }
557
558 void Formula::_push_identifier_(std::string_view ident) {
559 try {
560 _push_function_(ident);
561
562 } catch (OperationNotAllowed const&) {
563 try {
564 _push_variable_(ident);
565
566 } catch (OperationNotAllowed const&) { GUM_ERROR(OperationNotAllowed, "unknown identifier") }
567 }
568 }
569} // namespace gum
570
571#ifdef GUM_NO_INLINE
573#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:451
size_t argc() const
Returns the number of argument of the function stored in this gum::FormulaPart.
Definition formula.cpp:392
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:483
std::string str() const
Returns a string representation of this gum::FormulaPart value.
Definition formula.cpp:169
token_function function
The value stored by this gum::FormulaPart.
Definition formula.h:99
FormulaPart()
Class constructor.
Definition formula.cpp:111
size_t _function_argc_() const
Returns the number of arguments expected by the function stored in this gum::FormulaPart.
Definition formula.cpp:427
size_t _operator_argc_() const
Returns the number of arguments expected by the operator stored in this gum::FormulaPart.
Definition formula.cpp:408
FormulaPart & operator=(const FormulaPart &source)
Definition formula.cpp:147
bool isLeftAssociative() const
Returns true if this gum::FormulaPart is left associative.
Definition formula.cpp:344
~FormulaPart()
Class destuctor.
Definition formula.cpp:142
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:507
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:366
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:278
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:532
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:283
void _initialise_()
Initialise the formula scanner and parser.
Definition formula.cpp:194
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:558
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:204
double result() const
Returns the result of this gum::Formula.
Definition formula.cpp:310
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:523
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:61
std::string func2str(FormulaPart::token_function func)
Definition formula.cpp:85
std::string to_string(const Formula &f)
void print_output(std::vector< FormulaPart > v)
Definition formula.cpp:77
STL namespace.