## [e23e50]: src / modules / bugs / samplers / ShiftedCount.cc  Maximize  Restore  History

### 96 lines (78 with data), 2.3 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``` ```#include #include "ShiftedCount.h" #include #include #include #include using std::vector; using std::string; namespace jags { namespace bugs { ShiftedCount::ShiftedCount(SingletonGraphView const *gv) : ConjugateMethod(gv) { } bool ShiftedCount::canSample(StochasticNode *snode, Graph const &graph) { switch(getDist(snode)) { case POIS: case BIN: case NEGBIN: break; default: return false; } if (isBounded(snode)) return false; SingletonGraphView gv(snode, graph); // There should be no deterministic children if (!gv.deterministicChildren().empty()) return false; // Check stochastic children: Must have single child node ... vector const &child_nodes = gv.stochasticChildren(); if (child_nodes.size() != 1) return false; // ... with a Binomial(p, N) distribution such that N is the // sampled node and p does not depend on sampled node StochasticNode const *cnode = child_nodes.front(); if (getDist(cnode) != BIN) return false; if (isBounded(cnode)) return false; if (cnode->parents()[1] != snode) return false; if (cnode->parents()[0] == snode) return false; return true; } void ShiftedCount::update(unsigned int chain, RNG *rng) const { StochasticNode const* snode = _gv->node(); StochasticNode * cnode = _gv->stochasticChildren().front(); double y = *cnode->value(chain); //Child value // Prior rate (Poisson) or probability (Binomial) double lambda = *snode->parents()[0]->value(chain); // Binomial probability of child double pi = *cnode->parents()[0]->value(chain); double xnew = y; double N = 0; switch(_target_dist) { case POIS: lambda = (1 - pi) * lambda; xnew += rpois(lambda, rng); break; case BIN: N = *snode->parents()[1]->value(chain); lambda = (1 - pi) * lambda / ((1 - pi) * lambda + (1 - lambda)); xnew += rbinom(N - y, lambda, rng); break; case NEGBIN: N = *snode->parents()[1]->value(chain); lambda = (1 - pi) * lambda + pi; xnew += rnbinom(N - y, lambda, rng); break; default: throwLogicError("Invalid distribution in ShiftedCount"); } _gv->setValue(&xnew, 1, chain); } }} ```