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

Close

[0a5322]: src / lib / compiler / Compiler.cc Maximize Restore History

Download this file

Compiler.cc    1176 lines (1057 with data), 32.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
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
#include <config.h>
#include <compiler/Compiler.h>
#include <compiler/ParseTree.h>
#include <graph/ScalarLogicalNode.h>
#include <graph/VectorLogicalNode.h>
#include <graph/ArrayLogicalNode.h>
#include <graph/LinkNode.h>
#include <graph/ConstantNode.h>
#include <graph/ScalarStochasticNode.h>
#include <graph/VectorStochasticNode.h>
#include <graph/ArrayStochasticNode.h>
#include <graph/AggNode.h>
#include <graph/NodeError.h>
#include <sarray/RangeIterator.h>
#include <function/FunctionPtr.h>
#include <distribution/DistPtr.h>
#include <util/nainf.h>
#include <util/dim.h>
#include <util/integer.h>
#include "MixCompiler.h"
#include <utility>
#include <vector>
#include <stdexcept>
#include <cmath>
#include <list>
#include <algorithm>
#include <string>
#include <set>
#include <sstream>
using std::string;
using std::vector;
using std::list;
using std::map;
using std::pair;
using std::invalid_argument;
using std::runtime_error;
using std::logic_error;
using std::ostringstream;
using std::min;
using std::max;
using std::set;
using std::fabs;
#include <sstream>
template<class T>
string ToString(const T& val)
{
ostringstream strm;
strm << val;
return strm.str();
}
void CompileError(ParseTree const *p, string const &msg1,
string const &msg2 = "")
{
string msg = string("Compilation error on line ") + ToString(p->line())
+ ".";
if (!msg1.empty()) {
msg.append("\n");
msg.append(msg1);
}
if (!msg2.empty()) {
msg.append(" ");
msg.append(msg2);
}
throw runtime_error(msg);
}
Node * Compiler::constFromTable(ParseTree const *p)
{
// Get a constant value directly from the data table
if (!_index_expression) {
throw logic_error("Can only call constFromTable inside index expression");
}
map<string,SArray>::const_iterator i = _data_table.find(p->name());
if (i == _data_table.end()) {
return 0;
}
SArray const &sarray = i->second;
Range subset_range = getRange(p, sarray.range());
if (isNULL(subset_range)) {
return 0;
}
else {
// Range expression successfully evaluated
Node *cnode = 0;
if (subset_range.length() > 1) {
RangeIterator i(subset_range);
unsigned int n = subset_range.length();
//double const *v = sarray.value();
vector<double> const &v = sarray.value();
vector<double> value(n);
for (unsigned int j = 0; j < n; ++j, i.nextLeft()) {
unsigned int offset = sarray.range().leftOffset(i);
value[j] = v[offset];
if (value[j] == JAGS_NA) {
return 0;
}
}
cnode = new ConstantNode(subset_range.dim(false), value,
_model.nchain());
}
else {
unsigned int offset =
sarray.range().leftOffset(subset_range.lower());
double value = sarray.value()[offset];
if (value == JAGS_NA) {
return 0;
}
else {
cnode = new ConstantNode(value, _model.nchain());
}
return cnode;
}
_index_nodes.push_back(cnode);
return cnode;
}
}
bool Compiler::indexExpression(ParseTree const *p, int &value)
{
/*
Evaluates an index expression.
Index expressions occur in three contexts:
1) In the limits of a "for" loop
2) On the left hand side of a relation
3) On the right hand side of a relation
They are scalar, integer-valued, constant expressions. We
return true on success and the result is written to the
parameter value.
*/
/*
The counter _index_expression is non-zero if we are inside an
Index expression. This invokes special rules in the functions
getParameter and getArraySubset. The counter tracks the levels
of nesting of index expressions.
The vector _index_nodes holds the Nodes created during the
evaluation of the index expression.
*/
_index_expression++;
Node *node = getParameter(p);
_index_expression--;
if (!node || !node->isObserved()) {
return false;
}
if (node->length() != 1) {
throw NodeError(node, "Vector value in index expression");
}
if (!checkInteger(node->value(0)[0])) {
throw NodeError(node,
"Index expression evaluates to non-integer value");
}
value = asInteger(node->value(0)[0]);
if (_index_expression == 0) {
while(!_index_nodes.empty()) {
Node *inode = _index_nodes.back();
_index_nodes.pop_back();
delete inode;
}
}
return true;
}
Range Compiler::getRange(ParseTree const *p, Range const &default_range)
{
/*
Evaluate a range expression. If successful, it returns the range
corresponding to the expression. If unsuccessful (due to missing
values) returns a null range.
The default_range argument provides default values if the range
expression is blank: e.g. foo[] or bar[,1]. The default range
may be a null range, in which case, missing indices will result in
failure.
*/
vector<ParseTree*> const &range_list = p->parameters();
string const &name = p->name();
if (range_list.empty()) {
//An empty range expression implies the default range
return default_range;
}
// Check size and integrity of range expression
unsigned int size = range_list.size();
if (!isNULL(default_range) && size != default_range.ndim(false)) {
CompileError(p, "Dimension mismatch taking subset of", name);
}
for (unsigned int i = 0; i < size; ++i) {
if (range_list[i]->treeClass() != P_RANGE) {
throw logic_error("Malformed parse tree. Expected range expression");
}
}
// Now step through and evaluate lower and upper index expressions
vector<int> lower(size), upper(size);
for (unsigned int i = 0; i < size; i++) {
switch (range_list[i]->parameters().size()) {
case 0:
// Empty index implies default range
if (isNULL(default_range)) {
return default_range;
}
lower[i] = default_range.lower()[i];
upper[i] = default_range.upper()[i];
break;
case 1:
// Single index implies lower == upper
if (!indexExpression(range_list[i]->parameters()[0], lower[i])) {
return Range();
}
else {
upper[i] = lower[i];
}
break;
case 2:
if (!indexExpression(range_list[i]->parameters()[0], lower[i]) ||
!indexExpression(range_list[i]->parameters()[1], upper[i])) {
return Range();
}
break;
default:
throw logic_error("Malformed parse tree in index expression");
}
}
for (unsigned int i = 0; i < size; ++i) {
if (lower[i] > upper[i]) {
//Invalid range. We can't use the print method for Range
//objects to print it as we can't construct a Range object.
//So do it by hand
ostringstream ostr;
ostr << "[";
for (unsigned int j = 0; j < size; ++j) {
if (j > 0)
ostr << ",";
if (lower[j] == upper[j]) {
ostr << lower[j];
}
else {
ostr << lower[j] << ":" << upper[j];
}
}
ostr << "]";
CompileError(p, "Invalid range:", ostr.str());
}
}
return Range(lower, upper);
}
Range Compiler::VariableSubsetRange(ParseTree const *var)
{
/*
Get the range of a subset expression of a variable on the LHS of a
relation. This means that the subset expression must be constant.
*/
if (var->treeClass() != P_VAR) {
throw logic_error("Expecting variable expression");
}
string const &name = var->name();
if (_countertab.getCounter(name)) {
CompileError(var, "Counter cannot appear on LHS of relation:", name);
}
NodeArray *array = _model.symtab().getVariable(name);
if (array) {
// It's a declared node
vector<ParseTree*> const &range_list = var->parameters();
if (range_list.empty()) {
//Missing range implies the whole node
return array->range();
}
if (range_list.size() != array->range().ndim(false)) {
CompileError(var, "Dimension mismatch in subset expression of", name);
}
Range range = getRange(var, array->range());
if (isNULL(range)) {
CompileError(var, "Missing values in subset expression of", name);
}
return range;
}
else {
// Undeclared node
Range range = getRange(var, Range());
if (isNULL(range)) {
CompileError(var, "Cannot evaluate subset expression for", name);
}
return range;
}
}
Range Compiler::CounterRange(ParseTree const *var)
{
/* The range expression for a counter differs from that of
a variable in that it is
1) one-dimensional
2) may not be empty
Further, no variables are created for counters in the
Symbol Table
*/
if (var->treeClass() != P_COUNTER) {
throw logic_error("Expecting counter expression");
}
if (var->parameters().size() != 1) {
throw logic_error("Invalid counter expression");
}
Range range();
ParseTree const *prange = var->parameters()[0];
if (prange->treeClass() != P_RANGE) {
throw logic_error("Expecting range expression");
}
unsigned int size = prange->parameters().size();
if (size < 1 || size > 2) {
throw logic_error(string("Invalid range expression for counter ")
+ var->name());
}
int lower;
if(!indexExpression(prange->parameters()[0], lower)) {
CompileError(var, "Cannot evaluate lower index of counter", var->name());
}
int upper;
if (prange->parameters().size() == 2) {
if (!indexExpression(prange->parameters()[1], upper)) {
CompileError(var, "Cannot evaluate upper index of counter",
var->name());
}
}
else {
upper = lower;
}
if (lower > upper) {
return Range();
}
else {
return Range(vector<int>(1, lower), vector<int>(1, upper));
}
}
Node *Compiler::getArraySubset(ParseTree const *p)
{
Node *node = 0;
if (p->treeClass() != P_VAR) {
throw logic_error("Expecting expression");
}
Counter *counter = _countertab.getCounter(p->name()); //A counter
if (counter) {
if (_index_expression) {
node = new ConstantNode((*counter)[0], _model.nchain());
_index_nodes.push_back(node);
}
else {
node = _constantfactory.getConstantNode((*counter)[0], _model);
}
}
else {
NodeArray *array = _model.symtab().getVariable(p->name());
if (array) {
Range subset_range = getRange(p, array->range());
if (!isNULL(subset_range)) {
//A fixed subset
if (!array->range().contains(subset_range)) {
CompileError(p, "Subset out of range:", array->name() +
print(subset_range));
}
node = array->getSubset(subset_range, _model);
if (node == 0 && _strict_resolution) {
string msg = string("Unable to resolve node ")
+ array->name() + print(subset_range)
+ "\nThis may be due to an undefined ancestor node or"
+ " a directed cycle in the graph";
CompileError(p, msg);
}
}
else if (!_index_expression) {
//A stochastic subset
node = getMixtureNode(p, this);
}
}
else if (_strict_resolution) {
//Give an informative error message in case of failure
CompileError(p, "Unknown parameter", p->name());
}
if (!node && _index_expression) {
//It is possible to evaluate an index expression before
//any Nodes are available from the symbol table.
node = constFromTable(p);
}
}
return node;
}
static FunctionPtr const &
getFunction(ParseTree const *t, FuncTab const &functab)
{
if (t->treeClass() != P_FUNCTION)
throw logic_error("Malformed parse tree: Expected function");
FunctionPtr const &func = functab.find(t->name());
if (isNULL(func)) {
CompileError(t, "Unknown function:", t->name());
}
return func;
}
Node *Compiler::getLength(ParseTree const *p, SymTab const &symtab)
{
if (p->treeClass() != P_LENGTH) {
throw logic_error("Malformed parse tree. Expecting dim expression");
}
ParseTree const *var = p->parameters()[0];
if (var->treeClass() != P_VAR) {
throw logic_error("Malformed parse tree. Expecting variable name");
}
NodeArray const *array = symtab.getVariable(var->name());
if (array) {
Range subset_range = getRange(var, array->range());
if (isNULL(subset_range)) {
return 0;
}
else {
double length = product(subset_range.dim(true));
if (_index_expression) {
Node *node = new ConstantNode(length, _model.nchain());
_index_nodes.push_back(node);
return node;
}
else {
return _constantfactory.getConstantNode(length, _model);
}
}
}
else {
return 0;
}
}
Node *Compiler::getDim(ParseTree const *p, SymTab const &symtab)
{
if (p->treeClass() != P_DIM) {
throw logic_error("Malformed parse tree. Expecting dim expression");
}
ParseTree const *var = p->parameters()[0];
if (var->treeClass() != P_VAR) {
throw logic_error("Malformed parse tree. Expecting variable name");
}
NodeArray const *array = symtab.getVariable(var->name());
if (array) {
Range subset_range = getRange(var, array->range());
if (isNULL(subset_range)) {
return 0;
}
else {
vector<unsigned int> idim = subset_range.dim(false);
vector<double> ddim(idim.size());
for (unsigned int j = 0; j < idim.size(); ++j) {
ddim[j] = idim[j];
}
vector<unsigned int> d(1, idim.size());
if (_index_expression) {
Node *node = new ConstantNode(d, ddim, _model.nchain());
_index_nodes.push_back(node);
return node;
}
else {
return _constantfactory.getConstantNode(d, ddim, _model);
}
}
}
else {
return 0;
}
}
/*
* Evaluates the expression t, and returns a pointer to a Node. If the
* expression cannot be evaluated, a NULL pointer is returned.
*/
Node * Compiler::getParameter(ParseTree const *t)
{
vector<Node const *> parents;
Node *node = 0;
switch (t->treeClass()) {
case P_VALUE:
if (_index_expression) {
node = new ConstantNode(t->value(), _model.nchain());
_index_nodes.push_back(node);
}
else {
node = _constantfactory.getConstantNode(t->value(), _model);
}
break;
case P_VAR:
node = getArraySubset(t);
break;
case P_LENGTH:
node = getLength(t,_model.symtab());
break;
case P_DIM:
node = getDim(t, _model.symtab());
break;
case P_LINK:
if (getParameterVector(t, parents)) {
LinkFunction const *link = funcTab().findLink(t->name());
if (!link) {
CompileError(t, "Unknown link function:", t->name());
}
node = _logicalfactory.getNode(FunctionPtr(link), parents, _model);
}
break;
case P_FUNCTION:
if (getParameterVector(t, parents)) {
FunctionPtr const &func = getFunction(t, funcTab());
if (_index_expression) {
node = LogicalFactory::newNode(func, parents);
_index_nodes.push_back(node);
}
else {
node = _logicalfactory.getNode(func, parents, _model);
}
}
break;
default:
throw logic_error("Malformed parse tree.");
break;
}
if (!node)
return 0;
if (_index_expression) {
//Random variables in index expressions must be observed
if (node->isRandomVariable() && !node->isObserved())
return 0;
}
return node;
}
/*
* Before creating the node y <- foo(a,b), or z ~ dfoo(a,b), the parent
* nodes must a,b be created. This expression evaluates the vector(a,b)
* Arguments are the same as for getParameter.
*/
bool Compiler::getParameterVector(ParseTree const *t,
vector<Node const *> &parents)
{
if (!parents.empty()) {
throw logic_error("parent vector must be empty in getParameterVector");
}
switch (t->treeClass()) {
case P_FUNCTION: case P_LINK: case P_DENSITY:
for (unsigned int i = 0; i < t->parameters().size(); ++i) {
Node *node = getParameter(t->parameters()[i]);
if (node) {
parents.push_back(node);
}
else {
parents.clear();
return false;
}
}
break;
default:
throw logic_error("Invalid Parse Tree.");
}
return true;
}
Node * Compiler::allocateStochastic(ParseTree const *stoch_relation)
{
ParseTree const *distribution = stoch_relation->parameters()[1];
// Create the parameter vector
vector<Node const *> parameters;
if (!getParameterVector(distribution, parameters)) {
return 0;
}
// Set upper and lower bounds
Node *lBound = 0, *uBound = 0;
if (stoch_relation->parameters().size() == 3) {
//Truncated distribution
ParseTree const *truncated = stoch_relation->parameters()[2];
switch(truncated->treeClass()) {
case P_BOUNDS: case P_INTERVAL:
break;
default:
throw logic_error("Invalid parse tree");
}
ParseTree const *ll = truncated->parameters()[0];
ParseTree const *ul = truncated->parameters()[1];
if (ll) {
lBound = getParameter(ll);
if (!lBound) {
return 0;
}
}
if (ul) {
uBound = getParameter(ul);
if (!uBound) {
return 0;
}
}
}
/*
Check data table to see if this is an observed node. If it is,
we put the data in a array of doubles pointed to by this_data,
and set data_length equal to the length of the array
*/
double *this_data = 0;
unsigned int data_length = 0;
ParseTree *var = stoch_relation->parameters()[0];
map<string,SArray>::const_iterator q = _data_table.find(var->name());
if (q != _data_table.end()) {
vector<double> const &data_value = q->second.value();
Range const &data_range = q->second.range();
Range target_range = VariableSubsetRange(var);
data_length = target_range.length();
this_data = new double[data_length];
unsigned int i = 0;
unsigned int nmissing = 0;
for (RangeIterator p(target_range); !p.atEnd(); p.nextLeft()) {
unsigned int j = data_range.leftOffset(p);
if (data_value[j] == JAGS_NA) {
++nmissing;
}
this_data[i++] = data_value[j];
}
if (nmissing == data_length) {
delete [] this_data;
this_data = 0;
data_length = 0;
}
else if (nmissing != 0) {
delete [] this_data;
CompileError(var, var->name() + print(target_range),
"has missing values");
}
}
// Check that distribution exists
string const &distname = distribution->name();
DistPtr const &dist = distTab().find(distname);
if (isNULL(dist)) {
CompileError(distribution, "Unknown distribution:", distname);
}
if (!this_data) {
/*
Special rule for observable functions, which exist both as
a Function and a Distribution. If the node is unobserved,
and we find a function matched to the distribution in
obsFuncTab, then we create a Logical Node instead.
*/
FunctionPtr const &func = obsFuncTab().find(dist);
if (!isNULL(func)) {
//FIXME: Why are we not using a factory here?
LogicalNode *lnode = LogicalFactory::newNode(func, parameters);
_model.addNode(lnode);
return lnode;
}
}
/*
We allow BUGS-style interval censoring notation for
compatibility but only allow it if there are no free parameters
in the distribution
*/
if (stoch_relation->parameters().size() == 3) {
ParseTree const *t = stoch_relation->parameters()[2];
if (t->treeClass() == P_INTERVAL) {
for (unsigned int i = 0; i < parameters.size(); ++i) {
if (!parameters[i]->isObserved()) {
CompileError(stoch_relation,
"BUGS I(,) notation is not allowed unless",
"all parameters are fixed");
}
}
}
}
StochasticNode *snode = 0;
if (SCALAR(dist)) {
snode = new ScalarStochasticNode(SCALAR(dist), parameters,
lBound, uBound);
}
else if (VECTOR(dist)) {
snode = new VectorStochasticNode(VECTOR(dist), parameters,
lBound, uBound);
}
else if (ARRAY(dist)) {
snode = new ArrayStochasticNode(ARRAY(dist), parameters,
lBound, uBound);
}
else {
throw logic_error("Unable to classify distribution");
}
_model.addNode(snode);
// If Node is observed, set the data
if (this_data) {
for (unsigned int n = 0; n < snode->nchain(); ++n) {
snode->setValue(this_data, data_length, n);
}
snode->setObserved();
delete [] this_data;
}
return snode;
}
Node * Compiler::allocateLogical(ParseTree const *rel)
{
ParseTree *expression = rel->parameters()[1];
Node *node = 0;
ConstantNode *cnode = 0;
vector <Node const *> parents;
switch (expression->treeClass()) {
case P_VALUE:
cnode = new ConstantNode(expression->value(), _model.nchain());
_model.addNode(cnode);
node = cnode;
/* The reason we aren't using a ConstantFactory here is to ensure
that the nodes are correctly named */
break;
case P_VAR: case P_FUNCTION: case P_LINK: case P_LENGTH: case P_DIM:
node = getParameter(expression);
break;
default:
throw logic_error("Malformed parse tree in Compiler::allocateLogical");
}
/*
Check that there are no values in the data table corresponding to
this node.
*/
ParseTree *var = rel->parameters()[0];
map<string,SArray>::const_iterator q = _data_table.find(var->name());
if (q != _data_table.end()) {
vector<double> const &data_value = q->second.value();
Range const &data_range = q->second.range();
Range target_range = VariableSubsetRange(var);
for (RangeIterator p(target_range); !p.atEnd(); p.nextLeft()) {
unsigned int j = data_range.leftOffset(p);
if (data_value[j] != JAGS_NA) {
CompileError(var, var->name() + print(target_range),
"is a logical node and cannot be observed");
}
}
}
return node;
}
void Compiler::allocate(ParseTree const *rel)
{
if (_is_resolved[_n_relations])
return;
Node *node = 0;
switch(rel->treeClass()) {
case P_STOCHREL:
node = allocateStochastic(rel);
break;
case P_DETRMREL:
node = allocateLogical(rel);
break;
default:
throw logic_error("Malformed parse tree in Compiler::allocate");
break;
}
SymTab &symtab = _model.symtab();
if (node) {
ParseTree *var = rel->parameters()[0];
NodeArray *array = symtab.getVariable(var->name());
if (!array) {
//Undeclared array. It's size is inferred from the dimensions of
//the newly created node
symtab.addVariable(var->name(), node->dim());
array = symtab.getVariable(var->name());
array->insert(node, array->range());
}
else {
// Check if a node is already inserted into this range
Range range = VariableSubsetRange(var);
if (array->find(range)) {
CompileError(var, "Attempt to redefine node",
var->name() + print(range));
}
array->insert(node, range);
}
_n_resolved++;
_is_resolved[_n_relations] = true;
}
}
void Compiler::setConstantMask(ParseTree const *rel)
{
ParseTree const *var = rel->parameters()[0];
string const &name = var->name();
map<string,vector<bool> >::iterator p = _constant_mask.find(name);
if (p == _constant_mask.end()) {
return;
}
map<string,SArray>::const_iterator q = _data_table.find(name);
if (q == _data_table.end()) {
throw logic_error ("Error in Compiler::setConstantMask");
}
Range range = VariableSubsetRange(var);
Range const &var_range = q->second.range();
if (!var_range.contains(range)) {
throw logic_error("Invalid range in Compiler::setConstantMask.");
}
vector<bool> &mask = p->second;
for (RangeIterator i(range); !i.atEnd(); i.nextLeft()) {
mask[var_range.leftOffset(i)] = false;
}
}
void Compiler::getArrayDim(ParseTree const *p)
{
/*
Called by traverseTree, this function calculates the size
of all arrays from the left-hand side of all
relations, and stores the results in the map _node_array_ranges.
*/
ParseTree const *var = p->parameters()[0];
string const &name = var->name();
if(var->parameters().empty()) {
//No index expession => No info on array size
return;
}
Range new_range = VariableSubsetRange(var);
map<string, vector<vector<int> > >::iterator i =
_node_array_ranges.find(name);
if (i == _node_array_ranges.end()) {
//Create a new entry
vector<vector<int> > ivec;
ivec.push_back(new_range.lower());
ivec.push_back(new_range.upper());
_node_array_ranges.insert(pair<const string, vector<vector<int> > >(name,ivec));
}
else {
//Check against the existing entry, and modify if necessary
unsigned int ndim = i->second[0].size();
if (new_range.ndim(false) != ndim) {
CompileError(var, "Inconsistent dimensiosn for array", name);
}
else {
for (unsigned int j = 0; j < ndim; ++j) {
i->second[0][j] = min(i->second[0][j], new_range.lower()[j]);
i->second[1][j] = max(i->second[1][j], new_range.upper()[j]);
}
}
}
}
void Compiler::writeConstantData(ParseTree const *relations)
{
/*
Values supplied in the data table, but which DO NOT
appear on the left-hand side of a relation, are constants.
We have to find these values in order to create the
constant nodes that form the top level of any graphical
model.
*/
//First we set up the constant mask, setting all values to true by
//default
map<string, SArray>::const_iterator p;
for (p = _data_table.begin(); p != _data_table.end(); ++p) {
pair<string, vector<bool> > apair;
apair.first = p->first;
apair.second = vector<bool>(p->second.length(), true);
_constant_mask.insert(apair);
}
//Now traverse the parse tree, setting node array subsets that
//correspond to the left-hand side of any relation to be false
traverseTree(relations, &Compiler::setConstantMask);
//Create a temporary copy of the data table containing only
//data for constant nodes
map<string, SArray> temp_data_table = _data_table;
map<string, SArray>::iterator p2;
for(p2 = temp_data_table.begin(); p2 != temp_data_table.end(); ++p2) {
string const &name = p2->first;
SArray &temp_data = p2->second;
vector<bool> const &mask = _constant_mask.find(name)->second;
for (unsigned long i = 0; i < temp_data.length(); ++i) {
if (!mask[i]) {
temp_data.setValue(JAGS_NA, i);
}
}
}
_model.symtab().writeData(temp_data_table);
}
void Compiler::writeRelations(ParseTree const *relations)
{
writeConstantData(relations);
// Set up boolean vector for nodes to indicate whether they are
// resolved or not.
_is_resolved = new bool[_n_relations];
for (unsigned int i = 0; i < _n_relations; ++i) {
_is_resolved[i] = false;
}
for (unsigned long N = _n_relations; N > 0; N -= _n_resolved) {
_n_resolved = 0;
traverseTree(relations, &Compiler::allocate);
if (_n_resolved == 0) {
// Try again, but this time throw an exception from getSubsetNode
_strict_resolution = true;
traverseTree(relations, &Compiler::allocate);
// If that didn't work (but it should!) just throw a generic message
throw runtime_error("Unable to resolve relations");
}
}
delete [] _is_resolved; _is_resolved = 0;
}
void Compiler::traverseTree(ParseTree const *relations, CompilerMemFn fun,
bool resetcounter)
{
/*
Traverse parse tree, expanding FOR loops and applying function
fun to relations.
*/
if (resetcounter) {
_n_relations = 0;
}
vector<ParseTree*> const &relation_list = relations->parameters();
for (vector<ParseTree*>::const_iterator p = relation_list.begin();
p != relation_list.end(); ++p)
{
Counter *counter;
ParseTree *var;
switch ((*p)->treeClass()) {
case P_FOR:
var = (*p)->parameters()[0];
if (!isNULL(CounterRange(var))) {
counter = _countertab.pushCounter(var->name(), CounterRange(var));
for (; !counter->atEnd(); counter->next()) {
traverseTree((*p)->parameters()[1], fun, false);
}
_countertab.popCounter();
}
break;
case P_STOCHREL: case P_DETRMREL:
(this->*fun)(*p);
_n_relations++;
break;
default:
throw logic_error("Malformed parse tree in Compiler::traverseTree");
break;
}
}
}
Compiler::Compiler(BUGSModel &model, map<string, SArray> const &data_table)
: _model(model), _countertab(),
_data_table(data_table), _n_resolved(0),
_n_relations(0), _is_resolved(0), _strict_resolution(false),
_index_expression(0), _index_nodes(),
_constantfactory(model.nchain())
{
if (_model.graph().size() != 0)
throw invalid_argument("Non empty graph in Compiler constructor");
if (_model.symtab().size() != 0)
throw invalid_argument("Non empty symtab in Compiler constructor");
}
void Compiler::declareVariables(vector<ParseTree*> const &dec_list)
{
vector<ParseTree*>::const_iterator p;
for (p = dec_list.begin() ; p != dec_list.end(); ++p) {
if ((*p)->treeClass() != P_VAR) {
throw invalid_argument("Expected variable expression");
}
}
for (p = dec_list.begin() ; p != dec_list.end(); ++p) {
ParseTree const *node_dec = *p;
string const &name = node_dec->name();
unsigned int ndim = node_dec->parameters().size();
if (ndim == 0) {
// Variable is scalar
_model.symtab().addVariable(name, vector<unsigned int>(1,1));
}
else {
// Variable is an array
vector<unsigned int> dim(ndim);
for (unsigned int i = 0; i < ndim; ++i) {
int dim_i;
if (!indexExpression(node_dec->parameters()[i], dim_i)) {
CompileError(node_dec, "Unable to calculate dimensions of node",
name);
}
if (dim_i <= 0) {
CompileError(node_dec, "Non-positive dimension for node", name);
}
dim[i] = static_cast<unsigned int>(dim_i);
}
_model.symtab().addVariable(name, dim);
}
}
}
void Compiler::undeclaredVariables(ParseTree const *prelations)
{
// Get undeclared variables from data table
map<string, SArray>::const_iterator p = _data_table.begin();
for (; p != _data_table.end(); ++p) {
string const &name = p->first;
NodeArray const *array = _model.symtab().getVariable(name);
if (array) {
if (p->second.range() != array->range()) {
string msg = string("Dimensions of ") + name +
" in declaration (" + print(array->range()) +
") conflict with dimensions in data (" +
print(p->second.range()) + ")";
throw runtime_error(msg);
}
}
else {
_model.symtab().addVariable(name, p->second.dim(false));
}
}
// Infer the dimension of remaining nodes from the relations
traverseTree(prelations, &Compiler::getArrayDim);
map<string, vector<vector<int> > >::const_iterator i =
_node_array_ranges.begin();
for (; i != _node_array_ranges.end(); ++i) {
if (_model.symtab().getVariable(i->first)) {
//Node already declared. Check consistency
NodeArray const * array = _model.symtab().getVariable(i->first);
vector<int> const &upper = array->range().upper();
if (upper.size() != i->second[1].size()) {
string msg = "Dimension mismatch between data and model for node ";
msg.append(i->first);
throw runtime_error(msg);
}
for (unsigned int j = 0; j < upper.size(); ++j) {
if (i->second[1][j] > upper[j]) {
string msg = string("Index out of range for node ") + i->first;
throw runtime_error(msg);
}
}
}
else {
//Node not declared. Use inferred size
vector<int> const &upper = i->second[1];
unsigned int ndim = upper.size();
vector<unsigned int> dim(ndim);
for (unsigned int j = 0; j < ndim; ++j) {
if (upper[j] <= 0) {
string msg = string("Invalid index for node ") + i->first;
throw runtime_error(msg);
}
else {
dim[j] = static_cast<unsigned int>(upper[j]);
}
}
_model.symtab().addVariable(i->first, dim);
}
}
}
/*
We use construct-on-first-use for the lookup tables used by the
compiler. By dynamically allocating a table, 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 unload itself from a table that has already
been destroyed.
See also Model.cc, where the same technique is used for factory
lists.
*/
DistTab &Compiler::distTab()
{
static DistTab *_disttab = new DistTab();
return *_disttab;
}
FuncTab &Compiler::funcTab()
{
static FuncTab *_functab = new FuncTab();
return *_functab;
}
ObsFuncTab &Compiler::obsFuncTab()
{
static ObsFuncTab *_oftab = new ObsFuncTab();
return *_oftab;
}
MixtureFactory& Compiler::mixtureFactory1()
{
return _mixfactory1;
}
MixtureFactory& Compiler::mixtureFactory2()
{
return _mixfactory2;
}
BUGSModel &Compiler::model() const
{
return _model;
}