[1991be]: src / lib / model / Model.cc Maximize Restore History

Download this file

Model.cc    695 lines (608 with data), 17.4 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
#include <config.h>
#include <model/Model.h>
#include <model/MonitorFactory.h>
#include <model/Monitor.h>
#include <sampler/Sampler.h>
#include <sampler/SamplerFactory.h>
#include <rng/RNGFactory.h>
#include <rng/RNG.h>
#include <graph/GraphMarks.h>
#include <graph/StochasticNode.h>
#include <graph/DeterministicNode.h>
#include <graph/ConstantNode.h>
#include <graph/NodeError.h>
#include <graph/Node.h>
#include <util/nainf.h>
#include <fstream>
#include <sstream>
#include <set>
#include <stdexcept>
#include <string>
#include <algorithm>
#include <functional>
#include <map>
using std::map;
using std::pair;
using std::binary_function;
using std::sort;
using std::vector;
using std::list;
using std::set;
using std::ofstream;
using std::logic_error;
using std::runtime_error;
using std::string;
using std::ostringstream;
using std::stable_sort;
using std::copy;
using std::min;
using std::max;
using std::reverse;
namespace jags {
Model::Model(unsigned int nchain)
: _samplers(0), _nchain(nchain), _rng(nchain, 0), _iteration(0),
_is_initialized(false), _adapt(false), _data_gen(false), _node_index(1)
{
}
Model::~Model()
{
while(!_samplers.empty()) {
Sampler *sampler0 = _samplers.back();
delete sampler0;
_samplers.pop_back();
}
for (list<Monitor*>::const_iterator p = _default_monitors.begin();
p != _default_monitors.end(); ++p)
{
delete *p;
}
//Delete nodes in reverse sampling order
vector<Node*> managed_nodes;
_graph.getSortedNodes(managed_nodes);
while(!managed_nodes.empty())
{
Node *node = managed_nodes.back();
delete node;
managed_nodes.pop_back();
}
}
Graph const &Model::graph()
{
return _graph;
}
bool Model::isInitialized()
{
return _is_initialized;
}
void Model::chooseRNGs()
{
/* Assign default RNG objects for any chain that does not
currently have one */
//Count number of unassigned RNGs
unsigned int n = 0;
for (unsigned int i = 0; i < _nchain; ++i) {
if (_rng[i] == 0)
++n;
}
vector<RNG*> new_rngs;
list<pair<RNGFactory*, bool> >::const_iterator p;
for (p = rngFactories().begin(); p != rngFactories().end(); ++p) {
if (p->second) {
vector<RNG*> rngs = p->first->makeRNGs(n);
if (rngs.size() > n) {
throw logic_error("Too many rngs produced by RNG factory");
}
else {
n -= rngs.size();
}
for (unsigned int j = 0; j < rngs.size(); ++j) {
new_rngs.push_back(rngs[j]);
}
if (n == 0)
break;
}
}
if (n > 0) {
throw runtime_error("Cannot generate sufficient RNGs");
}
else {
unsigned int j = 0;
for (unsigned int i = 0; i < _nchain; ++i) {
if (_rng[i] == 0) {
_rng[i] = new_rngs[j++];
}
}
}
}
void Model::initialize(bool datagen)
{
if (_is_initialized)
throw logic_error("Model already initialized");
if (!_graph.isClosed())
throw runtime_error("Graph not closed");
// Choose random number generators
chooseRNGs();
//Initialize nodes
initializeNodes();
// Check initial values of all stochastic nodes
// Note that we need to do this before choosing samplers.
if (!datagen) {
for (unsigned int ch = 0; ch < _nchain; ++ch) {
for (unsigned int i = 0; i < _stochastic_nodes.size(); ++i) {
StochasticNode const *snode = _stochastic_nodes[i];
double ld = snode->logDensity(ch, PDF_PRIOR);
if (jags_isnan(ld)) {
string msg = "Error calculating log density at initial values";
throw NodeError(snode, msg);
}
else if (ld == JAGS_NEGINF || (!jags_finite(ld) && ld < 0)) {
string msg;
if (isObserved(snode)) {
msg = "Observed node";
}
else {
msg = "Unobserved node";
}
msg.append(" inconsistent with ");
bool fixed_parents = true;
for (unsigned int j = 0; j < snode->parents().size(); ++j) {
if (!snode->parents()[j]->isFixed()) {
fixed_parents = false;
break;
}
}
if (fixed_parents) {
msg.append("fixed parents");
}
else {
msg.append("parents");
}
msg.append(" at initialization.\n");
msg.append("Try setting appropriate initial values.");
throw NodeError(snode, msg);
}
}
}
}
// Choose Samplers
chooseSamplers();
if (datagen) {
Graph egraph;
for (set<Node *>::const_iterator p = _extra_nodes.begin();
p != _extra_nodes.end(); ++p)
{
egraph.insert(*p);
}
_sampled_extra.clear();
egraph.getSortedNodes(_sampled_extra);
_data_gen = true;
}
// Switch to adaptive mode if we find an adaptive sampler
for (unsigned int i = 0; i < _samplers.size(); ++i) {
if (_samplers[i]->isAdaptive()) {
_adapt = true;
break;
}
}
_is_initialized = true;
}
void Model::initializeNodes()
{
//Get nodes in forward-sampling order
vector<Node*> sorted_nodes;
_graph.getSortedNodes(sorted_nodes);
vector<Node*>::const_iterator i;
for (i = sorted_nodes.begin(); i != sorted_nodes.end(); ++i) {
Node *node = *i;
for (unsigned int n = 0; n < _nchain; ++n) {
if (!node->checkParentValues(n)) {
throw NodeError(node, "Invalid parent values");
}
if (!node->initialize(n)) {
throw NodeError(node, "Initialization failure");
}
}
}
}
struct less_sampler {
/*
Comparison operator for Samplers which sorts them in
order according to the supplied sampler map
*/
map<Sampler const*, unsigned int> const & _sampler_map;
less_sampler(map<Sampler const*, unsigned int> const &sampler_map)
: _sampler_map(sampler_map) {};
bool operator()(Sampler const *x, Sampler const *y) const {
return _sampler_map.find(x)->second < _sampler_map.find(y)->second;
};
};
void Model::chooseSamplers()
{
/*
* Selects samplers. Samplers are selected by traversing the list
* of SamplerFactories in order. If there are any informative
* stochastic nodes left without samplers after all factories have
* been tried, then a runtime error is thrown
*
* @see Model#samplerFactories
*/
GraphMarks marks(_graph);
Graph sample_graph;
// Add observed stochastic nodes to the sample graph and mark
// the informative nodes
vector<Node const*> informative;
vector<StochasticNode*>::const_iterator p;
for (p = _stochastic_nodes.begin(); p != _stochastic_nodes.end(); ++p) {
if (isObserved(*p)) {
sample_graph.insert(*p);
informative.push_back(*p);
}
}
marks.markAncestors(informative, 1);
for (p = _stochastic_nodes.begin(); p != _stochastic_nodes.end(); ++p) {
if (isObserved(*p)) {
marks.mark(*p, 2);
}
}
//Triage on marked nodes. We do this twice: once for stochastic
//nodes and once for all nodes.
set<StochasticNode*> sset;
for(p = _stochastic_nodes.begin(); p != _stochastic_nodes.end(); ++p) {
switch(marks.mark(*p)) {
case 0:
_extra_nodes.insert(*p);
break;
case 1:
sset.insert(*p);
sample_graph.insert(*p);
break;
case 2:
sample_graph.insert(*p);
break;
default:
throw logic_error("Invalid mark");
}
}
set<Node*>::const_iterator j;
for (j = _graph.begin(); j != _graph.end(); ++j) {
switch(marks.mark(*j)) {
case 0:
_extra_nodes.insert(*j);
break;
case 1: case 2:
sample_graph.insert(*j);
break;
}
}
// Traverse the list of samplers, selecting nodes that can be sampled
list<pair<SamplerFactory *, bool> > const &sf = samplerFactories();
for(list<pair<SamplerFactory *, bool> >::const_iterator q = sf.begin();
q != sf.end(); ++q)
{
if (q->second) {
vector<Sampler*> svec = q->first->makeSamplers(sset, sample_graph);
while (!svec.empty()) {
for (unsigned int i = 0; i < svec.size(); ++i) {
vector<StochasticNode*> const &nodes = svec[i]->nodes();
for (unsigned int j = 0; j < nodes.size(); ++j) {
sset.erase(nodes[j]);
}
_samplers.push_back(svec[i]);
}
svec = q->first->makeSamplers(sset, sample_graph);
}
}
}
// Make sure we found a sampler for all the nodes
if (!sset.empty()) {
throw NodeError(*sset.begin(),
"Unable to find appropriate sampler");
}
// Samplers are sorted in reverse sampling order: i.e. samplers
// that are closer to the data are updated before samplers that
// only affect higher-order parameters
// Create a map associating each stochastic node with its index
// in the vector _stochastic_nodes, corresponding to the order
// in which they were added to the model
map<StochasticNode const *, unsigned int> snode_map;
for (unsigned int i = 0; i < _stochastic_nodes.size(); ++i) {
snode_map[_stochastic_nodes[i]] = i;
}
// Create a map associating each sampler with the minimal index
// of its sampled nodes.
map<Sampler const *, unsigned int> sampler_map;
for (unsigned int i = 0; i < _samplers.size(); ++i) {
unsigned int min_index = _stochastic_nodes.size();
vector<StochasticNode*> const &snodes = _samplers[i]->nodes();
for (unsigned int j = 0; j < snodes.size(); ++j) {
map<StochasticNode const*, unsigned int>::const_iterator p
= snode_map.find(snodes[j]);
if (p == snode_map.end()) {
throw logic_error("Invalid stochastic node map");
}
if (p->second < min_index) {
min_index = p->second;
}
}
sampler_map[_samplers[i]] = min_index;
}
stable_sort(_samplers.begin(), _samplers.end(), less_sampler(sampler_map));
reverse(_samplers.begin(), _samplers.end());
}
void Model::update(unsigned int niter)
{
if (!_is_initialized) {
throw logic_error("Attempt to update uninitialized model");
}
for (unsigned int iter = 0; iter < niter; ++iter) {
for (vector<Sampler*>::iterator i = _samplers.begin();
i != _samplers.end(); ++i)
{
(*i)->update(_rng);
}
for (unsigned int n = 0; n < _nchain; ++n) {
for (vector<Node*>::const_iterator k = _sampled_extra.begin();
k != _sampled_extra.end(); ++k)
{
if (!(*k)->checkParentValues(n)) {
throw NodeError(*k, "Invalid parent values");
}
(*k)->randomSample(_rng[n], n);
}
}
_iteration++;
for (list<MonitorControl>::iterator k = _monitors.begin();
k != _monitors.end(); k++)
{
k->update(_iteration);
}
}
}
unsigned int Model::iteration() const
{
return _iteration;
}
void Model::adaptOff()
{
for (vector<Sampler*>::const_iterator p = _samplers.begin();
p != _samplers.end(); ++p)
{
(*p)->adaptOff();
}
_adapt = false;
}
bool Model::checkAdaptation() const
{
for (vector<Sampler*>::const_iterator p = _samplers.begin();
p != _samplers.end(); ++p)
{
if (!(*p)->checkAdaptation()) return false;
}
return true;
}
bool Model::isAdapting() const
{
return _adapt;
}
void Model::setSampledExtra()
{
/* If a mode is not a data generating model, uninformative nodes
do not need to be updated, unless they have a descendant that
is being monitored. This function finds those nodes and adds
them to the vector _sampled_extra.
*/
if (_data_gen) {
// In a data generating model, all uninformative nodes are
// sampled, so nothing to be done
return;
}
// Recalculate the vector of uninformative nodes that need sampling
//Insert extra nodes into a new graph
Graph egraph;
for (set<Node *>::const_iterator p = _extra_nodes.begin();
p != _extra_nodes.end(); ++p)
{
egraph.insert(*p);
}
//Mark the ancestors of all monitored nodes in this graph
GraphMarks emarks(egraph);
for (list<MonitorControl>::const_iterator p = _monitors.begin();
p != _monitors.end(); ++p)
{
for (unsigned int i = 0; i < p->monitor()->nodes().size(); ++i) {
Node const *node = p->monitor()->nodes()[i];
if (egraph.contains(node)) {
emarks.mark(node, 1);
//FIXME: call once
emarks.markAncestors(vector<Node const *>(1, node), 1);
}
}
}
//Remove unmarked nodes from graph
for (set<Node *>::const_iterator p = _extra_nodes.begin();
p != _extra_nodes.end(); ++p)
{
if (emarks.mark(*p) == 0)
egraph.erase(*p);
}
//Replace vector of sampled extra nodes
_sampled_extra.clear();
egraph.getSortedNodes(_sampled_extra);
}
void Model::addMonitor(Monitor *monitor, unsigned int thin)
{
if (_adapt) {
throw runtime_error("Turn off adaptive mode before setting monitors");
}
_monitors.push_back(MonitorControl(monitor, _iteration+1, thin));
setSampledExtra();
}
void Model::removeMonitor(Monitor *monitor)
{
for(list<MonitorControl>::iterator p = _monitors.begin();
p != _monitors.end(); ++p)
{
if (p->monitor() == monitor) {
_monitors.erase(p);
break;
}
}
setSampledExtra();
}
void Model::addExtraNode(Node *node)
{
if (!_is_initialized) {
throw logic_error("Attempt to add extra node to uninitialized model");
}
if (node->randomVariableStatus() == RV_TRUE_OBSERVED) {
for (unsigned int i = 0; i < node->parents().size(); ++i) {
if (!node->parents()[i]->isFixed())
throw logic_error("Cannot add observed node to initialized model");
}
}
if (!node->stochasticChildren()->empty() || !node->deterministicChildren()->empty()) {
throw logic_error("Cannot add extra node with children");
}
if (_extra_nodes.count(node)) {
throw logic_error("Extra node already in model");
}
for (vector<Node const *>::const_iterator p = node->parents().begin();
p != node->parents().end(); ++p)
{
if (!_graph.contains(*p)) {
throw logic_error("Extra node has parents not in model");
}
}
if (!_graph.contains(node)) {
_graph.insert(node);
}
_extra_nodes.insert(node);
if (_data_gen) {
//Extra nodes are automatically sampled
_sampled_extra.push_back(node);
}
}
/*
We use construct-on-first-use for the factory lists used by model
objects. By dynamically allocating a list, we ensure that its
destructor is never called - the memory is simply returned to the
OS on exit.
This fixes a nasty exit bug. We cannot guarantee the order that
static destructors are called in. Therefore, a segfault can occur
if a module tries to remove entries from a list that has already
been destroyed.
See also Compiler.cc, where the same technique is used for
lookup tables used by the compiler.
*/
list<pair<SamplerFactory *, bool> > &Model::samplerFactories()
{
static list<pair<SamplerFactory *, bool> > *_samplerfac =
new list<pair<SamplerFactory *, bool> >();
return *_samplerfac;
}
list<pair<RNGFactory *, bool> > &Model::rngFactories()
{
static list<pair<RNGFactory *, bool> > *_rngfac =
new list<pair<RNGFactory *, bool> >();
return *_rngfac;
}
list<pair<MonitorFactory *, bool> > &Model::monitorFactories()
{
static list<pair<MonitorFactory *, bool> > *_monitorfac =
new list<pair<MonitorFactory*,bool> >();
return *_monitorfac;
}
unsigned int Model::nchain() const
{
return _nchain;
}
RNG *Model::rng(unsigned int chain) const
{
return _rng[chain];
}
bool Model::setRNG(string const &name, unsigned int chain)
{
if (chain >= _nchain)
throw logic_error("Invalid chain number in Model::setRNG");
list<pair<RNGFactory*, bool> >::const_iterator p;
for (p = rngFactories().begin(); p != rngFactories().end(); ++p) {
if (p->second) {
RNG *rng = p->first->makeRNG(name);
if (rng) {
_rng[chain] = rng;
return true;
}
}
}
return false;
}
bool Model::setRNG(RNG *rng, unsigned int chain)
{
if (chain >= _nchain)
throw logic_error("Invalid chain number in Model::setRNG");
_rng[chain] = rng;
return true;
}
list<MonitorControl> const &Model::monitors() const
{
return _monitors;
}
/*
bool Model::setDefaultMonitors(string const &type, unsigned int thin)
{
list<MonitorFactory*> const &faclist = monitorFactories();
for(list<MonitorFactory*>::const_iterator j = faclist.begin();
j != faclist.end(); ++j)
{
vector <Node const *> default_nodes = (*j)->defaultNodes(this, type);
if (!default_nodes.empty()) {
unsigned int start = iteration() + 1;
for (unsigned int i = 0; i < default_nodes.size(); ++i) {
Monitor *monitor = (*j)->getMonitor(default_nodes[i], this,
type);
if (!monitor) {
throw logic_error("Invalid default monitor");
}
addMonitor(monitor, thin);
// Model takes ownership of default monitors
_default_monitors.push_back(monitor);
}
return true;
}
}
return false;
}
void Model::clearDefaultMonitors(string const &type)
{
list<Monitor*> dmonitors = _default_monitors;
for (list<Monitor*>::const_iterator p = dmonitors.begin();
p != dmonitors.end(); ++p)
{
Monitor *monitor = *p;
if (monitor->type() == type) {
_default_monitors.remove(monitor);
removeMonitor(monitor);
delete monitor;
}
}
setSampledExtra();
}
*/
void Model::addNode(StochasticNode *node)
{
_graph.insert(node);
_stochastic_nodes.push_back(node);
}
void Model::addNode(DeterministicNode *node)
{
_graph.insert(node);
}
void Model::addNode(ConstantNode *node)
{
_graph.insert(node);
}
vector<StochasticNode*> const &Model::stochasticNodes() const
{
return _stochastic_nodes;
}
} //namespace jags