Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo

Close

[18a63e]: src / lib / Console.cc Maximize Restore History

Download this file

Console.cc    832 lines (736 with data), 18.6 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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
#include <config.h>
#include <Console.h>
#include <compiler/Compiler.h>
#include <compiler/parser_extra.h>
#include <compiler/ParseTree.h>
#include <model/BUGSModel.h>
#include <model/Monitor.h>
#include <graph/NodeError.h>
#include <sampler/SamplerFactory.h>
#include <model/MonitorFactory.h>
#include <rng/RNGFactory.h>
#include <graph/Node.h>
#include <sarray/Range.h>
#include <sarray/SArray.h>
#include <rng/RNG.h>
#include <util/dim.h>
#include <module/Module.h>
#include <map>
#include <list>
#include <stdexcept>
#include <fstream>
#include <vector>
using std::ostream;
using std::endl;
using std::flush;
using std::vector;
using std::string;
using std::map;
using std::list;
using std::set;
using std::pair;
using std::FILE;
#define CATCH_ERRORS \
catch (NodeError except) { \
_err << "Error in node " << \
_model->symtab().getName(except.node) << "\n"; \
_err << except.what() << endl; \
clearModel(); \
return false; \
} \
catch (std::runtime_error except) { \
_err << "RUNTIME ERROR:\n"; \
_err << except.what() << endl; \
clearModel(); \
return false; \
} \
catch (std::logic_error except) { \
_err << "LOGIC ERROR:\n" << except.what() << '\n'; \
_err << "Please send a bug report to " \
<< PACKAGE_BUGREPORT << endl; \
clearModel(); \
return false; \
}
/* Helper functions for dumpState */
namespace jags {
static bool isData(Node const *node)
{
return node->randomVariableStatus() == RV_TRUE_OBSERVED;
}
static bool isParameter(Node const *node)
{
return node->randomVariableStatus() == RV_TRUE_UNOBSERVED;
}
static bool alwaysTrue(Node const *node)
{
return true;
}
Console::Console(ostream &out, ostream &err)
: _out(out), _err(err), _model(0), _pdata(0), _prelations(0),
_pvariables(0)
{
}
Console::~Console()
{
delete _model;
delete _pdata;
delete _prelations;
if (_pvariables) {
for (unsigned int i = 0; i < _pvariables->size(); ++i) {
delete (*_pvariables)[i];
}
delete _pvariables;
}
}
static void getVariableNames(ParseTree const *ptree, set<string> &names,
vector<string> &counterstack)
{
/*
Get variables from model, ensuring that we ignore counters.
*/
if (ptree->treeClass() == P_VAR) {
bool is_counter = false;
for (unsigned int i = 0; i < counterstack.size(); ++i) {
if (ptree->name() == counterstack[i]) {
is_counter = true;
break;
}
}
if (!is_counter) {
names.insert(ptree->name());
}
}
vector<ParseTree*> const &param = ptree->parameters();
for (vector<ParseTree*>::const_iterator p = param.begin();
p != param.end(); ++p)
{
ParseTree *counter;
if (*p) {
//ParseTree objects of type P_BOUND can have null parameters
switch ((*p)->treeClass()) {
case P_FOR:
counter = (*p)->parameters()[0];
for (unsigned int i = 0; i < counter->parameters().size(); ++i)
{
getVariableNames(counter->parameters()[i], names,
counterstack);
}
counterstack.push_back(counter->name());
getVariableNames((*p)->parameters()[1], names, counterstack);
counterstack.pop_back();
break;
default:
getVariableNames(*p, names, counterstack);
break;
}
}
}
}
bool Console::checkModel(FILE *file)
{
if (_model) {
_out << "Replacing existing model" << endl;
clearModel();
}
_model = 0;
string message;
int status = parse_bugs(file, _pvariables, _pdata, _prelations, message);
if (status != 0) {
_err << endl << "Error parsing model file:" << endl << message << endl;
//Tidy up
delete _pdata; _pdata = 0;
delete _prelations; _prelations = 0;
if (_pvariables) {
for (unsigned int i = 0; i < _pvariables->size(); ++i) {
delete (*_pvariables)[i];
}
delete _pvariables;
_pvariables = 0;
}
return false;
}
//Get names of all variables in the model
set<string> nameset;
vector<string> counterstack;
if (_pvariables) {
for (vector<ParseTree*>::const_iterator p = _pvariables->begin();
p != _pvariables->end(); ++p)
{
getVariableNames(*p, nameset, counterstack);
}
}
if (_pdata) {
getVariableNames(_pdata, nameset, counterstack);
}
if (_prelations) {
getVariableNames(_prelations, nameset, counterstack);
}
_array_names.clear();
_array_names.reserve(nameset.size());
for (set<string>::const_iterator p = nameset.begin(); p != nameset.end();
++p)
{
_array_names.push_back(*p);
}
return true;
}
bool Console::compile(map<string, SArray> &data_table, unsigned int nchain,
bool gendata)
{
if (nchain == 0) {
_err << "You must have at least one chain" << endl;
return true;
}
if (_model) {
_out << "Replacing existing model" << endl;
clearModel();
}
RNG *datagen_rng = 0;
if (_pdata && gendata) {
_model = new BUGSModel(1);
Compiler compiler(*_model, data_table);
_out << "Compiling data graph" << endl;
try {
if (_pvariables) {
_out << " Declaring variables" << endl;
compiler.declareVariables(*_pvariables);
}
_out << " Resolving undeclared variables" << endl;
compiler.undeclaredVariables(_pdata);
_out << " Allocating nodes" << endl;
compiler.writeRelations(_pdata);
/* Check validity of data generating model */
for (Graph::const_iterator r = _model->graph().begin();
r != _model->graph().end(); ++r)
{
if ((*r)->randomVariableStatus() == RV_TRUE_OBSERVED) {
vector<Node const*> const &parents = (*r)->parents();
for (vector<Node const*>::const_iterator p = parents.begin();
p != parents.end(); ++p)
{
if (!((*p)->isFixed())) {
_err << "Invalid data graph: observed node "
<< _model->symtab().getName(*r)
<< " has non-fixed parent "
<< _model->symtab().getName(*p)
<< "\n";
clearModel();
return false;
}
}
}
}
_out << " Initializing" << endl;
_model->initialize(true);
// Do a single update (by forward sampling)
_model->update(1);
//Save data generating RNG for later use. It is owned by the
//RNGFactory, not the model.
datagen_rng = _model->rng(0);
_out << " Reading data back into data table" << endl;
_model->symtab().readValues(data_table, 0, alwaysTrue);
delete _model;
_model = 0;
}
CATCH_ERRORS;
}
_model = new BUGSModel(nchain);
Compiler compiler(*_model, data_table);
_out << "Compiling model graph" << endl;
try {
if (_pvariables) {
_out << " Declaring variables" << endl;
compiler.declareVariables(*_pvariables);
}
if (_prelations) {
_out << " Resolving undeclared variables" << endl;
compiler.undeclaredVariables(_prelations);
_out << " Allocating nodes" << endl;
compiler.writeRelations(_prelations);
}
else {
_err << "Nothing to compile" << endl;
return true;
}
if (_model) {
_out << " Graph Size: " << _model->graph().size() << endl;
if (datagen_rng) {
// Reuse the data-generation RNG, if there is one, for chain 0
_model->setRNG(datagen_rng, 0);
}
}
else {
_err << "No model" << endl;
return true;
}
}
CATCH_ERRORS;
return true;
}
bool Console::initialize()
{
if (_model == 0) {
_err << "Can't initialize. No model!" << endl;
return false;
}
if (_model->graph().size() == 0) {
_err << "Can't initialize. No nodes in graph." << endl;
_err << "Have you compiled the model?" << endl;
return false;
}
if (_model->isInitialized()) {
_err << "Model is already initialized" << endl;
return true;
}
try {
_out << "Initializing model" << endl;
_model->initialize(false);
}
CATCH_ERRORS;
return true;
}
bool Console::setParameters(map<string, SArray> const &init_table,
unsigned int chain)
{
if (_model == 0) {
_err << "Can't set initial values. No model!" << endl;
return true;
}
if (chain == 0 || chain > nchain()) {
_err << "Invalid chain number" << endl;
return true;
}
try {
_model->setParameters(init_table, chain - 1);
}
CATCH_ERRORS;
return true;
}
bool Console::setRNGname(string const &name, unsigned int chain)
{
if (_model == 0) {
_err << "Can't set RNG name. No model!" << endl;
return true;
}
try {
bool name_ok = _model->setRNG(name, chain - 1);
if (!name_ok) {
_err << "WARNING: RNG name " << name << " not found\n";
}
}
CATCH_ERRORS;
return true;
}
bool Console::update(unsigned int n)
{
if (_model == 0) {
_err << "Can't update. No model!" << endl;
return false;
}
if (!_model->isInitialized()) {
_err << "Model not initialized" << endl;
return false;
}
try {
_model->update(n);
}
CATCH_ERRORS;
return true;
}
unsigned int Console::iter() const
{
if (!_model) {
return 0;
}
else {
return _model->iteration();
}
}
bool Console::setMonitor(string const &name, Range const &range,
unsigned int thin, string const &type)
{
if (!_model) {
_err << "Can't set monitor. No model!" << endl;
return false;
}
if (thin == 0) {
_err << "Failed to set " << type << " monitor for " <<
name << print(range) << endl;
_err << "Thinning interval must be > 0" << endl;
return false;
}
try {
if (_model->isAdapting()) {
_out << "NOTE: Stopping adaptation\n" << endl;
_model->adaptOff();
}
string msg;
bool ok = _model->setMonitor(name, range, thin, type, msg);
if (!ok) {
_err << "Failed to set " << type << " monitor for " <<
name << print(range) << endl;
if (!msg.empty()) {
_err << msg << endl;
}
return false;
}
}
CATCH_ERRORS;
return true;
}
bool Console::clearMonitor(string const &name, Range const &range,
string const &type)
{
if (!_model) {
_err << "Can't clear monitor. No model!" << endl;
return false;
}
try {
bool ok = _model->deleteMonitor(name, range, type);
if (!ok) {
_err << "Failed to clear " << type << " monitor for node " <<
name << print(range) << endl;
return false;
}
}
CATCH_ERRORS;
return true;
}
void Console::clearModel()
{
_out << "Deleting model" << endl;
delete _model;
_model = 0;
}
bool Console::dumpState(map<string,SArray> &data_table,
string &rng_name,
DumpType type, unsigned int chain)
{
if (!_model) {
_err << "No model" << endl;
return false;
}
if (_model->symtab().size() == 0) {
_err << "Symbol table is empty" << endl;
return false;
}
if (chain == 0 || chain > nchain()) {
_err << "Invalid chain number" << endl;
return false;
}
bool (*selection)(Node const *) = 0;
switch (type) {
case DUMP_PARAMETERS:
selection = isParameter;
break;
case DUMP_DATA:
selection = isData;
break;
case DUMP_ALL:
selection = alwaysTrue;
break;
}
try {
_model->symtab().readValues(data_table, chain - 1, selection);
if (type == DUMP_PARAMETERS || type == DUMP_ALL) {
vector<int> rngstate;
if (_model->rng(chain - 1)) {
_model->rng(chain - 1)->getState(rngstate);
vector<unsigned int> dimrng(1,rngstate.size());
SArray rngsarray(dimrng);
rngsarray.setValue(rngstate);
data_table.insert(pair<string, SArray>(".RNG.state",rngsarray));
rng_name = _model->rng(chain - 1)->name();
}
}
}
CATCH_ERRORS;
return true;
}
bool Console::dumpMonitors(map<string,SArray> &data_table,
string const &type, bool flat)
{
if (_model == 0) {
_err << "Cannot dump monitors. No model!" << endl;
return true;
}
try {
list<MonitorControl> const &monitors = _model->monitors();
list<MonitorControl>::const_iterator p;
for (p = monitors.begin(); p != monitors.end(); ++p) {
Monitor const *monitor = p->monitor();
if (p->niter() > 0 && monitor->type() == type) {
data_table.insert(pair<string,SArray>(monitor->name(),
monitor->dump(flat)));
}
}
}
CATCH_ERRORS;
return true;
}
bool Console::coda(string const &prefix)
{
if (!_model) {
_err << "Can't dump CODA output. No model!" << endl;
return false;
}
try {
string warn;
_model->coda(prefix, warn);
if (!warn.empty()) {
_err << "WARNING:\n" << warn;
}
}
CATCH_ERRORS;
return true;
}
bool Console::coda(vector<pair<string, Range> > const &nodes,
string const &prefix)
{
if (!_model) {
_err << "Can't dump CODA output. No model!" << endl;
return false;
}
try {
string warn;
_model->coda(nodes, prefix, warn);
if (!warn.empty()) {
_err << "WARNINGS:\n" << warn;
}
}
CATCH_ERRORS;
return true;
}
BUGSModel const *Console::model()
{
return _model;
}
unsigned int Console::nchain() const
{
if (_model == 0) {
return 0;
}
else {
return _model->nchain();
}
}
bool Console::checkAdaptation(bool &status)
{
if (_model == 0) {
_err << "Can't update. No model!" << endl;
return false;
}
if (!_model->isInitialized()) {
_err << "Model not initialized" << endl;
return false;
}
try {
status = _model->checkAdaptation();
}
CATCH_ERRORS;
return true;
}
bool Console::adaptOff(void)
{
if (_model == 0) {
_err << "Cannot stop adaptation. No model!" << endl;
return false;
}
if (!_model->isInitialized()) {
_err << "Cannot stop adaptation. Model not initialized" << endl;
return false;
}
try {
_model->adaptOff();
}
CATCH_ERRORS;
return true;
}
bool Console::isAdapting() const
{
return _model ? _model->isAdapting() : false;
}
vector<string> const &Console::variableNames() const
{
return _array_names;
}
bool Console::dumpSamplers(vector<vector<string> > &sampler_names)
{
if (_model == 0) {
_err << "Can't dump samplers. No model!" << endl;
return false;
}
if (!_model->isInitialized()) {
_err << "Model not initialized" << endl;
return false;
}
try {
_model->samplerNames(sampler_names);
}
CATCH_ERRORS;
return true;
}
bool Console::loadModule(string const &name)
{
list<Module*>::const_iterator p;
for (p = Module::modules().begin(); p != Module::modules().end(); ++p)
{
if ((*p)->name() == name) {
(*p)->load();
if (rngSeed() != 0) {
// Set default seed of RNG factories
vector<RNGFactory*> const &facs = (*p)->rngFactories();
for (unsigned int i = 0; i < facs.size(); ++i) {
facs[i]->setSeed(rngSeed());
}
}
return true;
}
}
return false;
}
vector<string> Console::listModules()
{
vector<string> ans;
list<Module*>::const_iterator p;
for (p = Module::loadedModules().begin();
p != Module::loadedModules().end(); ++p)
{
ans.push_back((*p)->name());
}
return ans;
}
bool Console::unloadModule(string const &name)
{
list<Module*>::iterator p;
for (p = Module::loadedModules().begin();
p != Module::loadedModules().end(); ++p)
{
if ((*p)->name() == name) {
(*p)->unload();
return true;
}
}
return false;
}
static bool setSamplerActive(string const &name, bool flag)
{
bool ans = false;
list<pair<SamplerFactory*, bool> > &faclist = Model::samplerFactories();
list<pair<SamplerFactory*, bool> >::iterator p;
for (p = faclist.begin(); p != faclist.end(); ++p) {
if (p->first->name() == name) {
p->second = flag;
ans = true;
}
}
return ans;
}
static bool setMonitorActive(string const &name, bool flag)
{
bool ans = false;
list<pair<MonitorFactory*, bool> > &faclist = Model::monitorFactories();
list<pair<MonitorFactory*, bool> >::iterator p;
for (p = faclist.begin(); p != faclist.end(); ++p) {
if (p->first->name() == name) {
p->second = flag;
ans = true;
}
}
return ans;
}
static bool setRNGActive(string const &name, bool flag)
{
bool ans = false;
list<pair<RNGFactory*, bool> > &faclist = Model::rngFactories();
list<pair<RNGFactory*, bool> >::iterator p;
for (p = faclist.begin(); p != faclist.end(); ++p) {
if (p->first->name() == name) {
p->second = flag;
ans = true;
}
}
return ans;
}
bool Console::setFactoryActive(string const &name, FactoryType type, bool flag)
{
bool ok = false;
switch(type) {
case SAMPLER_FACTORY:
ok = setSamplerActive(name, flag);
break;
case MONITOR_FACTORY:
ok = setMonitorActive(name, flag);
break;
case RNG_FACTORY:
ok = setRNGActive(name, flag);
break;
}
return ok;
}
static vector<pair<string, bool> > listSamplerFactories()
{
vector<pair<string, bool> > ans;
list<pair<SamplerFactory*, bool> > const &flist = Model::samplerFactories();
for (list<pair<SamplerFactory*, bool> >::const_iterator p = flist.begin();
p != flist.end(); ++p)
{
ans.push_back(pair<string,bool>(p->first->name(), p->second));
}
return ans;
}
static vector<pair<string, bool> > listMonitorFactories()
{
vector<pair<string, bool> > ans;
list<pair<MonitorFactory*, bool> > const &flist = Model::monitorFactories();
for (list<pair<MonitorFactory*, bool> >::const_iterator p = flist.begin();
p != flist.end(); ++p)
{
ans.push_back(pair<string,bool>(p->first->name(), p->second));
}
return ans;
}
static vector<pair<string, bool> > listRNGFactories()
{
vector<pair<string, bool> > ans;
list<pair<RNGFactory*, bool> > const &flist = Model::rngFactories();
for (list<pair<RNGFactory*, bool> >::const_iterator p = flist.begin();
p != flist.end(); ++p)
{
ans.push_back(pair<string,bool>(p->first->name(), p->second));
}
return ans;
}
vector<pair<string, bool> > Console::listFactories(FactoryType type)
{
vector<pair<string, bool> > ans;
switch(type) {
case SAMPLER_FACTORY:
ans = listSamplerFactories();
break;
case MONITOR_FACTORY:
ans = listMonitorFactories();
break;
case RNG_FACTORY:
ans = listRNGFactories();
break;
}
return ans;
}
unsigned int &Console::rngSeed()
{
static unsigned int seed = 0;
return seed;
}
void Console::setRNGSeed(unsigned int seed)
{
if (seed == 0) return;
list<pair<RNGFactory*, bool> >::const_iterator p;
for (p = Model::rngFactories().begin(); p != Model::rngFactories().end();
++p)
{
p->first->setSeed(seed);
}
rngSeed() = seed;
}
} //namespace jags