1 //
2 // CRF++ -- Yet Another CRF toolkit
3 //
4 // $Id: node.h 1595 2007-02-24 10:18:32Z taku $;
5 //
6 // Copyright(C) 2005-2007 Taku Kudo <taku@chasen.org>
7 //
8 #ifndef CRFPP_NODE_H_
9 #define CRFPP_NODE_H_
10
11 #include <vector>
12 #include <cmath>
13 #include "path.h"
14 #include "common.h"
15
16 #define LOG2 0.69314718055
17 #define MINUS_LOG_EPSILON 50
18
19 namespace CRFPP {
20 // log(exp(x) + exp(y));
21 // this can be used recursivly
22 // e.g., log(exp(log(exp(x) + exp(y))) + exp(z)) =
23 // log(exp (x) + exp(y) + exp(z))
logsumexp(double x,double y,bool flg)24 inline double logsumexp(double x, double y, bool flg) {
25 if (flg) return y; // init mode
26 const double vmin = std::min(x, y);
27 const double vmax = std::max(x, y);
28 if (vmax > vmin + MINUS_LOG_EPSILON) {
29 return vmax;
30 } else {
31 return vmax + std::log(std::exp(vmin - vmax) + 1.0);
32 }
33 }
34
35 struct Path;
36
37 struct Node {
38 unsigned int x;
39 unsigned short int y;
40 double alpha;
41 double beta;
42 double cost;
43 double bestCost;
44 Node *prev;
45 const int *fvector;
46 std::vector<Path *> lpath;
47 std::vector<Path *> rpath;
48
49 void calcAlpha();
50 void calcBeta();
51 void calcExpectation(double *expected, double, size_t) const;
52
clearNode53 void clear() {
54 x = y = 0;
55 alpha = beta = cost = 0.0;
56 prev = 0;
57 fvector = 0;
58 lpath.clear();
59 rpath.clear();
60 }
61
shrinkNode62 void shrink() {
63 std::vector<Path *>(lpath).swap(lpath);
64 std::vector<Path *>(rpath).swap(rpath);
65 }
66
NodeNode67 Node() : x(0), y(0), alpha(0.0), beta(0.0),
68 cost(0.0), bestCost(0.0), prev(0), fvector(0) {}
69 };
70 }
71 #endif
72