-
Notifications
You must be signed in to change notification settings - Fork 1
/
autograd.cpp
659 lines (518 loc) · 17.1 KB
/
autograd.cpp
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
#include <iostream>
#include <cassert>
#include <deque>
#include <array>
#include <string>
#include <sstream>
#include <memory>
#include <cmath>
#include <functional>
#include <type_traits>
using namespace std;
class Expression;
class Expr: public shared_ptr<Expression>
{
public:
Expr() : shared_ptr<Expression>() {}
Expr(Expression* ptr): shared_ptr<Expression>(ptr) {}
Expr(double value);
Expr(int value);
Expr(double value, string name);
};
template<typename Type, typename ...ParamTypes>
Expr make_expr(ParamTypes&& ...params)
{
// TODO properly implement this method
return Expr(new Type(std::forward<ParamTypes>(params)...));
}
class Expression
{
protected:
enum class ExprClass {Variable, Constant};
public:
Expression() {}
Expression(const initializer_list<Expr>& inputs_)
: inputs_(inputs_) {}
virtual ~Expression () {}
virtual Expr derivative(const Expr& target) const = 0;
virtual double value() const = 0;
virtual operator string() const = 0;
virtual Expr simplify() const = 0;
virtual ExprClass expressionClass() const {
for(const auto& operand: inputs_) {
if(operand->expressionClass() == ExprClass::Variable) {
return ExprClass::Variable;
}
}
return ExprClass::Constant;
}
protected:
template<typename ExprType>
Expr unaryOperatorSimplify() const;
template<typename ExprType>
Expr binaryOperatorSimplify(
const function<Expr(const Expr&, double)>& aConstantCbk,
const function<Expr(const Expr&, double)>& bConstantCbk) const;
deque<Expr> inputs_;
string binaryOperatorToString(const string& opString,
bool parenthesize = true) const;
string unaryOperatorToString(const string& opString,
bool parenthesize = true) const;
};
class Constant: public Expression
{
public:
Constant(double value) : value_(value) { }
virtual Expr derivative(const Expr&) const {
return Expr(0);//make_shared<Constant>(0);
}
virtual double value() const {
return value_;
}
virtual operator string() const {
return (stringstream() << value_).str();
}
virtual Expr simplify() const {
return Expr(value_);//make_shared<Constant>(value_);
}
virtual ExprClass expressionClass() const {
return ExprClass::Constant;
}
private:
double value_;
};
class Variable: public Expression
{
public:
// TODO check if name is repeated
Variable(double value,
const string& name)
: value_(value)
, name_(name) { }
void setValue(double v) {
value_ = v;
}
virtual Expr derivative(const Expr& expr) const;
virtual operator string() const {
return name_;
}
virtual double value() const {
return value_;
}
virtual Expr simplify() const {
return Expr(value_, name_);//make_shared<Variable>(value_, name_);
}
virtual ExprClass expressionClass() const {
return ExprClass::Variable;
}
private:
double value_;
string name_;
};
Expr operator-(Expr a);
Expr operator+(Expr a, Expr b);
Expr operator-(Expr a, Expr b);
Expr operator*(Expr a, Expr b);
Expr operator/(Expr a, Expr b);
#define MK_OPERATION_CONSTRUCTOR(OpClass) \
public: \
OpClass() {} \
OpClass(const initializer_list<Expr>& inputs_) \
: Expression(inputs_) {} \
OpClass& operator=(OpClass&){return *this;}\
#define MK_FUNCTION_CONSTRUCTOR(OpClass) \
public: \
OpClass(const initializer_list<Expr>& inputs_) \
: Function(inputs_) {}
class SignInversion: public Expression
{
public:
MK_OPERATION_CONSTRUCTOR(SignInversion)
virtual double value() const {
return -inputs_[0]->value();
}
virtual operator string() const {
return unaryOperatorToString("-");
}
virtual Expr derivative(const Expr& target) const {
return -inputs_[0]->derivative(target);
}
virtual Expr simplify() const {
return unaryOperatorSimplify<SignInversion>();
}
};
Expr operator-(Expr a) {
return make_expr<SignInversion>(initializer_list<Expr>{a});
}
class Addition: public Expression
{
MK_OPERATION_CONSTRUCTOR(Addition)
public:
virtual double value() const {
return inputs_[0]->value() + inputs_[1]->value();
}
virtual operator string() const {
return binaryOperatorToString(" + ");
}
virtual Expr derivative(const Expr& target) const {
return inputs_[0]->derivative(target) +
inputs_[1]->derivative(target);
}
virtual Expr simplify() const {
const auto oneConstantCbk =
[](const Expr& variable, double constant) -> Expr {
if(constant == 0) return variable;
return make_expr<Constant>(constant) + variable;
};
return binaryOperatorSimplify<Addition>(
oneConstantCbk, oneConstantCbk);
}
};
Expr operator+(Expr a, Expr b) {
return make_expr<Addition>(initializer_list<Expr>{a, b});
}
class Subtraction: public Expression
{
MK_OPERATION_CONSTRUCTOR(Subtraction)
public:
virtual double value() const {
return inputs_[0]->value() - inputs_[1]->value();
}
virtual operator string() const {
return binaryOperatorToString(" - ");
}
virtual Expr derivative(const Expr& target) const {
return inputs_[0]->derivative(target) - inputs_[1]->derivative(target);
}
virtual Expr simplify() const {
return binaryOperatorSimplify<Subtraction>(
[](const Expr& b, double a) -> Expr {
if(a == 0) return b;
return make_expr<Constant>(a) - b;
},
[](const Expr& a, double b) -> Expr {
if(b == 0) return a;
return a - make_expr<Constant>(b);
}
);
}
};
Expr operator-(Expr a, Expr b) {
return make_expr<Subtraction>(initializer_list<Expr>{a, b});
}
class Multiplication: public Expression
{
MK_OPERATION_CONSTRUCTOR(Multiplication)
public:
virtual double value() const {
return inputs_[0]->value() * inputs_[1]->value();
}
virtual operator string() const {
return binaryOperatorToString("*");
}
virtual Expr derivative(const Expr& target) const {
return inputs_[0]->derivative(target) * inputs_[1] +
inputs_[0] * inputs_[1]->derivative(target);
}
virtual Expr simplify() const {
const auto oneConstantCbk =
[](const Expr& variable, double constant) -> Expr {
if(constant == 0) return 0.0;
if(constant == 1) return variable;
return make_expr<Constant>(constant) * variable;
};
return binaryOperatorSimplify<Multiplication>(
oneConstantCbk, oneConstantCbk);
}
};
Expr operator*(Expr a, Expr b) {
return make_expr<Multiplication>(initializer_list<Expr>{a, b});
}
class Division: public Expression
{
MK_OPERATION_CONSTRUCTOR(Division)
public:
virtual double value() const {
return inputs_[0]->value() / inputs_[1]->value();
}
virtual operator string() const {
return binaryOperatorToString("/");
}
virtual Expr derivative(const Expr& target) const {
return (inputs_[0]->derivative(target) * inputs_[1] -
inputs_[0] * inputs_[1]->derivative(target)) /
(inputs_[1] * inputs_[1]);
}
virtual Expr simplify() const {
return binaryOperatorSimplify<Division>(
[](const Expr& b, double a) -> Expr {
if(a == 0) return 0.0;
return make_expr<Constant>(a) / b;
},
[](const Expr& a, double b) -> Expr {
if(b == 0) return
make_expr<Constant>(
std::numeric_limits<double>::quiet_NaN());
if(b == 1) return a;
return a / make_expr<Constant>(b);
}
);
}
};
Expr operator/(Expr a, Expr b) {
return make_expr<Division>(initializer_list<Expr>{a, b});
}
class Function: public Expression
{
MK_OPERATION_CONSTRUCTOR(Function)
public:
~Function() {}
virtual Expr fnDerivative(const Expr& target) const = 0;
virtual Expr derivative(const Expr& target) const {
// Chain rule: df(g1(x), g2(x), ...) = sum{df(g1, g2, ...)*dg_n}
auto result = fnDerivative(inputs_[0]) *
inputs_[0]->derivative(target);
for(int i = 1; i < inputs_.size(); ++i) {
result = result + fnDerivative(inputs_[i]) *
inputs_[i]->derivative(target);
}
return result;
}
protected:
string fnOperatorToString(const string& fnName) const {
stringstream res;
res << fnName << "(";
for(int i = 0; i < inputs_.size(); ++i) {
res << static_cast<string>(*inputs_[i]);
if(i < inputs_.size() - 1) {
res << ", ";
}
}
res << ")";
return res.str();
}
};
template<typename ExprType>
Expr Expression::unaryOperatorSimplify() const {
auto aExpr = inputs_[0]->simplify();
const auto aClass = aExpr->expressionClass();
const auto aVal = aExpr->value();
const bool isConstant = (aClass == ExprClass::Constant);
if(isConstant) {
return make_expr<Constant>(this->value());
} else {
return make_expr<ExprType>(
initializer_list<Expr>{aExpr});
}
}
template<typename ExprType>
Expr Expression::binaryOperatorSimplify(
const function<Expr(const Expr&, double)>& aConstantCbk,
const function<Expr(const Expr&, double)>& bConstantCbk) const {
auto aExpr = inputs_[0]->simplify();
auto bExpr = inputs_[1]->simplify();
const auto aClass = aExpr->expressionClass();
const auto bClass = bExpr->expressionClass();
const auto aVal = aExpr->value();
const auto bVal = bExpr->value();
const bool bothConstant =
(aClass == ExprClass::Constant) &&
(bClass == ExprClass::Constant);
const bool neitherConstant =
(aClass != ExprClass::Constant) &&
(bClass != ExprClass::Constant);
if(bothConstant) {
return make_expr<Constant>(this->value());
} else if(neitherConstant) {
return make_expr<ExprType>(
initializer_list<Expr>{aExpr, bExpr});
} else {
return bClass == ExprClass::Constant ?
bConstantCbk(aExpr, bVal) :
aConstantCbk(bExpr, aVal);
}
}
Expr cos(const Expr&);
Expr sin(const Expr&);
Expr tan(const Expr&);
class Cosine: public Function
{
MK_FUNCTION_CONSTRUCTOR(Cosine)
public:
virtual double value() const {
return cos(inputs_[0]->value());
}
virtual operator string() const {
return fnOperatorToString("cos");
}
virtual Expr fnDerivative(const Expr& target) const;
virtual Expr simplify() const {
return unaryOperatorSimplify<Cosine>();
}
};
Expr cos(const Expr& val) {
return make_expr<Cosine>(initializer_list<Expr>{val});
}
class Sine: public Function
{
MK_FUNCTION_CONSTRUCTOR(Sine)
public:
virtual double value() const {
return sin(inputs_[0]->value());
}
virtual operator string() const {
return fnOperatorToString("sin");
}
virtual Expr fnDerivative(const Expr& target) const {
return cos(inputs_[0]);
}
virtual Expr simplify() const {
return unaryOperatorSimplify<Sine>();
}
};
Expr sin(const Expr& val) {
return make_expr<Sine>(initializer_list<Expr>{val});
}
class Tangent: public Function
{
MK_FUNCTION_CONSTRUCTOR(Tangent)
public:
virtual double value() const {
return tan(inputs_[0]->value());
}
virtual operator string() const {
return fnOperatorToString("tan");
}
virtual Expr fnDerivative(const Expr& target) const {
return 1.0/(cos(inputs_[0]) * cos(inputs_[0]));
}
virtual Expr simplify() const {
return unaryOperatorSimplify<Tangent>();
}
};
Expr tan(const Expr& val) {
return make_expr<Tangent>(initializer_list<Expr>{val});
}
Expr log(const Expr& val);
Expr pow(const Expr& a, const Expr& b);
class LogNatural: public Function
{
MK_FUNCTION_CONSTRUCTOR(LogNatural)
public:
virtual double value() const {
return log(inputs_[0]->value());
}
virtual operator string() const {
return fnOperatorToString("log");
}
virtual Expr fnDerivative(const Expr& target) const {
return 1.0 / inputs_[0];
}
virtual Expr simplify() const {
return unaryOperatorSimplify<LogNatural>();
}
};
Expr log(const Expr& val) {
return make_expr<LogNatural>(initializer_list<Expr>{val});
}
class Power: public Function
{
MK_FUNCTION_CONSTRUCTOR(Power)
public:
virtual double value() const {
return pow(inputs_[0]->value(), inputs_[1]->value());
}
virtual operator string() const {
return fnOperatorToString("pow");
}
virtual Expr fnDerivative(const Expr& target) const {
if(target == inputs_[0]) {
// d x^k/dx
return inputs_[1] * pow(inputs_[0], inputs_[1] - 1.0);
} else {
// d k^x/dx
return pow(inputs_[0], inputs_[1]) * log(inputs_[0]);
}
}
virtual Expr simplify() const {
return binaryOperatorSimplify<Power>(
[](const Expr& b, double a) -> Expr {
if(a == 0) return 0.0;
if(a == 1) return 1.0;
return pow(make_expr<Constant>(a), b);
},
[](const Expr& a, double b) -> Expr {
if(b == 0) return 1.0;
if(b == 1) return a;
return pow(a, make_expr<Constant>(b));
}
);
}
};
Expr pow(const Expr& a, const Expr& b) {
return make_expr<Power>(initializer_list<Expr>{a, b});
}
class Sqrt: public Function
{
MK_FUNCTION_CONSTRUCTOR(Sqrt)
public:
virtual double value() const {
return sqrt(inputs_[0]->value());
}
virtual operator string() const {
return fnOperatorToString("sqrt");
}
virtual Expr fnDerivative(const Expr& target) const {
return 0.5 * pow(target, -0.5);
}
virtual Expr simplify() const {
return unaryOperatorSimplify<Sqrt>();
}
};
Expr sqrt(const Expr& a) {
return make_expr<Sqrt>(initializer_list<Expr>{a});
}
string Expression::binaryOperatorToString(const string& opString,
bool parenthesize) const {
stringstream res;
const string openPar = parenthesize ? "(" : "";
const string closePar = parenthesize ? ")" : "";
res << openPar << static_cast<string>(*inputs_[0])
<< opString
<< static_cast<string>(*inputs_[1]) << closePar;
return res.str();
}
string Expression::unaryOperatorToString(const string& opString,
bool parenthesize) const {
stringstream res;
const string openPar = parenthesize ? "(" : "";
const string closePar = parenthesize ? ")" : "";
res << opString << openPar
<< static_cast<string>(*inputs_[0]) << closePar;
return res.str();
}
Expr Cosine::fnDerivative(const Expr& target) const {
return -sin(inputs_[0]);
}
Expr Variable::derivative(const Expr& expr) const {
return expr.get() == this ? 1.0 : 0.0;
}
ostream& operator<<(ostream& out, const Expr& expr) {
out << static_cast<string>(*expr);
return out;
}
Expr::Expr(double value): shared_ptr<Expression>(new Constant(value)) { }
Expr::Expr(int value): shared_ptr<Expression>(new Constant(value)) { }
Expr::Expr(double value, string name): shared_ptr<Expression>(new Variable(value, name)) { }
int main() {
Expr x = make_expr<Variable>(3, "x");
Expr y = make_expr<Variable>(3, "y");
auto expr = pow(log(x), cos(y));
cout << expr->value() << endl;
cout << expr << endl;
cout << expr->derivative(y)->value() << endl;
cout << expr->derivative(y) << endl;
cout << expr->derivative(y)->simplify() << endl;
cout << sqrt(x) << endl;
return 0;
}