\input texinfo @c -*-texinfo-*-
@comment %**start of header (This is for running Texinfo on a region.)
@setfilename mcsimdoc
@settitle MCSim User' Manual
@setchapternewpage odd
@comment %**end of header (This is for running Texinfo on a region.)


@comment  the following is just for the texinfo file
@ifinfo
This file documents the MCSim simulation program, version 4.1.

Copyright @copyright{} 1997 Frederic Bois.  All rights reserved.

Permission is granted to make and distribute verbatim copies of
this manual provided the copyright notice and this permission notice
preserved on all copies.
     
@ignore
Permission is granted to process this file through TeX and print the
results, provided the printed document carries a copying permission
notice identical to this one except for the removal of this paragraph
(this paragraph not being relevant to the printed manual).
     
@end ignore
Permission is granted to copy and distribute modified versions of this
manual under the conditions for verbatim copying, provided that the
entire resulting derived work is distributed under the terms of a
permission notice identical to this one.
     
Permission is granted to copy and distribute translations of this
manual into another language, under the above conditions for modified
versions, except that this permission notice may be stated in a
translation approved by the author.
     
contact
     Frederic Bois or Don Maszle
     BEHS, School of Public Health
     University of California at Berkeley
     Berkeley, CA 94720

     fbois@@diana.lbl.gov

@end ifinfo
     

@comment  the following is just for the printed version
@titlepage
@sp 10
@center @titlefont{MCSim: A Monte Carlo Simulation Program}
@sp 2
@center User's Manual - version 4.1
@sp 2
@center Frederic Y. Bois - Don R. Maszle
     
@comment  The following two commands start the copyright page.
@page
@vskip 0pt plus 1filll
Copyright @copyright{} 1997 Frederic Bois.  All rights reserved.
     
Permission is granted to make and distribute verbatim copies of
this manual provided the copyright notice and this permission notice
preserved on all copies.
     
@ignore
Permission is granted to process this file through TeX and print the
results, provided the printed document carries a copying permission
notice identical to this one except for the removal of this paragraph
(this paragraph not being relevant to the printed manual).
     
@end ignore
Permission is granted to copy and distribute modified versions of this
manual under the conditions for verbatim copying, provided that the
entire resulting derived work is distributed under the terms of a
permission notice identical to this one.
     
Permission is granted to copy and distribute translations of this
manual into another language, under the above conditions for modified
versions, except that this permission notice may be stated in a
translation approved by the author.
     
contact
     Frederic Bois / Don Maszle
     BEHS, School of Public Health
     University of California at Berkeley
     Berkeley, CA 94720

     fbois@@diana.lbl.gov

@end titlepage
     
     

@comment ********* NODE *********
@node Top, Software License, (Dir), (Dir)
@comment  node-name,  next,  previous,  up


MCSim is a general purpose modeling and simulation program which also
performs standard or Markov chain Monte Carlo simulations. It allows you
to specify a set of linear or nonlinear equations (eventually
differential), and solve them using parameter values you choose or
parameter values sampled from specified statistical distributions.
Simulation outputs can be compared to experimental data for parameter
estimation.


@menu
* Software License::           MCSim is under GNU General Public License
* Overview::
* Installation::               details for Unix and Macintosh platforms
* Working Through an Example:: highly recommended!
* Defining Models::            syntax of model definition files
* Specifying Simulations::     syntax of simulation specification files
* Bibliographic References::

Appendices
* Using make:: in case 'man make' gets you lost
* Examples::   examples of models and input files

Index Table
* Concept Index::
@end menu



@comment ********* NODE *********
@node Software License, Overview, Top, Top
@comment  node-name,  next,  previous,  up
@chapter Software License
@cindex Software license
@cindex license


GNU GENERAL PUBLIC LICENSE

Version 2, June 1991

Copyright @copyright{} 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.


@section 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.


@section 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:

@bullet{} a) You must cause the modified files to carry prominent
notices stating that you changed the files and the date of any
change.@refill

@bullet{} 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.@refill

@bullet{} 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.)@refill

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:

@bullet{} 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,@refill

@bullet{} 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,@refill

@bullet{} 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.)@refill

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



@comment ********* NODE *********
@node Overview, Installation, Software License, Top
@comment  node-name,  next,  previous,  up
@chapter Overview
@cindex Overview


MCSim consists of two pieces, a model generator and a simulation engine.
The model generator, mod, was created to facilitate the model
maintenance and simulation definition, while keeping execution time
fast. Other programs have been created to the same end, the Matlab
family of graphical interactive programs being some of the more general
and easy to use. Still, many available tools are not optimal for
performing time and computer intensive Monte Carlo analyses. MCSim was
created specifically to this end: to perform Monte Carlo analyses in a
highly optimized, and easy to maintain environment.


@section General procedure

Model building and simulation proceeds in four stages:

@enumerate
@item
You create with any text editor a model description file. The reference
section on mod, later in this manual gives you the syntax to use
(@pxref{Defining Models}). This syntax allows you to describe the
model variables, parameters, equations, inputs and outputs in a C-like
fashion without having you to actually know how to write a C
program.@refill

@item
You instruct the model generator, mod, to preprocess your model
description file. Mod creates a C file, called "model.c".@refill

@item
You compile and link the newly created "model.c" file together
with the other C program files. MCSim C code is standard, so you should
be able to compile it with any standard C compiler, for example GNU gcc.
After compiling and linking, an executable simulation program "mcsim" is
created, specific of the particular model you have designed. These
preprocessing and compilation steps may seem clumsy but they produce the
most efficient code for your particular machine.@refill

@item
You design any number of simulation specification files and run them
with the "mcsim" program. The simulation specification files describe
the kind of simulation to run (simple simulations, Monte Carlo etc.),
various settings for the integration algorithm if needed, and a
description of one or several experimental conditions or observations to
simulate (@pxref{Specifying Simulations}). The simulation output is
written to standard ASCII files.@refill

@end enumerate

Little or no knowledge of computer programming is required, unless you
want to tailor the program to special needs, beyond what is described in
this manual (in which case you should contact us).


@section Types of simulations

Four types of simulations are available:

@itemize @bullet
@item
@cindex DefaultSim
A DefaultSim simulation will simply solve (eventually integrate) the
equations you specified, using the default parameter values and possible
overridings imposed in the simulation specification file.
User-requested outputs are sent to an output file (@pxref{SimType()
specification}).@refill

@item
@cindex Monte Carlo
A MonteCarlo simulation will perform repeated (stochastic)
simulations across a randomly sampled region of the model parameter
space (@pxref{MonteCarlo() specification}).@refill

@item
@cindex MCMC simulations
@cindex Markov-chain Monte Carlo simulations
A MCMC simulation performs a series of simulations along a Markov chain
in the model parameter space (@pxref{MCMC() specification}). These are
Monte Carlo simulations in which the choice of a new parameter value is
influenced by the current value. They can be used to obtain the Bayesian
posterior distribution of the model parameters, given their prior
distributions (that you specify) and data for which the likelihood
function can be computed. The program handles hierarchical (random
effect) statistical models, such as population pharmacokinetic
models (@pxref{Specifying a statistical model}).@refill

@item
@cindex SetPoints simulations
A SetPoints simulation integrates the model under the experimental
conditions for a series of specified parameter sets, listed in a
separate ASCII file (@pxref{SetPoints() specification}). You can create
these parameter sets yourself or use the output of a previous MonteCarlo
or MCMC simulation.@refill
@end itemize


@section Major changes introduced with this version
@cindex Major changes in versions 4.2


@itemize @bullet
@item
@cindex Spikes()
@cindex Input function Spikes()
A new input function, "Spikes()" is available. It simulates
instantaneous inputs (@pxref{Input functions}).@refill

@item
@cindex Distributions
@cindex Inverse-gamma distribution
@cindex Piecewise distribution
@cindex Normal_v distribution
@cindex TruncNormal_v distribution
@cindex LogNormal_v distribution
@cindex TruncLogNormal_v distribution
Six new distributions: "InvGamma" (inverse-gamma), "Piecewise",
"Normal_v", "TruncNormal_v", "LogNormal_v", and "TruncLogNormal_v" are
available for Monte Carlo simulations (@pxref{Distrib()
specification}).@refill

@item
In Monte Carlo simulations, shape parameters of Distrib() statements can
now reference other sampled parameters (@pxref{MonteCarlo()
specification}).@refill

@item
@cindex printPredFlag option
A "printPredFlag" option, in the "MCMC()" specification, allows
the printing of times, data and predictions for easy checking of the
model fit (@pxref{MCMC() specification}).@refill

@comment @item
@comment @cindex Optimdesign() specification
@comment The "OptimDesign()" specification allows you to optimize the
@comment design of experiments.
@end itemize



@comment ********* NODE *********
@node Installation, Working Through an Example, Overview, Top
@comment  node-name,  next,  previous,  up
@chapter Installation
@cindex Installation

@section System requirements

On a Unix system you will need an ANSI C compiler, and we recommend
having the make utility too. For Macintosh you will need version 8.0 (or
higher) of SymantecÕs Think C compiler and a Power PC compiler if you
want to take advantage of the Power PC processor.

@section Distribution

MCSim is distributed in a variety of formats for various platforms and
is available on Internet at ftp://rfs63.berkeley.edu/pub/mcsim and at
http://rfs63.berkeley.edu/users/fbois/.

@section Machine-Specific Installation

To install on a given machine, copy or download the distributed archive
file to your machine and follow the specific instructions given with the
"Installation.txt" file in the ftp source directory.



@comment ********* NODE *********
@node Working Through an Example, Defining Models, Installation, Top
@comment  node-name,  next,  previous,  up
@chapter Working Through an Example
@cindex Working Through an Example

Pharmacokinetics models describe the transport and transformation of
chemical compounds inn the body. These models often include nonlinear
first-order differential equations. The following example is taken from
our own work on the kinetics of tetrachloroethylene (a solvent) in the
human body (Bois et al., 1996; Bois et al., 1990) (@pxref{Bibliographic
References}).  Go to the sim "sim" directory (under Unix) or to the
"Development" folder (on a Macintosh).  Open the file "perc.model" with
any text editor (e.g. emacs or vi under Unix). This file is distributed
as an example of a model definition file (@pxref{perc.model}). You can
use it as a template for your own model, but you should leave it
unchanged for now. Notice that it defines:@refill

@itemize @bullet
@item
state variables for the model (for which differentials are
defined), for example:@refill

@example
States = @{Q_fat,        # Quantity of PERC in the fat
          Q_wp,         #   ...   in the well-perfused compartment
          Q_pp,         #   ...   in the poorly-perfused compartment
          Q_liv,        #   ...   in the liver
          Q_exh,        #   ...   exhaled
          Qmet@}         # Quantity of metabolite formed
@end example

@item
output variables (obtainable at any time as analytical functions
of the states, inputs and parameters), for example:@refill

@example
Outputs = @{C_liv,           # mg/l in the liver
           C_alv,           # ... in the alveolar air
           C_exh,           # ... in the exhaled air
           C_ven,           # ... in the venous blood
           Pct_metabolized, # % of the dose metabolized
           C_exh_ug@}        # ug/l in the exhaled air
@end example

@item
input variables (independent of the others variables, but
eventually varying with time), for example:@refill

@example
Inputs = @{C_inh@} # Concentration inhaled
@end example

@item
model parameters (independent of time), such as: 

@example
LeanBodyWt = 55; # lean body weight
@end example

@item
system's dynamics (differential equations defining the behavior
of the model),@refill

@item
parameters' scaling (the parameters used in the equations can be
made functions of other parameters: for example volumes can be computed
from masses and densities),@refill

@item
equations to compute the above defined output variables.

@end itemize

This model definition file as a simple syntax, easy to master. It needs
to be turned into a C program file before compilation and linking to the
other routines (integration, file management etc.). You will use mod for
that. First, quit the editor and return to the operating system.

To start mod just type "mod" under Unix, or double click the "Mod" icon
on your Macintosh. Mod prompts you for the name of your model definition
file. Type "perc.model": after a second, with no error messages if the
model definition is syntactically correct, Mod announces that the
"model.c" file has been generated. On a Macintosh you need to hit the
return key to exit Mod.

The next step is to compile and link together the various C files that
will constitute the simulation program for your particular model. Note
that each time you want to change an equation in your model you will
have to change the model definition file and repeat the step above.
However, changing just parameter values or state initial values does not
require recompilation since it can be done through simulation
specification files.

@itemize @bullet
@item
Under Unix, the simplest is to use the make utility. Just type "make"
and compilation will be done automatically (@pxref{Using make}). An
executable "mcsim" is created. You can rename it to better describe the
fact that it is model specific: name it "mcsim_perc" for example.@refill

@item
On a Macintosh the best is to use the Think C project provided.
You should first use the command "make" to compile the modified
"model.c" file. Then create an application (you should give it a name
specific to the model you are developing, e.g. "MCSim Perc"). Refer to
your Think C manual for details on how to use the Think C environment.
Your executable MCSim Perc program is now ready to perform simulations.
Several simulation specification files are provided with the package, as
examples (they are in the "sim" directory under Unix and in the
"Samples" folder on the Macintosh).@refill

@end itemize

To start your MCSim just type "mcsim_perc" (if you gave it that name)
under Unix, or double click the "MCSim Perc" Ð or whatever name you
specified Ð icon on your Macintosh. After an introductory banner
(telling which model the program is based upon), you are prompted for an
input file name: type "perc.lsodes.in" (@pxref{perc.lsodes.in} to see
this file now). The program then prompts you for the output file name:
type "perc.lsodes.out". After a few seconds or less (depending on your
machine) the program announces that it is finished and that the output
file is "perc.lsodes.out" (on a Macintosh you should hit the return key
to exit the program completely). You can open the output file with any
text editor or word processor, you can edit it for input in graphic
programs etc.@refill

Try the other sample simulation definition files and observe the output
you obtain. You can then start programming you own models and
simulation. The next sections of this manual reference the syntax for
model definition and simulation specifications.



@comment ********* NODE *********
@node Defining Models, Specifying Simulations, Working Through an Example, Top
@comment  node-name,  next,  previous,  up
@chapter Defining Models
@cindex Defining models
@cindex Model definition files
@cindex Models


@cindex Examples
Three examples of model simulation files: "linear.model", "1cpt.model"
and "perc.model" are included with the program files and appears in
Appendix of this manual (@pxref{Examples}).@refill


@menu
* Using mod::           how to process a model definition file
* Syntax of mod files:: how to write a model definition file
@end menu



@comment ********* NODE *********
@node Using mod, Syntax of mod files, , Defining Models
@comment  node-name,  next,  previous,  up
@section Using Mod to process model description files
@cindex mod usage

The mod program is a stand-alone facility. It takes a model description
file in the "user-friendly" format described below and creates a C
language file "model.c" which you will compile and link to
the simulation program. Mod allows the user to define equations for the
model, assign default values to parameters or default initial values to
model variables, and define scaling functions for both the input
parameters and the outputs variables. Mod lets the user create and
modify models without having to maintain C code.

In Unix the command line syntax for the mod program is:

@example
mod [input-file [output-file]]
@end example

where the brackets indicate that the input and output filenames are
optional. If the input filename is not specified, the program will
prompt for both. If only the input filename is specified, the output is
written by default to the file "model.c". Unless you feel like doing
some makefile programming, we recommend using this default since the
makefile for Sim assume the C language model file to have this name.

On the Macintosh you double-click the "Mod" icon and enter the name of
the model definition file at the prompt (on the Macintosh names can
include space characters).



@comment ********* NODE *********
@node Syntax of mod files, , Using mod, Defining Models
@comment  node-name,  next,  previous,  up
@section Syntax of the model description file
@cindex mod syntax
@cindex Syntax for mod


The model description file is a text (ASCII) file that consists of
several sections, including global declarations, dynamics specifications
(derivative calculation), model scaling, and output scaling:

@example
# Model description file (this is a comment)
<Global parameter specifications>

Dynamics @{
  <Equations for calculating the dynamics, or state derivatives>
@}

Scale @{
  <Equations for scaling model parameters>
@}

CalcOutputs @{
  <Equations for scaling the outputs>
@}
@end example

where Dynamics, Scale and CalcOutputs are keywords and, if used, must
appear as shown followed by the curly braces which delimit the section.
At least one of the sections Dynamics or CalcOutputs should be defined.
Dynamics is to be used if the model includes differential equations.


@menu
* General syntax::
* Global parameter declarations::
* Special functions::
* Input functions::
* Dynamics specifications::
* Parameter scaling::
* Output calculations::
* Comments on style::
@end menu



@comment ********* NODE *********
@node General syntax, Global parameter declarations, , Syntax of mod files
@comment  node-name,  next,  previous,  up
@subsection General syntax


The general syntax of the file is as follows:

@itemize @bullet
@item
@cindex Comments
@cindex '#' sign
Comments begin with a pound sign ('#') and continue to the end of the
line.@refill

@item
@cindex Blank lines
Blank lines are allowed and ignored.@refill

@item
@cindex ';' sign
@cindex semi-colon
All commands can span several lines and are terminated by a semi-colon
(';'). There should be no blank space before the semi-colon.@refill

@item
@cindex Assignment
Variable assignments have the following syntax:

@example
var-name '=' constant-value -or-expression ';'
@end example

where var-name is any valid C identifier, starting with a letter or '_'
and followed by any number of alpha-numeric characters or underscores,
up to a maximum of 80. Variable names are case sensitive. Note that the
name "IFN", in capital letters, is reserved by the program and should
not be used as parameter or variable name. The equal sign is needed. The
expression can be a valid C mathematical expression including already
defined variables and ANSI C mathematical functions. Additional
functions, called special functions, can be used, which take variable
names, constant values or expressions as parameters. Special functions
are detailed below (@pxref{Special functions}). Finally, there should be
no space before the terminating semi-colon.@refill

Colon conditional assignment can also be used. Syntax:
@cindex Colon conditional assignment
@cindex Conditional assignment

@example
var-name '=' (condition ? value-if-true : value-if-false);

For example:

Adj_Parm = (Input > 0.0 ? Parm * Adjust : Parm);
@end example

In this example, a parameter changes value if Input is positive. The
colon statement codifies this. If Input is greater than 0, the parameter
will be adjusted to reflect the dependency. Otherwise Adj_Parm takes on
the nominal parameter value. Adj_Parm can now be used in all future
calculations to represent the correct value, whether it has actually
been adjusted or not. The comparison operators allowed are the equality
operator "==", and non-equality operators "!=", "<", ">", "<>", "<=" and
">=".@refill
@cindex Comparison operators
@end itemize



@comment ********* NODE *********
@node Global parameter declarations, Special functions, General syntax, Syntax of mod files
@comment  node-name,  next,  previous,  up
@subsection Global parameter declarations
@cindex Parameter declaration

Commands not specified within the delimiting braces of another section
are considered to be global declarations. All the model parameters you
want to be able to change during simulations should be declared global.
Parameters must be given nominal values, following the assignment rules
given above. For example:

@example
BodyWt = 0.38; # (kg) Weight of the rat
@end example

In the global section you also declare the states, inputs, and outputs
variables, before they are given values. There should be at least one
state or output variable in your model.

@itemize @bullet
@item
@cindex State variables
States are variables for which a first-order differential equations is
defined (higher orders or partial differential equations are not
allowed).@refill

@item
@cindex Input variables
Inputs are variables independent of the others variables, but eventually
varying with time (for example an exposure concentration to a
chemical).@refill

@item
@cindex Output variables
Outputs are dependent model variables (obtainable at any time as
analytical functions of the states, inputs or parameters) that do not
have dynamics.@refill
@end itemize

The format for declaring each of these variables is the same, and
consists of the keyword States, Inputs or Outputs followed by a list of
the variable names enclosed in curly braces as shown here:

@example
States =   @{Qb_fat,  # Benzene in the fat
            Qb_bm,   # ...     in the bone marrow
            Qb_liv@}; # ...     in the liver and others

Inputs =   @{Q_gav,   # Gavage dose
            C_inh@};  # Inhalation concentration

Outputs =  @{Cb_exp,  # Concentration in expired air
            Cb_ven@}; # ...           in venous blood
@end example

After being defined, states, inputs and outputs can then be given
initial values (constants or expressions). Note that inputs can also be
assigned input functions, described below. Some examples of
initialization are shown here:

@example
Qb_fat = 0.1; # Initial value for Qb_fat

# Gavage input model with a periodic exponential input function
Q_gav = PerExp(1, 60, 0, 1); # Magnitude of 1.0,
                             # period of 60 time units,
                             # T0 in period is 0,
                             # Rate constant is 1.0
@end example

If a global state, input, or output variable is not given an initial
value, it will default to zero. Initial values are reset to their
specified value by the simulation program at the start of each
simulation of an Experiment (@pxref{Experiment definition}).@refill

All parameters and variables are computed in double precision
floating-point numbers. Note that the order of global declarations
matters within the global section itself (i.e. parameters and variables
should be defined and initialized before being used in assignments of
others), but not with respect to other blocks. A parameter defined at
the end of the description file can be used in the dynamics section
which may appear at the beginning of the file. Still, such an inverse
order should be avoided. For this reason, the format above, where global
declarations come first, is strongly suggested to avoid confusing
results. Note again that the name "IFN", in capital letters, is reserved
by the program and should not be used as parameter or variable name.
Finally, if a parameter is defined several times, only the first
definition is taken into account.



@comment ********* NODE *********
@node Special functions, Input functions, Global parameter declarations, Syntax of mod files
@comment  node-name,  next,  previous,  up
@subsection Special functions
@cindex Special functions
@cindex Functions, special


The following special functions are available to the user for assignment
of parameters and variables in the model definition file:

@itemize @bullet
@item
@cindex CDFNormal() function
@cindex Function, CDFNormal()
@cindex Normal cumulative density function
@cindex Cumulative density function, Normal
CDFNormal(x): the normal cumulative density function;

@item
@cindex erfc() function
@cindex Error function
@cindex Function, erfc()
erfc(x): the error function;

@item
@cindex lnDFNormal() function
@cindex Function, lnDFNormal()
@cindex Normal density function
@cindex Density function, Normal
lnDFNormal(x, mean, sd): the natural logarithm of the normal density
function;@refill

@item
@cindex lnGamma() function
@cindex Function, lnGamma()
@cindex Gamma function
lnGamma(x): the natural logarithm of the gamma function;

@item
@cindex UniformRandom() function
@cindex Function, UniformRandom()
@cindex Random number, uniform
UniformRandom(min, max): returns a uniformly distributed random
variable, sampled between min and max. The algorithm used is that of
Park and Miller (Barry, 1996; Park and Miller, 1988; Vattulainen et al.,
1994) (@pxref{Bibliographic References}). A default random generator
seed (314159265.3589793) is used;@refill

@item
@cindex NormalRandom() function
@cindex Function, NormalRandom()
@cindex Random number, normal
NormalRandom(mean, sd): returns a normally distributed random variable.
The default random generator seed is used.@refill
@end itemize



@comment ********* NODE *********
@node Input functions, Dynamics specifications, Special functions, Syntax of mod files
@comment  node-name,  next,  previous,  up
@subsection Input functions
@cindex Input functions
@cindex Functions, input


They constitute a special kind of assignment, valid only for input
variables. Inputs can be initialized as a constant or expression, or
assigned one of the following input functions:

@itemize @bullet
@item
@cindex PerDose() function
@cindex Function, PerDose()
PerDose() specifies a periodic input of constant magnitude. The input
begins at initial-time in the period and lasts for exposure-time time
units. Syntax:@refill

@example
PerDose(dose-magnitude, period, initial-time, exposure-time);
@end example

@item
@cindex PerExp() function
@cindex Function, PerExp()
PerExp() specifies a periodic exponential input. At time initial-time
the input rises instantaneously to exp-magnitude and begins to decay
exponentially with the constant decay-constant. The input is turned off
once the magnitude reaches a negligible percentage of its original
value. Syntax:@refill

@example
PerExp(exp-magnitude, period, initial-time, decay-constant);
@end example

@item
@cindex NDoses() function
@cindex Function, NDoses
NDoses() specifies a number of stepwise inputs of variable magnitude and
their starting times. The first argument, n, is the number of input
steps and start times. Each of the lists are comma separated. The
duration of input step is computed automatically by difference between
the specified times. Currently this function can only be used in the
simulation description file, and not in the model description file
(which simply implies that you cannot use it as a default).
Syntax:@refill

@example
NDoses(n, list-of-input-magnitudes, list-of-initial-times);
@end example

@item
@cindex Spikes() function
@cindex Function, Spikes()
Spikes() specifies a number of instantaneous inputs of variable
magnitude and their exact times of occurence. The first argument, n, is
the number of inputs and input times. Each of the lists are comma
separated. Currently this function can only be used in the simulation
description file, and not in the model description file (which simply
implies that you cannot use it as a default). Syntax:@refill

@example
Spikes(n, list-of-input-magnitudes, list-of-times);
@end example
@end itemize


The arguments of input functions can either be constants or variable
references. As an example, if GavMag and RateConst are defined model
parameters, then the input variable Q_gav can be defined as:

@example
Q_gav = PerExp(GavMag, 60, 0, RateConst);
@end example

In this way the parameters of the input function can, for example, be
assigned statistical distributions in Monte Carlo simulations
(@pxref{Distrib() specification}).@refill

Variable dependencies are resolved before the simulation is started. For
each of the periodic functions, a single exposure beginning at time
initial-time can be specified by giving an effectively infinite period,
e.g. 1e10. The first period starts at the initial time of the
simulation. Magnitudes change exactly at the initial times given.

Input functions can be combined to give a lot of flexibility (e.g. an
input can be sum of some others). Separate inputs can be declared in the
global section of the model definition file and combined in the Dynamics
and CalcOutputs sections. The only limitation is that for each input
function used, a separate input must be defined in the model, even
though this function may not be a real element of the model.



@comment ********* NODE *********
@node Dynamics specifications, Parameter scaling, Input functions, Syntax of mod files
@comment  node-name,  next,  previous,  up
@subsection Dynamics specifications
@cindex Dynamics specifications


The dynamics specification section begins with the keyword Dynamics and
is enclosed in curly braces. The equations given in this section will be
called by the integrator at each integration step.

Additional variables to those declared in the global section may be used
for any calculations within the section. They will be declared as local
temporary variables. (Note, for example, the use of Cout_fat and Cout_wp
in the "perc.model" sample file). Local variables are not accessible
from the simulation program, or from other sections of the model
definition file, so don't try to output them.

Each state variable declared in the global section must have one
corresponding state equation in the dynamics section. If a state
equation is missing, mod issues an error message such as:

@example
Error: State variable 'Q_foo' has no dynamics.
@end example

If one or more dynamics equations are missing, no program file will be
created. Most error messages are self-explanatory. Where appropriate,
they also show a line number in the input file where the error occurred.

@cindex dt() operator
@cindex Derivative specification
The derivative of a state variable is defined using the dt() operator,
as shown here:

@example
dt(state-variable) '=' constant-or-expression ';'
@end example

'Expression' is any valid C expression, including standard math library
calls and the special functions mentioned above. Note, however, that no
syntactic check is performed on the library function calls. Their
correctness is your responsibility.

The dt() operator can also be used in the right-hand side of equations
in the dynamics section to refer to the value of the derivative at the
that point in the calculations. For example:

@example
dt(Qm_in) = Qmetabolized - dt(Qm_out);
@end example

@cindex Integration variable
The integration variable (time usually) can be accessed if referred to
as t, as in:

@example
dt(Qm_in) = Qmetabolized - t;
@end example

@bullet{} Input variables and model parameters can indeed be used, but
cannot be assigned values in the dynamics section. Assignments to inputs
or parameters in this section causes an error message like the following
to be issued:

@example
Error: line 48: 'YourParm' used in invalid context.
Parameters cannot be defined in Dynamics@{@} section.
@end example



@comment ********* NODE *********
@node Parameter scaling, Output calculations, Dynamics specifications, Syntax of mod files
@comment  node-name,  next,  previous,  up
@subsection Parameter scaling
@cindex Scale, scaling specification
@cindex Parameter scaling


The parameter scaling section begins with the keyword Scale and is
enclosed in curly braces. The equations given in this section will
define a function that will be called by the simulation program at the
beginning of each simulation of an Experiment (@pxref{Experiment
definition}).@refill

@bullet{} All model variables, and parameters, can be changed in this section.
Modifications to state variables affect initial values only. Modifying
an input is not allowed and state variables can only appear at the left
hand side of equations.@refill

The dt() operator cannot be used in this section (@pxref{Dynamics
specifications}).@refill



@comment ********* NODE *********
@node Output calculations, Comments on style, Parameter scaling, Syntax of mod files
@comment  node-name,  next,  previous,  up
@subsection Output calculations
@cindex CalcOutputs, output specification
@cindex Output specification


The output calculation section begins with the keyword CalcOutputs and
is enclosed in curly braces. The equations given in this section will be
called by the simulation program before saving outputs. In this way, the
output scaling is done efficiently, only with values that are to be
saved, and not at each integration step.

@bullet{} Only variables that have been declared with the keyword
Outputs can be changed in this section.@refill

Assignments to other types of variables cause an error message like the
following to be issued:

@example
Error: line 56: 'Qb_fat' used in invalid context.
Only outputs can be defined in CalcOutputs@{@} section.
@end example

Any reference to an input will use the last calculated (current) value
of the input. The dt() operator can appear in the right hand side of
equations, and it refers to values of the derivative as calculated at
the last time step (@pxref{Dynamics specifications}). Like in the
Dynamics section, the integration variable (time usually) can be
accessed if referred to as t, as in:@refill

@example
Qx_out = DQx * t;
@end example



@comment ********* NODE *********
@node Comments on style, , Output calculations, Syntax of mod files
@comment  node-name,  next,  previous,  up
@subsection Comments on style
@cindex Style


For your model file to be readable and understandable, it is useful to
use a consistent style of notation. The example file "perc.model"
follows such a consistent notation (@pxref{perc.model}). For example we
suggest that:@refill

@itemize @bullet
@item
All variable names begin with a capital letter followed by meaningful
lower case subscripts.@refill

@item
Where two subscripts are necessary, they can be separated by an
underscore, such as in Qb_fat.@refill

@item
Where there is only one subscript an underscore can be used to
increase readability as in Q_fat.@refill

@item
Where two words are used in combination to name one item, they can be
separated visually by capitalizing each word, as in BodyWt.@refill
@end itemize


These conventions are suggestions only. The key to have a consistent
notation that makes sense to you. Consistency is one of the best ways
to:

@enumerate
@item
Increase readability, both for others and for yourself. If you
have to suspend work for a month or two and then come back to it, the
last thing you want is to have to decipher your own file.

@item
Decrease the likelihood of mistakes. If all of the equations are
coded with a consistent, logical convention, mistakes stand out more
readily.
@end enumerate



@comment ********* NODE *********
@node Specifying Simulations, Bibliographic References, Defining Models, Top
@comment  node-name,  next,  previous,  up
@chapter Specifying Simulations
@cindex Specifying simulations
@cindex Simulation definition files


After having your model defined and processed by mod, and the resulting
model.c file compiled with the MCSim routines, you are ready to run
simulations. For this you need to write a simulation file.

An example file "perc.lsodes.in", which works with the perchloroethylene
model, appears in Appendix (@pxref{perc.lsodes.in}).


@menu
* Using the compiled program:: how to process a simulation file
* Syntax of simulation files:: how to write a simulation file
@end menu



@comment ********* NODE *********
@node Using the compiled program, Syntax of simulation files, , Specifying Simulations
@comment  node-name,  next,  previous,  up
@section Using the compiled program

The simulation environment MCSim provides several types of simulations
for the models you create. Simulations are specified in a text file of
format similar to that of the model description file.

In Unix the command line syntax for the MCSim program is:

@example
mcsim [input-file [output-file]]
@end example

where the brackets indicate optional arguments. This assume that you
have not renamed the executable file. If you have, substitute the name
of your executable. If no file names are specified, the program will
prompt you for them. When the program starts up, it announces which
model description file it was created with.


On the Macintosh you double-click the "MCSim" icon and enter the name of
your simulation definition file at the first prompt and then the name of
the output file (or just hit return if you want the default or the name
you have specified in the input file to be used).



@comment ********* NODE *********
@node Syntax of simulation files, , Using the compiled program, Specifying Simulations
@comment  node-name,  next,  previous,  up
@section Syntax of the simulation definition file
@cindex Simulation file, syntax
@cindex Syntax of simulation files

The file starts with a global declaration section followed by a number
of Experiment (i.e. observation) definitions (@pxref{Experiment
definition}), eventually enclosed in a Level definition if Markov chain
Monte Carlo simulations are to be performed (@pxref{Specifying a
statistical model}). Each Experiment defines a set of simulation
conditions. The initial values of model state variables, the parameter
values, input variables, and which outputs are to print at which times
can all be changed in a given Experiment.@refill

The general syntax of the file is the same as that of mod with two
differences:

@bullet{} Variables can only be assigned constant values.

@bullet{} Input variables' assignments can use any input function
(including the NDoses() function) or constant values.@refill

Expressions are not allowed (unlike in the model definition file where
they can be used). Similarly, structural change to the model, for
instance, addition of a state, input, output or parameter, cannot be
done here and must be done in the model description file.

The simulation specification file is read until its end is reached, or
until an End command is reached.

The general layout of the file is:

@example
# Input file (this a comment)
<Global modifications and analysis specifications>

Experiment @{
  <Specifications for first experiment>
@}

Experiment @{
  <Specifications for second experiment>
@}

# Unlimited number of experiment specifications

End # Optional End statement. Everything after this line is ignored
@end example


For Markov chain Monte Carlo simulations (@pxref{MCMC() specification}),
the general layout of the file includes Level definitions:@refill

@example
# Input file (this is a comment)

SimType(MCMC);

<Global modifications and analysis specifications>

Level @{

  # Up to 10 levels of hierarchy
  Experiment @{
    Specifications for first experiment
  @}

  Experiment @{
    Specifications for second experiment
  @}

  # Unlimited number of experiment specifications

@} # end Level

End # Optional statement. Everything after this line is ignored
@end example


@menu
* Global specifications::
* Specifying basic conditions to simulate::
* Specifying a statistical model::
* Analyzing results::
* Error Handling::
@end menu



@comment ********* NODE *********
@node Global specifications, Specifying basic conditions to simulate, , Syntax of simulation files
@comment  node-name,  next,  previous,  up
@section Global specifications
@cindex Global specifications

The global section is used to give specifications relevant to all
experiments, for example specification of the type of analysis, how the
integrator should work, parameter modifications to be used for all
experiments, etc.

Both the global section and each experiment section can contain
modifications to defined model variables. At the beginning of a
simulation, all model parameters are initialized to the nominal values
specified in the model description file. Next, modifications given in
the global section are applied, and finally any modifications for the
current experiment are applied.


@menu
* SimType() specification::
* Integrate() specification::
* OutputFile() specification::
* MonteCarlo() specification::
* Distrib() specification::
* MCMC() specification::
* SetPoints() specification::
@end menu



@comment ********* NODE *********
@node SimType() specification, Integrate() specification, , Global specifications
@comment  node-name,  next,  previous,  up
@subsection SimType() specification
@cindex SimType() specification
@cindex Specification, SimType()

The type of analysis performed is specified using the SimType
specification. Example:

@example
SimType(MonteCarlo);
@end example

The following keywords can be used: 

@itemize @bullet
@item
DefaultSim: the list of specified experiments is simulated,

@item
MonteCarlo: the specified experiments are simulated several times with
random input parameters (@pxref{MonteCarlo() specification}),@refill

@item
MCMC (previously Gibbs): Markov chain Monte Carlo simulations are
performed to attain the posterior distribution of the model's
parameters, given their prior distributions Ñ that you specify Ñ and
data for which the likelihood function can be computed (@pxref{MCMC()
specification}),@refill

@item
SetPoints: the experiments are simulated using several lists of
user-defined parameters values in input (@pxref{SetPoints()
specification}).@refill
@end itemize

If MonteCarlo, MCMC, or SetPoints simulations are
requested, additional specifications are needed (see below).



@comment ********* NODE *********
@node Integrate() specification, OutputFile() specification, SimType() specification, Global specifications
@comment  node-name,  next,  previous,  up
@subsection Integrate() specification
@cindex Integrate() specification
@cindex Specification, Integrate()
@cindex Lsodes integrator
@cindex Integration routine, Lsodes
@cindex Euler integrator
@cindex Integration routine, Euler


The integrator settings can be changed with the Integrate specification.
Two integration routines are provided: Lsodes and Euler.


The syntax for Lsodes is:

@example
Integrate(Lsodes, rtol, atol, method);
@end example

Rtol is a scalar specifying the relative error tolerance for each
integration step. Atol is a scalar specifying the absolute error
tolerance parameter. They apply to all integration variables (state
variables). The estimated local error in a state variable y(i) will be
controlled so as to be roughly less (in magnitude) than rtol*|y(i)| +
atol. Thus the local error test passes if, in each component, either the
absolute error is less than atol, or the relative error is less than
rtol. Use rtolÊ=Ê0.0 for pure absolute error control, and use atolÊ=Ê0.0
for pure relative error control. Caution: actual (global) errors may
exceed these local tolerances, so choose them conservatively. The method
flag should be 0 (zero) for non-stiff differential systems and 1 for
stiff systems. You should try both and select the fastest for equal
accuracy of output, unless insight from your system leads you to choose
a priori.


The syntax for Euler is:

@example
Integrate(Euler, time-step, 0, 0);
@end example

time-step is a scalar specifying the constant time-step to be taken at
each integration step. The next two scalars are reserved for future use
and should be set to zero.


If the Integrate() specification is not used, the default integration
method is Lsodes with parameters 10-5, 10-7 and 1. We recommend using
Lsodes (which originates from the SLAC Fortran library and is originally
based on Gear's routine) (Gear, 1971b; Gear, 1971a; Press et al., 1989)
(@pxref{Bibliographic References}), since is it highly accurate and
efficient. Euler can be used for special applications (e.g. in system
dynamics) where a constant time step and a simple algorithm are needed
(Press et al., 1989).@refill



@comment ********* NODE *********
@node OutputFile() specification, MonteCarlo() specification, Integrate() specification, Global specifications
@comment  node-name,  next,  previous,  up
@subsection OutputFile() specification
@cindex OutputFile() specification
@cindex Specification, OutputFile()

The OutputFile specification allows you to specify a name for the output
file of DefaultSim simulations. If this specification is not given the
name "sim.out" is used. The corresponding syntax is:

@example
OutputFile("<OutputFilename>");
@end example



@comment ********* NODE *********
@node MonteCarlo() specification, Distrib() specification, OutputFile() specification, Global specifications
@comment  node-name,  next,  previous,  up
@subsection MonteCarlo() specification
@cindex MonteCarlo() specification
@cindex Specification, MonteCarlo()


Monte Carlo simulations (Hammersley and Handscomb, 1964; Manteufel,
1996) (@pxref{Bibliographic References}) require the use of two
specifications, MonteCarlo() and Distrib(), which must appear in the
global section of the file before the experiment sections. Such Monte
Carlo specifications are ignored if they appear in an Experiment
specification.@refill

The MonteCarlo specification gives general information required for the
runs: the output file name, the number of runs to perform, a starting
seed for the random number generator and whether each parameter is
statistically independent within a run, or all parameters positively
correlated. Its syntax is:

@example
MonteCarlo("<OutputFilename>", <nRuns>, <RandomSeed>);
@end example

The output filename is a string field and must be enclosed in quotes. If
a null-string "" is given, the default name "simmc.out" will be used.
The seed of the pseudo-random number generator can be any positive real
number. Seeds between 1.0 and 2147483646.0 are used as is, others are
rescaled silently within those bounds, e.g.:

@example
MonteCarlo("percsimmc.out", 5, 9386.630);
@end example

The parameters' sampling distributions are specified by a list of
Distrib specifications, as explained in the next section. The format of
the output file of Monte Carlo simulations is discussed in the
"Analyzing results" section (@pxref{Analyzing results}).@refill



@comment ********* NODE *********
@node Distrib() specification, MCMC() specification, MonteCarlo() specification, Global specifications
@comment  node-name,  next,  previous,  up
@subsection Distrib() specification
@cindex Distrib() specification
@cindex Specification, Distrib()


This specification indicates which variable to sample, and its sampling
distribution. One Distrib() specification must be included for each
variable to sample. The specification file can include any number of
these commands at global level, or within any Level section in the case
of Markov chain Monte Carlo sampling (@pxref{Specifying a statistical
model}). The syntax is:@refill

@example
Distrib(<identifier>, <iType>, [<shape parms>]);
@end example

The iType field specifies the sampling distribution to use and can be
one of following: 

@itemize @bullet
@item
@cindex Uniform distribution
@cindex Distribution, uniform
Uniform,
@item
@cindex LogUniform distribution
@cindex Distribution, loguniform
LogUniform,
@item
@cindex Normal distribution
@cindex Distribution, normal
Normal,
@item
@cindex Normal_v distribution
@cindex Distribution, normal_v
Normal_v,
@item
@cindex Lognormal distribution
@cindex Distribution, lognormal
LogNormal,
@item
@cindex LogNormal_v distribution
@cindex Distribution, lognormal_v
LogNormal_v,
@item
@cindex TruncNormal distribution
@cindex Distribution, truncated normal
TruncNormal,
@item
@cindex TruncNormal_v distribution
@cindex Distribution, truncnormal_v
TruncNormal_v,
@item
@cindex TruncLogNormal distribution
@cindex Distribution, truncated lognormal
TruncLogNormal,
@item
@cindex TruncLogNormal_v distribution
@cindex Distribution, trunclognormal_v
TruncLogNormal_v,
@item
@cindex Beta distribution
@cindex Distribution, beta
Beta,
@item
@cindex Gamma distribution
@cindex Distribution, gamma
Gamma,
@item
@cindex InvGamma distribution
@cindex Distribution, inverse-gamma
InvGamma,
@item
@cindex Chi2 distribution
@cindex Distribution, chi2
Chi2,
@item
@cindex Exponential distribution
@cindex Distribution, exponential
Exponential,
@item
@cindex Binomial distribution
@cindex Distribution, binomial
Binomial,
@item
@cindex Poisson distribution
@cindex Distribution, Poisson
Poisson,
@item
@cindex Piecewise distribution
@cindex Distribution, piecewise
Piecewise.
@end itemize

The corresponding shape parameters (Bernardo and Smith, 1994; Gelman et
al., 1995) (@pxref{Bibliographic References}) are as follow :@refill

@itemize @bullet

@item
Uniform and log-uniform distributions: minimum and maximum of the
sampling range, real numbers in natural space.@refill

@item
Normal distribution (two reals numbers): mean and standard deviation,
the latter being stricly positive. The variant Normal_v takes the
variance instead of the standard deviation as second parameter.@refill

@item
Truncated normal distribution (four reals numbers): mean, standard
deviation (stricly positive), minimum and maximum. The variant
TruncNormal_v takes the variance instead of the standard deviation as
second parameter.@refill

@item
LogNormal distribution (two reals numbers): geometric mean (exponential
of the mean in log-space) and geometric standard deviation (exponential,
stricly superior to 1, of the standard deviation in log-space). The
variant LogNormal_v takes the variance (in log-space!) instead of the
standard deviation as second parameter.@refill

@item
Truncated Lognormal distribution (four reals numbers): geometric mean
and geometric standard deviation (stricly superior to 1), minimum and
maximum in natural space. For example:@refill 

@example
Distrib(Var, TruncLogNormal, 1, 2.718, 0.01, 10)
@end example

samples Var such that loge(Var) is a standardized normal variate
Ñ of mean loge(1)Ê=Ê0 and standard deviation loge(2.718)Ê=Ê1 Ñ while Var
is truncated to fall between 0.01 to 10. The variant TruncLogNormal_v
takes the variance (in log-space!) instead of the standard deviation as
second parameter.@refill

@item
Beta distribution (at least two strictly positive real numbers): A and
B. By default the Beta distribution is defined over the interval [0;1].
If a range is given for the beta distribution, the [0;1] interval is
mapped onto the specified range.@refill

@item
Gamma distribution (two strictly positive real numbers): shape a and
inverse scale b.@refill

@item
Inverse-gamma distribution (two strictly positive real numbers): shape a
and scale b.@refill

@item
Chi-squared distribution (one strictly positive real number): n. This
distribution is the same as Gamma(n/2, 1/2).@refill

@item
Exponential distribution (one strictly positive real number):
inverse-scale b. The density of this distribution is equal to be^-bx.@refill

@item
Binomial distribution (two strictly positive number, a real and an
integer): p (in the interval [0;1]), and N. If N is not input as an
integer it will be rounded down during the simulations.@refill

@item
Poisson distribution (a strictly positive real): rate l.@refill

@item
Piecewise distribution (four reals): minimum, a, b, maximum. The
distribution has the form of a truncated triangle, with a plateau
between a and b. If aÊ=Êb the distribution is triangular.@refill
@end itemize

The shape parameters of the above distribution specifications can
reference other parameters, provided than distributions for these have
already been defined. For example:

@example
Distrib(A, Normal, 0, 1);
Distrib(B, Normal, A, 2);
@end example



@comment ********* NODE *********
@node MCMC() specification, SetPoints() specification, Distrib() specification, Global specifications
@comment  node-name,  next,  previous,  up
@subsection MCMC() specification
@cindex MCMC() specification
@cindex Specification, MCMC()
@cindex Markov-chain Monte Carlo simulations


Syntax:

@example
MCMC("<OutputFilename>", "<RestartFilename>", "", <nRuns>, 
     <printPredFlag>, <printFrequency>, <itersToPrint>, 
     <RandomSeed>);
@end example

Markov chain Monte Carlo (MCMC) simulations, used in a Bayesian context,
allow the user to specify a statistical model (eventually hierarchical)
and sample parameters from their joint posterior distribution, given a
prior distribution for each parameter, a set of data to simulate, and
corresponding likelihoods. Sampling from the posterior is not immediate:
it requires the simulation chain, which start by sampling purely from
the prior, to reach equilibrium. Checking that equilibrium is obtained
is best achieved, in our opinion, by running multiple independent
chains. Hence these computations are very intensive. For a discussion of
Markov chain Monte Carlo and convergence issues you should consult the
appropriate statistical literature (for example, Bernardo and Smith,
1994; Gelman, 1992; Gelman et al., in press; Gelman et al., 1995; Gelman
and Rubin, 1992; Smith, 1991; Smith and Roberts, 1993)
(@pxref{Bibliographic References}). Technically, MCSim uses
Metropolis-Hasting sampling. Like simple Monte Carlo simulations, MCMC
simulations require the use of two specifications, MCMC() and Distrib()
and of one special section definition: "Level". The syntax for the
MCMC() specification is:@refill

The output filename is a string field and must be enclosed in quotes. If
a null-string "" is given, the default name "MCMC.default.out" will be
used.

If a restart file name (enclosed in quotes) is given, the first
simulations will be read from that file (which must be a text file).
This allows you to continue a chain where you left it, since an MCMC
output file can be used as a restart file with no change. Note that the
first line of the file (which typically contains column headers) is
skipped. Also, the number of lines in the file must be less than or
equal to nRuns. The first column of the file should be integers, and the
following columns (tab or space separated) should give the various
parameters, in the same order as specified in the list of Distrib()
specifications in the input file. The third field is reserved for future
use and should just be a pair of empty quotes.

If a data file name is given, the observed (data) values for the
simulated output will be read from that file; otherwise, Data statements
(see below) will be used and should be provided. A set of lines starting
with # can be placed as comments at the beginning of the data file: they
will be ignored. Next an integer should give the total number of data
points, and the data values should follow. A data value of "-1" will be
treated as "missing data" and ignored in likelihood calculations. You
have to make sure that there is one data point per value in output. We
recommend that you use data statements rather that the data file, which
is much more error prone.

The integer nRuns gives the total number of runs to be performed,
including the runs eventually read in the restart file. The next field,
printPredFlag should be either 0 or 1. It should be set at zero for
usual MCMC simulations. If its value is set to 1, a restart file must
also be specified. In that case, the output file contains the printing
times, the data values and corresponding model predictions computed
using the last parameter vector of the restart file. This is useful to
check the model fit to the data. The integer printFrequency should be
set to 1 if you want an output at each iteration, to 2 if you want an
output at every other iteration etc. itersToPrint is the number of final
iterations for which output is required (e.g. 1000 will request output
for the last 1000 iterations; to print all iterations set this parameter
to the value of nRuns). Finally, the seed of the pseudo-random number
generator can be any positive real number. Seeds between 1.0 and
2147483646.0 are used as is, others are rescaled silently within those
bounds.

To use the MCMC specification, you must define a statistical model
precising each parameter's prior distribution, or conditional
distribution (in the case of a hierarchical model), and the data
likelihood (i.e. the distribution of observation errors). These
distributions must be enclosed in a Level section and are specified with
Distrib() statements (@pxref{Specifying a statistical model}). In the
context of MCMC sampling, MCSim provides an extension of the Distrib()
specification. First, the first two shape parameters of distributions
may depend on other model parameters. For example:@refill

@example
Distrib(A, Normal, 0, 1);
Distrib(B, Normal, A, C);
@end example

The data distribution is given by a similar statement, which uses the
specification Prediction() to differentiate data from their predicted
counterparts. The Prediction() specification can be used for the first
two shape parameters only (therefore, not for ranges). If Prediction()
in used for the the first shape parameter, the variable enclosed in
parentheses must be the same as the variable whose distribution is
described. There should be one and only one distribution specified for a
given type of data (this limitation will be removed in a future
release). Note that only states and outputs can use Prediction()
specifications.  For example:

@example
Distrib(y, TruncNormal, Prediction(y), Prediction(z), -10, 10);
@end example

To recapitulate, the extended Distrib() syntax, for use with MCMC
simulations is therefore:

@example
Distrib(<identifier>, <iType>, [<shape parms>]);
@end example

where the first two shape parameters can be Prediction(<identifier>), or
any model parameter or numerals, and the last two shape parameters
numerals only (this limitation will also be removed in a future
release).

If a statement like:

@example
Distrib(Var, <iType>, Prediction(Var), Prediction(Other_Var), ...);
@end example

is used, the two variables Var and Other_Var must have identical output
times. It is then useful to group them in the same Print() statement.

The other tool MCSim brings you to build a complete statistical model is
the Level keyword. The use of this keyword, is described below
(@pxref{Specifying a statistical model}).@refill

Finally, the format of the output file of MCMC simulations is discussed
in the "Analyzing results" section (@pxref{Analyzing results}).@refill



@comment ********* NODE *********
@node SetPoints() specification, , MCMC() specification, Global specifications
@comment  node-name,  next,  previous,  up
@subsection SetPoints() specification
@cindex SetPoint() specification
@cindex Specification, SetPoint()


To impose a series of set points (i.e. already tabulated values for the
parameters), the global section can include a SetPoints() specification.
It allows you to perform additional simulations with previously Monte
Carlo sampled parameter values, eventually filtered. You can also be
generated parameters values in a systematic fashion, over a grid for
example, by another program and used them as input to MCSim. Importance
sampling, latin hypercube sampling, grid sampling, can be accommodated
in this way.

This command specifies an output filename, the name of a text file
containing the chosen parameter values, the number of simulations to
perform and a list of model parameters to vary. It has the following
syntax:

@example
SetPoints("<OutputFilename>", "<SetPointsFilename>", <nRuns>, 
          <identifier>, <identifier>, É);
@end example

If a null string is given for the output filename, the set points output
will be written to the same default output file used for Monte Carlo
analyses, "simmc.out".

The set points file name is required and must refer to an existing file
containing the parameter values to use. The first line of the set points
file is skipped and can contain column headers for example. Each one of
the other lines should contain an integer (e.g. the line number)
followed by values of the various parameters in the order indicated in
the SetPoints() specification. If extra fields are at the end of each
line they are skipped. The first integer field is needed but is not used
(this allows you to directly use Monte Carlo output files for additional
SetPoints simulations).

The variable nRuns should be less or equal to the number of lines (minus
one) in the set points file. If a zero is given, all lines of the file
are read. The format of the output file of set points simulations is
discussed in the "Analyzing results" section, below.

Following the SetPoints() specification, Distrib() statements can be
given for parameters not already in the list (@pxref{Distrib()
specification}). These parameters will be sampled accordingly before to
performing each simulation. The shape parameters of the distribution
specifications can reference other parameters, including those of the
list.@refill



@comment ********* NODE *********
@node Specifying basic conditions to simulate, Specifying a statistical model, Global specifications, Syntax of simulation files
@comment  node-name,  next,  previous,  up
@section Specifying basic conditions to simulate


Any simulation file must define at least one "Experiment" to simulate.


@menu
* Experiment definition::
* StartTime() specification::
* Print() specification::
* PrintStep() specification::
* Data() specification::
@end menu



@comment ********* NODE *********
@node Experiment definition, StartTime() specification, , Specifying basic conditions to simulate
@comment  node-name,  next,  previous,  up
@subsection Experiment definition
@cindex Experiment definition


After global simulation specifications, "experiments" must be defined.
This defines experimental conditions to simulate and what to output.  An
experiment section starts with the keyword Experiment and is enclosed in
curly braces.

An experiment can make modifications to any model variable or parameter
that was defined in the global section of the model description file.
The syntax is the same, except that variables can only take constant
values. So, for example, in an experiment the body weight could be
modified with:

@example
BodyWt = new-value;
@end example

This overrides any previously assigned values, even if randomly sampled,
for the specified parameter.

Inputs can be redefined with the input functions listed in the Mod
reference section above. Input functions can reference other variables
(eventually random), as in:

@example
Q_gav = PerExp(GavMag, 60, 0, RateConst);
@end example

Within an experiment definition, or at the global level (if you want
them to apply to all experiments), several additional specifications can
also be used:
@itemize @bullet
@item
StartTime()
@item
Print()
@item
PrintStep()
@item
Data()
@end itemize



@comment ********* NODE *********
@node StartTime() specification, Print() specification, Experiment definition, Specifying basic conditions to simulate
@comment  node-name,  next,  previous,  up
@subsection StartTime() specification
@cindex StartTime() specification
@cindex Specification, StartTime()

The origin of time for a simulation, if it needs to be defined, is
specified with the StartTime specification:

@example
StartTime(initial-time);
@end example

If this specification is not given, a value of zero is used by default.
The final time is automatically computed to match the largest output
time specified in the Print or PrintStep statements (@pxref{Print()
specification}; @pxref{PrintStep() specification}).@refill



@comment ********* NODE *********
@node Print() specification, PrintStep() specification, StartTime() specification, Specifying basic conditions to simulate
@comment  node-name,  next,  previous,  up
@subsection Print() specification
@cindex Print() specification
@cindex Specification, Print()


The value of any model variable, input, output or parameter can be
output with the Print specification. The arguments are a list of names
of variables (at least one and up to five), and a list of increasing
times at which to output their value:

@example
Print(identifier1, .identifier2, É, time1, time2, É);
@end example

The same output times are used for all the variables specified. The size
of the time list is only limited by the available memory.



@comment ********* NODE *********
@node PrintStep() specification, Data() specification, Print() specification, Specifying basic conditions to simulate
@comment  node-name,  next,  previous,  up
@subsection PrintStep() specification
@cindex PrintStep() specification
@cindex Specification, PrintStep()


The value of any model variable, input or parameter can be also output
with the PrintStep specification. It allows almost continuous printing,
suitable for smooth plots, for example. The arguments are the name of
only one variable, the first output time, the last one, and a time
increment:

@example
Print(identifier, start-time, end-time, time-step);
@end example

The final time has to be superior to the initial time and the time step
has to be less than the time span between end and start. If the time
step is not an exact divider of the time span the last printing step is
shorter and the last output time is still the end-time specified. The
number of output produced is only limited by the available memory at run
time.



@comment ********* NODE *********
@node Data() specification, , PrintStep() specification, Specifying basic conditions to simulate
@comment  node-name,  next,  previous,  up
@subsection Data() specification
@cindex Data() specification
@cindex Specification, Data()


Experimental observations of model variables, inputs, outputs, or
parameters, can be specified with the Data() command. Markov chain Monte
Carlo sampling requires that you specify Data() statements
(@pxref{MCMC() specification}; @pxref{Specifying a statistical model}).
The data are then used internally to evaluate the likelihood function
for the model.  The arguments are the name of the variable for which
observations exist, and a list of data values:@refill

@example
Data(identifier, value1, value2, É);
@end example

This specification can only be used when a matching Print() or
PrintStep() for the same variable (@pxref{Print() specification};
@pxref{PrintStep() specification}). You must make sure that there is as
many data values in the Data() specification as output time requested in
the corresponding Print() or PrintStep(). A data value of "-1" will be
treated as "missing data" and ignored in likelihood calculations.@refill



@comment ********* NODE *********
@node Specifying a statistical model, Analyzing results, Specifying basic conditions to simulate, Syntax of simulation files
@comment  node-name,  next,  previous,  up
@section Specifying a statistical model
@cindex Statistical model specification
@cindex Specification, statistical model


Statistical models are defined in the simulation specification file,
rather than in the model defintion file.

@subsection Level definition
@cindex Level definition


Markov chain Monte Carlo simulations require the definition of a
statistical model and the use of the Level keyword. At least one level
must be defined. A level section starts with the keyword Level and is
enclosed in curly braces. It can include any number of sub-levels or
experiments. Experiments (where the data are specified) form the lowest
level of the hierarchy. There must be one and only one top level.

A level can make modifications to the sampling distribution of any model
parameter. For example:

@example
Level @{ # this is the top level

  Distrib(A, Uniform, 0, 1);

  Level @{ # this is sub-level 1
    Distrib(A, Normal, A, 1);
    Experiment @{ ... @} # experiment 1
    Experiment @{ ... @} # experiment 2
  @}
@}
@end example

These distribution assignments apply to all sub-levels of the level
where they take place. If several assignments are given, their position
within the level section is irrelevant (although a logical order is
recommended for clarity).

A level can also make modifications to any model parameter that was
defined in the global section of the model description file. The syntax
is the same, except that variables can only take constant values. So,
for example, in an experiment, the parameter A could be modified with:

@example
A = 2.0;
@end example

This overrides any previously assigned values, even if randomly sampled,
for the specified parameter. This assignment also applies to the
sub-levels of the level where they take place.

An important concept to grasp here is that of "instance". In the code
fragment given above, the parameter A defined at a given level is
"cloned" as many times as there are sub-levels or experiments enclosed.
In that way, the parameters distributions defined at one level in fact
apply to the next sub-level, or at the experiment level. This convention
saves a lot writing and effort in the long run. For example, the uniform
distribution assigned to A, above, applies to the sub-level 1. There is
only one "clone" of A at the sub-level 1 since only one sub-level is
included in the top level. In contrast two normally-distributed "clones"
of A will be defined and sampled. The first one will apply to experiment
1, and will be condition by the data of that experiment only, and the
other will apply to experiment 2. A total of three variables of "type" A
will be sampled and will be printed in the output file (coded so that
the position in the hierarchy is apparent): the "parent" A(1), a priori
uniformly distributed, and two "dependents" A(1.1) and A(1.2), a priori
normally distributed around A(1).



@comment ********* NODE *********
@node Analyzing results, Error Handling, Specifying a statistical model, Syntax of simulation files
@comment  node-name,  next,  previous,  up
@section Analyzing results
@cindex Analyzing results


The output from Monte Carlo or SetPoints simulations is a tab-delimited
text file with one row for each run (i.e., parameter set) and one column
for each parameter and output in the order specified. Thus each line of
the output file is in the following order:

@example
<# of run> <parameters> <outputs for Exp 1> <outputs for Exp2>É
@end example

The parameters are printed in the order they were sampled or set.

The first line gives the column headers. An variable called name
requested for output in an experiment i at a time j is labeled name_i.j.

The output of Markov chain Monte Carlo simulations is also a text file
with one row for each run. It displays a column of iteration labels, and
one column for each parameter sampled. The last three columns contain
respectively, the sum of the logarithms of each parameter's density
given its parents' values (LnPrior), the logarithm of the data
likelihood (LnData), and the sum of the previous two values
(LnPosterior). The first line gives the column headers. On this line,
parameters names are tagged with a code identifying their position in
the hierarchy defined by the Level statements. For example, the second
instance of a parameter called name placed at the fist level of the
hierarchy is labeled name(2); the first instance of the same parameter
placed at the second instance of the second level of the hierarchy is
labeled name(2.1) etc.

The tab-delimited file can easily be imported into your favorite
spreadsheet, graphic or statistical package for further analysis.



@comment ********* NODE *********
@node Error Handling, , Analyzing results, Syntax of simulation files
@comment  node-name,  next,  previous,  up
@section Error Handling
@cindex Error handling


If the Lsodes integration routine fails for an Experiment in DefaultSim
simulations no output is generated for that experiment, and the user is
warned by an error message on the screen. In MonteCarlo or SetPoints
simulations, the corresponding simulation line is not printed, but the
iteration number is incremented. Finally, in MCMC simulations, the
parameter for which the data likelihood was computed is simply not
updated (which implicitly forbids the uncomputable region of the
parameter space). In all cases an error message is given on the screen.



@comment ********* NODE *********
@node Bibliographic References, Using make, Specifying Simulations, Top
@comment  node-name,  next,  previous,  up
@unnumbered Bibliographic References
@cindex Bibliographic references


Barry, T. M. (1996). Recommendations on the testing and use of
pseudo-random number generators used in Monte Carlo analysis for risk
assessment. Risk Analysis 16, 93-105.

Bernardo, J. M. and Smith, A. F. M. (1994). Bayesian Theory. Wiley, New
York.

Bois, F. Y., Gelman, A., Jiang, J., Maszle, D., Zeise, L. and Alexeef,
G. (1996). Population toxicokinetics of tetrachloroethylene. Archives of
Toxicology 70, 347-355.

Bois, F. Y., Zeise, L. and Tozer, T. N. (1990). Precision and
sensitivity analysis of pharmacokinetic models for cancer risk
assessment: tetrachloroethylene in mice, rats and humans. Toxicology and
Applied Pharmacology 102, 300-315.

Gear, C. W. (1971a). Algorithm 407 - DIFSUB for solution of ordinary
differential equations [D2]. Communications of the ACM 14, 185-190.

Gear, C. W. (1971b). The automatic integration of ordinary differential
equations. Communications of the ACM 14, 176-179.

Gelman, A. (1992). Iterative and non-iterative simulation algorithms.
Computing Science and Statistics 24, 433-438.

Gelman, A., Bois, F. Y. and Jiang, J. (in press). Physiological
pharmacokinetic analysis using population modeling and informative prior
distributions. Journal of the American Statistical Association .

Gelman, A., Carlin, J. B., Stern, H. S. and Rubin, D. B. (1995).
Bayesian Data Analysis. Chapman & Hall, London.

Gelman, A. and Rubin, D. B. (1992). Inference from iterative simulation
using multiple sequences (with discussion). Statistical Science 7,
457-511.

Hammersley, J. M. and Handscomb, D. C. (1964). Monte Carlo Methods.
Chapman and Hall, London.

Manteufel, R. D. (1996). Variance-based importance analysis applied to a
complex probabilistic performance assessment. Risk Analysis 16, 587-598.

Park, S. K. and Miller, K. W. (1988). Random number generators: good
ones are hard to find. Communications of the ACM 31, 1192-1201.

Press, W. H., Flannery, B. P., Teukolsky, S. A. and Vetterling, W. T.
(1989). Numerical Recipes (2st ed.). Cambridge University Press,
Cambridge.

Smith, A. F. M. (1991). Bayesian computational methods. Philosophical
Transactions of the Royal Society of London, Series A 337, 369-386.

Smith, A. F. M. and Roberts, G. O. (1993). Bayesian computation via the
Gibbs sampler and related Markov chain Monte Carlo methods. Journal of
the Royal Statistical Society Series B 55, 3-23.

Vattulainen, I., Ala-Nissila, T. and Kankaala, K. (1994). Physical tests
for random numbers in simulations. Physical Review Letters 73,
2513-2516.



@comment ********* NODE *********
@node Using make, Examples, Bibliographic References, Top    
@comment  node-name,  next,  previous,  up
@appendix Using make
@cindex Unix make utility
@cindex make


Make is a utility that facilitates doing repetitive tasks like
compilation. A makefile is a text file that contains a description of
what make should do and under what circumstances. For example the
compilation Makefile included with the MCSim distribution only compile a
C-file if it has changed since the last compilation. This means that
when you change your model and create a new model.c file using mod, only
the model.c file needs to be compiled to recreate the simulation engine.

Before you run make you must change some settings in the makefile to
specify where your C compiler is on your file system, and some special
settings for the compiler. Refer to the documentation (or manual pages
in Unix) for your compiler to do this. In the makefile file there are
several variables defined which you may need to change. They are
described in the makefile itself.

You run the make program by entering "make" or "make -f Makefile" at the
prompt from the directory where the program is that you want to compile.



@comment ********* NODE *********
@node Examples, Concept Index, Using make, Top
@comment  node-name,  next,  previous,  up
@appendix Examples
@cindex Examples


You will find here some examples of model description files and 
simulation iput files


@menu
* linear.model::   a simple algebraic model
* 1cpt.model::     a one-compartment pharmacokinetic model
* perc.model::     a multi-compartment pharmacokinetic model
* perc.lsodes.in:: a sample simulation input file
@end menu



@comment ********* NODE *********
@node linear.model, 1cpt.model, , Examples
@comment  node-name,  next,  previous,  up
@section linear.model


# Linear Model with a random component
# y = A + B * time + N(0,SD_true)
# Setting SD_true to zero gives the deterministic version
#------------------------------------------------------------------------------

# Outputs
Outputs = @{y@};

# Model Parameters
A = 0;
B = 1;
SD_true = 0;
SD_esti = 0;

CalcOutputs @{ y = A + B * t + NormalRandom(0,SD_true); @} 



@comment ********* NODE *********
@node 1cpt.model, perc.model, linear.model, Examples
@comment  node-name,  next,  previous,  up
@section 1cpt.model: A sample model description file


# One Compartment Model
# First order input and output
#-----------------------------------------------------------------------------

# Inputs
Inputs = @{Dose@};

# Outputs
Outputs = @{C_central, AUC, ln_C_central, ln_AUC,
           SD_C_computed, SD_A_computed@};

# Model Parameters
ka = 1;
ke = 0.5;
F  = 1;
V  = 2;

# Statistical Parameters
SDb_ka = 0;
SDw_ka = 0;
SDb_ke = 0;
SDw_ke = 0;
SDb_V  = 0;
min_F  = 0;
max_F  = 0;
SD_C_central = 0;
SD_AUC       = 0;
CV_C_cen     = 0;
CV_AUC       = 0;
CV_C_cen_true = 0;
CV_AUC_true   = 0;


# Calculate Outputs
CalcOutputs @{

  # algebraic equation for C_central
  C_central = (ka != ke ?
               (exp(-ke * t) - exp(-ka * t)) * F * ka * Dose / (V * (ka - ke))):
               exp(-ka * t) * ka * t * F * Dose / V);

  # algebraic equation for AUC
  AUC = (ka != ke ?
         ((1 - exp(-ke * t)) / ke - (1 - exp(-ka * t)) / ka) * F * ka * Dose / 
         (V * (ka - ke))):
         F * Dose * (1 - (1 + ka * t) * exp(-ka * t)) / (V * ke));

  C_central = C_central + NormalRandom(0, C_central * CV_C_cen_true);
  AUC       = AUC + NormalRandom(0, AUC * CV_AUC_true);

  ln_C_central = (C_central > 0 ? log (C_central) : -100);
  ln_AUC = (AUC > 0 ? log (AUC) : -100);

  SD_C_computed = (C_central > 0 ? C_central * CV_C_cen : 1e-10);
  SD_A_computed = (AUC > 0 ? AUC * CV_AUC : 1e-10);

@} # End of output calculations



@comment ********* NODE *********
@node perc.model, perc.lsodes.in, 1cpt.model, Examples
@comment  node-name,  next,  previous,  up
@section perc.model: A sample model description file


#---------------------------------------------------------
# perc.model
# A four compartment model of Tetrachloroethylene (PERC)
# and total metabolites.
# Copyright (c) 1993.  Don Maszle, Frederic Bois.  All rights reserved.
#---------------------------------------------------------
# States are quantities of PERC and metabolite formed, they can be output

States = @{Q_fat,        # Quantity of PERC in the fat
          Q_wp,         #   ...   in the well-perfused compartment
          Q_pp,         #   ...   in the poorly-perfused compartment
          Q_liv,        #   ...   in the liver
          Q_exh,        #   ...   exhaled
          Qmet@};        # Quantity of metabolite formed


# Extra outputs are concentrations at various points

Outputs = @{C_liv,               # mg/l in the liver
           C_alv,               # ... in the alveolar air
           C_exh,               # ... in the exhaled air
           C_ven,               # ... in the venous blood
           Pct_metabolized,     # % of the dose metabolized
           C_exh_ug@};           # ug/l in the exhaled air

Inputs = @{C_inh@}                # Concentration inhaled

# Constants
# Conversions from/to ppm: 72 ppm = .488 mg/l

PPM_per_mg_per_l = 72.0 / 0.488;
mg_per_l_per_PPM = 1/PPM_per_mg_per_l;

#---------------------------------------------------------
# Nominal values for parameters
# Units:
# Volumes: liter
# Vmax:    mg / minute
# Weights: kg
# Km:      mg / minute
# Time:    minute
# Flows:   liter / minute
#---------------------------------------------------------

InhMag = 0.0;
Period = 0.0;
Exposure = 0.0;

C_inh = PerDose (InhMag, Period, 0.0, Exposure);

LeanBodyWt = 55;    # lean body weight

# Percent mass of tissues with ranges shown

Pct_M_fat  = .16;   # % total body mass
Pct_LM_liv = .03;   # liver, % of lean mass
Pct_LM_wp  = .17;   # well perfused tissue, % of lean mass
Pct_LM_pp  = .70;   # poorly perfused tissue, will be recomputed in scale

# Percent blood flows to tissues

Pct_Flow_fat = .09;
Pct_Flow_liv = .34;
Pct_Flow_wp  = .50; # will be recomputed in scale
Pct_Flow_pp  = .07;

# Tissue/blood partition coeficients

PC_fat = 144;
PC_liv = 4.6;
PC_wp  = 8.7;
PC_pp  = 1.4;
PC_art = 12.0;

Flow_pul   = 8.0;    # Pulmonary ventilation rate (minute volume)
Vent_Perf = 1.14;    # ventilation over perfusion ratio

sc_Vmax = .0026;     # scaling coeficient of body weight for Vmax

Km = 1.0;  

# The following parameters are calculated from the above values in the Scale 
# section before the start of each simulation.  They are left uninitialized here.

BodyWt = 0;

V_fat = 0;           # Actual volume of tissues
V_liv = 0;
V_wp  = 0;
V_pp  = 0;

Flow_fat = 0;        # Actual blood flows through tissues
Flow_liv = 0;
Flow_wp  = 0;
Flow_pp  = 0;

Flow_tot = 0;        # Total blood flow
Flow_alv = 0;        # Alveolar ventilation rate

Vmax = 0;            # kg/minute


#---------------------------------------------------------
# Dynamics
# Define the dynamics of the simulation. This section is
# calculated with each integration step. It includes
# specification of differential equations.
#---------------------------------------------------------

Dynamics @{

# Venous blood concentrations at the organ exit

Cout_fat = Q_fat / (V_fat * PC_fat);
Cout_wp  = Q_wp  / (V_wp  * PC_wp);
Cout_pp  = Q_pp  / (V_pp  * PC_pp);
Cout_liv = Q_liv / (V_liv * PC_liv);

# Sum of Flow * Concentration for all compartments

dQ_ven = Flow_fat * Cout_fat + Flow_wp * Cout_wp
         + Flow_pp * Cout_pp + Flow_liv * Cout_liv;

# Venous blood concentration

C_ven =  dQ_ven / Flow_tot;

# Arterial blood concentration
# Convert input given in ppm to mg/l to match other units

C_art = (Flow_alv * C_inh / PPM_per_mg_per_l +  dQ_ven) / 
        (Flow_tot + Flow_alv / PC_art);

# Alveolar air concentration

C_alv = C_art / PC_art;

# Exhaled air concentration
  
C_exh = 0.7 * C_alv + 0.3 * C_inh / PPM_per_mg_per_l;

# Differentials

dt (Q_exh) = Flow_alv * C_alv;
dt (Q_fat) = Flow_fat * (C_art - Cout_fat);
dt (Q_wp)  = Flow_wp  * (C_art - Cout_wp);
dt (Q_pp)  = Flow_pp  * (C_art - Cout_pp);

# Quantity metabolized in liver

dQmet_liv = Vmax * Q_liv / (Km + Q_liv);
dt (Q_liv) = Flow_liv * (C_art - Cout_liv) - dQmet_liv;

# Metabolite formation

dt (Qmet)  = dQmet_liv;

@} # End of Dynamics


#---------------------------------------------------------
# Scale
# Scale certain model parameters and resolve dependencies
# between parameters. Generally the scaling involves a
# change of units, or conversion from percentage to actual
# units.
#---------------------------------------------------------

Scale @{

# Volumes scaled to actual volumes

BodyWt = LeanBodyWt/(1 - Pct_M_fat);

V_fat = Pct_M_fat  * BodyWt/0.92;        # density of fat = 0.92 g/ml
V_liv = Pct_LM_liv * LeanBodyWt;
V_wp  = Pct_LM_wp  * LeanBodyWt;
V_pp  = 0.9 * LeanBodyWt - V_liv - V_wp; # 10% bones

# Calculate Flow_alv from total pulmonary flow

Flow_alv = Flow_pul * 0.7;

# Calculate total blood flow from the alveolar ventilation rate and 
# the V/P ratio.

Flow_tot = Flow_alv / Vent_Perf;
 
# Calculate actual blood flows from total flow and percent flows 

Flow_fat = Pct_Flow_fat * Flow_tot;
Flow_liv = Pct_Flow_liv * Flow_tot;
Flow_pp  = Pct_Flow_pp  * Flow_tot;
Flow_wp  = Flow_tot - Flow_fat - Flow_liv - Flow_pp;

# Vmax (mass/time) for Michaelis-Menten metabolism is scaled
# by multiplication of bdw^0.7 

Vmax = sc_Vmax * exp (0.7 * log (LeanBodyWt));

@} # End of model scaling


#---------------------------------------------------------
# CalcOutputs 
# The following outputs are only calculated just before values
# are saved.  They are not calculated with each integration step.
#---------------------------------------------------------

CalcOutputs @{

# Fraction of TCE metabolized per day

Pct_metabolized = (InhMag ?
                   Qmet / (1440 * Flow_alv * InhMag * mg_per_l_per_PPM) :
                   0);

C_exh_ug  = C_exh * 1000; # milli to micrograms

@} # End of output calculation



@comment ********* NODE *********
@node perc.lsodes.in, , perc.model, Examples
@comment  node-name,  next,  previous,  up
@section perc.lsodes.in

#---------------------------------------------------------
# perc.lsodes.in
#
# Copyright (c) 1993.  Don Maszle, Frederic Bois.  All rights reserved.
#
#---------------------------------------------------------

SimType (DefaultSim);

Integrate (Lsodes, 1e-4, 1e-6, 1);


#---------------------------------------------------------
# The following experiment is for a simulation of one of Dr. Monster's
# exposure experiments described in "Kinetics of Tetracholoroethylene 
# in Volunteers; Influence of Exposure Concentration and Work Load," 
# A.C. Monster, G. Boersma, and H. Steenweg, 
# Int. Arch. Occup. Environ. Health, v42, 1989, pp303-309
#
# The paper documents measurements of levels of TCE in blood and
# exhaled air for a group of 6 subjects exposed to 
# different concentrations of PERC in air.
#
# Inhalation is specified as a dose of magnitude InhMag for the
# given Exposure time.
#
# Inhalation is given in ppm
#---------------------------------------------------------

Experiment @{

InhMag = 72;            # ppm
Period = 1e10;          # Only one dose
Exposure = 240;         # 4 hour exposure

# measurements before end of exposure and at [5' 30'] 2hr 18 42 67 91 139 163

Print (C_exh_ug, 239.9 245 270 360 1320 2760 4260 5700 8580 10020 );
Print (C_ven, 239.9 360 1320 2760 4260 5700 8580 10020 );

@}

END.



@comment ********* NODE *********
@node    Concept Index,     , Examples, Top
@comment  node-name,  next,  previous,  up
@unnumbered Concept Index
     
@printindex cp
     
@contents
@bye

