-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathalphaFactory.cpp
More file actions
1888 lines (1662 loc) · 60.6 KB
/
alphaFactory.cpp
File metadata and controls
1888 lines (1662 loc) · 60.6 KB
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//=============================================================================
// Copyright (c) 2017, Universita' di Torino, Elvio G. Amparore ,amparore@di.unito.it>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//=============================================================================
//
// alphaFactory
//
// A software tool for the computation of alpha-factors for general
// events in a DSPN net. Takes in input the event function f_g(x),
// the CTMC rate and the accuracy, and outputs the coefficients needed
// for the Uniformization function.
//
// Written by: Elvio G. Amparore, Universita' di Torino, 2017.
//
// Compile with: (requires boost C++)
// clang++ -I/usr/local/include -L/usr/local/lib alphafactors.cpp
// -std=c++11 -O2 -o alphafactors
//=============================================================================
#include <iostream>
#include <memory>
#include <utility>
#include <map>
#include <stdexcept>
#include <algorithm>
#include "boost/variant.hpp"
#ifdef USE_GMP
# include <boost/multiprecision/gmp.hpp>
namespace mp = boost::multiprecision;
template<int PREC>
using base_mpfloat = mp::number<mp::gmp_float<PREC>>;
#else
# include <boost/multiprecision/cpp_dec_float.hpp>
namespace mp = boost::multiprecision;
template<int PREC>
using base_mpfloat = mp::number<mp::cpp_dec_float<PREC>>;
#endif
#include <boost/math/special_functions/gamma.hpp>
#include <boost/math/special_functions/expint.hpp>
using namespace boost;
using namespace std;
#define MPFLOAT_PRECISION 1024
// typedef mp::mpf_float_500 mpfloat;
// typedef mp::number<mp::cpp_dec_float<MPFLOAT_PRECISION>> mpfloat;
typedef base_mpfloat<MPFLOAT_PRECISION> mpfloat;
struct Symbol;
struct Term;
struct Function;
template<typename T> struct Any;
template<typename T>
struct Any {
T* ptr;
Any() : ptr(nullptr) { }
Any(T* p) : ptr(p) { }
Any(const Any&) = default;
Any(Any&&) = default;
Any& operator=(const Any&) = default;
bool operator==(const Any&) const { throw; }
};
struct AnyExpr;
typedef boost::variant<Term, Symbol, Function,
Any<Term>, Any<Symbol>, Any<Function>,
AnyExpr> expr;
//=============================================================================
const char DIRACT_DELTA = 'D';
const char RECT = 'R';
const char UNIFORM = 'U';
const char TRIANGULAR = 'T';
const char ERLANG = 'L';
const char TRUNCATED_EXP = 'N';
const char PARETO = 'P';
struct OpNameType {
const char *name;
char op;
size_t min_arity, max_arity;
};
static const OpNameType g_ops[] = {
OpNameType{ "Exp", 'e', 1, 1 },
OpNameType{ "Log", 'l', 1, 1 },
OpNameType{ "Add", '+', 2, 1000 },
OpNameType{ "Sub", '-', 2, 2 },
OpNameType{ "Prod", '*', 2, 1000 },
OpNameType{ "Divide", '/', 2, 2 },
OpNameType{ "Pow", '^', 2, 2 },
// Special functions for cdf/pdf description
OpNameType{ "DiracDelta", DIRACT_DELTA, 1, 1 },
OpNameType{ "Rect", RECT, 2, 2 },
OpNameType{ "Uniform", UNIFORM, 2, 2 },
OpNameType{ "Triangular", TRIANGULAR, 2, 2 },
OpNameType{ "Erlang", ERLANG, 2, 2 },
OpNameType{ "TruncatedExp", TRUNCATED_EXP, 2, 2 },
OpNameType{ "Pareto", PARETO, 2, 2 }
};
const OpNameType& OpDescr(char op) {
for (const OpNameType& ont : g_ops)
if (ont.op == op)
return ont;
cerr << "Operator with code " << op << "does not exists." << endl;
throw;
}
//=============================================================================
struct Term {
Term() { }
Term(mpfloat f) : value(f) {}
Term(const Term&) = default;
Term(Term&&) = default;
Term& operator=(const Term&) = default;
bool operator==(const Term& x) const { return value == x.value; }
mpfloat value;
};
struct Symbol {
Symbol() { }
Symbol(std::string f) : name(f) {}
Symbol(const Symbol&) = default;
Symbol(Symbol&&) = default;
Symbol& operator=(const Symbol&) = default;
bool operator==(const Symbol& x) const { return name == x.name; }
std::string name;
};
struct AnyExpr {
expr* ptr;
AnyExpr() : ptr(nullptr) { }
AnyExpr(expr* p) : ptr(p) { }
AnyExpr(const AnyExpr&) = default;
AnyExpr(AnyExpr&&) = default;
AnyExpr& operator=(const AnyExpr&) = default;
bool operator==(const AnyExpr&) const { throw; }
};
struct Function {
Function() { }
Function(char _op, expr e1) : op(_op), operands({e1}) { _check(); }
Function(char _op, expr e1, expr e2) : op(_op), operands({e1,e2}) { _check(); }
Function(char _op, expr e1, expr e2, expr e3) : op(_op), operands({e1,e2,e3}) { _check(); }
Function(char _op, expr e1, expr e2, expr e3, expr e4) : op(_op), operands({e1,e2,e3,e4}) { _check(); }
Function(char _op, std::vector<expr> _ex) : op(_op), operands(_ex) { _check(); }
Function(const Function&) = default;
Function(Function&&) = default;
Function& operator=(const Function&) = default;
bool operator==(const Function& x) const {
return op == x.op && operands == x.operands;
}
char op;
std::vector<expr> operands;
void _check() {
const OpNameType& ont = OpDescr(op);
if (operands.size() < ont.min_arity || operands.size() > ont.max_arity)
throw "Invalid operand size.";
}
};
//=============================================================================
mpfloat beta(int k, const mpfloat& v);
mpfloat eta(int k, mpfloat q, int m, mpfloat l, mpfloat a);
mpfloat factorial(int m);
mpfloat IncompleteEulerGammaN(mpfloat a, mpfloat z);
mpfloat gamma(int k, mpfloat q, int m, mpfloat l, mpfloat a);
mpfloat gamma_aInf(int k, mpfloat q, int m, mpfloat l);
mpfloat alpha(int k, const mpfloat& q, const expr& ex);
mpfloat moment(int k, const expr& f);
expr integrate(const expr& ex);
expr simplify(const expr& ex);
mpfloat evaluate(const expr& ex);
//=============================================================================
expr mkTerm(mpfloat f) { return Term(f); }
//=============================================================================
ostream& operator << (ostream& os, const Term& t) {
return os << t.value;
}
ostream& operator << (ostream& os, const Symbol& x) {
return os << x.name;
}
ostream& operator << (ostream& os, const Function& fn) {
os << OpDescr(fn.op).name << "(";
for (size_t i=0; i<fn.operands.size(); i++)
os << (i==0 ? "" : ", ") << fn.operands[i];
return os << ")";
}
ostream& operator << (ostream& os, const AnyExpr& e) {
return os << "Any<expr>";
}
template<typename T>
ostream& operator << (ostream& os, const Any<T>& e) {
return os << "Any<>";
}
//=============================================================================
class matcher : public boost::static_visitor<bool> {
expr match;
// bool match_ok(const expr& what) { *match=what; return true; }
template<typename T, typename Arg>
bool any_match(const Arg& arg) {
if (match.type() == typeid(Any<T>)) {
*boost::get<Any<T>>(match).ptr = arg;
return true;
}
return false;
}
template<typename Arg>
bool any_expr_match(const Arg& arg) {
if (match.type() == typeid(AnyExpr)) {
*boost::get<AnyExpr>(match).ptr = arg;
return true;
}
return false;
}
public:
matcher(expr _match) : match(_match) { }
bool operator()(const Term& t) {
if (any_expr_match(t))
return true;
if (any_match<Term>(t))
return true;
if (match.type() == typeid(Term)) {
if (boost::get<Term>(match).value == t.value)
return true;
}
return false;
}
bool operator()(const Symbol& sym) {
if (any_expr_match(sym))
return true;
if (any_match<Symbol>(sym))
return true;
if (match.type() == typeid(Symbol)) {
if (boost::get<Symbol>(match).name == sym.name)
return true;
}
return false;
}
bool operator()(const Function& fn) {
if (any_expr_match(fn))
return true;
if (any_match<Function>(fn))
return true;
if (match.type() == typeid(Function)) {
Function& f = boost::get<Function>(match);
if (f.op == fn.op && f.operands.size() == fn.operands.size()) {
for (size_t i=0; i<f.operands.size(); i++) { // Recursive match
matcher m(f.operands[i]);
if (!boost::apply_visitor(m, fn.operands[i]))
return false;
}
return true;
}
}
return false;
}
bool operator()(const AnyExpr& e) { throw; }
template<typename T> bool operator()(const Any<T>& e) { throw; }
};
//=============================================================================
// takes a product of terms and prepend a constant factor of 1
expr prepend_one(const expr& ex) {
if (ex.type() != typeid(Function))
throw;
if (boost::get<Function>(ex).op != '*')
throw;
std::vector<expr> newops = boost::get<Function>(ex).operands;
newops.insert(newops.begin(), mkTerm(1));
return Function('*', newops);
}
//=============================================================================
int require_int(mpfloat a) {
int n = (int)a;
if (n != a) {
cerr << "Parameter " << a << " is expected to be an integer." << endl;
throw;
}
return n;
}
//=============================================================================
// Determines if a polynomial term has shape: c * Exp(l * x) * x^h * Rect[0, a]
bool is_poly_x_explx_xh_R0a(const expr& ex, mpfloat& c, mpfloat& l, bool& has_exp,
mpfloat& h, bool& has_Rect, mpfloat& a)
{
c = 1;
l = 0;
h = 0;
auto check_has_c = [&c](const expr& e) -> bool {
if (e.type() == typeid(Term)) {
c *= boost::get<Term>(e).value;
return true;
}
return false;
};
auto check_has_exp = [&l](const expr& e) -> bool {
Symbol x;
matcher m(Function('e', Any<Symbol>(&x)));
if (boost::apply_visitor(m, e)) {
l += 1;
return true;
}
Term lt;
matcher m2(Function('e', Function('*', Any<Term>(<), Any<Symbol>(&x))));
if (boost::apply_visitor(m2, e)) {
l += lt.value;
return true;
}
return false;
};
auto check_has_xh = [&h](const expr& e) -> bool {
if (e.type() == typeid(Symbol)) {
h += 1;
return true;
}
Symbol x;
Term ht;
matcher m2(Function('^', Any<Symbol>(&x), Any<Term>(&ht)));
if (boost::apply_visitor(m2, e)) {
h += ht.value;
return true;
}
return false;
};
auto check_has_Rect = [&a](const expr& e) -> bool {
Term at;
matcher m(Function(RECT, mkTerm(0), Any<Term>(&at)));
if (boost::apply_visitor(m, e)){
a = at.value;
return true;
}
return false;
};
has_exp=false;
bool has_xh=false;
has_Rect=false;
// product of multiple terms
if (ex.type() == typeid(Function)) {
const Function& fex = boost::get<Function>(ex);
if (fex.op == '*') {
for (const expr opr : fex.operands) {
bool matched = check_has_c(opr);
if (matched)
continue;
matched = check_has_exp(opr);
has_exp |= matched;
if (matched)
continue;
matched = check_has_xh(opr);
has_xh |= matched;
if (matched)
continue;
matched = check_has_Rect(opr);
has_Rect |= matched;
if (matched)
continue;
// unmatched operand
return false;
}
}
else {
// single term
check_has_c(ex);
has_exp = check_has_exp(ex);
has_xh = check_has_xh(ex);
has_Rect = check_has_Rect(ex);
}
}
return (has_exp || has_xh || has_Rect);
}
//=============================================================================
expr integrate(const expr& ex) {
// expr __integrate(const expr& ex);
// expr t = __integrate(ex);
// cout << "integrate("<<ex<<") = " << t << endl;
// return t;
// }
// expr __integrate(const expr& ex) {
// integrate[x] -> 1/2 x^2
{
Symbol x;
matcher m((Any<Symbol>(&x)));
if (boost::apply_visitor(m, ex))
return Function('*', mkTerm(0.5), Function('^', x, mkTerm(2)));
}
// integrate[ term ] -> term * x
{
Term t;
matcher m((Any<Term>(&t)));
if (boost::apply_visitor(m, ex))
return Function('*', t, Symbol("x"));
}
// integrate[ e^x ] -> e^x
{
Symbol x;
matcher m(Function('e', Any<Symbol>(&x)));
if (boost::apply_visitor(m, ex))
return ex;
}
// integrate[ e^(k * x) ] -> 1/k * e^(k * x)
{
Symbol x;
Term k;
matcher m(Function('e', Function('*', Any<Term>(&k), Any<Symbol>(&x))));
if (boost::apply_visitor(m, ex))
return Function('*', mkTerm(1/k.value), Function('e', Function('*', k.value, x)));
}
// integrate[x^m] -> 1/(m+1) * x ^ (m+1)
{
Term t;
Symbol x;
matcher m(Function('^', Any<Symbol>(&x), Any<Term>(&t)));
if (boost::apply_visitor(m, ex))
return Function('*', mkTerm(1.0/(t.value+1)),
Function('^', x, mkTerm(t.value+1)));
}
// integrate[ DiracDelta(t) ] -> 1
{
Term t;
matcher m(Function(DIRACT_DELTA, Any<Term>(&t)));
if (boost::apply_visitor(m, ex))
return mkTerm(1);
}
// integrate[ x * DiracDelta(t) ] -> t
{
Term t;
Symbol x;
matcher m(Function('*', Any<Symbol>(&x), Function(DIRACT_DELTA, Any<Term>(&t))));
if (boost::apply_visitor(m, ex))
return t;
}
// integrate[ (c * x * DiracDelta(t)) ] -> c * t
{
Term c, t;
Symbol x;
matcher m(Function('*', Any<Term>(&c), Any<Symbol>(&x), Function(DIRACT_DELTA, Any<Term>(&t))));
if (boost::apply_visitor(m, ex))
return mkTerm(c.value * t.value);
}
// ---- rectangular signal ----
// integrate[ c * Exp(l * x) * x^h * Rect[0, a] ]
{
mpfloat c, l, h, a;
bool has_exp, has_Rect;
if (is_poly_x_explx_xh_R0a(ex, c, l, has_exp, h, has_Rect, a)) {
if (!has_exp) {
if (!has_Rect) {
cerr << ex << ": Integral of c * x^h does not converge on [0, infinity)." << endl;
throw;
}
return mkTerm(pow(a, 1+h) * c / (h+1));
}
// c * Exp(l * x) * x^h * Rect(0, a)
// -> c * (-l)^(-h-1) * (Gamma(h+1) - IncompleteGamma(h+1, -a * l))
mpfloat ig = 0;
if (has_Rect)
ig = IncompleteEulerGammaN(h+1, -a * l);
// cout << "integrate "<<ex<<" c="<<c<<" l="<<l<<" h="<<h<<" a="<<a<<" ig="<<ig<<endl;
return mkTerm(c / pow(abs(l), h+1) * (factorial(require_int(h)) - ig));
}
}
// // integrate[ R(a, b) ] -> integrate[ R(0, b) ] - integrate[ R(0, a) ]
{
Term a, b;
matcher m(Function(RECT, Any<Term>(&a), Any<Term>(&b)));
if (boost::apply_visitor(m, ex) && a.value != 0)
return Function('-', integrate(Function(RECT, mkTerm(0), b)),
integrate(Function(RECT, mkTerm(0), a)));
}
// integrate[ <...> * R(a, b) ] -> integrate[ <...> * R(0, b) ] - integrate[ <...> * R(0, a) ]
{
if (ex.type()==typeid(Function)) {
const Function& f = boost::get<Function>(ex);
if (f.op == '*') {
Term a, b;
matcher m(Function(RECT, Any<Term>(&a), Any<Term>(&b)));
if (boost::apply_visitor(m, f.operands.back()) && a.value != 0) {
std::vector<expr> opsA = f.operands, opsB;
opsA.pop_back();
opsB = opsA;
opsA.push_back(Function(RECT, mkTerm(0), a));
opsB.push_back(Function(RECT, mkTerm(0), b));
return Function('-', integrate(Function('*', opsB)),
integrate(Function('*', opsA)));
}
}
}
}
//---- low priority rules ----
// integrate[ term * f(x) ] -> term * integrate[f(x)]
{
Term t;
expr e;
matcher m(Function('*', Any<Term>(&t), AnyExpr(&e)));
if (boost::apply_visitor(m, ex))
return Function('*', t, integrate(e));
}
// integrate[ f1(x) - f2(x) ] -> integrate[f1(x)] - integrate[f2(x)]
{
expr e1, e2;
matcher msub(Function('-', AnyExpr(&e1), AnyExpr(&e2)));
if (boost::apply_visitor(msub, ex))
return Function('-', integrate(e1), integrate(e2));
}
// integrate[ sum of terms ] -> sum of integrate[terms]
{
if (ex.type() == typeid(Function)) {
const Function& f = boost::get<Function>(ex);
if (f.op == '+') {
std::vector<expr> int_opr;
for (const expr& opr : f.operands)
int_opr.push_back(integrate(opr));
return Function('+', int_opr);
}
}
}
cerr << "Cannot integrate " << ex << endl;
throw;
}
//=============================================================================
int grade_of(const expr& ex) {
if (ex.type() == typeid(Term))
return 0;
else if (ex.type() == typeid(Symbol))
return 2;
else if (ex.type() == typeid(Function)) {
const Function& f = boost::get<Function>(ex);
switch (f.op) {
case DIRACT_DELTA:
case RECT:
return 3; // special functions
default:
return 1;
}
}
else throw;
}
expr simplify(const expr& ex) {
// expr __simplify(const expr& ex);
// expr s = __simplify(ex);
// cout << " simplify " << ex << " -> ";
// if (s == ex)
// cout << "unchanged" << endl;
// else
// cout << s << endl;
// return s;
// }
// expr __simplify(const expr& ex) {
if (ex.type() == typeid(Term) || ex.type() == typeid(Symbol))
return ex;
try {
mpfloat value = evaluate(ex);
return mkTerm(value);
}
catch(...) { /* not evaluatable */ }
// Reorder & simplify terms
if (ex.type() == typeid(Function)) {
const Function& f = boost::get<Function>(ex);
if (f.op == '*' || f.op == '+') {
// Aggregate binary +/* operations into a single n-ary operation
std::vector<expr> operands;
std::function<void (const expr&)> aggreg;
aggreg = [&](const expr& e) {
if (e.type() != typeid(Function) ||
boost::get<Function>(e).op != f.op)
{
operands.push_back(simplify(e));
return;
}
for (const expr& eop : boost::get<Function>(e).operands)
aggreg(simplify(eop));
};
aggreg(ex);
assert(operands.size() >= 2);
// Reorder terms: first constants, sub-expressions, symbols and finally special functions
sort(operands.begin(), operands.end(), [](const expr& e1, const expr& e2){
return grade_of(e1) < grade_of(e2);
});
// Add/multiply the constant terms
while (operands.size() >= 2 &&
operands[0].type() == typeid(Term) &&
operands[1].type() == typeid(Term))
{
if (f.op == '*') {
operands[1] = mkTerm(boost::get<Term>(operands[0]).value *
boost::get<Term>(operands[1]).value);
}
else if (f.op == '+') {
operands[1] = mkTerm(boost::get<Term>(operands[0]).value +
boost::get<Term>(operands[1]).value);
}
else throw;
operands.erase(operands.begin());
}
// Remove neutral terms
if (operands[0].type() == typeid(Term)) {
if (f.op == '*') {
if (boost::get<Term>(operands[0]).value == 0)
return mkTerm(0);
if (boost::get<Term>(operands[0]).value == 1)
operands.erase(operands.begin());
}
else if (f.op == '+') {
if (boost::get<Term>(operands[0]).value == 0)
operands.erase(operands.begin());
}
}
// No add/product, actually....
if (operands.size() == 1)
return operands[0];
// Transform symbols into powers: x*x -> x^2
{
Symbol x;
Term t;
matcher powm(Function('^', Any<Symbol>(&x), Any<Term>(&t)));
for (size_t i=0; i<operands.size()-1; i++) {
if (operands[i+1].type() == typeid(Symbol)) {
if (operands[i] == operands[i+1]) {
operands[i] = Function('^', operands[i+1], mkTerm(2));
operands.erase(operands.begin() + i + 1);
i--;
}
else if (boost::apply_visitor(powm, operands[i])) {
operands[i] = Function('^', operands[i+1], mkTerm(t.value + 1));
operands.erase(operands.begin() + i + 1);
i--;
}
}
}
}
// Apply: a * b * (c + d) -> a*b*c + a*b*d
if (f.op == '*') {
auto it = operands.begin();
while (it != operands.end()) {
if (it->type() == typeid(Function) && boost::get<Function>(*it).op == '+') {
Function sum = boost::get<Function>(*it);
operands.erase(it);
for (size_t i=0; i<sum.operands.size(); i++) {
sum.operands[i] = Function('*',
operands.size()==1 ? operands[0] : Function('*', operands),
sum.operands[i]);
}
// cout << "sum = " << sum << endl;
return simplify(sum);
}
it++;
}
}
return Function(f.op, operands);
}
}
// convert Uniform[a, b] -> 1/(b-a) * Rect[a,b]
{
Term a, b;
matcher m(Function(UNIFORM, Any<Term>(&a), Any<Term>(&b)));
if (boost::apply_visitor(m, ex))
return Function('*', mkTerm(1 / (b.value - a.value)), Function(RECT, a, b));
}
// convert Triangular[a, b] -> 4/((a-b)^2) * (x-a) * Rect(a, (a+b)/2) -
// -4/((a-b)^2) * (x-b) * Rect((a+b)/2, b)
{
Term a, b;
matcher m(Function(TRIANGULAR, Any<Term>(&a), Any<Term>(&b)));
if (boost::apply_visitor(m, ex)) {
expr t = Function('+', Function('*', mkTerm(4 / pow((b.value - a.value), 2)),
Function('+', Symbol("x"), mkTerm(-a.value)),
Function(RECT, a, mkTerm((a.value + b.value) / 2))),
Function('*', mkTerm(-4 / pow((b.value - a.value), 2)),
Function('+', Symbol("x"), mkTerm(-b.value)),
Function(RECT, mkTerm((a.value + b.value) / 2), b)));
return simplify(t);
}
}
// convert Erlang(lambda, rr) -> (lambda^rr) / (rr-1)! * x ^ (rr-1) * Exp(-lambda * x)
{
Term lambda, rr;
matcher m(Function(ERLANG, Any<Term>(&lambda), Any<Term>(&rr)));
if (boost::apply_visitor(m, ex)) {
expr t = Function('*', mkTerm(pow(lambda.value, rr.value) / factorial(require_int(rr.value - 1))),
Function('^', Symbol("x"), mkTerm(rr.value - 1)),
Function('e', Function('*', mkTerm(-lambda.value), Symbol("x"))));
return simplify(t);
}
}
// convert TruncatedExp(l, t) -> l Exp(-l x) R[0, t] + Exp(-l t) DiracDelta[t]
{
Term l, a;
matcher m(Function(TRUNCATED_EXP, Any<Term>(&l), Any<Term>(&a)));
if (boost::apply_visitor(m, ex)) {
expr t = Function('+', Function('*', mkTerm(l.value),
Function('e', Function('*', mkTerm(-l.value), Symbol("x"))),
Function(RECT, mkTerm(0), a)),
Function('*', mkTerm(exp(-l.value * a.value)),
Function(DIRACT_DELTA, a)));
return simplify(t);
}
}
// simplify[ x ^ 0 ] -> 1
{
Symbol x;
matcher m(Function('^', Any<Symbol>(&x), mkTerm(0)));
if (boost::apply_visitor(m, ex))
return mkTerm(1);
}
// simplify[ f ^ 1 ] -> f
{
expr f;
matcher m(Function('^', AnyExpr(&f), mkTerm(1)));
if (boost::apply_visitor(m, ex))
return simplify(f);
}
// simplify[ f * (a + b) ] -> a * f + b * f
{
expr f, a, b;
matcher m(Function('*', AnyExpr(&f), Function('+', AnyExpr(&a), AnyExpr(&b))));
if (boost::apply_visitor(m, ex))
return simplify(Function('+', Function('*', a, f), Function('*', b, f)));
}
// simplify[ (a + b) * f ] -> a * f + b * f
{
expr f, a, b;
matcher m(Function('*', Function('+', AnyExpr(&a), AnyExpr(&b)), AnyExpr(&f)));
if (boost::apply_visitor(m, ex))
return simplify(Function('+', Function('*', a, f), Function('*', b, f)));
}
// recursively descend functions
if (ex.type() == typeid(Function)) {
const Function& f = boost::get<Function>(ex);
Function newf;
newf.op = f.op;
bool changed = false;
for (size_t i=0; i<f.operands.size(); i++) {
newf.operands.push_back(simplify(f.operands[i]));
if (!(newf.operands[i] == f.operands[i]))
changed = true;
}
return (changed ? simplify(newf) : newf);
}
cerr << "Cannot simplify " << ex << endl;
throw;
}
//=============================================================================
mpfloat evaluate(const expr& ex) {
if (ex.type() == typeid(Term))
return boost::get<Term>(ex).value;
if (ex.type() == typeid(Symbol))
throw "Cannot evaluate a symbol.";
if (ex.type() == typeid(Function)) {
const Function& f = boost::get<Function>(ex);
switch (f.op) {
case '+': {
mpfloat v = 0;
for (const expr& a : f.operands)
v += evaluate(a);
return v;
}
case '-':
assert(f.operands.size() == 2);
return evaluate(f.operands[0]) - evaluate(f.operands[1]);
case '*':{
mpfloat v = 1;
for (const expr& a : f.operands)
v *= evaluate(a);
return v;
}
case '/':
assert(f.operands.size() == 2);
return evaluate(f.operands[0]) / evaluate(f.operands[1]);
case '^':
assert(f.operands.size() == 2);
return pow(evaluate(f.operands[0]), evaluate(f.operands[1]));
case 'e':
assert(f.operands.size() == 1);
return exp(evaluate(f.operands[0]));
case 'l':
assert(f.operands.size() == 1);
return log(evaluate(f.operands[0]));
default:
// cerr << "Don't known how to evaluate function " << OpDescr(f.op).name << endl;
throw "Unknown function";
}
}
// cerr << "Cannot evaluate expression " << ex << endl;
throw "Cannot evaluate.";
}
//=============================================================================
static map<pair<int, mpfloat>, mpfloat> s_beta_mem; // memoized buffer
mpfloat beta(int k, const mpfloat& v) {
auto mem_key = make_pair(k, v);
if (s_beta_mem.count(mem_key) == 1)
return s_beta_mem[mem_key];
mpfloat result;
if (k == 0)
result = exp(-v);
else
result = (beta(k-1, v) * v) / k;
s_beta_mem[mem_key] = result;
return result;
}
//=============================================================================
static map<tuple<int, mpfloat, int, mpfloat, mpfloat>, mpfloat> s_eta_mem; // memoized buffer
mpfloat eta(int k, mpfloat q, int m, mpfloat l, mpfloat a) {
auto mem_key = make_tuple(k, q, m, l, a);
if (s_eta_mem.count(mem_key) == 1)
return s_eta_mem[mem_key];
mpfloat result;
if (k == 0)
result = pow(a, m) / (q + l);
else
result = eta(k - 1, q, m, l, a) * q / (q + l);
s_eta_mem[mem_key] = result;
return result;
}
//=============================================================================
static map<int, mpfloat> s_factorial_mem;
mpfloat factorial(int m) {
if (m == 0 || m == 1)
return 1;
if (s_factorial_mem.count(m) == 0) {
mpfloat f = m * factorial(m - 1);
s_factorial_mem[m] = f;
}
return s_factorial_mem[m];
}
//=============================================================================
template<int PREC>
mpfloat compute_positive_tgamma_at_precision(mpfloat a, mpfloat z) {
static_assert(PREC <= MPFLOAT_PRECISION, "Using an inconsisten precision for tgamma.");
typedef base_mpfloat<PREC> comp_float;
// Compute tgamma using a precision of PREC
// This will raise an oveflow exception if the precision is not enough.
comp_float result = boost::math::tgamma(comp_float(a), comp_float(z));
// cout << "compute_positive_tgamma("<<a<<", "<<z<<") = "<<result<<" PREC=cpp_dec_float<"<<PREC<<">"<<endl;
// Convert back to the precision of an mpfloat type
return mpfloat(result.str(0, std::ios_base::scientific));
}
// // End of template recursion
// struct EOR { };
// template<int PREC>
// mpfloat compute_positive_tgamma(mpfloat a, mpfloat z, EOR) {
// cout << "tgamma("<<a<<", "<<z<<") computation cannot be handled.\n"
// << "Increase the size of MPFLOAT_PRECISION.\n" <<endl;
// throw std::overflow_error("Not enough precision to compute a tgamma().");
// }
// template<int PREC>
// mpfloat compute_positive_tgamma(mpfloat a, mpfloat z, int) {
// static_assert(PREC <= MPFLOAT_PRECISION, "Wrong recursive template definition.");
// typedef mp::number<mp::cpp_dec_float<PREC>> comp_float;
// try {
// // Compute tgamma using a precision of PREC
// comp_float result = boost::math::tgamma(comp_float(a), comp_float(z));
// cout << "compute_positive_tgamma("<<a<<", "<<z<<") = "<<result<<" PREC=cpp_dec_float<"<<PREC<<">"<<endl;
// // Convert back to the precision of an mpfloat type
// return mpfloat(result.str(0, std::ios_base::scientific));
// }
// catch (std::overflow_error ovf) {
// // PREC is not enough - recompute doubling the precision
// typedef typename std::conditional<4 * PREC <= MPFLOAT_PRECISION, int, EOR>::type NextPrecType;
// return compute_positive_tgamma<4 * PREC>(a, z, NextPrecType());
// }
// }
// Compute the tgamma function using an increasing precision in case of overflow
mpfloat compute_positive_tgamma(mpfloat a, mpfloat z) {
try {
mpfloat result = mpfloat(boost::math::tgamma(double(a), double(z)));
// cout << "compute_positive_tgamma("<<a<<", "<<z<<") = "<<result<<" PREC=double"<<endl;
return result;
}
catch (std::overflow_error ovf) {
// try { return compute_positive_tgamma_at_precision<32>(a, z); }
// catch (std::overflow_error ovf) {
// try { return compute_positive_tgamma_at_precision<128>(a, z); }
// catch (std::overflow_error ovf) {
// try { return compute_positive_tgamma_at_precision<512>(a, z); }
// catch (std::overflow_error ovf) {
// // tgamma is too hard to compute, rethrow the exception
// throw ovf;
// }
// }
// }