JAGS-4.3.0/0000775000175000017500000000000013133423771007251 500000000000000JAGS-4.3.0/COPYING0000664000175000017500000004311013130731022010207 00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. JAGS-4.3.0/test-driver0000755000175000017500000001104013047260757011370 00000000000000#! /bin/sh # test-driver - basic testsuite driver script. scriptversion=2013-07-13.22; # UTC # Copyright (C) 2011-2014 Free Software Foundation, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # This file is maintained in Automake, please report # bugs to or send patches to # . # Make unconditional expansion of undefined variables an error. This # helps a lot in preventing typo-related bugs. set -u usage_error () { echo "$0: $*" >&2 print_usage >&2 exit 2 } print_usage () { cat <$log_file 2>&1 estatus=$? if test $enable_hard_errors = no && test $estatus -eq 99; then tweaked_estatus=1 else tweaked_estatus=$estatus fi case $tweaked_estatus:$expect_failure in 0:yes) col=$red res=XPASS recheck=yes gcopy=yes;; 0:*) col=$grn res=PASS recheck=no gcopy=no;; 77:*) col=$blu res=SKIP recheck=no gcopy=yes;; 99:*) col=$mgn res=ERROR recheck=yes gcopy=yes;; *:yes) col=$lgn res=XFAIL recheck=no gcopy=yes;; *:*) col=$red res=FAIL recheck=yes gcopy=yes;; esac # Report the test outcome and exit status in the logs, so that one can # know whether the test passed or failed simply by looking at the '.log' # file, without the need of also peaking into the corresponding '.trs' # file (automake bug#11814). echo "$res $test_name (exit status: $estatus)" >>$log_file # Report outcome to console. echo "${col}${res}${std}: $test_name" # Register the test result, and other relevant metadata. echo ":test-result: $res" > $trs_file echo ":global-test-result: $res" >> $trs_file echo ":recheck: $recheck" >> $trs_file echo ":copy-in-global-log: $gcopy" >> $trs_file # Local Variables: # mode: shell-script # sh-indentation: 2 # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC" # time-stamp-end: "; # UTC" # End: JAGS-4.3.0/INSTALL0000644000175000017500000003661013047260757010235 00000000000000Installation Instructions ************************* Copyright (C) 1994-1996, 1999-2002, 2004-2013 Free Software Foundation, Inc. Copying and distribution of this file, with or without modification, are permitted in any medium without royalty provided the copyright notice and this notice are preserved. This file is offered as-is, without warranty of any kind. Basic Installation ================== Briefly, the shell command `./configure && make && make install' should configure, build, and install this package. The following more-detailed instructions are generic; see the `README' file for instructions specific to this package. Some packages provide this `INSTALL' file but do not implement all of the features documented below. The lack of an optional feature in a given package is not necessarily a bug. More recommendations for GNU packages can be found in *note Makefile Conventions: (standards)Makefile Conventions. The `configure' shell script attempts to guess correct values for various system-dependent variables used during compilation. It uses those values to create a `Makefile' in each directory of the package. It may also create one or more `.h' files containing system-dependent definitions. Finally, it creates a shell script `config.status' that you can run in the future to recreate the current configuration, and a file `config.log' containing compiler output (useful mainly for debugging `configure'). It can also use an optional file (typically called `config.cache' and enabled with `--cache-file=config.cache' or simply `-C') that saves the results of its tests to speed up reconfiguring. Caching is disabled by default to prevent problems with accidental use of stale cache files. If you need to do unusual things to compile the package, please try to figure out how `configure' could check whether to do them, and mail diffs or instructions to the address given in the `README' so they can be considered for the next release. If you are using the cache, and at some point `config.cache' contains results you don't want to keep, you may remove or edit it. The file `configure.ac' (or `configure.in') is used to create `configure' by a program called `autoconf'. You need `configure.ac' if you want to change it or regenerate `configure' using a newer version of `autoconf'. The simplest way to compile this package is: 1. `cd' to the directory containing the package's source code and type `./configure' to configure the package for your system. Running `configure' might take a while. While running, it prints some messages telling which features it is checking for. 2. Type `make' to compile the package. 3. Optionally, type `make check' to run any self-tests that come with the package, generally using the just-built uninstalled binaries. 4. Type `make install' to install the programs and any data files and documentation. When installing into a prefix owned by root, it is recommended that the package be configured and built as a regular user, and only the `make install' phase executed with root privileges. 5. Optionally, type `make installcheck' to repeat any self-tests, but this time using the binaries in their final installed location. This target does not install anything. Running this target as a regular user, particularly if the prior `make install' required root privileges, verifies that the installation completed correctly. 6. You can remove the program binaries and object files from the source code directory by typing `make clean'. To also remove the files that `configure' created (so you can compile the package for a different kind of computer), type `make distclean'. There is also a `make maintainer-clean' target, but that is intended mainly for the package's developers. If you use it, you may have to get all sorts of other programs in order to regenerate files that came with the distribution. 7. Often, you can also type `make uninstall' to remove the installed files again. In practice, not all packages have tested that uninstallation works correctly, even though it is required by the GNU Coding Standards. 8. Some packages, particularly those that use Automake, provide `make distcheck', which can by used by developers to test that all other targets like `make install' and `make uninstall' work correctly. This target is generally not run by end users. Compilers and Options ===================== Some systems require unusual options for compilation or linking that the `configure' script does not know about. Run `./configure --help' for details on some of the pertinent environment variables. You can give `configure' initial values for configuration parameters by setting variables in the command line or in the environment. Here is an example: ./configure CC=c99 CFLAGS=-g LIBS=-lposix *Note Defining Variables::, for more details. Compiling For Multiple Architectures ==================================== You can compile the package for more than one kind of computer at the same time, by placing the object files for each architecture in their own directory. To do this, you can use GNU `make'. `cd' to the directory where you want the object files and executables to go and run the `configure' script. `configure' automatically checks for the source code in the directory that `configure' is in and in `..'. This is known as a "VPATH" build. With a non-GNU `make', it is safer to compile the package for one architecture at a time in the source code directory. After you have installed the package for one architecture, use `make distclean' before reconfiguring for another architecture. On MacOS X 10.5 and later systems, you can create libraries and executables that work on multiple system types--known as "fat" or "universal" binaries--by specifying multiple `-arch' options to the compiler but only a single `-arch' option to the preprocessor. Like this: ./configure CC="gcc -arch i386 -arch x86_64 -arch ppc -arch ppc64" \ CXX="g++ -arch i386 -arch x86_64 -arch ppc -arch ppc64" \ CPP="gcc -E" CXXCPP="g++ -E" This is not guaranteed to produce working output in all cases, you may have to build one architecture at a time and combine the results using the `lipo' tool if you have problems. Installation Names ================== By default, `make install' installs the package's commands under `/usr/local/bin', include files under `/usr/local/include', etc. You can specify an installation prefix other than `/usr/local' by giving `configure' the option `--prefix=PREFIX', where PREFIX must be an absolute file name. You can specify separate installation prefixes for architecture-specific files and architecture-independent files. If you pass the option `--exec-prefix=PREFIX' to `configure', the package uses PREFIX as the prefix for installing programs and libraries. Documentation and other data files still use the regular prefix. In addition, if you use an unusual directory layout you can give options like `--bindir=DIR' to specify different values for particular kinds of files. Run `configure --help' for a list of the directories you can set and what kinds of files go in them. In general, the default for these options is expressed in terms of `${prefix}', so that specifying just `--prefix' will affect all of the other directory specifications that were not explicitly provided. The most portable way to affect installation locations is to pass the correct locations to `configure'; however, many packages provide one or both of the following shortcuts of passing variable assignments to the `make install' command line to change installation locations without having to reconfigure or recompile. The first method involves providing an override variable for each affected directory. For example, `make install prefix=/alternate/directory' will choose an alternate location for all directory configuration variables that were expressed in terms of `${prefix}'. Any directories that were specified during `configure', but not in terms of `${prefix}', must each be overridden at install time for the entire installation to be relocated. The approach of makefile variable overrides for each directory variable is required by the GNU Coding Standards, and ideally causes no recompilation. However, some platforms have known limitations with the semantics of shared libraries that end up requiring recompilation when using this method, particularly noticeable in packages that use GNU Libtool. The second method involves providing the `DESTDIR' variable. For example, `make install DESTDIR=/alternate/directory' will prepend `/alternate/directory' before all installation names. The approach of `DESTDIR' overrides is not required by the GNU Coding Standards, and does not work on platforms that have drive letters. On the other hand, it does better at avoiding recompilation issues, and works well even when some directory options were not specified in terms of `${prefix}' at `configure' time. Optional Features ================= If the package supports it, you can cause programs to be installed with an extra prefix or suffix on their names by giving `configure' the option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'. Some packages pay attention to `--enable-FEATURE' options to `configure', where FEATURE indicates an optional part of the package. They may also pay attention to `--with-PACKAGE' options, where PACKAGE is something like `gnu-as' or `x' (for the X Window System). The `README' should mention any `--enable-' and `--with-' options that the package recognizes. For packages that use the X Window System, `configure' can usually find the X include and library files automatically, but if it doesn't, you can use the `configure' options `--x-includes=DIR' and `--x-libraries=DIR' to specify their locations. Some packages offer the ability to configure how verbose the execution of `make' will be. For these packages, running `./configure --enable-silent-rules' sets the default to minimal output, which can be overridden with `make V=1'; while running `./configure --disable-silent-rules' sets the default to verbose, which can be overridden with `make V=0'. Particular systems ================== On HP-UX, the default C compiler is not ANSI C compatible. If GNU CC is not installed, it is recommended to use the following options in order to use an ANSI C compiler: ./configure CC="cc -Ae -D_XOPEN_SOURCE=500" and if that doesn't work, install pre-built binaries of GCC for HP-UX. HP-UX `make' updates targets which have the same time stamps as their prerequisites, which makes it generally unusable when shipped generated files such as `configure' are involved. Use GNU `make' instead. On OSF/1 a.k.a. Tru64, some versions of the default C compiler cannot parse its `' header file. The option `-nodtk' can be used as a workaround. If GNU CC is not installed, it is therefore recommended to try ./configure CC="cc" and if that doesn't work, try ./configure CC="cc -nodtk" On Solaris, don't put `/usr/ucb' early in your `PATH'. This directory contains several dysfunctional programs; working variants of these programs are available in `/usr/bin'. So, if you need `/usr/ucb' in your `PATH', put it _after_ `/usr/bin'. On Haiku, software installed for all users goes in `/boot/common', not `/usr/local'. It is recommended to use the following options: ./configure --prefix=/boot/common Specifying the System Type ========================== There may be some features `configure' cannot figure out automatically, but needs to determine by the type of machine the package will run on. Usually, assuming the package is built to be run on the _same_ architectures, `configure' can figure that out, but if it prints a message saying it cannot guess the machine type, give it the `--build=TYPE' option. TYPE can either be a short name for the system type, such as `sun4', or a canonical name which has the form: CPU-COMPANY-SYSTEM where SYSTEM can have one of these forms: OS KERNEL-OS See the file `config.sub' for the possible values of each field. If `config.sub' isn't included in this package, then this package doesn't need to know the machine type. If you are _building_ compiler tools for cross-compiling, you should use the option `--target=TYPE' to select the type of system they will produce code for. If you want to _use_ a cross compiler, that generates code for a platform different from the build platform, you should specify the "host" platform (i.e., that on which the generated programs will eventually be run) with `--host=TYPE'. Sharing Defaults ================ If you want to set default values for `configure' scripts to share, you can create a site shell script called `config.site' that gives default values for variables like `CC', `cache_file', and `prefix'. `configure' looks for `PREFIX/share/config.site' if it exists, then `PREFIX/etc/config.site' if it exists. Or, you can set the `CONFIG_SITE' environment variable to the location of the site script. A warning: not all `configure' scripts look for a site script. Defining Variables ================== Variables not defined in a site shell script can be set in the environment passed to `configure'. However, some packages may run configure again during the build, and the customized values of these variables may be lost. In order to avoid this problem, you should set them in the `configure' command line, using `VAR=value'. For example: ./configure CC=/usr/local2/bin/gcc causes the specified `gcc' to be used as the C compiler (unless it is overridden in the site shell script). Unfortunately, this technique does not work for `CONFIG_SHELL' due to an Autoconf limitation. Until the limitation is lifted, you can use this workaround: CONFIG_SHELL=/bin/bash ./configure CONFIG_SHELL=/bin/bash `configure' Invocation ====================== `configure' recognizes the following options to control how it operates. `--help' `-h' Print a summary of all of the options to `configure', and exit. `--help=short' `--help=recursive' Print a summary of the options unique to this package's `configure', and exit. The `short' variant lists options used only in the top level, while the `recursive' variant lists options also present in any nested packages. `--version' `-V' Print the version of Autoconf used to generate the `configure' script, and exit. `--cache-file=FILE' Enable the cache: use and save the results of the tests in FILE, traditionally `config.cache'. FILE defaults to `/dev/null' to disable caching. `--config-cache' `-C' Alias for `--cache-file=config.cache'. `--quiet' `--silent' `-q' Do not print messages saying which checks are being made. To suppress all normal output, redirect it to `/dev/null' (any error messages will still be shown). `--srcdir=DIR' Look for the package's source code in directory DIR. Usually `configure' can determine that directory automatically. `--prefix=DIR' Use DIR as the installation prefix. *note Installation Names:: for more details, including other options available for fine-tuning the installation locations. `--no-create' `-n' Run the configure checks, but stop before creating any output files. `configure' also accepts some other, not widely useful, options. Run `configure --help' for more details. JAGS-4.3.0/doc/0000775000175000017500000000000013133423771010016 500000000000000JAGS-4.3.0/doc/jags.10000664000175000017500000000165113130731022010733 00000000000000.\" Man page contributed by Dirk Eddelbuettel and GPL'ed .TH JAGS 1 "June 2010" "IARC" .SH NAME jags - just another gibbs sampler .SH SYNOPSIS .BR jags\ [options]\ [scriptfile] .SH DESCRIPTION .PP \fIjags\fP is a program for analysis of Bayesian hierarchical models using Markov Chain Monte Carlo (MCMC) simulation not wholly unlike BUGS. If given a scriptfile argument, jags will be started in batch mode. Otherwise it will be started in interactive mode. .SH OPTIONS \fIjags\fP accepts the following options: .TP \fB\-d\fR, \fB\-\-debugger\fR=\fINAME\fR Run jags through debugger NAME .TP \fB\-\-debugger\-args\fR=\fIARGS\fR Pass ARGS as arguments to the debugger .RE .SH SEE ALSO .IR http://mcmc-jags.sourceforge.net .SH AUTHORS Martyn Plummer This manual page was contributed by Dirk Eddelbuettel for the Debian GNU/Linux distribution but may be used by others. JAGS-4.3.0/doc/manual/0000775000175000017500000000000013133423771011273 500000000000000JAGS-4.3.0/doc/manual/jags_installation_manual.tex0000664000175000017500000011363613131354350017003 00000000000000\documentclass[11pt, a4paper, titlepage]{article} \usepackage{amsmath} \usepackage{a4wide} \usepackage{url} \usepackage{multirow} \usepackage{amsfonts} \newcommand{\release}{4.3.0} \newcommand{\JAGS}{\textsf{JAGS}} \newcommand{\BUGS}{\textsf{BUGS}} \newcommand{\WinBUGS}{\textsf{WinBUGS}} \newcommand{\R}{\textsf{R}} \newcommand{\CODA}{\textsf{coda}} \usepackage{verbatim} \newcommand{\code}[1]{{\bgroup{\normalfont\ttfamily #1}\egroup}} \newcommand{\samp}[1]{{`\bgroup\normalfont\texttt{#1}'\egroup}} \newcommand{\file}[1]{{`\normalfont\textsf{#1}'}} \let\command=\code \let\option=\samp \begin{document} \title{JAGS Version \release\ installation manual} \author{Martyn Plummer \and Bill Northcott \and Matt Denwood} \date{10 July 2017} \maketitle \JAGS\ is distributed in binary format for Microsoft Windows, macOS, and most Linux distributions. The following instructions are for those who wish to build \JAGS\ from source. The manual is divided into three sections with instructions for Linux/Unix, macOS, and Windows. \section{Linux and UNIX} \JAGS\ follows the usual GNU convention of \begin{verbatim} ./configure make make install \end{verbatim} which is described in more detail in the file \texttt{INSTALL} in the top-level source directory. On some UNIX platforms, you may be required to use GNU make (gmake) instead of the native make command. On systems with multiple processors, you may use the option \option{-j} to speed up compilation, {\em e.g.} for a quad-core PC you may use: \begin{verbatim} make -j4 \end{verbatim} If you have the cppunit library installed then you can test the build with \begin{verbatim} make check \end{verbatim} WARNING. If you already have a copy of the jags library installed on your system then the test program created by \code{make check} will link against the {\bf installed} library and not the one in your build directory. So if the test suite includes a regression test for a bug that was fixed in the version you are building but a previous version of JAGS is already installed then the unit tests will fail. Best practice is to run the tests after \code{make install} so the build and installed versions are the same. \subsection{Configure options} At configure time you also have the option of defining options such as: \begin{itemize} \item The names of the C, C++, and Fortran compilers. \item Optimization flags for the compilers. \JAGS\ is optimized by default if the GNU compiler (gcc) is used. If you are using another compiler then you may need to explicitly supply optimization flags. \item Installation directories. \JAGS\ conforms to the GNU standards for where files are installed. You can control the installation directories in more detail using the flags that are listed when you type \command{./configure --help}. \end{itemize} \subsubsection{Configuration for a 64-bit build} By default, JAGS will install all libraries into \file{/usr/local/lib}. If you are building a 64-bit version of \JAGS, this may not be appropriate for your system. On Fedora and other RPM-based distributions, for example, 64-bit libraries should be installed in \file{lib64}, and on Solaris, 64-bit libraries are in a subdirectory of \file{lib} ({\em e.g.} \file{lib/amd64} if you are using a x86-64 processor), whereas on Debian, and other Linux distributions that conform to the FHS, the correct installation directory is \file{lib}. To ensure that \JAGS\ libraries are installed in the correct directory, you should supply the \option{--libdir} argument to the configure script, {\em e.g.}: \begin{verbatim} ./configure --libdir=/usr/local/lib64 \end{verbatim} It is important to get the installation directory right when using the \code{rjags} interface between R and \JAGS, otherwise the \code{rjags} package will not be able to find the \JAGS\ library. \subsubsection{Configuration for a private installation} If you do not have administrative privileges, you may wish to install \JAGS\ in your home directory. This can be done with the following configuration options \begin{verbatim} export JAGS_HOME=$HOME/jags #or wherever you want it ./configure --prefix=$JAGS_HOME \end{verbatim} For more detailed control over the installation directories type \begin{verbatim} ./configure --help \end{verbatim} and read the section ``Fine-tuning of the installation directories.'' With a private installation, you need to modify your PATH environment variable to include \file{\$JAGS\_HOME/bin}. You may also need to set \code{LD\_LIBRARY\_PATH} to include \file{\$JAGS\_HOME/lib} (On Linux this is not necessary as the location of libjags and libjrmath is hard-coded into the \JAGS\ binary). \subsection{BLAS and LAPACK} \label{section:blas:lapack} BLAS (Basic Linear Algebra System) and LAPACK (Linear Algebra Pack) are two libraries of routines for linear algebra. They are used by the multivariate functions and distributions in the \texttt{bugs} module. Most unix-like operating system vendors supply shared libraries that provide the BLAS and LAPACK functions, although the libraries may not literally be called ``blas'' and ``lapack''. During configuration, a default list of these libraries will be checked. If \texttt{configure} cannot find a suitable library, it will stop with an error message. You may use alternative BLAS and LAPACK libraries using the configure options \texttt{--with-blas} and \texttt{--with-lapack} \begin{verbatim} ./configure --with-blas="-lmyblas" --with-lapack="-lmylapack" \end{verbatim} If the BLAS and LAPACK libraries are in a directory that is not on the default linker path, you must set the \code{LDFLAGS} environment variable to point to this directory at configure time: \begin{verbatim} LDFLAGS="-L/path/to/my/libs" ./configure ... \end{verbatim} At runtime, if you have linked \JAGS\ against BLAS or LAPACK in a non-standard location, you must supply this location with the environment variable \code{LD\_LIBRARY\_PATH}, {\em e.g.} \begin{verbatim} LD_LIBRARY_PATH="/path/to/my/libs:${LD_LIBRARY_PATH}" \end{verbatim} Alternatively, you may hard-code the paths to the blas and lapack libraries at compile time. This is compiler and platform-specific, but is typically achieved with \begin{verbatim} LDFLAGS="-L/path/to/my/libs -R/path/to/my/libs \end{verbatim} JAGS can also be linked to static BLAS and LAPACK if they have both been compiled with the \texttt{-fPIC} flag. You will probably need to do a custom build of BLAS and LAPACK if you require this. The configure options for JAGS are then: \begin{verbatim} ./configure --with-blas="-L/path/to/my/libs -lmyblas -lgfortran -lquadmath" \ --with-lapack="-L/path/to/my/libs -lmylapack" \end{verbatim} Note that with static linking you must add the dependencies of the BLAS library manually. The LAPACK library will pick up the same dependencies. Note also that libtool does not like linking directly to archive files. If you attempt a configuration of the form \begin{verbatim} --with-blas="/path/to/my/libs/myblas.a" \end{verbatim} then this will pass at configure time but ``make'' will not correctly build the JAGS modules. \subsubsection{Multithreaded BLAS and LAPACK} \label{section:blas:multithreaded} Some high-performance computing libraries offer multi-threaded versions of the BLAS and LAPACK libraries. Although instructions for linking against some of these libraries are given below, this should not be taken as encouragement to use multithreaded BLAS. Testing shows that using multiple threads in BLAS can lead to significantly {\em worse} performance while using up substantially more computing resources. \subsection{GNU/Linux} \label{section:gnulinux} GNU/Linux is the development platform for \JAGS, and a variety of different build options have been explored, including the use of third-party compilers and linear algebra libraries. \subsubsection{Fortran compiler} The GNU FORTRAN compiler changed between gcc 3.x and gcc 4.x from \code{g77} to \code{gfortran}. Code produced by the two compilers is binary incompatible. If your BLAS and LAPACK libraries are linked against \code{libgfortran}, then they were built with \code{gfortran} and you must also use this to compile \JAGS. Most recent GNU/Linux distributions have moved completely to gcc 4.x. However, some older systems may have both compilers installed. Unfortunately, if \code{g77} is on your path then the configure script will find it first, and will attempt to use it to build \JAGS. This results in a failure to recognize the installed BLAS and LAPACK libraries. In this event, set the \code{F77} variable at configure time. \begin{verbatim} F77=gfortran ./configure \end{verbatim} \subsubsection{BLAS and LAPACK} The {\bf BLAS} and {\bf LAPACK} libraries from Netlib (\url{http://www.netlib.org}) should be provided as part of your Linux distribution. If your Linux distribution splits packages into ``user'' and ``developer'' versions, then you must install the developer package ({\em e.g.} \texttt{blas-devel} and \texttt{lapack-devel}). On {\bf Red Hat Enterprise Linux (RHEL)} you need to activate an optional repository in order to have access to BLAS and LAPACK. The repository is called is called \texttt{rhel---optional-rpms}, where \texttt{} is the RHEL release version and \texttt{} is the type of installation (server or workstation). Find the corresponding entry in the file \file{/etc/yum.repos.d/redhat.repo} and change the line \texttt{enabled = 0} to \texttt{enabled = 1}. {\bf Suse Linux Enterprise Server (SLES)} does not include BLAS and LAPACK in the main distribution. They are included in the SLES SDK, on a set of CD/DVD images which can be downloaded from \url{https://download.suse.com/index.jsp} (subscription and login required). \subsubsection{ATLAS} On Fedora Linux, pre-compiled atlas libraries are available via the \texttt{atlas} and \texttt{atlas-devel} RPMs. These RPMs install the atlas libraries in the non-standard directory \texttt{/usr/lib/atlas} (or \texttt{/usr/lib64/atlas} for 64-bit builds) to avoid conflicts with the standard \texttt{blas} and \texttt{lapack} RPMs. To use the atlas libraries, you must supply their location using the \code{LDFLAGS} variable (see section \ref{section:blas:lapack}) \begin{verbatim} ./configure LDFLAGS="-L/usr/lib/atlas" \end{verbatim} Runtime linking to the correct libraries is ensured by the automatic addition of \texttt{/usr/lib/atlas} to the linker path (see the directory \texttt{/etc/ld.so.conf.d}), so you do not need to set the environment variable \code{LD\_LIBRARY\_PATH} at run time. \subsubsection{AMD Core Math Library} \label{section:acml:linux} The AMD Core Math Library (acml) provides optimized BLAS and LAPACK routines for AMD processors. To link \JAGS\ with \texttt{acml}, you must supply the \texttt{acml} library as the argument to \texttt{--with-blas}. It is not necessary to set the \texttt{--with-lapack} argument as \texttt{acml} provides both sets of functions. See also section~\ref{section:blas:lapack} for run-time instructions. For example, to link to the 64-bit acml using gcc 4.0+: \begin{verbatim} LDFLAGS="-L/opt/acml4.3.0/gfortran64/lib" \ ./configure --with-blas="-lacml -lacml_mv" \end{verbatim} The \code{acmv\_mv} library is a vectorized math library that exists only for the 64-bit version and is omitted when linking against 32-bit acml. On multi-core systems, you may wish to use the threaded acml library (See the warning in section \ref{section:blas:multithreaded} however). To do this, link to \code{acml\_mp} and add the compiler flag \option{-fopenmp}: \begin{verbatim} LDFLAGS="-L/opt/acml4.3.0/gfortran64_mp/lib" \ CXXFLAGS="-O2 -g -fopenmp" ./configure --with-blas="-lacml_mp -lacml_mv" \end{verbatim} The number of threads used by multi-threaded acml may be controlled with the environment variable \code{OMP\_NUM\_THREADS}. \subsubsection{Intel Math Kernel Library} The Intel Math Kernel library (MKL) provides optimized BLAS and LAPACK routines for Intel processors. MKL is designed to be linked to executables, not shared libraries. This means that it can only be linked to a static version of \JAGS, in which the \JAGS\ library and modules are linked into the main executable. To build a static version of \JAGS, use the configure option \option{--disable-shared}. MKL version 10.0 and above uses a ``pure layered'' model for linking. The layered model gives the user fine-grained control over four different library layers: interface, threading, computation, and run-time. Some examples of linking to MKL using this layered model are given below. These examples are for GCC compilers on \code{x86\_64}. The choice of interface layer is important on \code{x86\_64} since the Intel Fortran compiler returns complex values differently from the GNU Fortran compiler. You must therefore use the interface layer that matches your compiler (\code{mkl\_intel*} or \code{mkl\_gf*}). For further guidance, consult the MKL Link Line advisor at \url{http://software.intel.com/en-us/articles/intel-mkl-link-line-advisor}. Recent versions of MKL include a shell script that sets up the environment variables necessary to build an application with MKL. \begin{verbatim} source /opt/intel/composerxe-2011/mkl/bin/mklvars.sh intel64 \end{verbatim} After calling this script, you can link \JAGS\ with a sequential version of MKL as follows: \begin{verbatim} ./configure --disable-shared \ --with-blas="-lmkl_gf_lp64 -lmkl_sequential -lmkl_core -lpthread" \end{verbatim} Note that \code{libpthread} is still required, even when linking to sequential MKL. Threaded MKL may be used with: \begin{verbatim} ./configure --disable-shared \ --with-blas="-lmkl_gf_lp64 -lmkl_gnu_thread -lmkl_core -liomp5 -lpthread" \end{verbatim} The default number of threads will be chosen by the OpenMP software, but can be controlled by setting \code{OMP\_NUM\_THREADS} or \code{MKL\_NUM\_THREADS}. (See the warning in section \ref{section:blas:multithreaded} however). \subsubsection{Using Intel Compilers} \JAGS\ has been successfully built with the Intel Composer XE compilers. To set up the environment for using these compilers call the \file{compilervars.sh} shell script, {\em e.g.} \begin{verbatim} source /opt/intel/composerxe-2011/bin/compilervars.sh intel64 \end{verbatim} Then call the configure script with the Intel compilers: \begin{verbatim} CC=icc CXX=icpc F77=ifort ./configure \end{verbatim} \subsubsection{Using Clang} \JAGS\ has been built with the clang compiler for C and C++ (version 3.1). The configuration was \begin{verbatim} LD="llvm-ld" CC="clang" CXX="clang++" ./configure \end{verbatim} In this configuration, the gfortran compiler was used for Fortran and the C++ code was linked to the GNU standard C++ library (libstdc++) rather than the version supplied by the LLVM project (libc++). \subsection{Solaris} \JAGS\ has been successfully built and tested on the Intel x86 platform under Solaris 11.3 using the Oracle Developer Studio 12.6 compilers. I experienced some difficulty with the libtool dynamic linker ltdl on Solaris. This is due to the fact that output from the solaris utility nm does not match what libtool expects. This can be overcome by exporting the environment variable NM: \begin{verbatim} export NM=gnm \end{verbatim} to use the GNU version of nm. The C++ library \file{libCstd} is not supported. You must therefore add the option \option{-library=stlport4} to \option{CXXFLAGS} to use the alternative STLPort4 library, \begin{verbatim} export LEX=flex CC=cc CXX="CC -std=sun03" F77=f95 ./configure \ CFLAGS="-O3 -xarch=sse2" \ CXXFLAGS="+w -O3 -xarch=sse2 -library=stlport4 -lCrun" \end{verbatim} or \option{-library=-stdcpp} for the libstdc++ library. \begin{verbatim} ./configure CC=cc CXX="CC -std=c++03" F77=f95 \ CFLAGS="-O3 -xarch=sse2" \ CXXFLAGS="+w -O3 -xarch=sse2 -library=stdcpp" \end{verbatim} The Sun Studio compiler is not optimized by default. Use the option \option{-xO3} for optimization (NB This is the letter ``O'' not the number 0) In order to use the optimization flag \option{-xO3} you must specify the architecture with the \option{-xarch} flag. The options above are for an Intel processor with SSE2 instructions. This must be adapted to your own platform. %C++11? To compile a 64-bit version of JAGS, add the option \option{-m64} to all the compiler flags. On Solaris, 64-bit files are generally installed in an architecture-specific sub-directory (e.g. \file{amd64} on the x86 platform). If you wish to conform to this convention for 64-bit JAGS then you should set the configure options \option{--libdir}, \option{--libexecdir}, and \option{--bindir} appropriately. The configure script automatically detects the Sun Performance library, which implements the BLAS/LAPACK functions. \clearpage \section{macOS} A binary distribution of \JAGS\ is provided for Mac OS X versions 10.9 to 10.11 and macOS 10.12 onwards, which is compatible with the current binary distribution of \R\ and the corresponding \texttt{rjags} and \texttt{runjags} packages that are provided on CRAN. These instructions are only for those users that want to install \JAGS\ from source. The recommended procedure is to build JAGS using clang and the libc++ standard library, which have been the default since OS 10.9. This provides compatibility with all builds of \R\ available on CRAN from version 3.3.0 onwards, as well as ``Mavericks builds'' of earlier versions of \R. Users needing to build against the libstdc++ library and/or with a version of Mac OS X predating 10.9 (Mavericks) should refer to the installation instructions given in older versions of the \JAGS~manual. \subsection{Required tools} If you wish to build from a released source package i.e. \file{JAGS-\release.tar.gz}, you will need to install command line compilers. The easiest way to do this is using the Terminal application from \file{/Applications/Utilities} - opening the application gives you a terminal with a UNIX shell. Run the following command on the terminal and follow the instructions: \begin{verbatim} xcode-select --install \end{verbatim} You will also need to install the gfortran package, which you can download from: \url{https://gcc.gnu.org/wiki/GFortranBinaries#MacOS} This setup should be sufficient to build the \JAGS\ sources and also source packages in R. All the necessary libraries such as BLAS and LAPACK are included within macOS. Additional tools are required to run the optional test suite (see section \ref{section:osxtest}). \subsection{Basic installation} \subsubsection{Prepare the source code} Move the downloaded \file{JAGS-\release.tar.gz} package to some suitable working space on your disk and double click the file. This will decompress the package to give a folder called \file{JAGS-\release}. You now need to re-open the Terminal and change the working directory to the \JAGS\ source code. In the Terminal window after the \$ prompt type \code{cd} followed by a space. In the Finder drag the \file{JAGS-\release} folder into the Terminal window and hit return. If this worked for you, typing \code{ls} followed by a return will list the contents of the \JAGS\ folder. \subsubsection{Set up the environment} \label{section:osxenvironment} Before configuring \JAGS\ it is first necessary to set a linker flag to include the Accelerate framework (\url{https://developer.apple.com/documentation/accelerate}). This allows the \JAGS\ installation to use Apple's implementation of BLAS. Copy and paste the following command into the Terminal window: \begin{verbatim} export LDFLAGS="-framework Accelerate" \end{verbatim} Other compiler options such as optimisation flags can also be set at this stage if desired, for example: \begin{verbatim} export CFLAGS="-Os" export CXXFLAGS="-Os" export FFLAGS="-Os" \end{verbatim} Note that \JAGS\ is usually compiled using \code{-O2} by default, but it may be necessary to specify this explicitly depending on the version of the compiler being used. \subsubsection{Configuration} To configure the package type: \begin{verbatim} ./configure \end{verbatim} This instruction should complete without reporting an error. \subsubsection{Compile} \label{section:osxcompile} To compile the code type: \begin{verbatim} make -j 8 \end{verbatim} The number `8' indicates the number of parallel build threads that should be used (this will speed up the build process). In general this is best as twice the number of CPU cores in the computer - you may want to change the number in the instruction to match your machine. Again, this instruction should complete without errors. \subsubsection{Install} \label{section:osxinstall} Finally to install \JAGS\ you need to be using an account with administrator privileges. Type: \begin{verbatim} sudo make install \end{verbatim} This will ask for your account password and install the code ready to run as described in the User Manual. You need to ensure that \texttt{/usr/local/bin} is in your PATH in order for the command \texttt{jags} to work from a shell prompt. \subsection{Running the test suite} \label{section:osxtest} \subsubsection{Installing CppUnit} As of \JAGS\ version 4, a test suite is included with the source code that can be run to ensure that the compiled code produces the expected results. To run this code on your installation, you will need to download the CppUnit framework either using Homebrew (see section \ref{section:osxtools}) or from: \url{http://freedesktop.org/wiki/Software/cppunit/} For the latter, download the source code under ``Release Versions'' corresponding to the latest release (currently Cppunit 1.14.0), unarchive the file, and then navigate a terminal window to the working directory inside the resulting folder. Then follow the usual terminal commands (as given on the website) to install CppUnit. \subsubsection{Running the tests} The test suite is run following the instructions given in section \ref{section:osxinstall}, using the following additional command: \begin{verbatim} make check \end{verbatim} If successful, a summary of the checks will be given. If compiler errors are encountered, you may need to add the following compiler flag (and subsequent reconfiguration) in order to force the compiler to build with C++11, as required by CppUnit 1.14.0 and later: \begin{verbatim} export CXXFLAGS="-std=c++11 $CXXFLAGS" ./configure make check \end{verbatim} Note that the configuration step may also need to be repeated if CppUnit was not installed the first time this was run. In this case, you may also need to clean the existing compiled code before running \texttt{make check} using: \begin{verbatim} make clean \end{verbatim} \subsection{Tips for developers and advanced users} \subsubsection{Additional tools} \label{section:osxtools} Some additional tools are required to work with code from the \JAGS\ repository. The easiest way of obtaining the necessary utilities is using Homebrew, which can be installed by following the instructions at \url{http://brew.sh} The following instructions have been verified to work with both Mac OS X 10.9 (Mavericks) and macOS 10.12 (Sierra), and should also work with other supported versions of OS X / macOS. If problems are encountered with these instructions on OS X 10.8 or earlier, then an alternative method of installing the required tools using e.g. MacPorts (as given in version 4.1.0 of the \JAGS\ manual) may be more successful. \subsubsection{Working with the development code} If you want to work on code from the \JAGS\ repository, you will need to build and install the auxillary GNU tools (autoconf, automake and libtool), as well as mercurial, bison, and flex as follows: \begin{verbatim} brew install mercurial brew install autoconf brew install automake brew install libtool brew install pkg-config brew install bison brew install flex \end{verbatim} Note that CppUnit can also be installed using the same method: \begin{verbatim} brew install cppunit \end{verbatim} The following sequence should then retrieve a clone of the current development branch of \JAGS, and prepare the source code: \begin{verbatim} hg clone -r release-4_patched http://hg.code.sf.net/p/mcmc-jags/code-0 cd code-0 autoreconf -fis \end{verbatim} The following modification to the \code{PATH} is also currently required to find the Homebrew versions of bison and flex: \begin{verbatim} export PATH="/usr/local/opt/bison/bin:/usr/local/opt/flex/bin:$PATH" \end{verbatim} For more information see \code{brew info bison} and \code{brew info flex} Once these commands have been run successfully, you should be able to follow the configuration and installation instructions from section \ref{section:osxenvironment} onwards. \subsubsection{Using ATLAS} Rather than using the versions of BLAS and LAPACK provided within OS X, it is possible to use ATLAS, which is available from \url{http://math-atlas.sourceforge.net} This can be either be installed by following the instructions given at \url{http://math-atlas.sourceforge.net/atlas_install/}, or by using MacPorts (\url{https://www.macports.org/}) with the following Terminal command: \begin{verbatim} sudo port install atlas \end{verbatim} Once ATLAS is successfully installed, the \texttt{-framework Accelerate} flag can be omitted from the instructions given in section \ref{section:osxenvironment}. \clearpage \section{Windows} \label{section:windows} These instructions use MinGW, the Minimalist GNU system for Windows. You need some familiarity with Unix in order to follow the build instructions but, once built, \JAGS\ can be installed on any PC running windows, where it can be run from the Windows command prompt. \subsection{Preparing the build environment} You need to install the following packages \begin{itemize} \item The Rtools compiler suite for Windows \item MSYS \item NSIS, including the AccessControl plug-in \end{itemize} \subsubsection{Rtools} Rtools is a set of compilers and utilities used for compiling R on Windows. Rtools can be downloaded from your nearest CRAN mirror (\url{https://cran.r-project.org/bin/windows/Rtools/}). We only need the compilers, as we use the utilities provided by MSYS (See below). For this reason, we choose not to add Rtools to the Windows environment variable \code{PATH} when asked by the installer. The JAGS binaries for Windows 4.0.0 and above are built with Rtools 3.3, which is based on gcc 4.6.3. We also successfully built JAGS with the TDM-GCC compilers (\url{http://tdm-gcc.tdragon.net}) based on gcc 5.1.0. However, the resulting JAGS binary is not compatible with R. The rjags package can be successfully compiled and linked against JAGS built with TDM-GCC 5.1.0, and runs correctly on 64-bit R, but the package spontaneously crashes in 32-bit R. \subsubsection{MSYS} MSYS (the Minimal SYStem) is part of the MinGW project (Minimal GNU for Windows). It provides a bash shell for you to build Unix software. Download the MinGW installer \file{mingw-get-setup.exe} from \url{http://www.mingw.org}. Run the installer and select \code{msys-base} (``A Basic MSYS Installation (meta)'') for installation and then select \code{Apply Changes} from the \code{Installation} menu. There is no need to install the developer toolkit (\code{mingw-developer-toolkit}) if you are working with a release tarball of \JAGS. You should not install any of the compilers that come with MinGW as we shall be using the Rtools versions. To make MSYS use the TDM compilers edit the file \file{c:/mingw/msys/1.0/etc/fstab} to read \begin{verbatim} c:\Rtools\gcc-4.6.3\bin /mingw \end{verbatim} This adds the Rtools compilers to your PATH inside the MSYS shell. MSYS creates a home directory for you in \file{c:/mingw/msys/1.0/home/username}, where \code{username} is your user name under Windows. You will need to copy and paste the source files for LAPACK and JAGS into this directory. At the time of writing, the MinGW installer does not create a shortcut for MSYS on either the desktop or the start menu, even when these options are requested. Create your own shortcut to \file{c:/MingGW/msys/1.0/msys.bat} which launches the MSYS shell. For completeness, you may wish to use the icon \file{c:/MinGW/msys/1.0/msys.ico} for your shortcut. \subsubsection{NSIS} The Nullsoft Scriptable Install System (\url{http://nsis.sourceforge.net}) allows you to create a self-extracting executable that installs \JAGS\ on the target PC. These instructions were tested with NSIS 2.46. You must also install the AccessControl plug-in for NSIS, which is available from \url{http://nsis.sourceforge.net/AccessControl_plug-in}. The plug-in is distributed as a zip file which is unpacked into the installation directory of NSIS. \subsection{Building LAPACK} Download the LAPACK source file from \url{http://www.netlib.org/lapack} to your MSYS home directory. We used version 3.5.0. You need to build LAPACK twice: once for 32-bit \JAGS\ and once for 64-bit \JAGS. The instructions below are for 32-bit \JAGS. To build 64-bit versions, repeat the instructions with the flag \option{-m32} replaced by \option{-m64} and start in a clean build directory. Note that you cannot cross-build 64-bit BLAS and LAPACK on a 32-bit Windows system. This is because the build process must run some 64-bit test programs. Launch MSYS (\file{c:/MingW/msys/1.0/msys.bat}) and unpack the tarball. \begin{verbatim} tar xfvz lapack-3.5.0.tgz cd lapack-3.5.0 \end{verbatim} Copy the file \file{INSTALL/make.inc.gfortran} to \file{make.inc} in the top level source directory. Then edit \file{make.inc} replacing the following lines: \begin{verbatim} FORTRAN = gfortran -m32 LOADER = gfortran -m32 \end{verbatim} Type \begin{verbatim} make blaslib make lapacklib \end{verbatim} This will create two static libraries \file{librefblas.a} and \file{liblapack.a}. These are insufficient for building \JAGS: you need to create dynamic link library (DLL) for each one. First create a definition file \file{libblas.def} that exports all the symbols from the BLAS library \begin{verbatim} dlltool -z libblas.def --export-all-symbols librefblas.a \end{verbatim} Then link this with the static library to create a DLL (\file{libblas.dll}) and an import library (\file{libblas.dll.a}) \begin{verbatim} gcc -m32 -shared -o libblas.dll -Wl,--out-implib=libblas.dll.a \ libblas.def librefblas.a -lgfortran \end{verbatim} Repeat the same steps for the LAPACK library, creating an import library (\file{liblapack.dll.a}) and DLL (\file{liblapack.dll}) \begin{verbatim} dlltool -z liblapack.def --export-all-symbols liblapack.a gcc -m32 -shared -o liblapack.dll -Wl,--out-implib=liblapack.dll.a \ liblapack.def liblapack.a -L./ -lblas -lgfortran \end{verbatim} \subsection{Compiling \JAGS} Unpack the JAGS source \begin{verbatim} tar xfvz JAGS-4.0.0.tar.gz cd JAGS-4.0.0 \end{verbatim} and configure JAGS for a 32-bit build \begin{verbatim} CC="gcc -m32" CXX="g++ -m32 -std=c++98" F77="gfortran -m32" \ LDFLAGS="-L/path/to/import/libs/ -Wl,--enable-auto-import" \ ./configure \end{verbatim} where \file{/path/to/import/libs} is a directory that contains the 32-bit import libraries (\file{libblas.dll.a} and \file{liblapack.dll.a}). This must be an {\em absolute} path name, and not relative to the JAGS build directory. After the configure step, type \begin{verbatim} make win32-install \end{verbatim} This will install JAGS into the subdirectory \file{win/inst32}. Note that you must go straight from the configure step to \texttt{make win32-install} without the usual step of typing \texttt{make} on its own. The \texttt{win32-install} target resets the installation prefix, and this will cause an error if the source is already compiled. To install the 64-bit version, clean the build directory \begin{verbatim} make clean \end{verbatim} reconfigure JAGS for a 64-bit build: \begin{verbatim} CC="gcc -m64" CXX="g++ -m64" F77="gfortran -m64" \ LDFLAGS="-L/path/to/import/libs/ -Wl,--enable-auto-import" \ ./configure \end{verbatim} Then type \begin{verbatim} make win64-install \end{verbatim} This will install JAGS into the subdirectory \file{win/inst64}. With both 32-bit and 64-bit installations in place you can create the installer. Normally you will want to distribute the blas and lapack libraries with JAGS. In this case, put the 32-bit DLLs and import libraries in the sub-directory \file{win/runtime32} and the 64-bit DLLs and import libraries in the sub-directory \file{win/runtime64}. They will be detected and included with the distribution. Make sure that the file \file{makensis.exe}, provided by NSIS, is in your PATH. For a typical installation of NSIS, on 64-bit windows: \begin{verbatim} PATH=$PATH:/c/Program\ Files\ \(x86\)/NSIS \end{verbatim} Then type \begin{verbatim} make installer \end{verbatim} After the build process finishes, the self extracting archive will be in the subdirectory \file{win}. \subsection{Running the unit tests} In order to run the unit tests on Windows you must first install the cppunit library from source. Download the file \file{cppunit-1.12.1.tar.gz} from Sourceforge (\url{http://sourceforge.net/projects/cppunit/files/cppunit/1.12.1/}) and unpack it: \begin{verbatim} tar xfvz cppunit-1.12.1.tar.gz cd cppunit-1.12.1 \end{verbatim} Then compile and install as follows: \begin{verbatim} CXX="g++ -m32" ./configure --prefix=/opt32 --disable-shared make make install \end{verbatim} The configure option \verb+--prefix=/opt32+ installs the 32-bit library into \file{/opt32} instead of the default location {/usr/local}. Using this option allows you to do a parallel installation of the 64-bit version of the library, by rebuilding with configure options \verb|CXX=g++ -m64| and \verb+--prefix=/opt64+. The two installations will not interfere with each other. The configure option \verb+--disable-shared+ prevents the creation of the DLL \file{libccpunit.dll} and builds only the static library \file{libcppunit.a}. Without this option, the unit tests will fail. One of the major limitations of static linking to the C++ runtime is that you cannot throw exceptions across a DLL boundary. Linking the test programs against \file{libcppunit.dll} will result in uncaught exceptions and apparent failures for some of the tests, so it must be disabled.\footnote{One of the attractions of the TDM-GCC compilers is that they do allow exceptions across DLL boundaries with static linking. However, we are not currently using TDM-GCC to build the JAGS binaries}. To run the unit tests, add the option \verb+--with-cppunit-prefix=/optXX+ when configuring JAGS where \code{XX} is 32 or 64. Then run \code{make check} after \code{make winXX-install}. \subsection{Running the examples} The BUGS classic examples (file \file{classic-bugs.tar.gz} from the JAGS Sourceforge site) can be run from the Windows command prompt using the \command{make} command provided by Rtools. This requires adding Rtools to the Windows search path if it is not currently there. \begin{verbatim} set PATH=c:\Rtools\bin;%PATH% \end{verbatim} You must have R installed, along with the packages \code{rjags} and \code{coda}, both of which are available from CRAN (\url{cran.r-project.org}). It is necessary to add R to the search path and to set the variable \verb+R_LIBS+. Note that here we are using the 64-bit version of R. You may use the 32-bit version by substituting \code{i386} for \code{x64}. \begin{verbatim} set PATH=c:\Program Files\R\R-3.2.2\bin\x64;%PATH% set R_LIBS=c:\Users\username\Documents\R\win-library\3.2 \end{verbatim} where \file{username} is your Windows user name. Then \begin{verbatim} tar xfvz classic-bugs.tar.gz cd classic-bugs cd vol1 make Rcheck \end{verbatim} will check all examples in volume 1 using the \code{rjags} package. Repeat for \file{vol2} to complete the checks. You can also run checks using the command line interface of JAGS. This requires adding JAGS to the search path and overriding the default name of the JAGS executable. \begin{verbatim} set PATH=c:\Program Files\JAGS\JAGS-4.0.0\bin\x64;%PATH% set JAGS=jags.bat \end{verbatim} Then \begin{verbatim} make check \end{verbatim} in directory \file{vol1} or \file{vol2} will run the checks using the command line interface. \subsection{Using TDM-GCC compilers} This section documents the use of TDM-GCC compilers to build JAGS. TDM-GCC was used to build Windows binaries for JAGS 3.x.y, but has been dropped in favour of Rtools for the 4.x.y release series. One reason for this is that the 32-bit version of JAGS built with TDM-GCC 5.1.0 causes the rjags package to spontaneously crash. The 64-bit version runs correctly. TDM-GCC has a nice installer, available from Sourceforge (follow the links on the main TDM-GCC web site (\url{http://tdm-gcc.tdragon.net}). Ensure that you download the TDM64 MinGW-w64 edition as this is capable of producing both 32-bit and 64-bit binaries. We tested JAGS with \file{tdm64-gcc-5.1.0-2.exe} based on gcc 5.1.0. Select a ``Recommended C/C++'' installation and customize it by selecting the Fortran compiler, which is not installed by default. The installer gives you the option of adding TDM-GCC \file{bin} folder to the windows PATH variable. We choose not to do this, but added the \file{bin} to the PATH within the MSYS shell by editing \file{c:/mingw/msys/1.0/etc/fstab} to read \begin{verbatim} c:\TDM-GCC-64 /mingw \end{verbatim} After installation of TDM-GCC, to force the compiler to use static linking, delete any import libraries (files ending in \file{.dll.a} in the TDM-GCC tree. If you do not do this then you will need to distribute runtime DLLs from TDM-GCC with JAGS. You can easily do this by copying the DLLs to \file{runtime32} and \file{runtime64} before building the installer, as described above. Nevertheless, it is often more convenient to use static linking. Installation proceeds in the same way as for the Rtools build but with two differences. Firstly, when building the DLLs for blas and lapack, you need to add the linker flag \verb+-lquadmath+ after \verb+-lgfortran+. Secondly, when configuring JAGS you should set the environment variable \begin{verbatim} CPPFLAGS=-D_GLIBCXX_USE_CXX11_ABI=0 \end{verbatim} This is necessary because gcc 5.1.0 introduced a new application binary interface (ABI) for the C++ standard library (See \url{https://gcc.gnu.org/onlinedocs/libstdc++/manual/using_dual_abi.html}. The old ABI is still supported and is used if you set the above flag. If you want to link JAGS with any software compiled with an earlier version of gcc then you need to use the old ABI. Failure to do so will result in error messages about undefined symbols from the linker. \end{document} JAGS-4.3.0/doc/manual/jags_developer_manual.tex0000664000175000017500000002363313130731022016256 00000000000000\documentclass[11pt, a4paper, titlepage]{report} \usepackage{a4wide} \usepackage{url} \usepackage{multirow} \usepackage{amsfonts} %\usepackage{amssym} \newcommand{\JAGS}{\textsf{JAGS}} \newcommand{\BUGS}{\textsf{BUGS}} \newcommand{\WinBUGS}{\textsf{WinBUGS}} \newcommand{\R}{\textsf{R}} \newcommand{\CODA}{\textsf{coda}} \begin{document} \title{JAGS Developers Manual} \author{Martyn Plummer} \date{6 July 2011} \maketitle \tableofcontents \chapter{Introduction} This is currently a collection of notes on working with the JAGS source. It will eventually grow into an explanation of how to extend the capabilities of JAGS by writing new modules. \chapter{Working with the CVS repository} The \JAGS\ source code is held in a CVS repository. Clear instructions on how to access the CVS source are given at the project web site \url{http://sourceforge.net/projects/mcmc-jags}. To access the instructions, click the link marked ``develop'' then the ``Code'' tab and select ``CVS'' from the pull-down menu. You need a complete installation of GNU autotools (autoconf, automake, and libtool) to work with the CVS source, since all non-essential files have been stripped out of the repository. You must build local versions of these files by changing directory into the top-level source directory and typing \begin{verbatim} autoreconf -fi \end{verbatim} Your source tree is then ready to work with. Note that JAGS is not currently compatible with automake-1.12. You must use automake-1.11 or earlier. The CVS repository also excludes some \texttt{C++} source files that are included in the source tarball. These files are re-created in the build tree by the GNU tools \verb+flex+ and \verb+bison+. You must also have these tools installed if you are using the CVS repository. Note that the standard unix versions of these tools -- \verb+lex+ and \verb+yacc+ -- are not sufficient, and you must have an up-to-date version of \verb+flex+. \footnote{On Solaris, the OpenCSW package \texttt{flex} contains version 2.5.4, which is not compatible with JAGS. Use the \texttt{flexnew} package} Once you have checked out a CVS tree, you can keep it up to date with \begin{verbatim} cvs update -Pd \end{verbatim} You may occasionally need to rerun the autoreconf function when files are added, removed, or moved within the repository. I recommend keeping one or more build directories that are separate from the source directory. I have several build directories for JAGS configured in different ways: one standard one for testing the BUGS examples, one with no optimization for debugging, another statically linked one for profiling, and so on. \chapter{Testing the Installation} The classic bugs are available in the CVS module ``examples''. They can also be downloaded in a tarball from the JAGS home page. There are two sub-directories: ``vol1'' and ``vol2''. Within each sub-directory you can test the installation with \begin{verbatim} make check \end{verbatim} To test a subset of examples, set the environment variable \verb+EXAMPLES+: \begin{verbatim} make check EXAMPLES="blocker bones" \end{verbatim} If you are not using a GNU system, you may need to use GNU make (\verb+gmake+). You need to have R installed in order to check the output of JAGS against the benchmarks. If you have the \texttt{rjags} package installed, then you may also test the rjags package with \begin{verbatim} make Rcheck \end{verbatim} \chapter{Directory structure} The \JAGS\ source is divided into three main directories: \texttt{lib}, \texttt{modules}, and \texttt{terminal}. The \texttt{lib} directory contains the \JAGS\ library, which contains all the facilities for defining a Bayesian graphical model in the \BUGS\ language, running the Gibbs sampler and monitoring the sampled values. The \JAGS\ library is divided into several convenience libraries \begin{description} \item[sarray] which defines the basic SArray class, modelled on an \textsf{S} language array, and its associated classes. \item[function] which defines the interface for functions and the \texttt{FuncTab} class that allows you to reference them by name. \item[distribution] which defines the interface for distribution and the \texttt{DistTab} class that allows you to reference them by name. \item[graph] which defines the various Node classes used by \JAGS\ when constructing a Bayesian graphical model, as well as the \texttt{Graph} class which is a container for nodes. \item[sampler] which defines the interface for Samplers, which update stochastic nodes in the graph. \item[model] which defines all the classes needed to create a model, including monitor classes. \item[compiler] which contains the Compiler class and a number of supporting classes designed for an efficient translation of a BUGS-language description the model into a \texttt{Graph}. \item[rng] which defines the interface for random number generators (RNGs) and the factories that create them. \item[util] which contains some utility functions used in the rest of the \JAGS\ library. \end{description} The \texttt{Console} class provides a clean interface to the \JAGS\ library. The member functions of the \texttt{Console} class conduct all of the operations one may wish to do on a Bayesian graphical model. They are designed to catch any exceptions thrown by the library and print an informative message to either an output stream or an error stream, depending on the result. The \texttt{modules} directory contains the source code for JAGS modules, which contain concrete classes corresponding to the abstract classes defined in the \JAGS\ library. The \texttt{terminal} directory contains the source code for a reference front end for the \JAGS\ library, which uses the \textsf{Stata}-like syntax described in the user manual \chapter{Debugging and Profiling} \label{chapter:debugging} Debugging and profiling tools are essential for finding bugs and bottlenecks in the code. The most important tools are \texttt{gdb}, \texttt{valgrind}, \texttt{gprof} and \texttt{oprofile}. \section{Debugging with gdb} \JAGS\ can be run from within the GNU debugger \texttt{gdb} by typing \begin{verbatim} jags -d gdb \end{verbatim} To run a script, type \begin{verbatim} r \end{verbatim} at the gdb prompt. Debugging of optimized C++ code is not easy, especially when using code from the Standard Template Library (STL). Unless you speak fluent STL, you will need to work with a non-optimized build of \JAGS. Using \verb+gcc+ this is done with the following build flags. \begin{verbatim} CXXFLAGS="-g -O0" CFLAGS="-g -O0" \end{verbatim} It is helpful to keep a separate non-optimized build directory for occasions when you need to use a debugger. It is not possible to set a break point in a module before it has been dynamically loaded. To do so, run JAGS by typing ``r'' at the \verb+gdb+ prompt, then control-C to return to the gdb prompt after the modules have been loaded. \section{Debugging with valgrind} Valgrind (\url{www.valgrind.org}) is a memory profiler and debugger. To run \JAGS\ through valgrind, type \begin{verbatim} jags -d valgrind \end{verbatim} If you need to pass options to valgrind, enclose these in quotes \begin{verbatim} jags -d 'valgrind --leak-check=full' \end{verbatim} \JAGS\ will run very slowly inside valgrind, and will use more memory, so its use should be limited to small test programs. \section{Profiling with gprof} The GNU profiler \texttt{gprof} does not debug dynamic libraries. It is therefore not very useful for a standard installation of \JAGS, since almost all of the functionality is contained in the jags library, the jrmath library, and the modules. However, you can build a statically linked version in which the libraries and modules are folded into the executable \texttt{jags-terminal}. To build this version of \JAGS, with profiling information for \texttt{gprof}, use the following configure options: \begin{verbatim} CXXFLAGS="-g -O2 -pg" \ CFLAGS="-g -O2 -pg" \ /path/to/JAGS/configure --disable-shared \end{verbatim} Whenever \JAGS\ is run, it will create a file \texttt{gmon.out} in the working directory that can be used for profiling with \texttt{gprof}. \section{Profiling with oprofile} Oprofile (\url{oprofile.sourceforge.net}) is a linux-based profiler that runs as a daemon. Unlike \texttt{gprof} it does not require any special configuration options, and can be used to debug dynamic libraries. You must be root to start the profiler \begin{verbatim} opcontrol --no-vmlinux opcontrol --start \end{verbatim} Then, as a normal user, you may run a model and dump the profiling information to file with \begin{verbatim} opcontrol --dump \end{verbatim} To see how much time \JAGS\ is spending in the functions in a module type \begin{verbatim} opreport -l /usr/local/lib/JAGS/modules/bugs.so | less \end{verbatim} The opreport command gives copious information, so you will need to redirect the output to a file or, as in this example, a pager. The same command works for the main \JAGS\ library \begin{verbatim} opreport -l /usr/local/lib/libjags.so \end{verbatim} More detailed profiling information can be obtained with the \verb+opannotate+ command, provided that \JAGS\ has been compiled with debugging symbols. The command \begin{verbatim} opannotate --source /usr/local/lib/JAGS/modules/bugs.so | less \end{verbatim} reconstructs the source code and gives annotations in a column in the left hand side counting the number of samples in each function, block or line. This can be useful for finding bottlenecks in the code. Oprofile will continue to accumulate samples from multiple runs of JAGS, although the output of the \verb+opreport+ and \verb+opannotate+ commands will not change until you dump the data again with \verb+opcontrol --dump+. If you do not wish to see the cumulative samples from multiple runs -- for instance if you have modified the \JAGS\ code and want to check that a previous bottleneck has been removed -- then you can clear the existing data collection by typing, as root \begin{verbatim} opcontrol --reset \end{verbatim} \end{document} JAGS-4.3.0/doc/manual/jags_user_manual.tex0000664000175000017500000041656313131673621015272 00000000000000\documentclass[11pt, a4paper, titlepage]{report} \usepackage{amsmath} \usepackage{natbib} \usepackage{a4wide} \usepackage{url} \usepackage{multirow} \usepackage{amsfonts} \usepackage{graphicx} \newcommand{\release}{4.3.0} \newcommand{\JAGS}{\textsf{JAGS}} \newcommand{\rjags}{\textsf{rjags}} \newcommand{\BUGS}{\textsf{BUGS}} \newcommand{\OpenBUGS}{\textsf{OpenBUGS}} \newcommand{\R}{\textsf{R}} \newcommand{\CODA}{\textsf{coda}} \begin{document} \title{JAGS Version \release\ user manual} \author{Martyn Plummer} \date{28 June 2017} \maketitle \tableofcontents \chapter{Introduction} \JAGS\ is ``Just Another Gibbs Sampler''. It is a program for the analysis of Bayesian models using Markov Chain Monte Carlo (MCMC) which is not wholly unlike \OpenBUGS\ (\url{http://www.openbugs.info}). \JAGS\ is written in C++ and is portable to all major operating systems. %Cite the bugs book \JAGS\ is designed to work closely with the \R\ language and environment for statistical computation and graphics (\url{http://www.r-project.org}). You will find it useful to install the \CODA\ package for \R\ to analyze the output. Several \R\ packages are available to run a \JAGS\ model. See chapter~\ref{chapter:R}. \JAGS\ is licensed under the GNU General Public License version 2. You may freely modify and redistribute it under certain conditions (see the file \texttt{COPYING} for details). \section{Downloading \JAGS} \JAGS\ is hosted on Sourceforge at \url{https://sourceforge.net/projects/mcmc-jags/}. Binary distributions of \JAGS\ for Windows and macOS can be downloaded directly from there. Binaries for various Linux distributions are also available, but not directly from Sourceforge. See \url{http://mcmc-jags.sourceforge.net} for details. You can also download the source tarball from Sourceforge. Details on installing \JAGS\ from source are given in a separate \JAGS\ Installation manual. \section{Getting help} \label{section:help} The best way to get help on \JAGS\ is to use the discussion forums hosted on Sourceforge at \url{https://sourceforge.net/p/mcmc-jags/discussion/}. You will need to create a Sourceforge account in order to post. Bug reports can be sent to \url{martyn_plummer@users.sourceforge.net}. Occasionally, \JAGS\ will stop with an error instructing you to send a message to this address. I am particularly interested in the following issues: \begin{itemize} \item Crashes, including both segmentation faults and uncaught exceptions. \item Incomprehensible error messages \item Models that should compile, but don't \item Output that cannot be validated against other software such as \OpenBUGS \item Documentation erors \end{itemize} If you submit a bug report, it must be reproducible. Please send the model file, the data file, the initial value file and a script file that will reproduce the problem. Describe what you think should happen, and what did happen. \section{Acknowledgements} Many thanks to the \BUGS\ development team, without whom \JAGS\ would not exist. Thanks also to Simon Frost for pioneering \JAGS\ on Windows and Bill Northcott for getting \JAGS\ on Mac OS X to work. Kostas Oikonomou found many bugs while getting \JAGS\ to work on Solaris using Sun development tools and libraries. Bettina Gruen, Chris Jackson, Greg Ridgeway and Geoff Evans also provided useful feedback. Special thanks to Jean-Baptiste Denis who has been very diligent in providing feedback on JAGS. Matt Denwood is a co-developer of \JAGS\ with full access to the Sourceforge repository. \chapter{The BUGS language} \label{chapter:bugslang} A \JAGS\ model is defined in a text file using a dialect of the \BUGS\ language \citep{LunnEtal2012}. The model definition consists of a series of {\em relations} inside a block delimited by curly brackets \verb+{+ and \verb+}+ and preceded by the keyword \verb+model+. Here is a simple linear regression example: \begin{verbatim} model { for (i in 1:N) { Y[i] ~ dnorm(mu[i], tau) mu[i] <- alpha + beta * (x[i] - x.bar) } x.bar <- mean(x) alpha ~ dnorm(0.0, 1.0E-4) beta ~ dnorm(0.0, 1.0E-4) sigma <- 1.0/sqrt(tau) tau ~ dgamma(1.0E-3, 1.0E-3) } \end{verbatim} %Something about verbosity \section{Relations} Each relation defines a node in the model. The node on the left of a relation is defined in terms of other nodes -- referred to as parent nodes -- that appear on the right hand side. Taken together, the nodes in the model form a directed acyclic graph (with the parent/child relationships represented as directed edges). The very top-level nodes in the graph, with no parents, are constant nodes, which are defined either in the model definition ({\em e.g.} \verb+1.0E-3+), or in the data when the model is compiled ({\em e.g.} \verb+x[1]+). Relations can be of two types. A {\em stochastic relation} (\verb+~+) defines a stochastic node, representing a random variable in the model. A {\em deterministic relation} (\verb+<-+) defines a deterministic node, the value of which is determined exactly by the values of its parents. The equals sign (\verb+=+) can be used for a deterministic relation in place of the left arrow (\verb+<-+). \section{Arrays and subsetting} Nodes defined by a relation are embedded in named arrays. Arrays can be vectors (one-dimensional), or matrices (two-dimensional), or they may have more than two dimensions. Array names may contain letters, numbers, decimal points and underscores, but they must start with a letter. In the code example above, the node array \verb+mu+ is a vector of length $N$ containing $N$ nodes (\verb+mu[1]+, $\ldots$, \verb+mu[N]+). The node array \verb+alpha+ is a scalar. \JAGS\ follows the S language convention that scalars are considered as vectors of length 1. Hence the array \verb+alpha+ contains a single node \verb+alpha[1]+. \subsection{Subsetting vectors} Subsets of node arrays may be obtained with expressions of the form \verb+alpha[e]+ where \verb+e+ is any expression that evaluates to an integer vector. Typically expressions of the form \verb+L:U+ are used, where $L$ and $U$ are integer arguments to the operator ``\texttt{:}''. This creates an integer vector of length $U - L + 1$ with elements $L, L+1, \ldots U-1, U$.\footnote{If $L > U$ then the operator $:$ returns a vector of length zero, which may not be used to take array subsets} Both the arguments $L$ and $U$ must be fixed because JAGS does not allow the length of a node to change from one iteration to the next. \subsection{Subsetting matrices} For a two-dimensional array \verb+B+, the element in row $r$ and column $c$ is accessed as \verb+B[r,c]+. Complex subsets may be obtained with expressions of the form \verb+B[rows, cols]+ where \verb+rows+ is an integer vector of row indices and \verb+cols+ is an integer vector of column indices. An index expression in any dimension may be omitted, and this implies taking the whole range of possible indices. So if \verb+B+ is an $M \times N$ matrix then \verb+B[r,]+ is the whole of row $r$, and is equivalent to \verb+B[r,1:N]+. Likewise \verb+B[,c]+ is the whole of column $c$ and is equivalent to \verb+B[1:M,c]+. Finally, \verb+B[,]+ is the whole matrix, equivalent to \verb+B[1:M,1:N]+. In this case, one may also simply write \verb+B+ without any square brackets. Note that writing \verb+B[]+ for a 2-dimensional array will result in a compilation error: the number of indices separated by commas within the square brackets must match the dimensions of the array. \subsection{Restrictions on index expressions} There are some restrictions on index expressions that are allowed on the left hand side of a relation. Firstly, they must be fixed, meaning that they must be expressed in terms of data, or constants defined in the model, or the index of an enclosing for loop (see below). As a counter-example, the following code snippet is illegal: \begin{verbatim} i ~ dcat(p) x[i] ~ dnorm(0, 1) \end{verbatim} unless $i$ is observed and is supplied with the data. This restriction ensures that the node \verb+x[i]+ can be unambiguously referred to elsewhere in the model -- e.g. as a function argument or the parameter for a distribution -- and does not change from one iteration to another. Secondly, for vector-valued subsets, the same index must not be repeated. For example, supposed $\mu$ is a 2-vector and $T$ is a $2 \times 2$ matrix. Then \verb+dmnorm(mu, T)+ defines a bivariate normal random variable. However, this code snippet is illegal: \begin{verbatim} indices <- c(1,1) x[indices] ~ dmnorm(mu, T) \end{verbatim} as it implies writing two different values to the same element \verb+x[1]+. \section{Constructing vectors} Vectors can be constructed using the combine function \texttt{c} from the \textsf{bugs} module, {\em e.g.} \begin{verbatim} y <- c(x1, x2, x3) \end{verbatim} creates a new vector $y$ combining the elements of $x1$, $x2$, and $x3$. The combine function can be used with a single array argument \begin{verbatim} v <- c(a) \end{verbatim} In this case the return value $v$ is a vector with the values of the input array $a$ in column-major order (i.e. with the left hand index moving fastest). For example if $a$ is a $2 \times 2$ matrix then this is equivalent to \begin{verbatim} v <- c(a[1,1], a[2,1], a[1,2], a[2,2]) \end{verbatim} \section{For loops} \label{section:forloops} For loops are used in the the \BUGS\ language to simplify writing repeated expressions. A for loop takes the form: \begin{verbatim} for (i in exp) { } \end{verbatim} where \texttt{exp} is any expression that evaluates to an integer vector. The contents of the for loop inside the curly braces will then be expanded with the index \texttt{i} taking each value in the vector \texttt{exp}. For example \begin{verbatim} for (i in 1:3) { Y[i] ~ dnorm(mu, tau) } \end{verbatim} is equivalent to \begin{verbatim} Y[1] ~ dnorm(mu, tau) Y[2] ~ dnorm(mu, tau) Y[3] ~ dnorm(mu, tau) \end{verbatim} As in the above example, for loops generally use the sequence operator \verb+:+ to generate an increasing sequence of integers. This operator has high precedence, so is important to use brackets to ensure that the expression is interpreted correctly. For example, to get a for loop from $1$ to $m+1$ the correct expression is \begin{verbatim} for (i in 1:(m+1)) { } \end{verbatim} Omitting the brackets as in the following expression: \begin{verbatim} for (i in 1:m+1) { } \end{verbatim} gives a for loop from $2$ to $m+1$. The sequence operator \verb+:+ can only produce increasing sequences. If $n < m$ then \verb+m:n+ produces a vector of length zero and when this is used in a for loop index expression the contents of loop inside the curly brackets are skipped. Note that this behaviour is different from the sequence operator in R, where \verb+m:n+ will produce a {\em decreasing} sequence if $n < m$. \section{Data transformations} \label{section:data:tranformations} Sometimes it is useful to transform the data before analysing them. For example, a transformation of outcomes may be necessary to reduce skewness and allow the outcome to be represented by a normal or other symmetric distribution. You can transform the data supplied to \JAGS\ in a separate block of relations preceded by the keyword \texttt{data}. Here for example, the input data \texttt{y} is transformed via a square-root transformation to \texttt{z}, which is then used as an outcome variable in the model block: \begin{verbatim} data { for (i in 1:N) { z[i] <- sqrt(y[i]) } } model { for (i in 1:N) { z[i] ~ dnorm(mu, tau) } ... } \end{verbatim} In effect, the data block defines a distinct model, which describes how the data are generated. Each node in this model is forward-sampled once, and then the node values are read back into the data table. \subsection{Modelling simulated data} The data block is not limited to logical relations, but may also include stochastic relations. You may therefore use it in simulations, generating data from a stochastic model that is different from the one used to analyse the data in the \texttt{model} statement. This example shows a simple location-scale problem in which the ``true'' values of the parameters \texttt{mu} and \texttt{tau} are generated from a given prior in the \texttt{data} block, and the generated data is analyzed in the \texttt{model} block. \begin{verbatim} data { for (i in 1:N) { y[i] ~ dnorm(mu.true, tau.true) } mu.true ~ dnorm(0,1); tau.true ~ dgamma(1,3); } model { for (i in 1:N) { y[i] ~ dnorm(mu, tau) } mu ~ dnorm(0, 1.0E-3) tau ~ dgamma(1.0E-3, 1.0E-3) } \end{verbatim} Beware, however, that every node in the \texttt{data} statement will be considered as data in the subsequent \texttt{model} statement. This example, although superficially similar, has a quite different interpretation. \begin{verbatim} data { for (i in 1:N) { y[i] ~ dnorm(mu, tau) } mu ~ dnorm(0,1); tau ~ dgamma(1,3); } model { for (i in 1:N) { y[i] ~ dnorm(mu, tau) } mu ~ dnorm(0, 1.0E-3) tau ~ dgamma(1.0E-3, 1.0E-3) } \end{verbatim} Since the names \texttt{mu} and \texttt{tau} are used in both \texttt{data} and \texttt{model} blocks, these nodes will be considered as {\em observed} in the model and their values will be fixed at those values generated in the \texttt{data} block. \section{Node Array dimensions} \subsection{Array declarations} \JAGS\ allows the option of declaring the dimensions of node arrays in the model file. The declarations consist of the keyword \texttt{var} (for variable) followed by a comma-separated list of array names, with their dimensions in square brackets. The dimensions may be given in terms of any expression of the data that returns a single integer value. In the linear regression example, the model block could be preceded by \begin{verbatim} var x[N], Y[N], mu[N], alpha, beta, tau, sigma, x.bar; \end{verbatim} \subsection{Undeclared nodes} If a node array is not declared then JAGS has three methods of determining its size. \begin{enumerate} \item {\bf Using the data.} The dimension of an undeclared node array may be inferred if it is supplied in the data file. \item {\bf Using the left hand side of the relations.} The maximal index values on the left hand side of a relation are taken to be the dimensions of the node array. For example, in this case: \begin{verbatim} for (i in 1:N) { for (j in 1:M) { Y[i,j] ~ dnorm(mu[i,j], tau) } } \end{verbatim} $Y$ would be inferred to be an $N \times M$ matrix. This method cannot be used when there are empty indices ({\em e.g.} \verb+Y[i,]+) on the left hand side of the relation. \item {\bf Using the dimensions of the parents} If a whole node array appears on the left hand side of a relation, then its dimensions can be inferred from the dimensions of the nodes on the right hand side. For example, if \verb+A+ is known to be an $N \times N$ matrix and \begin{verbatim} B <- inverse(A) \end{verbatim} Then \verb+B+ is also an $N \times N$ matrix. \end{enumerate} \subsection{Querying array dimensions} The \JAGS\ compiler has two built-in functions for querying array sizes. The \verb+length()+ function returns the number of elements in a node array, and the \verb+dim()+ function returns a vector containing the dimensions of an array. These two functions may be used to simplify the data preparation. For example, if \verb+Y+ represents a vector of observed values, then using the \verb+length()+ function in a for loop: \begin{verbatim} for (i in 1:length(Y)) { Y[i] ~ dnorm(mu[i], tau) } \end{verbatim} avoids the need to put a separate data value \verb+N+ in the file representing the length of \verb+Y+. For multi-dimensional arrays, the \verb+dim+ function serves a similar purpose. The \verb+dim+ function returns a vector, which must be stored in an array before its elements can be accessed. For this reason, calls to the \verb+dim+ function must always be in a data block (see section \ref{section:data:tranformations}). \begin{verbatim} data { D <- dim(Z) } model { for (i in 1:D[1]) { for (j in 1:D[2]) { Z[i,j] <- dnorm(alpha[i] + beta[j], tau) } } ... } \end{verbatim} Clearly, the \verb+length()+ and \verb+dim()+ functions can only work if the size of the node array can be inferred, using one of the three methods outlined above. Note: the \verb+length()+ and \verb+dim()+ functions are different from all other functions in \JAGS: they do not act on nodes, but only on node {\em arrays}. As a consequence, an expression such as \verb+dim(a %*% b)+ is syntactically incorrect. \chapter{Steps in running a model} \label{chapter:running} \JAGS\ is designed for inference on Bayesian models using Markov Chain Monte Carlo (MCMC) simulation. Running a model refers to generating samples from the posterior distribution of the model parameters. This takes place in five steps: \begin{enumerate} \item Definition of the model \item Compilation \item Initialization \item Adaptation and burn-in \item Monitoring \end{enumerate} The next stages of analysis are done outside of \JAGS: convergence diagnostics, model criticism, and summarizing the samples must be done using other packages more suited to this task. There are several \R\ packages designed for running a \JAGS\ model and analyzing the output. See chapter~\ref{chapter:R} for details. \section{Modules} \label{section:modules} The \JAGS\ library is distributed along with dynamically loadable modules that extend its functionality. A module can define new objects of the following classes: \begin{enumerate} \item {\bf Functions} and {\bf distributions}, the basic building blocks of the BUGS language. \item {\bf Samplers}, the objects which update the parameters of the model at each iteration, and {\bf sampler factories}, the objects that create new samplers for specific model structures. \item {\bf Monitors}, the objects that record sampled values for later analysis, and {\bf monitor factories} that create them. \item {\bf Random number generators}, the objects that drive the MCMC algorithm and {\bf RNG factories} that create them. \end{enumerate} The \texttt{base} module and the \texttt{bugs} module are loaded automatically at start time. Others may be loaded by the user. It is important to load the modules you need {\rm before} running the model. The two most useful optional modules are the \texttt{glm} module (chapter~\ref{chapter:glm}), which provides efficient samplers for generalized linear mixed modules, and the \texttt{dic} module (chapter~\ref{chapter:dic}), which provides novel monitors for assessing model fit using deviance statistics. \section{Compilation} When a \JAGS\ model is compiled, the model description is combined with the data to create a {\em virtual graphical model}, which is a representation of the model as a directed acyclic graph (DAG) in computer memory.%compilation vs interpretation One of the interesting features of the \BUGS\ language is that it does not clearly distinguish between data and parameters. A stochastic node -- {\em i.e.} a node defined on the left hand side of a stochastic relation -- may be either observed (data) or unobserved (parameter). The distinction is made only when the model is compiled and depends entirely on whether a data value was supplied or not. Data may also be supplied for {\em constant nodes}. These are nodes that are used on the right hand side of a relation (or in the index expression of a for loop) but are never defined on the left hand side. In fact you must supply data for these nodes or the \JAGS\ compiler will stop with an error message. Data may not be supplied for deterministic nodes -- {\em i.e.} those defined on the left hand side of a deterministic relation. These nodes always calculate their value according to the current value of the parents. Recall the simple linear regression model from chapter~\ref{chapter:bugslang}. \begin{verbatim} model { for (i in 1:N) { Y[i] ~ dnorm(mu[i], tau) mu[i] <- alpha + beta * (x[i] - x.bar) } x.bar <- mean(x) alpha ~ dnorm(0.0, 1.0E-4) beta ~ dnorm(0.0, 1.0E-4) sigma <- 1.0/sqrt(tau) tau ~ dgamma(1.0E-3, 1.0E-3) } \end{verbatim} This model may be compiled by combining with data values for \texttt{x}, \texttt{Y} and \texttt{N}. Exactly how the data are supplied depends on which interface is being used. With any of the \R\ interfaces to \JAGS, the user can create a list of values to be supplied as data, e.g. \begin{verbatim} line_data <- list("x" = c(1, 2, 3, 4, 5), "Y" = c(1, 3, 3, 3, 5), "N" = 5) \end{verbatim} and then supply this list as the \texttt{data} argument to any of the modelling functions (NB the above is \R\ code, not \BUGS\ code). This is explored in more detail in chapter~\ref{chapter:R}. With the command line interface, the data are supplied in a separate file with values written in the \texttt{dump()} format of the \R\ language, e.g. \begin{verbatim} #contents of file line-data.R "x" <- c(1, 2, 3, 4, 5) "Y" <- c(1, 3, 3, 3, 5) "N" <- 5 \end{verbatim} See section~\ref{section:cmdline:data} for more details. In our simple linear regression model, data values must always be supplied for \texttt{N}, since it is used to index the for loop. Data must also be supplied for \texttt{x} since it is used on the right hand side of the relation defining \texttt{mu} but never defined on the left hand side of a relation. %One way to think about the minimal data for a model is that it %\JAGS\ be able to sample values from the prior distribution. In this example, data values are also supplied for the outcome variables \verb+Y[1]+ to \verb+Y[5]+. The parameters of the model are the three stochastic nodes for which no data are supplied: \texttt{alpha}, \texttt{beta} and \texttt{tau}. \JAGS\ will generate samples from the posterior distribution of these parameters given \texttt{Y}. As can be seen from the example above, data values are supplied for whole node arrays If a node array contains both observed and unobserved nodes, then the data should contain missing values (\texttt{NA}) for the unobserved elements. Suppose that if \verb+Y[2]+ and \verb+Y[5]+ were unobserved, then the data supplied for the node array \texttt{Y} would be. \begin{verbatim} Y = c(1, NA, 3, 3, NA) \end{verbatim} Then \verb+Y[2]+ and \verb+Y[5]+ are parameters and \JAGS\ will generate samples from their posterior predictive distributions, given the observed \texttt{Y} values. Multivariate nodes cannot be partially observed, so if a node takes up two or more elements of a node array, then the corresponding data values must be all present or all missing. \subsection{Compilation failures} Compilation may fail for a number of reasons. The three most common are: \begin{enumerate} \item The model uses a function or distribution that has not been defined in any of the loaded modules. %crossref \item The graph contains a directed cycle. These are forbidden in \JAGS. \item A node is used in an expression but never defined by a relation or supplied with the data. \end{enumerate} %Causes \subsection{Parallel chains} The number of parallel chains to be run by \JAGS\ is also defined at compilation time. Each parallel chain should produce an independent sequence of samples from the posterior distribution. \section{Initialization} Before a model can be run, it must be initialized. There are three steps in the initialization of a model: \begin{enumerate} \item The initial values of the model parameters are set. \item A Random Number Generator (RNG) is chosen for each parallel chain, and its seed is set. \item The Samplers are chosen for each parameter in the model. \end{enumerate} \subsection{Initial values} The user may supply initial value files -- one for each chain -- containing initial values for the model parameters. Initial values may not be supplied for logical or constant nodes. The format for initial values is the same as the one used for data (i.e. a list using the R interface or a separate file when using the command line interface). As with the data, initial values are supplied for whole node arrays and may include missing values for elements of the array that are not to be initialized. This need typically arises with contrast parameters. Suppose $X$ is a categorical covariate, taking values from 1 to 4, which is used as a predictor variable in a linear model: \begin{verbatim} for (i in 1:N) { Y[i] ~ alpha + beta[x[i]] } # Prior distribution alpha ~ dnorm(0, 1.0E-3) beta[1] <- 0 for(i in 2:4) { beta[i] ~ dnorm(0, 1.0E-3) } \end{verbatim} There is one parameter for each level of x ($\beta_1 \ldots \beta_4$), but the first parameter $\beta_1$ is set to zero for identifiability. The remaining parameters $\beta_2 \ldots \beta_4$ represent contrasts with respect to the first level of $X$. A suitable set of initial values (for a single chain) would be \begin{verbatim} list(alpha = 0, beta = c(NA, 1.03, -2.03, 0.52)) \end{verbatim} This allows parameter values to be supplied for the stochastic elements of \verb+beta+ but not the constant first element. If initial values are not supplied by the user, then each parameter chooses its own initial value based on the values of its parents. The initial value is chosen to be a ``typical value'' from the prior distribution. The exact meaning of ``typical value'' depends on the distribution of the stochastic node, but is usually the mean, median, or mode. If you rely on automatic initial value generation and are running multiple parallel chains, then the initial values will be the same in all chains.\footnote{This is undesirable behaviour and it will be changed in a future release of \JAGS.} You are advised to set the starting values manually. \subsection{Random Number Generators} \label{section:rngs} Each chain in \JAGS\ has its own random number generator (RNG). RNGs are more correctly referred to as {\em pseudo}-random number generators. They generate a sequence of numbers that merely looks random but is, in fact, entirely determined by the initial state. You may optionally set the name of the RNG and its initial state with the initial values for the parameters. There are four RNGs supplied by the \texttt{base} module in \JAGS\ with the following names: \begin{verbatim} "base::Wichmann-Hill" "base::Marsaglia-Multicarry" "base::Super-Duper" "base::Mersenne-Twister" \end{verbatim} There are two ways to set the starting state of the RNG. The simplest is to supply the name of the RNG and its seed (a single integer value) with the initial values, {\em e.g.} using the \R\ interface to \JAGS: \begin{verbatim} list(".RNG.name" = "base::Wichmann-Hill", ".RNG.seed" = 314159, ...) \end{verbatim} Here we use \texttt{...} to denote that the same list includes initial values for the parameters (not shown). It is also possible to save the state of the RNG from one JAGS session and use this as the initial state of a new chain. The state of any RNG in JAGS can be saved and loaded as an integer vector with the name \texttt{.RNG.state}. For example, \begin{verbatim} list(".RNG.name" = "base::Marsaglia-Multicarry", ".RNG.state" = as.integer(c(20899,10892,29018)), ...) \end{verbatim} is a valid state for the Marsaglia-Multicarry generator. You cannot supply an arbitrary integer vector to \texttt{.RNG.state}. Both the length of the vector and the permitted values of its elements are determined by the class of the RNG. The only safe way to use \texttt{.RNG.state} is to re-use a previously saved state. If no RNG names are supplied, then RNGs will be chosen automatically so that each chain has its own independent random number stream. The exact behaviour depends on which modules are loaded. The \texttt{base} module uses the four generators listed above for the first four chains, then recycles them with different seeds for the next four chains, and so on. By default, \JAGS\ bases the initial state on the time stamp. This means that, when a model is re-run, it generates an independent set of samples. If you want your model run to be reproducible, you must explicitly set the \texttt{.RNG.seed} for each chain. \subsection{Samplers} A Sampler is an object that acts on a set of parameters and updates them from one iteration to the next. During initialization of the model, samplers are chosen automatically for all parameters. \JAGS\ holds a list of {\em sampler factory} objects, which inspect the graph, recognize sets of parameters that can be updated with specific methods, and generate sampler objects for them. The list of sampler factories is traversed in order, starting with sampling methods that are efficient, but limited to certain specific model structures and ending with the most generic, possibly inefficient, methods. If no suitable sampler can be generated for one of the model parameters, an error message is generated. The user has no direct control over the process of choosing samplers. However, you may indirectly control the process by loading a module that defines a new sampler factory. The module will insert the new sampler sactory at the beginning of the list, where it will be queried before all of the other sampler factories. You can also optionally turn on and off sampler factories. %crossref \section{Adaptation and burn-in} In theory, output from an MCMC sampler converges to the target distribution ({\em i.e.} the posterior distribution of the model parameters) in the limit as the number of iterations tends to infinity. In practice, all MCMC runs are finite. By convention, the MCMC output is divided into two parts: an initial ``burn-in'' period, which is discarded, and the remainder of the run, in which the output is considered to have converged (sufficiently close) to the target distribution. Samples from the second part are used to create approximate summary statistics for the target distribution. By default, \JAGS\ keeps only the current value of each node in the model, unless a monitor has been defined for that node. The burn-in period of a \JAGS\ run is therefore the interval between model initialization and the creation of the first monitor. When a model is initialized, it may be in {\em adaptive mode}, meaning that the Samplers used by the model may modify their behaviour for increased efficiency. Since this adaptation may depend on the entire sample history, the sequence generated by an adapting sampler is no longer a Markov chain, and is not guaranteed to converge to the target distribution. Therefore, adaptive mode must be turned off at some point during burn-in, and a sufficient number of iterations must take place {\em after} the adaptive phase to ensure successful burnin. All samplers have a built in test to determine whether they have converged to their optimal sampling behaviour. If any sampler fails this validation test, a warning will be printed. To ensure optimal sampling behaviour, the model should be run again from scratch using a longer adaptation period. \section{Monitoring} \label{section:monitoring} A {\em monitor} in \JAGS\ is an object that records sampled values. The simplest monitor is a {\em trace monitor}, which stores the sampled value of a node at each iteration. Other types of monitor are available: monitors of type ``mean'' and ``variance'' defined by the base module store the running mean and variance, respectively, of a given node (See section \ref{section:base:monitors}). The dic module defines various monitors based on deviance statistics for model criticism (See chapter~\ref{chapter:dic}). \section{Errors} There are two kinds of errors in \JAGS: runtime errors, which are due to mistakes in the model specification, and logic errors which are internal errors in the JAGS program. Logic errors are generally created in the lower-level parts of the \JAGS\ library, where it is not possible to give an informative error message. The upper layers of the \JAGS\ program are supposed to catch such errors before they occur, and return a useful error message that will help you diagnose the problem. Inevitably, some errors slip through. Hence, if you get a logic error, there is probably an error in your input to \JAGS, although it may not be obvious what it is. Please send a bug report (see ``Getting help'' on page~\pageref{section:help}) whenever you get a logic error. Error messages may also be generated when parsing files (model files, data files, command files). The error messages generated in this case are created automatically by the program \texttt{bison}. They generally take the form ``syntax error, unexpected FOO, expecting BAR'' and are not always abundantly clear, but this is out of my control. \chapter{Running JAGS from R} \label{chapter:R} The native interface from R to \JAGS\ is the \texttt{rjags} package \citep{Plummer2016}. This provides an object-based functional interface to \JAGS, in which most of the steps of running a model are separated into different function calls. Several alternative packages have been developed that offer a unified interface to \JAGS. The main ones are detailed below, but there are many other R packages that interface to \JAGS. See the list of reverse depends, imports, suggests and enhances at \url{https://cran.r-project.org/package=rjags} To illustrate each package, we consider the linear regression model from chapter~\ref{chapter:bugslang} with a trivial data set of 5 observations. The data and initial values for this model are given below and are used by all R interfaces: \begin{verbatim} line_data <- list("x" = c(1, 2, 3, 4, 5), "Y" = c(1, 3, 3, 3, 5), "N"=5) line_inits <- list(list("alpha" = 3, "beta"= 0, "tau" = 1.5), list("alpha" = 0, "beta" = 1, "tau" = 0.375)) \end{verbatim} \section{rjags} \label{section:rjags} To run a model with the \texttt{rjags} package, we first create a model object with the \texttt{jags.model()} function. \begin{verbatim} library(rjags) model <- jags.model("line.bug", data=line_data, inits=line_inits, n.chains=2) \end{verbatim} This compiles and initializes the model, and if necessary runs an adaptive phase for 1000 iterations (see chapter~\ref{chapter:running} for an explanation of these steps). If adaptation is required then a progress bar made of \texttt{'+'} signs will be printed. The object created by \texttt{jags.model} is of class ``jags''. It is an R interface to the virtual graphical model created by \JAGS\ and does not contain any samples. To get samples from the posterior distribution of the parameters, we use the \texttt{coda.samples} function after first using the \texttt{update} function to run the Markov Chain for a burn-in period of 1000 iterations. \begin{verbatim} update(model, n.iter=1000) samples <- coda.samples(model, variable.names=c("alpha", "beta", "sigma"), n.iter=1000) \end{verbatim} The \texttt{samples} object is of class \texttt{mcmc.list} defined by the \texttt{coda} package \citep{PlummerEtal2005}. It contains monitored samples of the variables \texttt{alpha}, \texttt{beta}, and \texttt{sigma} for the two parallel chains. To get an informative summary of the samples, we use the \texttt{summary} function: \begin{verbatim} > summary(samples) Iterations = 1001:2000 Thinning interval = 1 Number of chains = 2 Sample size per chain = 1000 1. Empirical mean and standard deviation for each variable, plus standard error of the mean: Mean SD Naive SE Time-series SE alpha 3.0001 0.5344 0.011949 0.012392 beta 0.7997 0.3921 0.008769 0.009133 sigma 1.0326 0.7120 0.015920 0.030337 2. Quantiles for each variable: 2.5% 25% 50% 75% 97.5% alpha 1.95654 2.7452 2.9916 3.2488 4.158 beta 0.01763 0.6178 0.8037 0.9877 1.559 sigma 0.41828 0.6376 0.8276 1.1838 2.804 \end{verbatim} The \texttt{mcmc.list} class also has a plot method. Hence \begin{verbatim} plot(samples) \end{verbatim} will produce trace plots and density plots for the sampled values. \section{runjags} The \texttt{runjags} package \citep{Denwood2016} includes many enhancements to \JAGS, including a custom \JAGS\ module that contains some additional distributions in the Pareto family. The basic function for running a model with the \texttt{runjags} package is \texttt{run.jags()}, which can be used as follows: \begin{verbatim} library(runjags) out <- run.jags(model="line.bug", monitor=c("alpha","beta","sigma","dic"), data=line_data, n.chains=2, inits=line_inits) \end{verbatim} The optional \texttt{method} argument to \texttt{run.jags} allows the user to choose whether the model is run through the \texttt{rjags} interface (section~\ref{section:rjags}) or through the command line interface of \JAGS\ (chapter~\ref{chapter:cmdline}). In addition, the \texttt{method} argument controls how parallel chains are run. Running parallel chains in different processes can offer considerable speed improvements on a multi-processor computer. The output of the \texttt{run.jags()} function is an object of class ``runjags''. The print method for ``runjags'' objects prints a summary of the posterior distribution of the parameters. \begin{verbatim} > print(out) JAGS model summary statistics from 20000 samples (chains = 2; adapt+burnin = 5000): Lower95 Median Upper95 Mean SD Mode MCerr MC%ofSD SSeff alpha 1.9171 3.0004 4.0096 2.9971 0.54331 2.9936 0.0037325 0.7 21189 beta 0.046318 0.79919 1.5288 0.79989 0.39328 0.79952 0.0028322 0.7 19283 sigma 0.31105 0.82308 2.155 1.0107 0.73651 0.68375 0.0094755 1.3 6042 AC.10 psrf alpha -0.0029037 1 beta -0.0044582 1.0004 sigma -0.00090713 1 Model fit assessment: DIC = 21.16815 [PED not available from the stored object] Estimated effective number of parameters: pD = 8.24059 Total time taken: 0.9 seconds \end{verbatim} The print method also shows some convergence diagnostics for each parameter: \texttt{SSeff} is the effective sample size, controlling for autocorrelation of the Markov chain; \texttt{AC.10} is the autocorrelation at lag 10; and \texttt{psrf} is the Gelman-Rubin convergence diagnostic \citep{GelmanRubin1992}, or the {\em potential scale reduction factor}. If the chain is showing signs of poor mixing then the \texttt{extend.jags} function can be used to continue running the model. The \texttt{autorun.jags} is an alternative to \texttt{run.jags} that takes control of the run-length of the MCMC process and runs the chain until convergence. The default plot method for ``runjags'' objects shows a traceplot, the cumulative distribution function, the density function and the autocorrelation function for each variable. A cross-correlation plot for all variables is also generated. There are a number of other methods available for ``runjags'' objects, including \texttt{as.mcmc.list} for extraction of the MCMC objects, and \texttt{as.jags} for conversion to an object that can be used with the rjags package. The reverse operation is also possible by using \texttt{as.runjags} on an rjags model. One of the motivations for the runjags package is to allow comments embedded directly within the the \JAGS\ model code to specify variables to be monitored, and to indicate any variables for which data or initial values should be extracted automatically from the \R\ session. The \texttt{template.jags} function uses these features to create complete model, data and initial value definitions based on a data frame and formula-based representation of a generalised linear mixed model as provided by the user. \section{R2jags} The R2jags package \citep{SuYajima2015} was modelled on the pre-existing R2WinBUGS package \citep{SturtzEtal2005} which provided the first interface from WinBUGS to R. With R2jags and R2WinBUGS the user may switch between the two BUGS engines while keeping a consistent R interface. The R2OpenBUGS package is an updated version of R2WinBUGS that works with OpenBUGS. Like the \texttt{runjags} package, the \texttt{R2jags} package offers a single interface to \JAGS\ that carries out all the steps of running the model, with reasonable default values. The interface function is \texttt{jags()}. \begin{verbatim} library(R2jags) out <- jags(data=line_data, inits=line_inits, parameters.to.save=c("alpha","beta","sigma"), model.file="line.bug", n.chains=2) \end{verbatim} The output from the \texttt{jags} function is an object of class ``rjags''. The print method for ``rjags'' objects summarizes the output (There is also a \texttt{plot} method). \begin{verbatim} > out Inference for Bugs model at "line.bug", fit using jags, 2 chains, each with 2000 iterations (first 1000 discarded) n.sims = 2000 iterations saved mu.vect sd.vect 2.5% 25% 50% 75% 97.5% Rhat n.eff alpha 2.992 0.552 1.888 2.757 3.002 3.258 4.037 1.001 2000 beta 0.797 0.381 0.041 0.618 0.795 0.988 1.549 1.005 1000 sigma 1.014 0.664 0.417 0.636 0.840 1.165 2.581 1.002 2000 deviance 12.981 3.595 8.832 10.358 12.104 14.660 22.215 1.002 1100 For each parameter, n.eff is a crude measure of effective sample size, and Rhat is the potential scale reduction factor (at convergence, Rhat=1). DIC info (using the rule, pD = var(deviance)/2) pD = 6.5 and DIC = 19.4 DIC is an estimate of expected predictive error (lower deviance is better). \end{verbatim} In addition to summaries of the posterior distribution, the print method for ``rjags'' objects includes \texttt{Rhat}, the Gelman-Rubin convergence diagnostic \citep{GelmanRubin1992} and \texttt{n.eff} the effective sample size. If an ``rjags'' object shows signs of lack of convergence, then it can be passed to the \texttt{autojags} function which will update it until convergence. \section{jagsUI} The \texttt{jagsUI} package offers similar facilities to the \texttt{runjags} and \texttt{R2jags} package. In fact \texttt{jagsUI} offers two interface functions -- \texttt{jags()} and \texttt{autojags()} -- with the same names as the ones in the \texttt{R2jags} package. It is therefore not a good idea to load both packages in the same \R\ session. Compared with the other packages, the output from \texttt{jagsUI} tends to be more verbose and didactic. It may therefore be suitable for users who are not familiar with MCMC. The \texttt{jags} function is illustrated below. \begin{verbatim} library(jagsUI) out <- jags(data=line_data, inits=line_inits, parameters.to.save=c("alpha","beta","sigma"), model.file="line.bug", n.chains=2, n.iter=2000, n.burnin=1000) \end{verbatim} Note that you must supply arguments \texttt{n.iter} and \texttt{n.burnin}. However, noted above, there is also an \texttt{autojags()} function that controls the run length for you. The output of the \texttt{jags} function is an object of class ``jagsUI''. The print method for ``jagsUI'' objects gives summary statistics and diagnostics similar to the \texttt{R2jags} package, but with more explanation. \begin{verbatim} JAGS output for model 'line.bug', generated by jagsUI. Estimates based on 2 chains of 1000 iterations, burn-in = 0 iterations and thin rate = 1, yielding 2000 total samples from the joint posterior. MCMC ran for 0.001 minutes at time 2017-06-27 17:57:07. mean sd 2.5% 50% 97.5% overlap0 f Rhat n.eff alpha 2.995 0.615 1.883 2.984 4.053 FALSE 0.997 1.002 2000 beta 0.798 0.402 0.062 0.813 1.486 FALSE 0.977 1.011 332 sigma 1.041 0.768 0.420 0.828 3.218 FALSE 1.000 1.023 2000 deviance 12.984 3.880 8.849 11.921 23.821 FALSE 1.000 1.002 2000 Successful convergence based on Rhat values (all < 1.1). Rhat is the potential scale reduction factor (at convergence, Rhat=1). For each parameter, n.eff is a crude measure of effective sample size. overlap0 checks if 0 falls in the parameter's 95% credible interval. f is the proportion of the posterior with the same sign as the mean; i.e., our confidence that the parameter is positive or negative. DIC info: (pD = var(deviance)/2) pD = 7.5 and DIC = 20.51 DIC is an estimate of expected predictive error (lower is better). \end{verbatim} \chapter{Running \JAGS\ on the command line} \label{chapter:cmdline} \JAGS\ has a command line interface. To invoke jags interactively, simply type \texttt{jags} at the shell prompt on Unix, a Terminal window on MacOS, or the Windows command prompt on Windows. To invoke JAGS with a script file, type \begin{verbatim} jags