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 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="author" content="Stan Development Team" />
<meta name="date" content="2024-07-15" />
<title>Using the Stan Math C++ Library</title>
<style type="text/css">
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
</style>
<style type="text/css">
code {
white-space: pre;
}
.sourceCode {
overflow: visible;
}
</style>
<style type="text/css" data-origin="pandoc">
a.sourceLine { display: inline-block; line-height: 1.25; }
a.sourceLine { pointer-events: none; color: inherit; text-decoration: inherit; }
a.sourceLine:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode { white-space: pre; position: relative; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
code.sourceCode { white-space: pre-wrap; }
a.sourceLine { text-indent: -1em; padding-left: 1em; }
}
pre.numberSource a.sourceLine
{ position: relative; left: -4em; }
pre.numberSource a.sourceLine::before
{ content: attr(title);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; pointer-events: all; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
color: #aaaaaa;
}
pre.numberSource { margin-left: 3em; border-left: 1px solid #aaaaaa; padding-left: 4px; }
div.sourceCode
{ }
@media screen {
a.sourceLine::before { text-decoration: underline; }
}
code span.al { color: #ff0000; font-weight: bold; } /* Alert */
code span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
code span.at { color: #7d9029; } /* Attribute */
code span.bn { color: #40a070; } /* BaseN */
code span.bu { } /* BuiltIn */
code span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
code span.ch { color: #4070a0; } /* Char */
code span.cn { color: #880000; } /* Constant */
code span.co { color: #60a0b0; font-style: italic; } /* Comment */
code span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
code span.do { color: #ba2121; font-style: italic; } /* Documentation */
code span.dt { color: #902000; } /* DataType */
code span.dv { color: #40a070; } /* DecVal */
code span.er { color: #ff0000; font-weight: bold; } /* Error */
code span.ex { } /* Extension */
code span.fl { color: #40a070; } /* Float */
code span.fu { color: #06287e; } /* Function */
code span.im { } /* Import */
code span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
code span.kw { color: #007020; font-weight: bold; } /* Keyword */
code span.op { color: #666666; } /* Operator */
code span.ot { color: #007020; } /* Other */
code span.pp { color: #bc7a00; } /* Preprocessor */
code span.sc { color: #4070a0; } /* SpecialChar */
code span.ss { color: #bb6688; } /* SpecialString */
code span.st { color: #4070a0; } /* String */
code span.va { color: #19177c; } /* Variable */
code span.vs { color: #4070a0; } /* VerbatimString */
code span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
</style>
<script>
// apply pandoc div.sourceCode style to pre.sourceCode instead
(function() {
var sheets = document.styleSheets;
for (var i = 0; i < sheets.length; i++) {
if (sheets[i].ownerNode.dataset["origin"] !== "pandoc") continue;
try { var rules = sheets[i].cssRules; } catch (e) { continue; }
var j = 0;
while (j < rules.length) {
var rule = rules[j];
// check if there is a div.sourceCode rule
if (rule.type !== rule.STYLE_RULE || rule.selectorText !== "div.sourceCode") {
j++;
continue;
}
var style = rule.style.cssText;
// check if color or background-color is set
if (rule.style.color === '' && rule.style.backgroundColor === '') {
j++;
continue;
}
// replace div.sourceCode by a pre.sourceCode rule
sheets[i].deleteRule(j);
sheets[i].insertRule('pre.sourceCode{' + style + '}', j);
}
}
})();
</script>
<style type="text/css">body {
background-color: #fff;
margin: 1em auto;
max-width: 700px;
overflow: visible;
padding-left: 2em;
padding-right: 2em;
font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
line-height: 1.35;
}
#TOC {
clear: both;
margin: 0 0 10px 10px;
padding: 4px;
width: 400px;
border: 1px solid #CCCCCC;
border-radius: 5px;
background-color: #f6f6f6;
font-size: 13px;
line-height: 1.3;
}
#TOC .toctitle {
font-weight: bold;
font-size: 15px;
margin-left: 5px;
}
#TOC ul {
padding-left: 40px;
margin-left: -1.5em;
margin-top: 5px;
margin-bottom: 5px;
}
#TOC ul ul {
margin-left: -2em;
}
#TOC li {
line-height: 16px;
}
table {
margin: 1em auto;
border-width: 1px;
border-color: #DDDDDD;
border-style: outset;
border-collapse: collapse;
}
table th {
border-width: 2px;
padding: 5px;
border-style: inset;
}
table td {
border-width: 1px;
border-style: inset;
line-height: 18px;
padding: 5px 5px;
}
table, table th, table td {
border-left-style: none;
border-right-style: none;
}
table thead, table tr.even {
background-color: #f7f7f7;
}
p {
margin: 0.5em 0;
}
blockquote {
background-color: #f6f6f6;
padding: 0.25em 0.75em;
}
hr {
border-style: solid;
border: none;
border-top: 1px solid #777;
margin: 28px 0;
}
dl {
margin-left: 0;
}
dl dd {
margin-bottom: 13px;
margin-left: 13px;
}
dl dt {
font-weight: bold;
}
ul {
margin-top: 0;
}
ul li {
list-style: circle outside;
}
ul ul {
margin-bottom: 0;
}
pre, code {
background-color: #f7f7f7;
border-radius: 3px;
color: #333;
white-space: pre-wrap;
}
pre {
border-radius: 3px;
margin: 5px 0px 10px 0px;
padding: 10px;
}
pre:not([class]) {
background-color: #f7f7f7;
}
code {
font-family: Consolas, Monaco, 'Courier New', monospace;
font-size: 85%;
}
p > code, li > code {
padding: 2px 0px;
}
div.figure {
text-align: center;
}
img {
background-color: #FFFFFF;
padding: 2px;
border: 1px solid #DDDDDD;
border-radius: 3px;
border: 1px solid #CCCCCC;
margin: 0 5px;
}
h1 {
margin-top: 0;
font-size: 35px;
line-height: 40px;
}
h2 {
border-bottom: 4px solid #f7f7f7;
padding-top: 10px;
padding-bottom: 2px;
font-size: 145%;
}
h3 {
border-bottom: 2px solid #f7f7f7;
padding-top: 10px;
font-size: 120%;
}
h4 {
border-bottom: 1px solid #f7f7f7;
margin-left: 8px;
font-size: 105%;
}
h5, h6 {
border-bottom: 1px solid #ccc;
font-size: 105%;
}
a {
color: #0033dd;
text-decoration: none;
}
a:hover {
color: #6666ff; }
a:visited {
color: #800080; }
a:visited:hover {
color: #BB00BB; }
a[href^="http:"] {
text-decoration: underline; }
a[href^="https:"] {
text-decoration: underline; }
code > span.kw { color: #555; font-weight: bold; }
code > span.dt { color: #902000; }
code > span.dv { color: #40a070; }
code > span.bn { color: #d14; }
code > span.fl { color: #d14; }
code > span.ch { color: #d14; }
code > span.st { color: #d14; }
code > span.co { color: #888888; font-style: italic; }
code > span.ot { color: #007020; }
code > span.al { color: #ff0000; font-weight: bold; }
code > span.fu { color: #900; font-weight: bold; }
code > span.er { color: #a61717; background-color: #e3d2d2; }
</style>
</head>
<body>
<h1 class="title toc-ignore">Using the Stan Math C++ Library</h1>
<h4 class="author">Stan Development Team</h4>
<h4 class="date">2024-07-15</h4>
<div id="using-the-stanheaders-package-from-other-r-packages" class="section level1">
<h1>Using the <strong>StanHeaders</strong> Package from Other R Packages</h1>
<p>The <strong>StanHeaders</strong> package contains no R functions. To use the Stan Math Library in other packages, it is often sufficient to specify</p>
<pre><code>LinkingTo: StanHeaders (>= 2.26.0), RcppParallel (>= 5.0.1)</code></pre>
<p>in the DESCRIPTION file of another package and put something like</p>
<pre><code>CXX_STD = CXX17
PKG_CXXFLAGS = $(shell "$(R_HOME)/bin$(R_ARCH_BIN)/Rscript" -e "RcppParallel::CxxFlags()") \
$(shell "$(R_HOME)/bin$(R_ARCH_BIN)/Rscript" -e "StanHeaders:::CxxFlags()")
PKG_LIBS = $(shell "$(R_HOME)/bin$(R_ARCH_BIN)/Rscript" -e "RcppParallel::RcppParallelLibs()") \
$(shell "$(R_HOME)/bin$(R_ARCH_BIN)/Rscript" -e "StanHeaders:::LdFlags()")</code></pre>
<p>in the src/Makevars and src/Makevars.win files and put <code>GNU make</code> in the <code>SystemRequirements:</code> field of the package’s DESCRIPTION file. If, in addition, the other package needs to utilize the MCMC, optimization, variational inference, or parsing facilities of the Stan Library, then it is also necessary to include the <code>src</code> directory of <strong>StanHeaders</strong> in the other package’s <code>PKG_CXXFLAGS</code> in the src/Makevars and src/Makevars.win files with something like</p>
<pre><code>STANHEADERS_SRC = $(shell "$(R_HOME)/bin$(R_ARCH_BIN)/Rscript" -e "message()" \
-e "cat(system.file('include', 'src', package = 'StanHeaders', mustWork = TRUE))" \
-e "message()" | grep "StanHeaders")
PKG_CXXFLAGS += -I"$(STANHEADERS_SRC)"</code></pre>
</div>
<div id="calling-functions-in-the-stanheaders-package-from-r" class="section level1">
<h1>Calling functions in the <strong>StanHeaders</strong> Package from R</h1>
<p>The only exposed R function in the in the <strong>StanHeaders</strong> package is <code>stanFunction</code>, which can be used to call most functions in the Stan Math Library.</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb4-1" title="1"><span class="kw">example</span>(stanFunction, <span class="dt">package =</span> <span class="st">"StanHeaders"</span>, <span class="dt">run.dontrun =</span> <span class="ot">TRUE</span>)</a>
<a class="sourceLine" id="cb4-2" title="2"><span class="co">#> </span></a>
<a class="sourceLine" id="cb4-3" title="3"><span class="co">#> stnFnc> files <- dir(system.file("include", "stan", "math", "prim",</span></a>
<a class="sourceLine" id="cb4-4" title="4"><span class="co">#> stnFnc+ package = "StanHeaders"), </span></a>
<a class="sourceLine" id="cb4-5" title="5"><span class="co">#> stnFnc+ pattern = "hpp$", recursive = TRUE)</span></a>
<a class="sourceLine" id="cb4-6" title="6"><span class="co">#> </span></a>
<a class="sourceLine" id="cb4-7" title="7"><span class="co">#> stnFnc> functions <- sub("\\.hpp$", "", </span></a>
<a class="sourceLine" id="cb4-8" title="8"><span class="co">#> stnFnc+ sort(unique(basename(files[dirname(files) != "."]))))</span></a>
<a class="sourceLine" id="cb4-9" title="9"><span class="co">#> </span></a>
<a class="sourceLine" id="cb4-10" title="10"><span class="co">#> stnFnc> length(functions) # you could call most of these Stan functions</span></a>
<a class="sourceLine" id="cb4-11" title="11"><span class="co">#> [1] 955</span></a>
<a class="sourceLine" id="cb4-12" title="12"><span class="co">#> </span></a>
<a class="sourceLine" id="cb4-13" title="13"><span class="co">#> stnFnc> log(sum(exp(exp(1)), exp(pi))) # true value</span></a>
<a class="sourceLine" id="cb4-14" title="14"><span class="co">#> [1] 3.645318</span></a>
<a class="sourceLine" id="cb4-15" title="15"><span class="co">#> </span></a>
<a class="sourceLine" id="cb4-16" title="16"><span class="co">#> stnFnc> stanFunction("log_sum_exp", x = exp(1), y = pi)</span></a>
<a class="sourceLine" id="cb4-17" title="17"><span class="co">#> [1] 3.645318</span></a>
<a class="sourceLine" id="cb4-18" title="18"><span class="co">#> </span></a>
<a class="sourceLine" id="cb4-19" title="19"><span class="co">#> stnFnc> args(log_sum_exp) # now exists in .GlobalEnv</span></a>
<a class="sourceLine" id="cb4-20" title="20"><span class="co">#> function (x, y) </span></a>
<a class="sourceLine" id="cb4-21" title="21"><span class="co">#> NULL</span></a>
<a class="sourceLine" id="cb4-22" title="22"><span class="co">#> </span></a>
<a class="sourceLine" id="cb4-23" title="23"><span class="co">#> stnFnc> log_sum_exp(x = pi, y = exp(1))</span></a>
<a class="sourceLine" id="cb4-24" title="24"><span class="co">#> [1] 3.645318</span></a>
<a class="sourceLine" id="cb4-25" title="25"><span class="co">#> </span></a>
<a class="sourceLine" id="cb4-26" title="26"><span class="co">#> stnFnc> # but log_sum_exp() was not defined for a vector or matrix</span></a>
<a class="sourceLine" id="cb4-27" title="27"><span class="co">#> stnFnc> x <- c(exp(1), pi)</span></a>
<a class="sourceLine" id="cb4-28" title="28"><span class="co">#> </span></a>
<a class="sourceLine" id="cb4-29" title="29"><span class="co">#> stnFnc> try(log_sum_exp(x))</span></a>
<a class="sourceLine" id="cb4-30" title="30"><span class="co">#> Error in log_sum_exp(x) : argument "y" is missing, with no default</span></a>
<a class="sourceLine" id="cb4-31" title="31"><span class="co">#> </span></a>
<a class="sourceLine" id="cb4-32" title="32"><span class="co">#> stnFnc> stanFunction("log_sum_exp", x = x) # now it is</span></a>
<a class="sourceLine" id="cb4-33" title="33"><span class="co">#> [1] 3.645318</span></a>
<a class="sourceLine" id="cb4-34" title="34"><span class="co">#> </span></a>
<a class="sourceLine" id="cb4-35" title="35"><span class="co">#> stnFnc> # log_sum_exp() is now also defined for a matrix</span></a>
<a class="sourceLine" id="cb4-36" title="36"><span class="co">#> stnFnc> log_sum_exp(as.matrix(x))</span></a>
<a class="sourceLine" id="cb4-37" title="37"><span class="co">#> [1] 3.645318</span></a>
<a class="sourceLine" id="cb4-38" title="38"><span class="co">#> </span></a>
<a class="sourceLine" id="cb4-39" title="39"><span class="co">#> stnFnc> log_sum_exp(t(as.matrix(x)))</span></a>
<a class="sourceLine" id="cb4-40" title="40"><span class="co">#> [1] 3.645318</span></a>
<a class="sourceLine" id="cb4-41" title="41"><span class="co">#> </span></a>
<a class="sourceLine" id="cb4-42" title="42"><span class="co">#> stnFnc> log_sum_exp(rbind(x, x))</span></a>
<a class="sourceLine" id="cb4-43" title="43"><span class="co">#> [1] 4.338465</span></a>
<a class="sourceLine" id="cb4-44" title="44"><span class="co">#> </span></a>
<a class="sourceLine" id="cb4-45" title="45"><span class="co">#> stnFnc> # but log_sum_exp() was not defined for a list</span></a>
<a class="sourceLine" id="cb4-46" title="46"><span class="co">#> stnFnc> try(log_sum_exp(as.list(x)))</span></a>
<a class="sourceLine" id="cb4-47" title="47"><span class="co">#> Error in eval(ei, envir) : </span></a>
<a class="sourceLine" id="cb4-48" title="48"><span class="co">#> Not compatible with requested type: [type=list; target=double].</span></a>
<a class="sourceLine" id="cb4-49" title="49"><span class="co">#> </span></a>
<a class="sourceLine" id="cb4-50" title="50"><span class="co">#> stnFnc> stanFunction("log_sum_exp", x = as.list(x)) # now it is</span></a>
<a class="sourceLine" id="cb4-51" title="51"><span class="co">#> [1] 3.645318</span></a>
<a class="sourceLine" id="cb4-52" title="52"><span class="co">#> </span></a>
<a class="sourceLine" id="cb4-53" title="53"><span class="co">#> stnFnc> # in rare cases, passing a nested list is needed</span></a>
<a class="sourceLine" id="cb4-54" title="54"><span class="co">#> stnFnc> stanFunction("dims", x = list(list(1:3)))</span></a>
<a class="sourceLine" id="cb4-55" title="55"><span class="co">#> [1] 1 1 3</span></a>
<a class="sourceLine" id="cb4-56" title="56"><span class="co">#> </span></a>
<a class="sourceLine" id="cb4-57" title="57"><span class="co">#> stnFnc> # functions of complex arguments work</span></a>
<a class="sourceLine" id="cb4-58" title="58"><span class="co">#> stnFnc> stanFunction("eigenvalues", # different ordering than base:eigen()</span></a>
<a class="sourceLine" id="cb4-59" title="59"><span class="co">#> stnFnc+ x = matrix(complex(real = 1:9, imaginary = pi),</span></a>
<a class="sourceLine" id="cb4-60" title="60"><span class="co">#> stnFnc+ nrow = 3, ncol = 3))</span></a>
<a class="sourceLine" id="cb4-61" title="61"><span class="co">#> [1] -8.179880e-17+1.622085e-18i -8.612657e-01+4.854073e-01i 1.586127e+01+8.939371e+00i</span></a>
<a class="sourceLine" id="cb4-62" title="62"><span class="co">#> </span></a>
<a class="sourceLine" id="cb4-63" title="63"><span class="co">#> stnFnc> # nullary functions work but are not that interesting</span></a>
<a class="sourceLine" id="cb4-64" title="64"><span class="co">#> stnFnc> stanFunction("negative_infinity")</span></a>
<a class="sourceLine" id="cb4-65" title="65"><span class="co">#> [1] -Inf</span></a>
<a class="sourceLine" id="cb4-66" title="66"><span class="co">#> </span></a>
<a class="sourceLine" id="cb4-67" title="67"><span class="co">#> stnFnc> # PRNG functions work by adding a seed argument</span></a>
<a class="sourceLine" id="cb4-68" title="68"><span class="co">#> stnFnc> stanFunction("lkj_corr_rng", K = 3L, eta = 1)</span></a>
<a class="sourceLine" id="cb4-69" title="69"><span class="co">#> [,1] [,2] [,3]</span></a>
<a class="sourceLine" id="cb4-70" title="70"><span class="co">#> [1,] 1.00000000 0.5654780 0.03415387</span></a>
<a class="sourceLine" id="cb4-71" title="71"><span class="co">#> [2,] 0.56547796 1.0000000 0.24813894</span></a>
<a class="sourceLine" id="cb4-72" title="72"><span class="co">#> [3,] 0.03415387 0.2481389 1.00000000</span></a>
<a class="sourceLine" id="cb4-73" title="73"><span class="co">#> </span></a>
<a class="sourceLine" id="cb4-74" title="74"><span class="co">#> stnFnc> args(lkj_corr_rng) # has a seed argument</span></a>
<a class="sourceLine" id="cb4-75" title="75"><span class="co">#> function (K, eta, random_seed = sample.int(.Machine$integer.max, </span></a>
<a class="sourceLine" id="cb4-76" title="76"><span class="co">#> size = 1L)) </span></a>
<a class="sourceLine" id="cb4-77" title="77"><span class="co">#> NULL</span></a></code></pre></div>
<style type="text/css">
.scroll-100 {
max-height: 100px;
overflow-y: auto;
background-color: inherit;
}
</style>
<p>The <code>functions</code> object defined in this example lists the many Stan functions that could be called (if all their arguments are numeric, see <code>help(stanFunction, package = "StanHeaders")</code> for details)</p>
<pre><code>#> [,1] [,2]
#> [1,] "Eigen" "LDLT_factor"
#> [2,] "Phi" "Phi_approx"
#> [3,] "StdVectorBuilder" "VectorBuilder"
#> [4,] "VectorBuilderHelper" "abs"
#> [5,] "accumulator" "acos"
#> [6,] "acosh" "ad_promotable"
#> [7,] "add" "add_diag"
#> [8,] "algebra_solver_adapter" "all"
#> [9,] "any" "append_array"
#> [10,] "append_col" "append_return_type"
#> [11,] "append_row" "apply"
#> [12,] "apply_scalar_binary" "apply_scalar_ternary"
#> [13,] "apply_scalar_unary" "apply_vector_unary"
#> [14,] "arg" "array_builder"
#> [15,] "as_array_or_scalar" "as_bool"
#> [16,] "as_column_vector_or_scalar" "as_value_array_or_scalar"
#> [17,] "as_value_column_array_or_scalar" "as_value_column_vector_or_scalar"
#> [18,] "asin" "asinh"
#> [19,] "assign" "atan"
#> [20,] "atan2" "atanh"
#> [21,] "autocorrelation" "autocovariance"
#> [22,] "base_type" "bernoulli_ccdf_log"
#> [23,] "bernoulli_cdf" "bernoulli_cdf_log"
#> [24,] "bernoulli_lccdf" "bernoulli_lcdf"
#> [25,] "bernoulli_log" "bernoulli_logit_glm_log"
#> [26,] "bernoulli_logit_glm_lpmf" "bernoulli_logit_glm_rng"
#> [27,] "bernoulli_logit_log" "bernoulli_logit_lpmf"
#> [28,] "bernoulli_logit_rng" "bernoulli_lpmf"
#> [29,] "bernoulli_rng" "bessel_first_kind"
#> [30,] "bessel_second_kind" "beta"
#> [31,] "beta_binomial_ccdf_log" "beta_binomial_cdf"
#> [32,] "beta_binomial_cdf_log" "beta_binomial_lccdf"
#> [33,] "beta_binomial_lcdf" "beta_binomial_log"
#> [34,] "beta_binomial_lpmf" "beta_binomial_rng"
#> [35,] "beta_ccdf_log" "beta_cdf"
#> [36,] "beta_cdf_log" "beta_lccdf"
#> [37,] "beta_lcdf" "beta_log"
#> [38,] "beta_lpdf" "beta_proportion_ccdf_log"
#> [39,] "beta_proportion_cdf_log" "beta_proportion_lccdf"
#> [40,] "beta_proportion_lcdf" "beta_proportion_log"
#> [41,] "beta_proportion_lpdf" "beta_proportion_rng"
#> [42,] "beta_rng" "binary_log_loss"
#> [43,] "binomial_ccdf_log" "binomial_cdf"
#> [44,] "binomial_cdf_log" "binomial_coefficient_log"
#> [45,] "binomial_lccdf" "binomial_lcdf"
#> [46,] "binomial_log" "binomial_logit_log"
#> [47,] "binomial_logit_lpmf" "binomial_lpmf"
#> [48,] "binomial_rng" "block"
#> [49,] "bool_constant" "boost_policy"
#> [50,] "broadcast_array" "categorical_log"
#> [51,] "categorical_logit_glm_lpmf" "categorical_logit_log"
#> [52,] "categorical_logit_lpmf" "categorical_logit_rng"
#> [53,] "categorical_lpmf" "categorical_rng"
#> [54,] "cauchy_ccdf_log" "cauchy_cdf"
#> [55,] "cauchy_cdf_log" "cauchy_lccdf"
#> [56,] "cauchy_lcdf" "cauchy_log"
#> [57,] "cauchy_lpdf" "cauchy_rng"
#> [58,] "cbrt" "ceil"
#> [59,] "check_2F1_converges" "check_3F2_converges"
#> [60,] "check_bounded" "check_cholesky_factor"
#> [61,] "check_cholesky_factor_corr" "check_column_index"
#> [62,] "check_consistent_size" "check_consistent_sizes"
#> [63,] "check_consistent_sizes_mvt" "check_corr_matrix"
#> [64,] "check_cov_matrix" "check_finite"
#> [65,] "check_flag_sundials" "check_greater"
#> [66,] "check_greater_or_equal" "check_ldlt_factor"
#> [67,] "check_less" "check_less_or_equal"
#> [68,] "check_lower_triangular" "check_matching_dims"
#> [69,] "check_matching_sizes" "check_multiplicable"
#> [70,] "check_nonnegative" "check_nonzero_size"
#> [71,] "check_not_nan" "check_ordered"
#> [72,] "check_pos_definite" "check_pos_semidefinite"
#> [73,] "check_positive" "check_positive_finite"
#> [74,] "check_positive_ordered" "check_range"
#> [75,] "check_row_index" "check_simplex"
#> [76,] "check_size_match" "check_sorted"
#> [77,] "check_square" "check_std_vector_index"
#> [78,] "check_symmetric" "check_unit_vector"
#> [79,] "check_vector" "check_vector_index"
#> [80,] "chi_square_ccdf_log" "chi_square_cdf"
#> [81,] "chi_square_cdf_log" "chi_square_lccdf"
#> [82,] "chi_square_lcdf" "chi_square_log"
#> [83,] "chi_square_lpdf" "chi_square_rng"
#> [84,] "child_type" "chol2inv"
#> [85,] "cholesky_corr_constrain" "cholesky_corr_free"
#> [86,] "cholesky_decompose" "cholesky_factor_constrain"
#> [87,] "cholesky_factor_free" "choose"
#> [88,] "col" "cols"
#> [89,] "columns_dot_product" "columns_dot_self"
#> [90,] "compiler_attributes" "complex_base"
#> [91,] "complex_schur_decompose" "conj"
#> [92,] "conjunction" "constants"
#> [93,] "constraint_tolerance" "contains_fvar"
#> [94,] "contains_std_vector" "copysign"
#> [95,] "corr_constrain" "corr_free"
#> [96,] "corr_matrix_constrain" "corr_matrix_free"
#> [97,] "cos" "cosh"
#> [98,] "coupled_ode_system" "cov_exp_quad"
#> [99,] "cov_matrix_constrain" "cov_matrix_constrain_lkj"
#> [100,] "cov_matrix_free" "cov_matrix_free_lkj"
#> [101,] "crossprod" "csr_extract"
#> [102,] "csr_extract_u" "csr_extract_v"
#> [103,] "csr_extract_w" "csr_matrix_times_vector"
#> [104,] "csr_to_dense_matrix" "csr_u_to_z"
#> [105,] "cumulative_sum" "determinant"
#> [106,] "diag_matrix" "diag_post_multiply"
#> [107,] "diag_pre_multiply" "diagonal"
#> [108,] "digamma" "dims"
#> [109,] "dirichlet_log" "dirichlet_lpdf"
#> [110,] "dirichlet_lpmf" "dirichlet_rng"
#> [111,] "discrete_range_ccdf_log" "discrete_range_cdf"
#> [112,] "discrete_range_cdf_log" "discrete_range_lccdf"
#> [113,] "discrete_range_lcdf" "discrete_range_log"
#> [114,] "discrete_range_lpmf" "discrete_range_rng"
#> [115,] "disjunction" "distance"
#> [116,] "divide" "divide_columns"
#> [117,] "domain_error" "domain_error_vec"
#> [118,] "dot" "dot_product"
#> [119,] "dot_self" "double_exponential_ccdf_log"
#> [120,] "double_exponential_cdf" "double_exponential_cdf_log"
#> [121,] "double_exponential_lccdf" "double_exponential_lcdf"
#> [122,] "double_exponential_log" "double_exponential_lpdf"
#> [123,] "double_exponential_rng" "eigen_comparisons"
#> [124,] "eigendecompose" "eigendecompose_sym"
#> [125,] "eigenvalues" "eigenvalues_sym"
#> [126,] "eigenvectors" "eigenvectors_sym"
#> [127,] "elementwise_check" "elt_divide"
#> [128,] "elt_multiply" "erf"
#> [129,] "erfc" "error_index"
#> [130,] "eval" "exp"
#> [131,] "exp2" "exp_mod_normal_ccdf_log"
#> [132,] "exp_mod_normal_cdf" "exp_mod_normal_cdf_log"
#> [133,] "exp_mod_normal_lccdf" "exp_mod_normal_lcdf"
#> [134,] "exp_mod_normal_log" "exp_mod_normal_lpdf"
#> [135,] "exp_mod_normal_rng" "expm1"
#> [136,] "exponential_ccdf_log" "exponential_cdf"
#> [137,] "exponential_cdf_log" "exponential_lccdf"
#> [138,] "exponential_lcdf" "exponential_log"
#> [139,] "exponential_lpdf" "exponential_rng"
#> [140,] "fabs" "factor_U"
#> [141,] "factor_cov_matrix" "falling_factorial"
#> [142,] "fdim" "fft"
#> [143,] "fill" "finite_diff_gradient"
#> [144,] "finite_diff_gradient_auto" "finite_diff_stepsize"
#> [145,] "floor" "fma"
#> [146,] "fmax" "fmin"
#> [147,] "fmod" "for_each"
#> [148,] "forward_as" "frechet_ccdf_log"
#> [149,] "frechet_cdf" "frechet_cdf_log"
#> [150,] "frechet_lccdf" "frechet_lcdf"
#> [151,] "frechet_log" "frechet_lpdf"
#> [152,] "frechet_rng" "gamma_ccdf_log"
#> [153,] "gamma_cdf" "gamma_cdf_log"
#> [154,] "gamma_lccdf" "gamma_lcdf"
#> [155,] "gamma_log" "gamma_lpdf"
#> [156,] "gamma_p" "gamma_q"
#> [157,] "gamma_rng" "gaussian_dlm_obs_log"
#> [158,] "gaussian_dlm_obs_lpdf" "gaussian_dlm_obs_rng"
#> [159,] "generalized_inverse" "get"
#> [160,] "get_base1" "get_base1_lhs"
#> [161,] "get_imag" "get_lp"
#> [162,] "get_real" "gp_dot_prod_cov"
#> [163,] "gp_exp_quad_cov" "gp_exponential_cov"
#> [164,] "gp_matern32_cov" "gp_matern52_cov"
#> [165,] "gp_periodic_cov" "grad_2F1"
#> [166,] "grad_F32" "grad_inc_beta"
#> [167,] "grad_pFq" "grad_reg_inc_beta"
#> [168,] "grad_reg_inc_gamma" "grad_reg_lower_inc_gamma"
#> [169,] "gumbel_ccdf_log" "gumbel_cdf"
#> [170,] "gumbel_cdf_log" "gumbel_lccdf"
#> [171,] "gumbel_lcdf" "gumbel_log"
#> [172,] "gumbel_lpdf" "gumbel_rng"
#> [173,] "hcubature" "head"
#> [174,] "hmm_check" "hmm_hidden_state_prob"
#> [175,] "hmm_latent_rng" "hmm_marginal"
#> [176,] "holder" "hypergeometric_2F1"
#> [177,] "hypergeometric_2F2" "hypergeometric_3F2"
#> [178,] "hypergeometric_log" "hypergeometric_lpmf"
#> [179,] "hypergeometric_pFq" "hypergeometric_rng"
#> [180,] "hypot" "i_times"
#> [181,] "identity_constrain" "identity_free"
#> [182,] "identity_matrix" "if_else"
#> [183,] "imag" "inc_beta"
#> [184,] "inc_beta_dda" "inc_beta_ddb"
#> [185,] "inc_beta_ddz" "include_summand"
#> [186,] "index_apply" "index_type"
#> [187,] "init_threadpool_tbb" "initialize"
#> [188,] "initialize_fill" "int_step"
#> [189,] "integrate_1d" "integrate_1d_adapter"
#> [190,] "integrate_ode_rk45" "integrate_ode_std_vector_interface_adapter"
#> [191,] "inv" "inv_Phi"
#> [192,] "inv_chi_square_ccdf_log" "inv_chi_square_cdf"
#> [193,] "inv_chi_square_cdf_log" "inv_chi_square_lccdf"
#> [194,] "inv_chi_square_lcdf" "inv_chi_square_log"
#> [195,] "inv_chi_square_lpdf" "inv_chi_square_rng"
#> [196,] "inv_cloglog" "inv_erfc"
#> [197,] "inv_gamma_ccdf_log" "inv_gamma_cdf"
#> [198,] "inv_gamma_cdf_log" "inv_gamma_lccdf"
#> [199,] "inv_gamma_lcdf" "inv_gamma_log"
#> [200,] "inv_gamma_lpdf" "inv_gamma_rng"
#> [201,] "inv_inc_beta" "inv_logit"
#> [202,] "inv_sqrt" "inv_square"
#> [203,] "inv_wishart_cholesky_lpdf" "inv_wishart_cholesky_rng"
#> [204,] "inv_wishart_log" "inv_wishart_lpdf"
#> [205,] "inv_wishart_rng" "invalid_argument"
#> [206,] "invalid_argument_vec" "inverse"
#> [207,] "inverse_softmax" "inverse_spd"
#> [208,] "is_any_nan" "is_arena_matrix"
#> [209,] "is_autodiff" "is_base_pointer_convertible"
#> [210,] "is_cholesky_factor" "is_cholesky_factor_corr"
#> [211,] "is_column_index" "is_complex"
#> [212,] "is_constant" "is_container"
#> [213,] "is_container_or_var_matrix" "is_corr_matrix"
#> [214,] "is_dense_dynamic" "is_detected"
#> [215,] "is_double_or_int" "is_eigen"
#> [216,] "is_eigen_dense_base" "is_eigen_dense_dynamic"
#> [217,] "is_eigen_matrix" "is_eigen_matrix_base"
#> [218,] "is_eigen_sparse_base" "is_fvar"
#> [219,] "is_inf" "is_integer"
#> [220,] "is_kernel_expression" "is_ldlt_factor"
#> [221,] "is_less_or_equal" "is_lower_triangular"
#> [222,] "is_mat_finite" "is_matching_dims"
#> [223,] "is_matching_size" "is_matrix"
#> [224,] "is_matrix_cl" "is_nan"
#> [225,] "is_nonpositive_integer" "is_nonzero_size"
#> [226,] "is_not_nan" "is_ordered"
#> [227,] "is_plain_type" "is_pos_definite"
#> [228,] "is_positive" "is_rev_matrix"
#> [229,] "is_scal_finite" "is_size_match"
#> [230,] "is_square" "is_stan_scalar"
#> [231,] "is_stan_scalar_or_eigen" "is_string_convertible"
#> [232,] "is_symmetric" "is_tuple"
#> [233,] "is_uninitialized" "is_unit_vector"
#> [234,] "is_var" "is_var_and_matrix_types"
#> [235,] "is_var_dense_dynamic" "is_var_eigen"
#> [236,] "is_var_matrix" "is_var_or_arithmetic"
#> [237,] "is_vari" "is_vector"
#> [238,] "is_vector_like" "isfinite"
#> [239,] "isinf" "isnan"
#> [240,] "isnormal" "lambert_w"
#> [241,] "lb_constrain" "lb_free"
#> [242,] "lbeta" "ldexp"
#> [243,] "lgamma" "lgamma_stirling"
#> [244,] "lgamma_stirling_diff" "linspaced_array"
#> [245,] "linspaced_int_array" "linspaced_row_vector"
#> [246,] "linspaced_vector" "lkj_corr_cholesky_log"
#> [247,] "lkj_corr_cholesky_lpdf" "lkj_corr_cholesky_rng"
#> [248,] "lkj_corr_log" "lkj_corr_lpdf"
#> [249,] "lkj_corr_rng" "lkj_cov_log"
#> [250,] "lkj_cov_lpdf" "lmgamma"
#> [251,] "lmultiply" "log"
#> [252,] "log10" "log1m"
#> [253,] "log1m_exp" "log1m_inv_logit"
#> [254,] "log1p" "log1p_exp"
#> [255,] "log2" "log_determinant"
#> [256,] "log_determinant_ldlt" "log_determinant_spd"
#> [257,] "log_diff_exp" "log_falling_factorial"
#> [258,] "log_inv_logit" "log_inv_logit_diff"
#> [259,] "log_mix" "log_modified_bessel_first_kind"
#> [260,] "log_rising_factorial" "log_softmax"
#> [261,] "log_sum_exp" "log_sum_exp_signed"
#> [262,] "logb" "logical_and"
#> [263,] "logical_eq" "logical_gt"
#> [264,] "logical_gte" "logical_lt"
#> [265,] "logical_lte" "logical_negation"
#> [266,] "logical_neq" "logical_or"
#> [267,] "logistic_ccdf_log" "logistic_cdf"
#> [268,] "logistic_cdf_log" "logistic_lccdf"
#> [269,] "logistic_lcdf" "logistic_log"
#> [270,] "logistic_lpdf" "logistic_rng"
#> [271,] "logit" "loglogistic_cdf"
#> [272,] "loglogistic_log" "loglogistic_lpdf"
#> [273,] "loglogistic_rng" "lognormal_ccdf_log"
#> [274,] "lognormal_cdf" "lognormal_cdf_log"
#> [275,] "lognormal_lccdf" "lognormal_lcdf"
#> [276,] "lognormal_log" "lognormal_lpdf"
#> [277,] "lognormal_rng" "lub_constrain"
#> [278,] "lub_free" "make_iter_name"
#> [279,] "make_nu" "map_rect"
#> [280,] "map_rect_combine" "map_rect_concurrent"
#> [281,] "map_rect_mpi" "map_rect_reduce"
#> [282,] "matrix_exp" "matrix_exp_2x2"
#> [283,] "matrix_exp_action_handler" "matrix_exp_multiply"
#> [284,] "matrix_exp_pade" "matrix_normal_prec_log"
#> [285,] "matrix_normal_prec_lpdf" "matrix_normal_prec_rng"
#> [286,] "matrix_power" "max"
#> [287,] "max_size" "max_size_mvt"
#> [288,] "mdivide_left" "mdivide_left_ldlt"
#> [289,] "mdivide_left_spd" "mdivide_left_tri"
#> [290,] "mdivide_left_tri_low" "mdivide_right"
#> [291,] "mdivide_right_ldlt" "mdivide_right_spd"
#> [292,] "mdivide_right_tri" "mdivide_right_tri_low"
#> [293,] "mean" "min"
#> [294,] "minus" "modified_bessel_first_kind"
#> [295,] "modified_bessel_second_kind" "modulus"
#> [296,] "mpi_cluster" "mpi_command"
#> [297,] "mpi_distributed_apply" "mpi_parallel_call"
#> [298,] "multi_gp_cholesky_log" "multi_gp_cholesky_lpdf"
#> [299,] "multi_gp_log" "multi_gp_lpdf"
#> [300,] "multi_normal_cholesky_log" "multi_normal_cholesky_lpdf"
#> [301,] "multi_normal_cholesky_rng" "multi_normal_log"
#> [302,] "multi_normal_lpdf" "multi_normal_prec_log"
#> [303,] "multi_normal_prec_lpdf" "multi_normal_prec_rng"
#> [304,] "multi_normal_rng" "multi_student_t_cholesky_lpdf"
#> [305,] "multi_student_t_cholesky_rng" "multi_student_t_log"
#> [306,] "multi_student_t_lpdf" "multi_student_t_rng"
#> [307,] "multinomial_log" "multinomial_logit_log"
#> [308,] "multinomial_logit_lpmf" "multinomial_logit_rng"
#> [309,] "multinomial_lpmf" "multinomial_rng"
#> [310,] "multiply" "multiply_log"
#> [311,] "multiply_lower_tri_self_transpose" "neg_binomial_2_ccdf_log"
#> [312,] "neg_binomial_2_cdf" "neg_binomial_2_cdf_log"
#> [313,] "neg_binomial_2_lccdf" "neg_binomial_2_lcdf"
#> [314,] "neg_binomial_2_log" "neg_binomial_2_log_glm_log"
#> [315,] "neg_binomial_2_log_glm_lpmf" "neg_binomial_2_log_log"
#> [316,] "neg_binomial_2_log_lpmf" "neg_binomial_2_log_rng"
#> [317,] "neg_binomial_2_lpmf" "neg_binomial_2_rng"
#> [318,] "neg_binomial_ccdf_log" "neg_binomial_cdf"
#> [319,] "neg_binomial_cdf_log" "neg_binomial_lccdf"
#> [320,] "neg_binomial_lcdf" "neg_binomial_log"
#> [321,] "neg_binomial_lpmf" "neg_binomial_rng"
#> [322,] "norm" "norm1"
#> [323,] "norm2" "normal_ccdf_log"
#> [324,] "normal_cdf" "normal_cdf_log"
#> [325,] "normal_id_glm_log" "normal_id_glm_lpdf"
#> [326,] "normal_lccdf" "normal_lcdf"
#> [327,] "normal_log" "normal_lpdf"
#> [328,] "normal_rng" "normal_sufficient_log"
#> [329,] "normal_sufficient_lpdf" "num_elements"
#> [330,] "ode_ckrk" "ode_rk45"
#> [331,] "ode_store_sensitivities" "offset_multiplier_constrain"
#> [332,] "offset_multiplier_free" "one_hot_array"
#> [333,] "one_hot_int_array" "one_hot_row_vector"
#> [334,] "one_hot_vector" "ones_array"
#> [335,] "ones_int_array" "ones_row_vector"
#> [336,] "ones_vector" "operands_and_partials"
#> [337,] "operator_addition" "operator_division"
#> [338,] "operator_equal_equal" "operator_minus"
#> [339,] "operator_multiplication" "operator_not_equal"
#> [340,] "operator_plus" "operator_subtraction"
#> [341,] "ordered_constrain" "ordered_free"
#> [342,] "ordered_logistic_glm_lpmf" "ordered_logistic_log"
#> [343,] "ordered_logistic_lpmf" "ordered_logistic_rng"
#> [344,] "ordered_probit_log" "ordered_probit_lpmf"
#> [345,] "ordered_probit_rng" "out_of_range"
#> [346,] "owens_t" "pareto_ccdf_log"
#> [347,] "pareto_cdf" "pareto_cdf_log"
#> [348,] "pareto_lccdf" "pareto_lcdf"
#> [349,] "pareto_log" "pareto_lpdf"
#> [350,] "pareto_rng" "pareto_type_2_ccdf_log"
#> [351,] "pareto_type_2_cdf" "pareto_type_2_cdf_log"
#> [352,] "pareto_type_2_lccdf" "pareto_type_2_lcdf"
#> [353,] "pareto_type_2_log" "pareto_type_2_lpdf"
#> [354,] "pareto_type_2_rng" "partials_propagator"
#> [355,] "partials_return_type" "partials_type"
#> [356,] "plain_type" "plus"
#> [357,] "poisson_binomial_ccdf_log" "poisson_binomial_cdf"
#> [358,] "poisson_binomial_cdf_log" "poisson_binomial_lccdf"
#> [359,] "poisson_binomial_lcdf" "poisson_binomial_log"
#> [360,] "poisson_binomial_log_probs" "poisson_binomial_lpmf"
#> [361,] "poisson_binomial_rng" "poisson_ccdf_log"
#> [362,] "poisson_cdf" "poisson_cdf_log"
#> [363,] "poisson_lccdf" "poisson_lcdf"
#> [364,] "poisson_log" "poisson_log_glm_log"
#> [365,] "poisson_log_glm_lpmf" "poisson_log_log"
#> [366,] "poisson_log_lpmf" "poisson_log_rng"
#> [367,] "poisson_lpmf" "poisson_rng"
#> [368,] "polar" "positive_constrain"
#> [369,] "positive_free" "positive_ordered_constrain"
#> [370,] "positive_ordered_free" "possibly_sum"
#> [371,] "pow" "primitive_value"
#> [372,] "prob_constrain" "prob_free"
#> [373,] "prod" "proj"
#> [374,] "promote_args" "promote_elements"
#> [375,] "promote_scalar" "promote_scalar_type"
#> [376,] "pseudo_eigenvalues" "pseudo_eigenvectors"
#> [377,] "qr" "qr_Q"
#> [378,] "qr_R" "qr_thin"
#> [379,] "qr_thin_Q" "qr_thin_R"
#> [380,] "quad_form" "quad_form_diag"
#> [381,] "quad_form_sym" "quantile"
#> [382,] "rank" "rayleigh_ccdf_log"
#> [383,] "rayleigh_cdf" "rayleigh_cdf_log"
#> [384,] "rayleigh_lccdf" "rayleigh_lcdf"
#> [385,] "rayleigh_log" "rayleigh_lpdf"
#> [386,] "rayleigh_rng" "read_corr_L"
#> [387,] "read_corr_matrix" "read_cov_L"
#> [388,] "read_cov_matrix" "real"
#> [389,] "reduce_sum" "reduce_sum_static"
#> [390,] "ref_type" "rep_array"
#> [391,] "rep_matrix" "rep_row_vector"
#> [392,] "rep_vector" "require_generics"
#> [393,] "require_helpers" "resize"
#> [394,] "return_type" "reverse"
#> [395,] "rising_factorial" "round"
#> [396,] "row" "rows"
#> [397,] "rows_dot_product" "rows_dot_self"
#> [398,] "scalar_seq_view" "scalar_type"
#> [399,] "scalar_type_pre" "scalbn"
#> [400,] "scale_matrix_exp_multiply" "scaled_add"
#> [401,] "scaled_inv_chi_square_ccdf_log" "scaled_inv_chi_square_cdf"
#> [402,] "scaled_inv_chi_square_cdf_log" "scaled_inv_chi_square_lccdf"
#> [403,] "scaled_inv_chi_square_lcdf" "scaled_inv_chi_square_log"
#> [404,] "scaled_inv_chi_square_lpdf" "scaled_inv_chi_square_rng"
#> [405,] "sd" "segment"
#> [406,] "select" "seq_view"
#> [407,] "sign" "signbit"
#> [408,] "simplex_constrain" "simplex_free"
#> [409,] "sin" "singular_values"
#> [410,] "sinh" "size"
#> [411,] "size_mvt" "size_zero"
#> [412,] "skew_double_exponential_ccdf_log" "skew_double_exponential_cdf"
#> [413,] "skew_double_exponential_cdf_log" "skew_double_exponential_lccdf"
#> [414,] "skew_double_exponential_lcdf" "skew_double_exponential_log"
#> [415,] "skew_double_exponential_lpdf" "skew_double_exponential_rng"
#> [416,] "skew_normal_ccdf_log" "skew_normal_cdf"
#> [417,] "skew_normal_cdf_log" "skew_normal_lccdf"
#> [418,] "skew_normal_lcdf" "skew_normal_log"
#> [419,] "skew_normal_lpdf" "skew_normal_rng"
#> [420,] "softmax" "sort_asc"
#> [421,] "sort_desc" "sort_indices"
#> [422,] "sort_indices_asc" "sort_indices_desc"
#> [423,] "sqrt" "square"
#> [424,] "squared_distance" "stan_print"
#> [425,] "static_select" "std_normal_ccdf_log"
#> [426,] "std_normal_cdf" "std_normal_cdf_log"
#> [427,] "std_normal_lccdf" "std_normal_lcdf"
#> [428,] "std_normal_log" "std_normal_log_qf"
#> [429,] "std_normal_lpdf" "std_normal_rng"
#> [430,] "step" "student_t_ccdf_log"
#> [431,] "student_t_cdf" "student_t_cdf_log"
#> [432,] "student_t_lccdf" "student_t_lcdf"
#> [433,] "student_t_log" "student_t_lpdf"
#> [434,] "student_t_rng" "sub_col"
#> [435,] "sub_row" "subtract"
#> [436,] "sum" "svd"
#> [437,] "svd_U" "svd_V"
#> [438,] "symmetrize_from_lower_tri" "symmetrize_from_upper_tri"
#> [439,] "system_error" "tail"
#> [440,] "tan" "tanh"
#> [441,] "tcrossprod" "tgamma"
#> [442,] "throw_domain_error" "throw_domain_error_mat"
#> [443,] "throw_domain_error_vec" "to_array_1d"
#> [444,] "to_array_2d" "to_complex"
#> [445,] "to_int" "to_matrix"
#> [446,] "to_ref" "to_row_vector"
#> [447,] "to_vector" "trace"
#> [448,] "trace_gen_inv_quad_form_ldlt" "trace_gen_quad_form"
#> [449,] "trace_inv_quad_form_ldlt" "trace_quad_form"
#> [450,] "transpose" "trigamma"
#> [451,] "trunc" "typedefs"
#> [452,] "ub_constrain" "ub_free"
#> [453,] "uniform_ccdf_log" "uniform_cdf"
#> [454,] "uniform_cdf_log" "uniform_lccdf"
#> [455,] "uniform_lcdf" "uniform_log"
#> [456,] "uniform_lpdf" "uniform_rng"
#> [457,] "uniform_simplex" "unit_vector_constrain"
#> [458,] "unit_vector_free" "unitspaced_array"
#> [459,] "validate_non_negative_index" "validate_positive_index"
#> [460,] "validate_unit_vector_index" "value_of"
#> [461,] "value_of_rec" "value_type"
#> [462,] "variance" "vec_concat"
#> [463,] "vector_seq_view" "void_t"
#> [464,] "von_mises_ccdf_log" "von_mises_cdf"
#> [465,] "von_mises_cdf_log" "von_mises_lccdf"
#> [466,] "von_mises_lcdf" "von_mises_log"
#> [467,] "von_mises_lpdf" "von_mises_rng"
#> [468,] "weibull_ccdf_log" "weibull_cdf"
#> [469,] "weibull_cdf_log" "weibull_lccdf"
#> [470,] "weibull_lcdf" "weibull_log"
#> [471,] "weibull_lpdf" "weibull_rng"
#> [472,] "welford_covar_estimator" "welford_var_estimator"
#> [473,] "wiener_log" "wiener_lpdf"
#> [474,] "wishart_cholesky_lpdf" "wishart_cholesky_rng"
#> [475,] "wishart_log" "wishart_lpdf"
#> [476,] "wishart_rng" "zeros_array"
#> [477,] "zeros_int_array" "zeros_row_vector"
#> [478,] "zeros_vector" ""</code></pre>
</div>
<div id="using-higher-order-functions-in-the-stanheaders-package" class="section level1">
<h1>Using Higher-Order Functions in the <strong>StanHeaders</strong> Package</h1>
<p>This section will demonstrate how to use some of the C++ functions in the <strong>StanHeaders</strong> package whose first argument is another C++ function, in which case the <code>stanFunction</code> in the previous section will not work and you have to write your own C++.</p>
<div id="derivatives-and-minimization" class="section level2">
<h2>Derivatives and Minimization</h2>
<p>The following is a toy example of using the Stan Math library via <code>Rcpp::sourceCpp</code>: to minimize the function <span class="math display">\[\left(\mathbf{x} - \mathbf{a}\right)^\top \left(\mathbf{x} - \mathbf{a}\right)\]</span> which has a global minimum when <span class="math inline">\(\mathbf{x} = \mathbf{a}\)</span>. To find this minimum with autodifferentiation, we need to define the objective function. Then, its gradient with respect to <span class="math inline">\(\mathbf{x}\)</span>, which we know is <span class="math inline">\(2\left(\mathbf{x} - \mathbf{a}\right)\)</span> in this case, can be calculated by autodifferentiation. At the optimum (or on the way to the optimum), we might want to evaluate the Hessian matrix, which we know is <span class="math inline">\(2\mathbf{I}\)</span>, but would need an additional function to evaluate it via autodifferentiation. Finally, one could reconceptualize the problem as solving a homogeneous system of equations where the gradient is set equal to a vector of zeros. The <code>stan::math::algebra_solver</code> function can solve such a system using autodifferentiation to obtain the Jacobian, which we know to be the identity matrix in this case.</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb6-1" title="1"><span class="kw">Sys.setenv</span>(<span class="dt">PKG_CXXFLAGS =</span> StanHeaders<span class="op">:::</span><span class="kw">CxxFlags</span>(<span class="dt">as_character =</span> <span class="ot">TRUE</span>))</a>
<a class="sourceLine" id="cb6-2" title="2">SH <-<span class="st"> </span><span class="kw">system.file</span>(<span class="kw">ifelse</span>(.Platform<span class="op">$</span>OS.type <span class="op">==</span><span class="st"> "windows"</span>, <span class="st">"libs"</span>, <span class="st">"lib"</span>), .Platform<span class="op">$</span>r_arch,</a>
<a class="sourceLine" id="cb6-3" title="3"> <span class="dt">package =</span> <span class="st">"StanHeaders"</span>, <span class="dt">mustWork =</span> <span class="ot">TRUE</span>)</a>
<a class="sourceLine" id="cb6-4" title="4"><span class="kw">Sys.setenv</span>(<span class="dt">PKG_LIBS =</span> <span class="kw">paste0</span>(StanHeaders<span class="op">:::</span><span class="kw">LdFlags</span>(<span class="dt">as_character =</span> <span class="ot">TRUE</span>),</a>
<a class="sourceLine" id="cb6-5" title="5"> <span class="st">" -L"</span>, <span class="kw">shQuote</span>(SH), <span class="st">" -lStanHeaders"</span>))</a>
<a class="sourceLine" id="cb6-6" title="6"> </a></code></pre></div>
<p>Here is C++ code that does all of the above, except for the part of finding the optimum, which is done using the R function <code>optim</code> below.</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode cpp"><code class="sourceCode cpp"><a class="sourceLine" id="cb7-1" title="1"><span class="co">// [[Rcpp::depends(BH)]]</span></a>
<a class="sourceLine" id="cb7-2" title="2"><span class="co">// [[Rcpp::depends(RcppEigen)]]</span></a>
<a class="sourceLine" id="cb7-3" title="3"><span class="co">// [[Rcpp::depends(RcppParallel)]]</span></a>
<a class="sourceLine" id="cb7-4" title="4"><span class="co">// [[Rcpp::depends(StanHeaders)]]</span></a>
<a class="sourceLine" id="cb7-5" title="5"><span class="pp">#include </span><span class="im"><stan/math/mix.hpp></span><span class="pp"> </span><span class="co">// stuff from mix/ must come first</span></a>
<a class="sourceLine" id="cb7-6" title="6"><span class="pp">#include </span><span class="im"><stan/math.hpp></span><span class="pp"> </span><span class="co">// finally pull in everything from rev/ and prim/</span></a>
<a class="sourceLine" id="cb7-7" title="7"><span class="pp">#include </span><span class="im"><Rcpp.h></span></a>
<a class="sourceLine" id="cb7-8" title="8"><span class="pp">#include </span><span class="im"><RcppEigen.h></span><span class="pp"> </span><span class="co">// do this AFTER including stuff from stan/math</span></a>
<a class="sourceLine" id="cb7-9" title="9"></a>
<a class="sourceLine" id="cb7-10" title="10"><span class="co">// [[Rcpp::plugins(cpp17)]]</span></a>
<a class="sourceLine" id="cb7-11" title="11"></a>
<a class="sourceLine" id="cb7-12" title="12"><span class="co">/* Objective function */</span></a>
<a class="sourceLine" id="cb7-13" title="13"></a>
<a class="sourceLine" id="cb7-14" title="14"><span class="co">// [[Rcpp::export]]</span></a>
<a class="sourceLine" id="cb7-15" title="15"><span class="kw">auto</span> f(Eigen::VectorXd x, Eigen::VectorXd a) { <span class="co">// objective function in doubles</span></a>
<a class="sourceLine" id="cb7-16" title="16"> <span class="kw">using</span> stan::math::dot_self; <span class="co">// dot_self() is a dot product with self</span></a>
<a class="sourceLine" id="cb7-17" title="17"> <span class="cf">return</span> dot_self( (x - a) );</a>
<a class="sourceLine" id="cb7-18" title="18">}</a>
<a class="sourceLine" id="cb7-19" title="19"></a>
<a class="sourceLine" id="cb7-20" title="20"><span class="co">/* Gradient */</span></a>
<a class="sourceLine" id="cb7-21" title="21"></a>
<a class="sourceLine" id="cb7-22" title="22"><span class="co">// [[Rcpp::export]]</span></a>
<a class="sourceLine" id="cb7-23" title="23"><span class="kw">auto</span> g(Eigen::VectorXd x, Eigen::VectorXd a) { <span class="co">// gradient by AD using Stan</span></a>
<a class="sourceLine" id="cb7-24" title="24"> <span class="dt">double</span> fx;</a>
<a class="sourceLine" id="cb7-25" title="25"> Eigen::VectorXd grad_fx;</a>
<a class="sourceLine" id="cb7-26" title="26"> <span class="kw">using</span> stan::math::dot_self;</a>
<a class="sourceLine" id="cb7-27" title="27"> stan::math::gradient([&a](<span class="kw">auto</span> x) { <span class="cf">return</span> dot_self( (x - a) ); },</a>
<a class="sourceLine" id="cb7-28" title="28"> x, fx, grad_fx);</a>
<a class="sourceLine" id="cb7-29" title="29"> <span class="cf">return</span> grad_fx;</a>
<a class="sourceLine" id="cb7-30" title="30">}</a>
<a class="sourceLine" id="cb7-31" title="31"></a>
<a class="sourceLine" id="cb7-32" title="32"><span class="co">/* Hessian */</span></a>
<a class="sourceLine" id="cb7-33" title="33"></a>
<a class="sourceLine" id="cb7-34" title="34"><span class="co">// [[Rcpp::export]]</span></a>
<a class="sourceLine" id="cb7-35" title="35"><span class="kw">auto</span> H(Eigen::VectorXd x, Eigen::VectorXd a) { <span class="co">// Hessian by AD using Stan</span></a>
<a class="sourceLine" id="cb7-36" title="36"> <span class="dt">double</span> fx;</a>
<a class="sourceLine" id="cb7-37" title="37"> Eigen::VectorXd grad_fx;</a>
<a class="sourceLine" id="cb7-38" title="38"> Eigen::MatrixXd H;</a>
<a class="sourceLine" id="cb7-39" title="39"> <span class="kw">using</span> stan::math::dot_self;</a>
<a class="sourceLine" id="cb7-40" title="40"> stan::math::hessian([&a](<span class="kw">auto</span> x) { <span class="cf">return</span> dot_self(x - a); },</a>
<a class="sourceLine" id="cb7-41" title="41"> x, fx, grad_fx, H);</a>
<a class="sourceLine" id="cb7-42" title="42"> <span class="cf">return</span> H;</a>
<a class="sourceLine" id="cb7-43" title="43">}</a>
<a class="sourceLine" id="cb7-44" title="44"></a>
<a class="sourceLine" id="cb7-45" title="45"><span class="co">/* Jacobian */</span></a>
<a class="sourceLine" id="cb7-46" title="46"></a>
<a class="sourceLine" id="cb7-47" title="47"><span class="co">// [[Rcpp::export]]</span></a>
<a class="sourceLine" id="cb7-48" title="48"><span class="kw">auto</span> J(Eigen::VectorXd x, Eigen::VectorXd a) { <span class="co">// not actually used</span></a>
<a class="sourceLine" id="cb7-49" title="49"> Eigen::VectorXd fx;</a>
<a class="sourceLine" id="cb7-50" title="50"> Eigen::MatrixXd J;</a>
<a class="sourceLine" id="cb7-51" title="51"> <span class="kw">using</span> stan::math::dot_self;</a>
<a class="sourceLine" id="cb7-52" title="52"> stan::math::jacobian([&a](<span class="kw">auto</span> x) {</a>
<a class="sourceLine" id="cb7-53" title="53"> <span class="cf">return</span> (<span class="dv">2</span> * (x - a));</a>
<a class="sourceLine" id="cb7-54" title="54"> }, x, fx, J);</a>
<a class="sourceLine" id="cb7-55" title="55"> <span class="cf">return</span> J;</a>
<a class="sourceLine" id="cb7-56" title="56">}</a>
<a class="sourceLine" id="cb7-57" title="57"></a>
<a class="sourceLine" id="cb7-58" title="58"><span class="kw">struct</span> equations_functor {</a>
<a class="sourceLine" id="cb7-59" title="59"> <span class="kw">template</span> <<span class="kw">typename</span> T0, <span class="kw">typename</span> T1></a>
<a class="sourceLine" id="cb7-60" title="60"> <span class="kw">inline</span> Eigen::Matrix<T0, Eigen::Dynamic, <span class="dv">1</span>></a>
<a class="sourceLine" id="cb7-61" title="61"> <span class="kw">operator</span>()(<span class="at">const</span> Eigen::Matrix<T0, Eigen::Dynamic, <span class="dv">1</span>>& x,</a>
<a class="sourceLine" id="cb7-62" title="62"> <span class="at">const</span> Eigen::Matrix<T1, Eigen::Dynamic, <span class="dv">1</span>>& theta,</a>
<a class="sourceLine" id="cb7-63" title="63"> <span class="at">const</span> <span class="bu">std::</span>vector<<span class="dt">double</span>>& x_r, <span class="at">const</span> <span class="bu">std::</span>vector<<span class="dt">int</span>>& x_i,</a>
<a class="sourceLine" id="cb7-64" title="64"> <span class="bu">std::</span>ostream* pstream__) <span class="at">const</span> {</a>
<a class="sourceLine" id="cb7-65" title="65"> <span class="cf">return</span> <span class="dv">2</span> * (x - stan::math::to_vector(x_r));</a>
<a class="sourceLine" id="cb7-66" title="66"> }</a>
<a class="sourceLine" id="cb7-67" title="67">};</a>
<a class="sourceLine" id="cb7-68" title="68"></a>
<a class="sourceLine" id="cb7-69" title="69"><span class="co">// [[Rcpp::export]]</span></a>
<a class="sourceLine" id="cb7-70" title="70"><span class="kw">auto</span> solution(Eigen::VectorXd a, Eigen::VectorXd guess) {</a>
<a class="sourceLine" id="cb7-71" title="71"> Eigen::VectorXd theta;</a>
<a class="sourceLine" id="cb7-72" title="72"> <span class="kw">auto</span> x_r = stan::math::to_array_1d(a);</a>
<a class="sourceLine" id="cb7-73" title="73"> equations_functor f;</a>
<a class="sourceLine" id="cb7-74" title="74"> <span class="kw">auto</span> x = stan::math::algebra_solver(f, guess, theta, x_r, {});</a>
<a class="sourceLine" id="cb7-75" title="75"> <span class="cf">return</span> x;</a>
<a class="sourceLine" id="cb7-76" title="76">}</a></code></pre></div>
<p>In this compiled RMarkdown document, the <strong>knitr</strong> package has exported functions <code>f</code>, <code>g</code>, <code>H</code>, <code>J</code> and <code>solution</code> (but not <code>equations_functor</code>) to R’s global environment using the <code>sourceCpp</code> function in the <strong>Rcpp</strong> package, so that they can now be called from R. Here we find the optimum starting from a random point in three dimensions:</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb8-1" title="1">x <-<span class="st"> </span><span class="kw">optim</span>(<span class="kw">rnorm</span>(<span class="dv">3</span>), <span class="dt">fn =</span> f, <span class="dt">gr =</span> g, <span class="dt">a =</span> <span class="dv">1</span><span class="op">:</span><span class="dv">3</span>, <span class="dt">method =</span> <span class="st">"BFGS"</span>, <span class="dt">hessian =</span> <span class="ot">TRUE</span>)</a>
<a class="sourceLine" id="cb8-2" title="2">x<span class="op">$</span>par</a>
<a class="sourceLine" id="cb8-3" title="3"><span class="co">#> [1] 1 2 3</span></a>
<a class="sourceLine" id="cb8-4" title="4">x<span class="op">$</span>hessian</a>
<a class="sourceLine" id="cb8-5" title="5"><span class="co">#> [,1] [,2] [,3]</span></a>
<a class="sourceLine" id="cb8-6" title="6"><span class="co">#> [1,] 2 0 0</span></a>
<a class="sourceLine" id="cb8-7" title="7"><span class="co">#> [2,] 0 2 0</span></a>
<a class="sourceLine" id="cb8-8" title="8"><span class="co">#> [3,] 0 0 2</span></a>
<a class="sourceLine" id="cb8-9" title="9"><span class="kw">H</span>(x<span class="op">$</span>par, <span class="dt">a =</span> <span class="dv">1</span><span class="op">:</span><span class="dv">3</span>)</a>
<a class="sourceLine" id="cb8-10" title="10"><span class="co">#> [,1] [,2] [,3]</span></a>
<a class="sourceLine" id="cb8-11" title="11"><span class="co">#> [1,] 2 0 0</span></a>
<a class="sourceLine" id="cb8-12" title="12"><span class="co">#> [2,] 0 2 0</span></a>
<a class="sourceLine" id="cb8-13" title="13"><span class="co">#> [3,] 0 0 2</span></a>
<a class="sourceLine" id="cb8-14" title="14"><span class="kw">J</span>(x<span class="op">$</span>par, <span class="dt">a =</span> <span class="dv">1</span><span class="op">:</span><span class="dv">3</span>)</a>
<a class="sourceLine" id="cb8-15" title="15"><span class="co">#> [,1] [,2] [,3]</span></a>
<a class="sourceLine" id="cb8-16" title="16"><span class="co">#> [1,] 2 0 0</span></a>
<a class="sourceLine" id="cb8-17" title="17"><span class="co">#> [2,] 0 2 0</span></a>
<a class="sourceLine" id="cb8-18" title="18"><span class="co">#> [3,] 0 0 2</span></a>
<a class="sourceLine" id="cb8-19" title="19"><span class="kw">solution</span>(<span class="dt">a =</span> <span class="dv">1</span><span class="op">:</span><span class="dv">3</span>, <span class="dt">guess =</span> <span class="kw">rnorm</span>(<span class="dv">3</span>))</a>
<a class="sourceLine" id="cb8-20" title="20"><span class="co">#> [1] 1 2 3</span></a></code></pre></div>
</div>
</div>
<div id="integrals-and-ordinary-differential-equations" class="section level1">
<h1>Integrals and Ordinary Differential Equations</h1>
<p>The Stan Math library can do one-dimensional numerical integration and can solve stiff and non-stiff systems of differential equations, such as the harmonic oscillator example below. Solving stiff systems utilizes the CVODES library, which is included in <strong>StanHeaders</strong>.</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode cpp"><code class="sourceCode cpp"><a class="sourceLine" id="cb9-1" title="1"><span class="co">// [[Rcpp::depends(BH)]]</span></a>
<a class="sourceLine" id="cb9-2" title="2"><span class="co">// [[Rcpp::depends(RcppEigen)]]</span></a>
<a class="sourceLine" id="cb9-3" title="3"><span class="co">// [[Rcpp::depends(RcppParallel)]]</span></a>
<a class="sourceLine" id="cb9-4" title="4"><span class="co">// [[Rcpp::depends(StanHeaders)]]</span></a>
<a class="sourceLine" id="cb9-5" title="5"><span class="pp">#include </span><span class="im"><stan/math.hpp></span><span class="pp"> </span><span class="co">// pulls in everything from rev/ and prim/</span></a>
<a class="sourceLine" id="cb9-6" title="6"><span class="pp">#include </span><span class="im"><Rcpp.h></span></a>
<a class="sourceLine" id="cb9-7" title="7"><span class="pp">#include </span><span class="im"><RcppEigen.h></span><span class="pp"> </span><span class="co">// do this AFTER including stan/math</span></a>
<a class="sourceLine" id="cb9-8" title="8"></a>
<a class="sourceLine" id="cb9-9" title="9"><span class="co">// [[Rcpp::plugins(cpp17)]]</span></a>
<a class="sourceLine" id="cb9-10" title="10"></a>
<a class="sourceLine" id="cb9-11" title="11"><span class="co">/* Definite integrals */</span></a>
<a class="sourceLine" id="cb9-12" title="12"></a>
<a class="sourceLine" id="cb9-13" title="13"><span class="co">// [[Rcpp::export]]</span></a>
<a class="sourceLine" id="cb9-14" title="14"><span class="dt">double</span> Cauchy(<span class="dt">double</span> scale) {</a>
<a class="sourceLine" id="cb9-15" title="15"> <span class="bu">std::</span>vector<<span class="dt">double</span>> theta;</a>
<a class="sourceLine" id="cb9-16" title="16"> <span class="kw">auto</span> half = stan::math::integrate_1d([](<span class="kw">auto</span> x, <span class="kw">auto</span> xc, <span class="kw">auto</span> theta,</a>
<a class="sourceLine" id="cb9-17" title="17"> <span class="kw">auto</span> x_r, <span class="kw">auto</span> x_i, <span class="kw">auto</span> msgs) {</a>
<a class="sourceLine" id="cb9-18" title="18"> <span class="cf">return</span> exp(stan::math::cauchy_lpdf(x, <span class="dv">0</span>, x_r[<span class="dv">0</span>]));</a>
<a class="sourceLine" id="cb9-19" title="19"> }, -scale, scale, theta, {scale}, {}, <span class="kw">nullptr</span>, <span class="fl">1e-7</span>);</a>
<a class="sourceLine" id="cb9-20" title="20"> <span class="cf">return</span> half * <span class="dv">2</span>; <span class="co">// should equal 1 for any positive scale</span></a>
<a class="sourceLine" id="cb9-21" title="21">}</a>
<a class="sourceLine" id="cb9-22" title="22"></a>
<a class="sourceLine" id="cb9-23" title="23"><span class="co">/* Ordinary Differential Equations */</span></a>
<a class="sourceLine" id="cb9-24" title="24"></a>
<a class="sourceLine" id="cb9-25" title="25"><span class="co">// [[Rcpp::export]]</span></a>
<a class="sourceLine" id="cb9-26" title="26"><span class="kw">auto</span> nonstiff(Eigen::MatrixXd A, Eigen::VectorXd y0) {</a>
<a class="sourceLine" id="cb9-27" title="27"> <span class="kw">using</span> stan::math::integrate_ode_rk45;</a>
<a class="sourceLine" id="cb9-28" title="28"> <span class="kw">using</span> stan::math::to_vector;</a>
<a class="sourceLine" id="cb9-29" title="29"> <span class="kw">using</span> stan::math::to_array_1d;</a>
<a class="sourceLine" id="cb9-30" title="30"> <span class="bu">std::</span>vector<<span class="dt">double</span>> theta;</a>
<a class="sourceLine" id="cb9-31" title="31"> <span class="bu">std::</span>vector<<span class="dt">double</span>> times = {<span class="dv">1</span>, <span class="dv">2</span>};</a>
<a class="sourceLine" id="cb9-32" title="32"> <span class="kw">auto</span> y = integrate_ode_rk45([&A](<span class="kw">auto</span> t, <span class="kw">auto</span> y, </a>
<a class="sourceLine" id="cb9-33" title="33"> <span class="kw">auto</span> theta, <span class="kw">auto</span> x_r, <span class="kw">auto</span> x_i, <span class="bu">std::</span>ostream *msgs) {</a>
<a class="sourceLine" id="cb9-34" title="34"> <span class="cf">return</span> to_array_1d( (A * to_vector(y)).eval() );</a>
<a class="sourceLine" id="cb9-35" title="35"> }, to_array_1d(y0), <span class="dv">0</span>, times, theta, {}, {});</a>
<a class="sourceLine" id="cb9-36" title="36"> Eigen::VectorXd truth = stan::math::matrix_exp(A) * y0;</a>
<a class="sourceLine" id="cb9-37" title="37"> <span class="cf">return</span> (to_vector(y[<span class="dv">0</span>]) - truth).eval(); <span class="co">// should be "zero"</span></a>
<a class="sourceLine" id="cb9-38" title="38">}</a>
<a class="sourceLine" id="cb9-39" title="39"></a>
<a class="sourceLine" id="cb9-40" title="40"><span class="co">// [[Rcpp::export]]</span></a>
<a class="sourceLine" id="cb9-41" title="41"><span class="kw">auto</span> stiff(Eigen::MatrixXd A, Eigen::VectorXd y0) { <span class="co">// not actually stiff</span></a>
<a class="sourceLine" id="cb9-42" title="42"> <span class="kw">using</span> stan::math::integrate_ode_bdf; <span class="co">// but use the stiff solver anyways</span></a>
<a class="sourceLine" id="cb9-43" title="43"> <span class="kw">using</span> stan::math::to_vector;</a>
<a class="sourceLine" id="cb9-44" title="44"> <span class="kw">using</span> stan::math::to_array_1d;</a>
<a class="sourceLine" id="cb9-45" title="45"> <span class="bu">std::</span>vector<<span class="dt">double</span>> theta;</a>
<a class="sourceLine" id="cb9-46" title="46"> <span class="bu">std::</span>vector<<span class="dt">double</span>> times = {<span class="dv">1</span>, <span class="dv">2</span>};</a>
<a class="sourceLine" id="cb9-47" title="47"> <span class="kw">auto</span> y = integrate_ode_bdf([&A](<span class="kw">auto</span> t, <span class="kw">auto</span> y, </a>
<a class="sourceLine" id="cb9-48" title="48"> <span class="kw">auto</span> theta, <span class="kw">auto</span> x_r, <span class="kw">auto</span> x_i, <span class="bu">std::</span>ostream *msgs) {</a>
<a class="sourceLine" id="cb9-49" title="49"> <span class="cf">return</span> to_array_1d( (A * to_vector(y)).eval() );</a>
<a class="sourceLine" id="cb9-50" title="50"> }, to_array_1d(y0), <span class="dv">0</span>, times, theta, {}, {});</a>
<a class="sourceLine" id="cb9-51" title="51"> Eigen::VectorXd truth = stan::math::matrix_exp(A) * y0;</a>
<a class="sourceLine" id="cb9-52" title="52"> <span class="cf">return</span> (to_vector(y[<span class="dv">0</span>]) - truth).eval(); <span class="co">// should be "zero"</span></a>
<a class="sourceLine" id="cb9-53" title="53">}</a></code></pre></div>
<p>Again, in this compiled RMarkdown document, the <strong>knitr</strong> package has exported the <code>Cauchy</code>, <code>nonstiff</code> and <code>stiff</code> functions to R’s global environment using the <code>sourceCpp</code> function in the <strong>Rcpp</strong> package so that they can be called from R.</p>
<p>First, we numerically integrate the Cauchy PDF over its interquartile range — which has an area of <span class="math inline">\(\frac{1}{2}\)</span> — that we then double to verify that it is almost within machine precision of <span class="math inline">\(1\)</span>.</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb10-1" title="1"><span class="kw">all.equal</span>(<span class="dv">1</span>, <span class="kw">Cauchy</span>(<span class="kw">rexp</span>(<span class="dv">1</span>)), <span class="dt">tol =</span> <span class="fl">1e-15</span>)</a>
<a class="sourceLine" id="cb10-2" title="2"><span class="co">#> [1] TRUE</span></a></code></pre></div>
<p>Next, we consider the system of differential equations <span class="math display">\[\frac{d}{dt}\mathbf{y} = \mathbf{A}\mathbf{y}\]</span> where <span class="math inline">\(\mathbf{A}\)</span> is a square matrix such as that for a simple harmonic oscillator</p>
<p><span class="math display">\[\mathbf{A} = \begin{bmatrix}0 & 1 \\ -1 & -\theta\end{bmatrix}\]</span> for <span class="math inline">\(\theta \in \left(0,1\right)\)</span>. The solution for <span class="math inline">\(\mathbf{y}_t = e^{t\mathbf{A}}\mathbf{y}_0\)</span> can be obtained via the matrix exponential function, which is available in the Stan Math Library, but it can also be obtained numerically using a fourth-order Runge-Kutta solver, which is appropriate for non-stiff systems of ODEs, such as this one. However, it is possible, albeit less efficient in this case, to use the backward-differentiation formula solver for stiff systems of ODEs. In both cases, we calculate the difference between the analytical solution and the numerical one, and the stiff version does produce somewhat better accuracy in this case.</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb11-1" title="1">A <-<span class="st"> </span><span class="kw">matrix</span>(<span class="kw">c</span>(<span class="dv">0</span>, <span class="dv">-1</span>, <span class="dv">1</span>, <span class="op">-</span><span class="kw">runif</span>(<span class="dv">1</span>)), <span class="dt">nrow =</span> <span class="dv">2</span>, <span class="dt">ncol =</span> <span class="dv">2</span>)</a>
<a class="sourceLine" id="cb11-2" title="2">y0 <-<span class="st"> </span><span class="kw">rexp</span>(<span class="dv">2</span>)</a>
<a class="sourceLine" id="cb11-3" title="3"><span class="kw">all.equal</span>(<span class="kw">nonstiff</span>(A, y0), <span class="kw">c</span>(<span class="dv">0</span>, <span class="dv">0</span>), <span class="dt">tol =</span> <span class="fl">1e-5</span>)</a>
<a class="sourceLine" id="cb11-4" title="4"><span class="co">#> [1] TRUE</span></a>
<a class="sourceLine" id="cb11-5" title="5"><span class="kw">all.equal</span>( <span class="kw">stiff</span>(A, y0), <span class="kw">c</span>(<span class="dv">0</span>, <span class="dv">0</span>), <span class="dt">tol =</span> <span class="fl">1e-8</span>)</a>
<a class="sourceLine" id="cb11-6" title="6"><span class="co">#> [1] TRUE</span></a></code></pre></div>
</div>
<div id="parellelization" class="section level1">
<h1>Parellelization</h1>
<div id="map_rect-function" class="section level2">
<h2><code>map_rect</code> Function</h2>
<p>The Stan Math Library includes the <code>map_rect</code> function, which applies a function to each element of rectangular arrays and returns a vector, making it a bit like a restricted version of R’s <code>sapply</code> function. However, <code>map_rect</code> can also be executed in parallel by defining the pre-processor directive <code>STAN_THREADS</code> and then setting the <code>STAN_NUM_THREADS</code> environmental variable to be the number of threads to use, as in</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb12-1" title="1"><span class="kw">Sys.setenv</span>(<span class="dt">STAN_NUM_THREADS =</span> <span class="dv">2</span>) <span class="co"># specify -1 to use all available cores</span></a></code></pre></div>
<p>Below is C++ code to test whether an integer is prime, using a rather brute-force algorithm and running it in parallel via <code>map_rect</code>.</p>
<div class="sourceCode" id="cb13"><pre class="sourceCode cpp"><code class="sourceCode cpp"><a class="sourceLine" id="cb13-1" title="1"><span class="co">// [[Rcpp::depends(BH)]]</span></a>
<a class="sourceLine" id="cb13-2" title="2"><span class="co">// [[Rcpp::depends(RcppEigen)]]</span></a>
<a class="sourceLine" id="cb13-3" title="3"><span class="co">// [[Rcpp::depends(RcppParallel)]]</span></a>
<a class="sourceLine" id="cb13-4" title="4"><span class="co">// [[Rcpp::depends(StanHeaders)]]</span></a>
<a class="sourceLine" id="cb13-5" title="5"><span class="pp">#include </span><span class="im"><stan/math.hpp></span><span class="pp"> </span><span class="co">// pulls in everything from rev/ and prim/</span></a>
<a class="sourceLine" id="cb13-6" title="6"><span class="pp">#include </span><span class="im"><Rcpp.h></span></a>
<a class="sourceLine" id="cb13-7" title="7"><span class="pp">#include </span><span class="im"><RcppEigen.h></span><span class="pp"> </span><span class="co">// do this AFTER including stan/math</span></a>
<a class="sourceLine" id="cb13-8" title="8"></a>
<a class="sourceLine" id="cb13-9" title="9"><span class="co">// [[Rcpp::plugins(cpp17)]]</span></a>
<a class="sourceLine" id="cb13-10" title="10"></a>
<a class="sourceLine" id="cb13-11" title="11"><span class="co">// see https://en.wikipedia.org/wiki/Primality_test#Pseudocode</span></a>
<a class="sourceLine" id="cb13-12" title="12"><span class="kw">struct</span> is_prime {</a>
<a class="sourceLine" id="cb13-13" title="13"> is_prime() {}</a>
<a class="sourceLine" id="cb13-14" title="14"> <span class="kw">template</span> <<span class="kw">typename</span> T1, <span class="kw">typename</span> T2></a>
<a class="sourceLine" id="cb13-15" title="15"> <span class="kw">auto</span></a>
<a class="sourceLine" id="cb13-16" title="16"> <span class="kw">operator</span>()(<span class="at">const</span> Eigen::Matrix<T1, Eigen::Dynamic, <span class="dv">1</span>>& eta,</a>
<a class="sourceLine" id="cb13-17" title="17"> <span class="at">const</span> Eigen::Matrix<T2, Eigen::Dynamic, <span class="dv">1</span>>& theta,</a>
<a class="sourceLine" id="cb13-18" title="18"> <span class="at">const</span> <span class="bu">std::</span>vector<<span class="dt">double</span>>& x_r, <span class="at">const</span> <span class="bu">std::</span>vector<<span class="dt">int</span>>& x_i,</a>
<a class="sourceLine" id="cb13-19" title="19"> <span class="bu">std::</span>ostream* msgs = <span class="kw">nullptr</span>) <span class="at">const</span> {</a>
<a class="sourceLine" id="cb13-20" title="20"> Eigen::VectorXd res(<span class="dv">1</span>); <span class="co">// can only return double or var vectors</span></a>
<a class="sourceLine" id="cb13-21" title="21"> <span class="dt">int</span> n = x_i[<span class="dv">0</span>];</a>
<a class="sourceLine" id="cb13-22" title="22"> <span class="cf">if</span> (n <= <span class="dv">3</span>) {</a>
<a class="sourceLine" id="cb13-23" title="23"> res.coeffRef(<span class="dv">0</span>) = n > <span class="dv">1</span>;</a>
<a class="sourceLine" id="cb13-24" title="24"> <span class="cf">return</span> res;</a>
<a class="sourceLine" id="cb13-25" title="25"> } <span class="cf">else</span> <span class="cf">if</span> ( (n % <span class="dv">2</span> == <span class="dv">0</span>) || (n % <span class="dv">3</span> == <span class="dv">0</span>) ) {</a>
<a class="sourceLine" id="cb13-26" title="26"> res.coeffRef(<span class="dv">0</span>) = <span class="kw">false</span>;</a>
<a class="sourceLine" id="cb13-27" title="27"> <span class="cf">return</span> res;</a>
<a class="sourceLine" id="cb13-28" title="28"> }</a>
<a class="sourceLine" id="cb13-29" title="29"> <span class="dt">int</span> i = <span class="dv">5</span>;</a>
<a class="sourceLine" id="cb13-30" title="30"> <span class="cf">while</span> (i * i <= n) {</a>
<a class="sourceLine" id="cb13-31" title="31"> <span class="cf">if</span> ( (n % i == <span class="dv">0</span>) || (n % (i + <span class="dv">2</span>) == <span class="dv">0</span>) ) {</a>
<a class="sourceLine" id="cb13-32" title="32"> res.coeffRef(<span class="dv">0</span>) = <span class="kw">false</span>;</a>
<a class="sourceLine" id="cb13-33" title="33"> <span class="cf">return</span> res;</a>
<a class="sourceLine" id="cb13-34" title="34"> }</a>
<a class="sourceLine" id="cb13-35" title="35"> i += <span class="dv">6</span>;</a>
<a class="sourceLine" id="cb13-36" title="36"> }</a>
<a class="sourceLine" id="cb13-37" title="37"> res.coeffRef(<span class="dv">0</span>) = <span class="kw">true</span>;</a>
<a class="sourceLine" id="cb13-38" title="38"> <span class="cf">return</span> res;</a>
<a class="sourceLine" id="cb13-39" title="39"> }</a>
<a class="sourceLine" id="cb13-40" title="40">};</a>
<a class="sourceLine" id="cb13-41" title="41"></a>
<a class="sourceLine" id="cb13-42" title="42"><span class="co">/* parallelization */</span></a>
<a class="sourceLine" id="cb13-43" title="43"><span class="co">// [[Rcpp::export]]</span></a>
<a class="sourceLine" id="cb13-44" title="44"><span class="kw">auto</span> psapply(<span class="bu">std::</span>vector<<span class="bu">std::</span>vector<<span class="dt">int</span>> > n) {</a>
<a class="sourceLine" id="cb13-45" title="45"> <span class="bu">std::</span>vector<Eigen::VectorXd> eta(n.size()); <span class="co">// these all have to be the same size</span></a>
<a class="sourceLine" id="cb13-46" title="46"> Eigen::VectorXd theta;</a>
<a class="sourceLine" id="cb13-47" title="47"> <span class="bu">std::</span>vector<<span class="bu">std::</span>vector<<span class="dt">double</span>> > x_d(n.size());</a>
<a class="sourceLine" id="cb13-48" title="48"> <span class="cf">return</span> stan::math::map_rect<<span class="dv">0</span>, is_prime>(theta, eta, x_d, n, &Rcpp::Rcout);</a>
<a class="sourceLine" id="cb13-49" title="49">}</a></code></pre></div>
<p>Since the signature for <code>n</code> is a <code>std::vector<std::vector<int> ></code>, we have to pass it from R as a list (which is converted to the outer <code>std::vector<></code>) of integer vectors (which is converted to the inner <code>std::vector<int></code>) that happen to be of size one in this case.</p>
<div class="sourceCode" id="cb14"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb14-1" title="1">odd <-<span class="st"> </span><span class="kw">seq.int</span>(<span class="dt">from =</span> <span class="dv">2</span><span class="op">^</span><span class="dv">25</span> <span class="op">-</span><span class="st"> </span><span class="dv">1</span>, <span class="dt">to =</span> <span class="dv">2</span><span class="op">^</span><span class="dv">26</span> <span class="op">-</span><span class="st"> </span><span class="dv">1</span>, <span class="dt">by =</span> <span class="dv">2</span>)</a>
<a class="sourceLine" id="cb14-2" title="2"><span class="kw">tail</span>(<span class="kw">psapply</span>(<span class="dt">n =</span> <span class="kw">as.list</span>(odd))) <span class="op">==</span><span class="st"> </span><span class="dv">1</span> <span class="co"># check your process manager while this is running</span></a>
<a class="sourceLine" id="cb14-3" title="3"><span class="co">#> [1] FALSE FALSE FALSE TRUE FALSE FALSE</span></a></code></pre></div>
<p>Thus, <span class="math inline">\(2^{26} - 5 = 67,108,859\)</span> is a prime number.</p>
</div>
<div id="reduce_sum-function" class="section level2">
<h2><code>reduce_sum</code> Function</h2>
<p>The <code>reduce_sum</code> function can be used to sum a function of recursively-partitioned data in parallel. The Probability Mass Function (PMF) of the logarithmic distribution is</p>
<p><span class="math display">\[\Pr\left(x = k \mid p\right) = \frac{p^k}{-k\ln\left(1 - p\right)} \]</span> for a positive integer <span class="math inline">\(k\)</span> and <span class="math inline">\(0 < p < 1\)</span>. To verify that this PMF sums to <span class="math inline">\(1\)</span> over the natural numbers, we could accumulate it for a large finite number of terms, but would like to do so in parallel. To do so, we need to define a <code>partial_sum</code> function that adds the PMF for some subset of natural numbers and pass it to the <code>reduce_sum</code> function like</p>
<div class="sourceCode" id="cb15"><pre class="sourceCode cpp"><code class="sourceCode cpp"><a class="sourceLine" id="cb15-1" title="1"><span class="co">// [[Rcpp::depends(BH)]]</span></a>
<a class="sourceLine" id="cb15-2" title="2"><span class="co">// [[Rcpp::depends(RcppEigen)]]</span></a>
<a class="sourceLine" id="cb15-3" title="3"><span class="co">// [[Rcpp::depends(RcppParallel)]]</span></a>
<a class="sourceLine" id="cb15-4" title="4"><span class="co">// [[Rcpp::depends(StanHeaders)]]</span></a>
<a class="sourceLine" id="cb15-5" title="5"><span class="pp">#include </span><span class="im"><stan/math.hpp></span><span class="pp"> </span><span class="co">// pulls in everything from rev/ and prim/</span></a>
<a class="sourceLine" id="cb15-6" title="6"><span class="pp">#include </span><span class="im"><Rcpp.h></span></a>
<a class="sourceLine" id="cb15-7" title="7"><span class="pp">#include </span><span class="im"><RcppEigen.h></span><span class="pp"> </span><span class="co">// do this AFTER including stan/math</span></a>
<a class="sourceLine" id="cb15-8" title="8"></a>
<a class="sourceLine" id="cb15-9" title="9"><span class="co">// [[Rcpp::plugins(cpp17)]]</span></a>
<a class="sourceLine" id="cb15-10" title="10"></a>
<a class="sourceLine" id="cb15-11" title="11"><span class="kw">template</span> <<span class="kw">typename</span> T></a>
<a class="sourceLine" id="cb15-12" title="12"><span class="kw">struct</span> partial_sum {</a>
<a class="sourceLine" id="cb15-13" title="13"> partial_sum() {}</a>
<a class="sourceLine" id="cb15-14" title="14"> T <span class="kw">operator</span>()(<span class="at">const</span> <span class="bu">std::</span>vector<<span class="dt">int</span>>& k_slice, </a>
<a class="sourceLine" id="cb15-15" title="15"> <span class="dt">int</span> start, <span class="dt">int</span> end, <span class="co">// these are ignored in this example</span></a>
<a class="sourceLine" id="cb15-16" title="16"> <span class="bu">std::</span>ostream* msgs, <span class="dt">double</span> p) {</a>
<a class="sourceLine" id="cb15-17" title="17"> <span class="dt">double</span> S = <span class="dv">0</span>;</a>
<a class="sourceLine" id="cb15-18" title="18"> <span class="cf">for</span> (<span class="dt">int</span> n = <span class="dv">0</span>; n < k_slice.size(); n++) {</a>
<a class="sourceLine" id="cb15-19" title="19"> <span class="dt">int</span> k = k_slice[n];</a>
<a class="sourceLine" id="cb15-20" title="20"> S += stan::math::pow(p, k) / k;</a>
<a class="sourceLine" id="cb15-21" title="21"> }</a>
<a class="sourceLine" id="cb15-22" title="22"> <span class="cf">return</span> S;</a>
<a class="sourceLine" id="cb15-23" title="23"> }</a>
<a class="sourceLine" id="cb15-24" title="24">};</a>
<a class="sourceLine" id="cb15-25" title="25"></a>
<a class="sourceLine" id="cb15-26" title="26"><span class="co">// [[Rcpp::export]]</span></a>
<a class="sourceLine" id="cb15-27" title="27"><span class="dt">double</span> check_logarithmic_PMF(<span class="at">const</span> <span class="dt">double</span> p, <span class="at">const</span> <span class="dt">int</span> N = <span class="dv">1000</span>) {</a>
<a class="sourceLine" id="cb15-28" title="28"> <span class="kw">using</span> stan::math::reduce_sum;</a>
<a class="sourceLine" id="cb15-29" title="29"> <span class="bu">std::</span>vector<<span class="dt">int</span>> k(N);</a>
<a class="sourceLine" id="cb15-30" title="30"> <span class="bu">std::</span>iota(k.begin(), k.end(), <span class="dv">1</span>);</a>
<a class="sourceLine" id="cb15-31" title="31"> <span class="cf">return</span> reduce_sum<partial_sum<<span class="dt">double</span>> >(k, <span class="dv">1</span>, <span class="kw">nullptr</span>, p) / -<span class="bu">std::</span>log1p(-p);</a>
<a class="sourceLine" id="cb15-32" title="32">}</a></code></pre></div>
<p>The second argument passed to <code>reduce_sum</code> is the <code>grainsize</code>, which governs the size (and number) of the recursive subsets of <code>k</code> that are passed to the <code>partial_sum</code> function. A <code>grainsize</code> of <span class="math inline">\(1\)</span> indicates that the software will try to automatically tune the subset size for good performance, but that may be worse than choosing a <code>grainsize</code> by hand in a problem-specific fashion.</p>
<p>In any event, we can call the wrapper function <code>check_logarithmic_PMF</code> in R to verify that it returns <span class="math inline">\(1\)</span> to numerical tolerance:</p>
<div class="sourceCode" id="cb16"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb16-1" title="1"><span class="kw">stopifnot</span>(<span class="kw">all.equal</span>(<span class="dv">1</span>, <span class="kw">check_logarithmic_PMF</span>(<span class="dt">p =</span> <span class="dv">1</span> <span class="op">/</span><span class="st"> </span><span class="kw">sqrt</span>(<span class="dv">2</span>))))</a></code></pre></div>
</div>
</div>
<div id="defining-a-stan-model-in-c" class="section level1">
<h1>Defining a Stan Model in C++</h1>
<p>The Stan <em>language</em> does not have much support for sparse matrices for a variety of reasons. Essentially the only applicable function is <code>csr_matrix_times_vector</code>, which pre-multiplies a vector by a sparse matrix in compressed row storage by taking as arguments its number of rows, columns, non-zero values, column indices of non-zero values, and locations where the non-zero values start in each row. While the <code>csr_matrix_times_vector</code> function could be used to implement the example below, we illustrate how to use the sparse data structures in the <strong>Matrix</strong> and <strong>RcppEigen</strong> packages in a Stan model written in C++, which could easily be extended to more complicated models with sparse data structures.</p>
<p>Our C++ file for the log-likelihood of a linear model with a sparse design matrix reads as</p>
<pre><code>#include <stan/model/model_header.hpp>
#include <Rcpp.h>
#include <RcppEigen.h>
class sparselm_stan {
public: // these would ordinarily be private in the C++ code generated by Stan
Eigen::Map<Eigen::SparseMatrix<double> > X;
Eigen::VectorXd y;
sparselm_stan(Eigen::Map<Eigen::SparseMatrix<double> > X, Eigen::VectorXd y) :
X(X), y(y) {}
template <bool propto__ = false, bool jacobian__ = false, typename T__ = double>
// propto__ is usually true but causes log_prob() to return 0 when called from R
// jacobian__ is usually true for MCMC but typically is false for optimization
T__ log_prob(std::vector<T__>& params_r__) const {
using namespace stan::math;
T__ lp__(0.0);
accumulator<T__> lp_accum__;
// set up model parameters
std::vector<int> params_i__;
stan::io::deserializer<T__> in__(params_r__, params_i__);
auto beta = in__.template read<Eigen::Matrix<T__,-1,1> >(X.cols());
auto sigma = in__.template read_constrain_lb<T__, jacobian__>(0, lp__);
// log-likelihood (should add priors)
lp_accum__.add(lp__);
lp_accum__.add(normal_lpdf<propto__>(y, (X * beta).eval(), sigma));
return lp_accum__.sum();
}
template <bool propto__ = false, bool jacobian__ = false>
std::vector<double> gradient(std::vector<double>& params_r__) const {
// Calculate gradients using reverse-mode autodiff
// although you could do them analytically in this case
using std::vector;
using stan::math::var;
double lp;
std::vector<double> gradient;
try {
vector<var> ad_params_r(params_r__.size());
for (size_t i = 0; i < params_r__.size(); ++i) {
var var_i(params_r__[i]);
ad_params_r[i] = var_i;
}
var adLogProb
= this->log_prob<propto__, jacobian__>(ad_params_r);
lp = adLogProb.val();
adLogProb.grad(ad_params_r, gradient);
} catch (const std::exception &ex) {
stan::math::recover_memory();
throw;
}
stan::math::recover_memory();
return gradient;
}
};</code></pre>
<p>To use it from R, we call the <code>exposeClass</code> function in the <strong>Rcpp</strong> package with the necessary arguments and then call <code>sourceCpp</code> on the file it wrote in the temporary directory:</p>
<div class="sourceCode" id="cb18"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb18-1" title="1"><span class="kw">library</span>(Rcpp)</a>
<a class="sourceLine" id="cb18-2" title="2">tf <-<span class="st"> </span><span class="kw">tempfile</span>(<span class="dt">fileext =</span> <span class="st">"Module.cpp"</span>)</a>
<a class="sourceLine" id="cb18-3" title="3"><span class="kw">exposeClass</span>(<span class="st">"sparselm_stan"</span>,</a>
<a class="sourceLine" id="cb18-4" title="4"> <span class="dt">constructors =</span> <span class="kw">list</span>(<span class="kw">c</span>(<span class="st">"Eigen::Map<Eigen::SparseMatrix<double> >"</span>, </a>
<a class="sourceLine" id="cb18-5" title="5"> <span class="st">"Eigen::VectorXd"</span>)),</a>
<a class="sourceLine" id="cb18-6" title="6"> <span class="dt">fields =</span> <span class="kw">c</span>(<span class="st">"X"</span>, <span class="st">"y"</span>),</a>
<a class="sourceLine" id="cb18-7" title="7"> <span class="dt">methods =</span> <span class="kw">c</span>(<span class="st">"log_prob<>"</span>, <span class="st">"gradient<>"</span>),</a>
<a class="sourceLine" id="cb18-8" title="8"> <span class="dt">rename =</span> <span class="kw">c</span>(<span class="dt">log_prob =</span> <span class="st">"log_prob<>"</span>, <span class="dt">gradient =</span> <span class="st">"gradient<>"</span>),</a>
<a class="sourceLine" id="cb18-9" title="9"> <span class="dt">header =</span> <span class="kw">c</span>(<span class="st">"// [[Rcpp::depends(BH)]]"</span>,</a>
<a class="sourceLine" id="cb18-10" title="10"> <span class="st">"// [[Rcpp::depends(RcppEigen)]]"</span>,</a>
<a class="sourceLine" id="cb18-11" title="11"> <span class="st">"// [[Rcpp::depends(RcppParallel)]"</span>,</a>
<a class="sourceLine" id="cb18-12" title="12"> <span class="st">"// [[Rcpp::depends(StanHeaders)]]"</span>,</a>
<a class="sourceLine" id="cb18-13" title="13"> <span class="st">"// [[Rcpp::plugins(cpp17)]]"</span>,</a>
<a class="sourceLine" id="cb18-14" title="14"> <span class="kw">paste0</span>(<span class="st">"#include <"</span>, <span class="kw">file.path</span>(<span class="kw">getwd</span>(), <span class="st">"sparselm_stan.hpp"</span>), <span class="st">">"</span>)),</a>
<a class="sourceLine" id="cb18-15" title="15"> <span class="dt">file =</span> tf,</a>
<a class="sourceLine" id="cb18-16" title="16"> <span class="dt">Rfile =</span> <span class="ot">FALSE</span>)</a>
<a class="sourceLine" id="cb18-17" title="17"><span class="kw">Sys.setenv</span>(<span class="dt">PKG_CXXFLAGS =</span> <span class="kw">paste0</span>(<span class="kw">Sys.getenv</span>(<span class="st">"PKG_CXXFLAGS"</span>), <span class="st">" -I"</span>,</a>
<a class="sourceLine" id="cb18-18" title="18"> <span class="kw">system.file</span>(<span class="st">"include"</span>, <span class="st">"src"</span>, </a>
<a class="sourceLine" id="cb18-19" title="19"> <span class="dt">package =</span> <span class="st">"StanHeaders"</span>, <span class="dt">mustWork =</span> <span class="ot">TRUE</span>)))</a>
<a class="sourceLine" id="cb18-20" title="20"><span class="kw">sourceCpp</span>(tf)</a>
<a class="sourceLine" id="cb18-21" title="21">sparselm_stan</a>
<a class="sourceLine" id="cb18-22" title="22"><span class="co">#> C++ class 'sparselm_stan' <0x557ae52e0380></span></a>
<a class="sourceLine" id="cb18-23" title="23"><span class="co">#> Constructors:</span></a>
<a class="sourceLine" id="cb18-24" title="24"><span class="co">#> sparselm_stan(Eigen::Map<Eigen::SparseMatrix<double, 0, int>, 0, Eigen::Stride<0, 0> >, Eigen::Matrix<double, -1, 1, 0, -1, 1>)</span></a>
<a class="sourceLine" id="cb18-25" title="25"><span class="co">#> </span></a>
<a class="sourceLine" id="cb18-26" title="26"><span class="co">#> Fields: </span></a>
<a class="sourceLine" id="cb18-27" title="27"><span class="co">#> Eigen::Map<Eigen::SparseMatrix<double, 0, int>, 0, Eigen::Stride<0, 0> > X</span></a>
<a class="sourceLine" id="cb18-28" title="28"><span class="co">#> Eigen::Matrix<double, -1, 1, 0, -1, 1> y</span></a>
<a class="sourceLine" id="cb18-29" title="29"><span class="co">#> </span></a>
<a class="sourceLine" id="cb18-30" title="30"><span class="co">#> Methods: </span></a>
<a class="sourceLine" id="cb18-31" title="31"><span class="co">#> std::vector<double, std::allocator<double> > gradient(std::vector<double, std::allocator<double> >) const </span></a>
<a class="sourceLine" id="cb18-32" title="32"><span class="co">#> </span></a>
<a class="sourceLine" id="cb18-33" title="33"><span class="co">#> double log_prob(std::vector<double, std::allocator<double> >) const </span></a>
<a class="sourceLine" id="cb18-34" title="34"><span class="co">#> </span></a></code></pre></div>
<p>At this point, we need a sparse design matrix and (dense) outcome vector to pass to the constructor. The former can be created with a variety of functions in the <strong>Matrix</strong> package, such as</p>
<div class="sourceCode" id="cb19"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb19-1" title="1">dd <-<span class="st"> </span><span class="kw">data.frame</span>(<span class="dt">a =</span> <span class="kw">gl</span>(<span class="dv">3</span>, <span class="dv">4</span>), <span class="dt">b =</span> <span class="kw">gl</span>(<span class="dv">4</span>, <span class="dv">1</span>, <span class="dv">12</span>))</a>
<a class="sourceLine" id="cb19-2" title="2">X <-<span class="st"> </span>Matrix<span class="op">::</span><span class="kw">sparse.model.matrix</span>(<span class="op">~</span><span class="st"> </span>a <span class="op">+</span><span class="st"> </span>b, <span class="dt">data =</span> dd)</a>
<a class="sourceLine" id="cb19-3" title="3">X</a>
<a class="sourceLine" id="cb19-4" title="4"><span class="co">#> 12 x 6 sparse Matrix of class "dgCMatrix"</span></a>
<a class="sourceLine" id="cb19-5" title="5"><span class="co">#> (Intercept) a2 a3 b2 b3 b4</span></a>
<a class="sourceLine" id="cb19-6" title="6"><span class="co">#> 1 1 . . . . .</span></a>
<a class="sourceLine" id="cb19-7" title="7"><span class="co">#> 2 1 . . 1 . .</span></a>
<a class="sourceLine" id="cb19-8" title="8"><span class="co">#> 3 1 . . . 1 .</span></a>
<a class="sourceLine" id="cb19-9" title="9"><span class="co">#> 4 1 . . . . 1</span></a>
<a class="sourceLine" id="cb19-10" title="10"><span class="co">#> 5 1 1 . . . .</span></a>
<a class="sourceLine" id="cb19-11" title="11"><span class="co">#> 6 1 1 . 1 . .</span></a>
<a class="sourceLine" id="cb19-12" title="12"><span class="co">#> 7 1 1 . . 1 .</span></a>
<a class="sourceLine" id="cb19-13" title="13"><span class="co">#> 8 1 1 . . . 1</span></a>
<a class="sourceLine" id="cb19-14" title="14"><span class="co">#> 9 1 . 1 . . .</span></a>
<a class="sourceLine" id="cb19-15" title="15"><span class="co">#> 10 1 . 1 1 . .</span></a>
<a class="sourceLine" id="cb19-16" title="16"><span class="co">#> 11 1 . 1 . 1 .</span></a>
<a class="sourceLine" id="cb19-17" title="17"><span class="co">#> 12 1 . 1 . . 1</span></a></code></pre></div>
<p>Finally, we call the <code>new</code> function in the <strong>methods</strong> package, which essentially calls our C++ constructor and provides an R interface to the instantiated object, which contains the <code>log_prob</code> and <code>gradient</code> methods we defined and can be called with arbitrary inputs.</p>
<div class="sourceCode" id="cb20"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb20-1" title="1">sm <-<span class="st"> </span><span class="kw">new</span>(sparselm_stan, <span class="dt">X =</span> X, <span class="dt">y =</span> <span class="kw">rnorm</span>(<span class="kw">nrow</span>(X)))</a>
<a class="sourceLine" id="cb20-2" title="2">sm<span class="op">$</span><span class="kw">log_prob</span>(<span class="kw">c</span>(<span class="dt">beta =</span> <span class="kw">rnorm</span>(<span class="kw">ncol</span>(X)), <span class="dt">log_sigma =</span> <span class="kw">log</span>(pi)))</a>
<a class="sourceLine" id="cb20-3" title="3"><span class="co">#> [1] -26.01577</span></a>
<a class="sourceLine" id="cb20-4" title="4"><span class="kw">round</span>(sm<span class="op">$</span><span class="kw">gradient</span>(<span class="kw">c</span>(<span class="dt">beta =</span> <span class="kw">rnorm</span>(<span class="kw">ncol</span>(X)), <span class="dt">log_sigma =</span> <span class="kw">log</span>(pi))), <span class="dt">digits =</span> <span class="dv">4</span>)</a>
<a class="sourceLine" id="cb20-5" title="5"><span class="co">#> [1] -2.1984 -1.0424 -0.5089 -0.4552 -0.6047 -0.8303 -6.6551</span></a></code></pre></div>
</div>
<!-- code folding -->
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
document.getElementsByTagName("head")[0].appendChild(script);
})();
</script>
</body>
</html>
|