-
Notifications
You must be signed in to change notification settings - Fork 3
/
had.h
559 lines (502 loc) · 16.3 KB
/
had.h
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
/**
HAD is a single header C++ reverse-mode automatic differentiation library using operator overloading, with focus on
second-order derivatives (Hessian).
It implements the edge_pushing algorithm (see "Hessian Matrices via Automatic Differentiation",
Gower and Mello 2010) to efficiently compute the second derivatives.
See https://github.com/BachiLi/had for more details.
Author: Tzu-Mao Li
The MIT License (MIT)
Copyright (c) 2015 Tzu-Mao Li
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
**/
#ifndef HAD_H__
#define HAD_H__
#include <vector>
#include <cmath>
#ifdef WIN32
#define threadDefine thread_local
#endif
#ifdef __unix
#define USE_AATREE
#define threadDefine __thread
#endif
#include <vector>
#include <cmath>
#include <algorithm>
#ifndef M_PI
#define M_PI std::acos(-1)
#endif
namespace had {
// Change the following line if you want to use single precision floats
typedef double Real;
typedef unsigned int VertexId;
struct ADGraph;
struct AReal;
extern threadDefine ADGraph* g_ADGraph;
// Declare this in your .cpp source
#define DECLARE_ADGRAPH() namespace had { threadDefine ADGraph* g_ADGraph = 0; }
AReal NewAReal(const Real val);
struct AReal {
AReal() {}
AReal(const Real val) {
*this = NewAReal(val);
}
AReal(const Real val, const VertexId varId) :
val(val), varId(varId) {}
Real val;
VertexId varId;
};
struct ADEdge {
ADEdge() {}
ADEdge(const VertexId to, const Real w = Real(0.0)) :
to(to), w(w) {}
VertexId to;
Real w;
};
// We assume there is at most 2 outgoing edges from this vertex
struct ADVertex {
ADVertex(const VertexId newId) {
e1 = e2 = ADEdge(newId);
w = soW = Real(0.0);
}
// If ei.to == the id of this vertex, then the edge does not exist
ADEdge e1, e2;
// first-order weight
Real w;
// second-order weights
// for vertex with single outgoing edge,
// soW represents the second-order weight of the conntecting vertex (d^2f/dx^2)
// for vertex with two outgoing edges,
// soW represents the second-order weight between the conntecting vertices (d^2f/dxdy)
// the system assumes d^2f/dx^2 & d^2f/dy^2 are both zero in the two outgoing edges case to save memory
Real soW;
};
struct BTNode {
BTNode() {}
BTNode(const VertexId key, const Real val) : key(key), val(val) {
left = right = - 1;
#ifdef USE_AATREE
level = 1;
#endif
}
VertexId key;
Real val;
int left;
int right;
#ifdef USE_AATREE
int level;
#endif
};
struct BTree {
BTree() {
nodes.reserve(32);
root = 0;
}
#ifdef USE_AATREE
inline void Skew() {
if (nodes.size() == 0 ||
nodes[root].left == -1) {
return;
}
while (nodes[nodes[root].left].level == nodes[root].level) {
int l = nodes[root].left;
nodes[root].left = nodes[l].right;
nodes[l].right = root;
root = l;
}
}
inline void Split() {
if (nodes.size() == 0 ||
nodes[root].right == -1 ||
nodes[nodes[root].right].right == -1) {
return;
}
while (nodes[root].level == nodes[nodes[nodes[root].right].right].level) {
int r = nodes[root].right;
nodes[root].right = nodes[r].left;
nodes[r].left = root;
nodes[r].level++;
root = r;
}
}
#endif
inline void Insert(const VertexId key, const Real val) {
int index = root;
if (nodes.size() > 0) {
int *lastEdge;
do {
if (key == nodes[index].key) {
nodes[index].val += val;
return;
}
lastEdge = &(nodes[index].left) + (key > nodes[index].key);
index = *lastEdge;
} while (index >= 0);
*lastEdge = nodes.size();
}
nodes.push_back(BTNode(key, val));
#ifdef USE_AATREE
Skew();
Split();
#endif
}
inline Real Query(const VertexId key) {
int index = root;
while (index >= 0 && index < (int)nodes.size()) {
if (key == nodes[index].key) {
return nodes[index].val;
} else if (key < nodes[index].key) {
index = nodes[index].left;
} else {
index = nodes[index].right;
}
}
return Real(0.0);
}
inline void Clear() {
nodes.clear();
root = 0;
}
std::vector<BTNode> nodes;
int root;
};
struct ADGraph {
ADGraph() {
g_ADGraph = this;
}
inline void Clear() {
vertices.clear();
soEdges.clear();
selfSoEdges.clear();
}
std::vector<ADVertex> vertices;
std::vector<BTree> soEdges;
std::vector<Real> selfSoEdges;
};
inline AReal NewAReal(const Real val) {
std::vector<ADVertex> &vertices = g_ADGraph->vertices;
VertexId newId = vertices.size();
vertices.push_back(ADVertex(newId));
return AReal(val, newId);
}
inline void AddEdge(const AReal &c, const AReal &p,
const Real w, const Real soW) {
ADVertex &v = g_ADGraph->vertices[c.varId];
v.e1 = ADEdge(p.varId, w);
v.soW = soW;
}
inline void AddEdge(const AReal &c,
const AReal &p1, const AReal &p2,
const Real w1, const Real w2,
const Real soW) {
ADVertex &v = g_ADGraph->vertices[c.varId];
v.e1 = ADEdge(p1.varId, w1);
v.e2 = ADEdge(p2.varId, w2);
v.soW = soW;
}
////////////////////// Addition ///////////////////////////
inline AReal operator+(const AReal &l, const AReal &r) {
AReal ret = NewAReal(l.val + r.val);
AddEdge(ret, l, r, Real(1.0), Real(1.0), Real(0.0));
return ret;
}
inline AReal operator+(const AReal &l, const Real r) {
AReal ret = NewAReal(l.val + r);
AddEdge(ret, l, Real(1.0), Real(0.0));
return ret;
}
inline AReal operator+(const Real l, const AReal &r) {
return r + l;
}
inline AReal& operator+=(AReal &l, const AReal &r) {
return (l = l + r);
}
inline AReal& operator+=(AReal &l, const Real r) {
return (l = l + r);
}
///////////////////////////////////////////////////////////
////////////////// Subtraction ////////////////////////////
inline AReal operator-(const AReal &l, const AReal &r) {
AReal ret = NewAReal(l.val - r.val);
AddEdge(ret, l, r, Real(1.0), -Real(1.0), Real(0.0));
return ret;
}
inline AReal operator-(const AReal &l, const Real r) {
AReal ret = NewAReal(l.val - r);
AddEdge(ret, l, Real(1.0), Real(0.0));
return ret;
}
inline AReal operator-(const Real l, const AReal &r) {
AReal ret = NewAReal(l - r.val);
AddEdge(ret, r, Real(-1.0), Real(0.0));
return ret;
}
inline AReal& operator-=(AReal &l, const AReal &r) {
return (l = l - r);
}
inline AReal& operator-=(AReal &l, const Real r) {
return (l = l - r);
}
inline AReal operator-(const AReal &x) {
AReal ret = NewAReal(-x.val);
AddEdge(ret, x, Real(-1.0), Real(0.0));
return ret;
}
///////////////////////////////////////////////////////////
////////////////// Multiplication /////////////////////////
inline AReal operator*(const AReal &l, const AReal &r) {
AReal ret = NewAReal(l.val * r.val);
AddEdge(ret, l, r, r.val, l.val, Real(1.0));
return ret;
}
inline AReal operator*(const AReal &l, const Real r) {
AReal ret = NewAReal(l.val * r);
AddEdge(ret, l, r, Real(0.0));
return ret;
}
inline AReal operator*(const Real l, const AReal &r) {
return r * l;
}
inline AReal& operator*=(AReal &l, const AReal &r) {
return (l = l * r);
}
inline AReal& operator*=(AReal &l, const Real r) {
return (l = l * r);
}
///////////////////////////////////////////////////////////
////////////////// Inversion //////////////////////////////
inline AReal Inv(const AReal &x) {
Real invX = Real(1.0) / x.val;
Real invXSq = invX * invX;
Real invXCu = invXSq * invX;
AReal ret = NewAReal(invX);
AddEdge(ret, x, -invXSq, Real(2.0) * invXCu);
return ret;
}
inline Real Inv(const Real x) {
return Real(1.0) / x;
}
///////////////////////////////////////////////////////////
////////////////// Division ///////////////////////////////
inline AReal operator/(const AReal &l, const AReal &r) {
return l * Inv(r);
}
inline AReal operator/(const AReal &l, const Real r) {
return l * Inv(r);
}
inline AReal operator/(const Real l, const AReal &r) {
return l * Inv(r);
}
inline AReal& operator/=(AReal &l, const AReal &r) {
return (l = l / r);
}
inline AReal& operator/=(AReal &l, const Real r) {
return (l = l / r);
}
///////////////////////////////////////////////////////////
////////////////// Comparisons ////////////////////////////
inline bool operator<(const AReal &l, const AReal &r) {
return l.val < r.val;
}
inline bool operator<=(const AReal &l, const AReal &r) {
return l.val <= r.val;
}
inline bool operator>(const AReal &l, const AReal &r) {
return l.val > r.val;
}
inline bool operator>=(const AReal &l, const AReal &r) {
return l.val >= r.val;
}
inline bool operator==(const AReal &l, const AReal &r) {
return l.val == r.val;
}
///////////////////////////////////////////////////////////
//////////////// Misc functions ///////////////////////////
inline Real square(const Real x) {
return x * x;
}
inline AReal square(const AReal &x) {
Real sqX = x.val * x.val;
AReal ret = NewAReal(sqX);
AddEdge(ret, x, Real(2.0) * x.val, Real(0.0));
return ret;
}
inline AReal sqrt(const AReal &x) {
Real sqrtX = std::sqrt(x.val);
Real invSqrtX = Real(1.0) / sqrtX;
AReal ret = NewAReal(sqrtX);
AddEdge(ret, x, Real(0.5) * invSqrtX, - Real(0.25) * invSqrtX / x.val);
return ret;
}
inline AReal pow(const AReal &x, const Real a) {
Real powX = std::pow(x.val, a);
AReal ret = NewAReal(powX);
AddEdge(ret, x, a * std::pow(x.val, a - Real(1.0)),
a * (a - Real(1.0)) * std::pow(x.val, a - Real(2.0)));
return ret;
}
inline AReal exp(const AReal &x) {
Real expX = std::exp(x.val);
AReal ret = NewAReal(expX);
AddEdge(ret, x, expX, expX);
return ret;
}
inline AReal log(const AReal &x) {
Real logX = std::log(x.val);
AReal ret = NewAReal(logX);
Real invX = Real(1.0) / x.val;
AddEdge(ret, x, invX, - invX * invX);
return ret;
}
inline AReal sin(const AReal &x) {
Real sinX = std::sin(x.val);
AReal ret = NewAReal(sinX);
AddEdge(ret, x, std::cos(x.val), -sinX);
return ret;
}
inline AReal cos(const AReal &x) {
Real cosX = std::cos(x.val);
AReal ret = NewAReal(cosX);
AddEdge(ret, x, -std::sin(x.val), -cosX);
return ret;
}
inline AReal tan(const AReal &x) {
Real tanX = std::tan(x.val);
Real secX = Real(1.0) / std::cos(x.val);
Real sec2X = secX * secX;
AReal ret = NewAReal(tanX);
AddEdge(ret, x, sec2X, Real(2.0) * tanX * sec2X);
return ret;
}
inline AReal asin(const AReal &x) {
Real asinX = std::asin(x.val);
AReal ret = NewAReal(asinX);
Real tmp = Real(1.0) / (Real(1.0) - x.val * x.val);
Real sqrtTmp = std::sqrt(tmp);
AddEdge(ret, x, sqrtTmp, x.val * sqrtTmp * tmp);
return ret;
}
inline AReal acos(const AReal &x) {
Real acosX = std::acos(x.val);
AReal ret = NewAReal(acosX);
Real tmp = Real(1.0) / (Real(1.0) - x.val * x.val);
Real negSqrtTmp = -std::sqrt(tmp);
AddEdge(ret, x, negSqrtTmp, x.val * negSqrtTmp * tmp);
return ret;
}
///////////////////////////////////////////////////////////
inline void SetAdjoint(const AReal &v, const Real adj) {
g_ADGraph->vertices[v.varId].w = adj;
}
inline Real GetAdjoint(const AReal &v) {
return g_ADGraph->vertices[v.varId].w;
}
inline Real GetAdjoint(const AReal &i, const AReal &j) {
if (i.varId == j.varId) {
return g_ADGraph->selfSoEdges[i.varId];
} else {
return g_ADGraph->soEdges[std::max(i.varId, j.varId)].Query(std::min(i.varId, j.varId));
}
}
inline VertexId SingleEdgePropagate(VertexId x, Real &a) {
bool cont = g_ADGraph->vertices[x].e1.to != x &&
g_ADGraph->vertices[x].e2.to == x;
while (cont) {
a *= g_ADGraph->vertices[x].e1.w;
x = g_ADGraph->vertices[x].e1.to;
cont = g_ADGraph->vertices[x].e1.to != x &&
g_ADGraph->vertices[x].e2.to == x;
}
return x;
}
inline void PushEdge(const ADEdge &foEdge, const ADEdge &soEdge) {
if (foEdge.to == soEdge.to) {
g_ADGraph->selfSoEdges[foEdge.to] += Real(2.0) * foEdge.w * soEdge.w;
} else {
g_ADGraph->soEdges[std::max(foEdge.to, soEdge.to)].Insert(
std::min(foEdge.to, soEdge.to), foEdge.w * soEdge.w);
}
}
inline void PropagateAdjoint() {
if (g_ADGraph->vertices.size() > g_ADGraph->soEdges.size()) {
g_ADGraph->soEdges.resize(g_ADGraph->vertices.size());
} else {
for (int i = 0; i < (int)g_ADGraph->soEdges.size(); i++) {
g_ADGraph->soEdges[i].Clear();
}
}
g_ADGraph->selfSoEdges.resize(g_ADGraph->vertices.size(), Real(0.0));
// Any chance for SSE/AVX parallism?
for (VertexId vid = g_ADGraph->vertices.size() - 1; vid > 0; vid--) {
ADVertex &vertex = g_ADGraph->vertices[vid];
ADEdge &e1 = vertex.e1;
ADEdge &e2 = vertex.e2;
if (e1.to == vid) {
continue;
}
// Pushing
BTree &btree = g_ADGraph->soEdges[vid];
std::vector<BTNode>::iterator it;
if (e2.to == vid) {
for (it = btree.nodes.begin(); it != btree.nodes.end(); it++) {
ADEdge soEdge(it->key, it->val);
PushEdge(e1, soEdge);
}
} else {
for (it = btree.nodes.begin(); it != btree.nodes.end(); it++) {
ADEdge soEdge(it->key, it->val);
PushEdge(e1, soEdge);
PushEdge(e2, soEdge);
}
}
if (g_ADGraph->selfSoEdges[vid] != Real(0.0)) {
g_ADGraph->selfSoEdges[e1.to] += e1.w * e1.w * g_ADGraph->selfSoEdges[vid];
if (e2.to != vid) {
g_ADGraph->selfSoEdges[e2.to] += e2.w * e2.w * g_ADGraph->selfSoEdges[vid];
if (e1.to == e2.to) {
g_ADGraph->selfSoEdges[e2.to] += Real(2.0) * e1.w * e2.w * g_ADGraph->selfSoEdges[vid];
} else {
g_ADGraph->soEdges[std::max(e1.to, e2.to)].Insert(std::min(e1.to, e2.to),
e1.w * e2.w * g_ADGraph->selfSoEdges[vid]);
}
}
}
// release memory?
Real a = vertex.w;
if (a != Real(0.0)) {
// Creating
if (vertex.soW != Real(0.0)) {
if (e2.to == vid) { // single-edge
g_ADGraph->selfSoEdges[e1.to] += a * vertex.soW;
} else if (e1.to == e2.to) {
g_ADGraph->selfSoEdges[e1.to] += Real(2.0) * a * vertex.soW;
} else {
g_ADGraph->soEdges[std::max(e1.to, e2.to)].Insert(std::min(e1.to, e2.to),
a * vertex.soW);
}
}
// Adjoint
vertex.w = Real(0.0);
g_ADGraph->vertices[e1.to].w += a * e1.w;
if (e2.to != vid) {
g_ADGraph->vertices[e2.to].w += a * e2.w;
}
}
}
}
} //namespace had
#endif // HAD_H__