diff --git a/MrBayes-3.2.0_installer_MACx64.pkg b/MrBayes-3.2.0_installer_MACx64.pkg new file mode 100644 index 00000000..c9d70f44 Binary files /dev/null and b/MrBayes-3.2.0_installer_MACx64.pkg differ diff --git a/src/CompileInstructions.txt b/src/CompileInstructions.txt deleted file mode 100644 index 0d4a0544..00000000 --- a/src/CompileInstructions.txt +++ /dev/null @@ -1,196 +0,0 @@ - -Content -======= - -1) How to compile MrBayes from source -2) Configuration options -3) Troubleshooting for Mac -4) Tips for Windows -5) Further references - - -How to compile MrBayes from source -================================== - -Pre-requirements: -* gcc (or other C compiler) -* autotools (autoconf, automake, etc) -* optional: MPI compiler and library -* optional: BEAGLE library - -Compilation: -To compile MrBayes in UNIX-like environments, first navigate to the folder containing -the source code, then execute the following commands in your terminal (without '>'): - -> autoconf -> ./configure -> make - -The compilation will produce an executable in the source directory with the name "mb". -To start the program, simply type - -> ./mb - -For more convenient access to the program, you may want to install it in your path, in -which case you can invoke the program from any directory by simply typing - -> mb - -If you wish to make the program available to all users in this way, you can use - -> sudo make install - -after having compiled the program. - - -Configuration options -===================== - -1) BEAGLE -MrBayes 3.2 uses the BEAGLE library by default. You should install the library from -"https://code.google.com/p/beagle-lib", or disable the use of the library with option -"--with-beagle=no", i.e. - -> ./configure --with-beagle=no - -Note: without BEAGLE library MrBayes may run slower. For more instructions, please see -https://code.google.com/p/beagle-lib/ - -2) SSE code -All main-stream modern processors have support for SSE instructions which are utilized -by default by MrBayes 3.2 in order to substantially speed up execution. If you -experience problems with the SSE code, you can disable the use of SSE code with option -"--enable-sse=no", i.e. - -> ./configure --enable-sse=no - -If you use SSE code, you may encounter problems with older compilers. Specifically, -if you are getting errors about undefined references to "posix_memalign", you should -update your compiler. You should have libc library of at least version 2.1.91 for the -SSE code to compile. - -3) MPI version -To make use of MPI code to parallelize MrBayes computations across several processors -or CPU cores, you should invoke the configure script with option "--enable-mpi=yes". -The MPI code can be used together with the BEAGLE library and the SSE code. Your -computer also needs to have an MPI implementation installed, for instance OpenMPI or -MPICH, and the environment needs to be set up to run MPI programs. To install an MPI -version of MrBayes with BEAGLE and SSE, use: - -> autoconf -> ./configure --enable-mpi=yes -> make - -The resulting program will be called mb. A typical run might be started with a command -like: - -> mpirun -np 8 mb data.nex > output.txt & - -This will run MrBayes on eight processors or cores (-np 8), using the data file -"data.nex" as input. The output will not be printed to screen but to the file -"output.txt" (> output.txt). The ampersand (&) causes the control to return immediately -to the console, while the job will continue running in the background. - -To examine the most recent output from the run, you might e.g. use the tail command of -UNIX like this: - -> tail -f output.txt - -This will print the lines onto the screen as they get added to the file "output.txt". -To stop the output, simply press ctrl-C (this will stop the output from the tail -command, it will not stop the MrBayes run). - -4) Debugging -For testing or developing purpose, you may need to compile a debugging version by -invoking the configure script with the option "--enable-debug=yes", i.e. - -> ./configure --enable-debug=yes - - -Troubleshooting for Mac -======================= - -Problem: > autoconf: command not found - -Solution: Xcode 4.5 or later no longer ships with autotools, including autoconf that -is used by MrBayes and most other open-source Unix software packages. -To install these tools, we recommend using HomeBrew, see below. - -Problem: The compilation process hangs on model.c. For instance, this happens when -using the compiler that ships with Xcode 4.6 (in the command line tools). - -Solution: Install newer command line tools (e.g., in Xcode 5 or higher), or install a -different gcc version for Mac using HomeBrew, see below. - ------------------------ -To install missed Unix tools, we recommend using HomeBrew (http://brew.sh). Follow the -instructions on HomeBrew's homepage to install it on Mac. -Other options include MacPorts (http://www.macports.org), GNU (http://www.gnu.org), -and Open MPI (http://open-mpi.org). - -To install autoconf and automake after having installed HomeBrew, use: - -> brew install autoconf -> brew install automake - -To install the most recent version of openmpi, use: - -> brew install openmpi - -Simply, you can directly install MrBayes using HomeBrew: - -> brew tap homebrew/science -> brew install mrbayes - -The dependent formulas will be installed simultaneously. To enable MPI and BEAGLE, use: - -> brew install mrbayes --with-beagle --with-mpi - -To uninstall mrbayes, use: - -> brew uninstall mrbayes - -To install an alternative gcc (not recommended), use the following commands: - -> brew install gcc - -After installation, you might need to redirect the symbolic gcc link in /usr/bin/ to the -new version of gcc. For instance, you can use the following commands: - -> sudo mv -i /usr/bin/gcc /usr/bin/gcc-old -> sudo ln -s /usr/local/bin/gcc-4.9 /usr/bin/gcc - - -Tips for Windows -================ -To compile MrBayes in Windows is relatively not straightforward. You can use Microsoft -Visual Studio to open and build one of the projects in the "projects" folder, after -downloading all the files from SourceForge (e.g., Download Snapshot). -http://sourceforge.net/p/mrbayes/code/HEAD/tree/ - -Here we introduce another way to compile using MinGW (http://www.mingw.org/). You need -to download the installer "mingw-get-setup.exe" and install it in Windows. Then open -"MinGW Installation Manager" you just installed. Click the square before "mingw32-base" -under "Basic Setup" and choose "Mark for Installation", then choose "Apply Changes" from -the "Installation" menu. - -Additionally, add "C:\MinGW\bin" (path to your MinGW installation) to your system path -in setting "Environment Variables" (please Google :)) - -Open Command Prompt (cmd.exe), "cd" to the src folder you just downloaded, e.g., - -> cd Downloads\MrBayes\trunk\src - -and use the following command to compile: - -> gcc -O3 -DNDEBUG -o mb bayes.c best.c command.c mbbeagle.c mcmc.c model.c proposal.c sumpt.c utils.c -lm - -An executable named "mb.exe" will be generated in the same folder, if everything -goes smoothly. You may want to edit the fist few lines in bayes.h to define/undef -some macros (SSE_ENABLED, etc). - - -Further references -================== - -See the manual for more compilation/installation instructions. diff --git a/src/Makefile.in b/src/Makefile.in deleted file mode 100644 index df709fac..00000000 --- a/src/Makefile.in +++ /dev/null @@ -1,38 +0,0 @@ -srcdir = @srcdir@ -RM = rm -CC = @CC@ -CFLAGS = @CFLAGS@ -DUSECONFIG_H -LDFLAGS = @LDFLAGS@ -lm -INSTALL = @INSTALL@ -BINDIR = /usr/local/bin - -SRC = bayes.c command.c mcmc.c model.c proposal.c sumpt.c utils.c mbbeagle.c best.c -OBJECTS = bayes.o command.o mcmc.o model.o proposal.o sumpt.o utils.o mbbeagle.o best.o -PROGS = mb - -all: $(PROGS) - -mb: $(OBJECTS) - $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS) - -install: $(PROGS) - $(INSTALL) -m 755 $(PROGS) $(BINDIR) - -clean: - $(RM) -f *.o *~ mb - -distclean: clean - $(RM) -rf Makefile config.log config.status config.h *.cache - -showdep: - @$(CC) -MM $(SRC) - -bayes.o: bayes.c bayes.h command.h model.h sumpt.h utils.h -command.o: command.c bayes.h command.h mbbeagle.h model.h mcmc.h sumpt.h utils.h -mcmc.o: mcmc.c bayes.h best.h command.h mbbeagle.h mcmc.h model.h sumpt.h utils.h -model.o: model.c bayes.h best.h command.h model.h mcmc.h sumpt.h utils.h -proposal.o: proposal.c bayes.h best.h command.h mcmc.h model.h utils.h -sumpt.o: sumpt.c bayes.h command.h mcmc.h sumpt.h utils.h -utils.o: utils.c bayes.h best.h command.h mcmc.h model.h utils.h -mbbeagle.o: mbbeagle.c bayes.h mbbeagle.h utils.h -best.o: best.c bayes.h best.h command.h mcmc.h model.h utils.h diff --git a/src/bayes.c b/src/bayes.c deleted file mode 100644 index 8eaffe7d..00000000 --- a/src/bayes.c +++ /dev/null @@ -1,998 +0,0 @@ -/* - * MrBayes 3 - * - * (c) 2002-2013 - * - * John P. Huelsenbeck - * Dept. Integrative Biology - * University of California, Berkeley - * Berkeley, CA 94720-3140 - * johnh@berkeley.edu - * - * Fredrik Ronquist - * Swedish Museum of Natural History - * Box 50007 - * SE-10405 Stockholm, SWEDEN - * fredrik.ronquist@nrm.se - * - * With important contributions by - * - * Paul van der Mark (paulvdm@sc.fsu.edu) - * Maxim Teslenko (maxim.teslenko@nrm.se) - * - * and by many users (run 'acknowledgments' to see more info) - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details (www.gnu.org). - * - */ - -#include "bayes.h" -#include "command.h" -#include "model.h" -#include "sumpt.h" -#include "utils.h" - - const char* const svnRevisionBayesC = "$Rev$"; /* Revision keyword which is expended/updated by svn on each commit/update */ -extern const char* const svnRevisionBestC; -extern const char* const svnRevisionCommandC; -extern const char* const svnRevisionMbbeagleC; -extern const char* const svnRevisionMcmcC; -extern const char* const svnRevisionModelC; -extern const char* const svnRevisionProposalC; -extern const char* const svnRevisionSumptC; -extern const char* const svnRevisionUtilsC; - -#ifdef HAVE_LIBREADLINE -#include -#include -static char **readline_completion(const char *, int, int); -#endif - -/* local prototypes */ -int CommandLine (int argc, char **argv); -void GetTimeSeed (void); -int InitializeMrBayes (void); -void PrintHeader (void); -int ReinitializeMrBayes (void); - -/* global variables, declared in this file */ -BitsLong bitsLongWithAllBitsSet; /* BitsLong with all bits set, for bit ops */ -ModelParams defaultModel; /* Default model; vals set in InitializeMrBayes */ -int defTaxa; /* flag for whether number of taxa is known */ -int defChars; /* flag for whether number of chars is known */ -int defMatrix; /* flag for whether matrix is successfull read */ -int defPartition; /* flag for whether character partition is read */ -int defPairs; /* flag for whether pairs are read */ -Doublet doublet[16]; /* holds information on states for doublets */ -int fileNameChanged; /* has file name been changed ? */ -RandLong globalSeed; /* seed that is initialized at start up */ -char **modelIndicatorParams; /* model indicator params */ -char ***modelElementNames; /* names for component models */ -int nBitsInALong; /* number of bits in a BitsLong */ -int nPThreads; /* number of pthreads to use */ -int numUserTrees; /* number of defined user trees */ -int readComment; /* should we read comment (looking for &) ? */ -int readWord; /* should we read word next ? */ -RandLong runIDSeed; /* seed used only for determining run ID [stamp] */ -RandLong swapSeed; /* seed used only for determining which to swap */ -int userLevel; /* user level */ -PolyTree *userTree[MAX_NUM_USERTREES];/* array of user trees */ -char workingDir[100]; /* working directory */ - -#if defined (MPI_ENABLED) -int proc_id; /* process ID (0, 1, ..., num_procs-1) */ -int num_procs; /* number of active processors */ -MrBFlt myStateInfo[7]; /* likelihood/prior/heat/ran/moveInfo vals of me */ -MrBFlt partnerStateInfo[7]; /* likelihood/prior/heat/ran/moveInfo vals of partner */ -#endif - -#if defined (FAST_LOG) -CLFlt scalerValue[400]; -CLFlt logValue[400]; -#endif -/* Define to use a log lookup for 4by4 nucleotide data (actually SLOWER than normal code on intel processors) */ - - -int main (int argc, char *argv[]) -{ - int i; - -# if defined (MPI_ENABLED) - int ierror; -# endif - -# if defined (WIN_VERSION) - HANDLE scbh; - BOOL ok; - DWORD lastError; - COORD largestWindow; - CONSOLE_SCREEN_BUFFER_INFO csbi; - int currBottom; - char poltmp[256]; - - scbh = GetStdHandle(STD_OUTPUT_HANDLE); - GetConsoleScreenBufferInfo(scbh, &csbi); - currBottom = csbi.srWindow.Bottom; - largestWindow = GetLargestConsoleWindowSize(scbh); - - /* Allow for screen buffer 3000 lines long and 140 characters wide */ - csbi.dwSize.Y = 3000; - csbi.dwSize.X = 140; - - SetConsoleScreenBufferSize(scbh, csbi.dwSize); - /* Allow for maximum possible screen height */ - csbi.srWindow.Left = 0; /* no change relative to current value */ - csbi.srWindow.Top = 0; /* no change relative to current value */ - csbi.srWindow.Right = 0; /* no change relative to current value */ - csbi.srWindow.Bottom = largestWindow.Y - currBottom -10; /**/ - ok = SetConsoleWindowInfo(scbh, FALSE, &csbi.srWindow); - if (ok == FALSE) - { - lastError = GetLastError(); - GetConsoleScreenBufferInfo(scbh, &csbi); - sprintf(poltmp, "\nlastError = %d", lastError); - // printf (poltmp); - } -# endif - - /* calculate the size of a long - used by bit manipulation functions */ - nBitsInALong = sizeof(BitsLong) * 8; - for (i=0; i' (i is for interactive)\n", spacer); - MrBayesPrint ("%s or use 'set mode=interactive'\n\n", spacer); - return (NO_ERROR); - } - /* normally, we simply wait at the prompt for a - user action */ -# if defined (MPI_ENABLED) - if (proc_id == 0) - { - /* do not use readline because OpenMPI does not handle it */ - MrBayesPrint ("MrBayes > "); - fflush (stdin); - if (fgets (cmdStr, CMD_STRING_LENGTH - 2, stdin) == NULL) - { - if (feof(stdin)) - MrBayesPrint ("%s End of File encountered on stdin; quitting\n", spacer); - else - MrBayesPrint ("%s Could not read command from stdin; quitting\n", spacer); - strcpy (cmdStr,"quit;\n"); - } - } - ierror = MPI_Bcast (&cmdStr, CMD_STRING_LENGTH, MPI_CHAR, 0, MPI_COMM_WORLD); - if (ierror != MPI_SUCCESS) - { - MrBayesPrint ("%s Problem broadcasting command string\n", spacer); - } -# else -# ifdef HAVE_LIBREADLINE - cmdStrP = readline("MrBayes > "); - if (cmdStrP!=NULL) - { - strncpy (cmdStr,cmdStrP,CMD_STRING_LENGTH - 2); - if (*cmdStrP) - add_history (cmdStrP); - free (cmdStrP); - } - else /* fall through to if (feof(stdin))..*/ -# else - MrBayesPrint ("MrBayes > "); - fflush (stdin); - if (fgets (cmdStr, CMD_STRING_LENGTH - 2, stdin) == NULL) -# endif - { - if (feof(stdin)) - MrBayesPrint ("%s End of File encountered on stdin; quitting\n", spacer); - else - MrBayesPrint ("%s Could not read command from stdin; quitting\n", spacer); - strcpy (cmdStr,"quit;\n"); - } -# endif - } - i = 0; - while (cmdStr[i] != '\0' && cmdStr[i] != '\n') - i++; - cmdStr[i++] = ';'; - cmdStr[i] = '\0'; - MrBayesPrint ("\n"); - if (cmdStr[0] != ';') - { - /* check that all characters in the string are valid */ - if (CheckStringValidity (cmdStr) == ERROR) - { - MrBayesPrint (" Unknown character in command string\n\n"); - } - else - { - expecting = Expecting(COMMAND); - message = ParseCommand (cmdStr); - - if (message == NO_ERROR_QUIT) - return (NO_ERROR); - - if (message == ERROR && quitOnError == YES) - { - MrBayesPrint ("%s Will exit with signal 1 (error) because quitonerror is set to yes\n", spacer); - MrBayesPrint ("%s If you want control to be returned to the command line on error,\n", spacer); - MrBayesPrint ("%s use 'mb -i ' (i is for interactive) or use 'set quitonerror=no'\n\n", spacer); - return (ERROR); - } - -# if defined (MPI_ENABLED) - ierror = MPI_Barrier (MPI_COMM_WORLD); - if (ierror != MPI_SUCCESS) - { - MrBayesPrint ("%s Problem at command barrier\n", spacer); - } -# endif - - MrBayesPrint ("\n"); - } - } - } -} - - -#ifdef HAVE_LIBREADLINE -extern char *command_generator(const char *text, int state); - -char **readline_completion (const char *text, int start, int stop) -{ - char **matches = (char **) NULL; - -# ifdef COMPLETIONMATCHES - if (start == 0) - matches = rl_completion_matches (text, command_generator); -# endif - - return (matches); -} -#endif - - -unsigned FindMaxRevision (unsigned amount, ...) -{ - const char* cur; - char tmp[20]; - unsigned val,i,max; - - va_list vl; - va_start(vl,amount); - max=0; - for (i=0;ival)?max:val; - } - va_end(vl); - return max; -} - - -void GetTimeSeed (void) -{ - time_t curTime; - -# if defined (MPI_ENABLED) - int ierror; - - if (proc_id == 0) - { - curTime = time(NULL); - globalSeed = (RandLong)curTime; - if (globalSeed < 0) - globalSeed = -globalSeed; - } - ierror = MPI_Bcast(&globalSeed, 1, MPI_LONG, 0, MPI_COMM_WORLD); - if (ierror != MPI_SUCCESS) - { - MrBayesPrint ("%s Problem broadcasting seed\n", spacer); - } - - if (proc_id == 0) - { - /* Note: swapSeed will often be same as globalSeed */ - curTime = time(NULL); - swapSeed = (RandLong)curTime; - if (swapSeed < 0) - swapSeed = -swapSeed; - } - ierror = MPI_Bcast(&swapSeed, 1, MPI_LONG, 0, MPI_COMM_WORLD); - if (ierror != MPI_SUCCESS) - { - MrBayesPrint ("%s Problem broadcasting swap seed\n", spacer); - } - - if (proc_id == 0) - { - /* Note: runIDSeed will often be same as globalSeed */ - curTime = time(NULL); - runIDSeed = (RandLong)curTime; - if (runIDSeed < 0) - runIDSeed = -runIDSeed; - } - ierror = MPI_Bcast(&runIDSeed, 1, MPI_LONG, 0, MPI_COMM_WORLD); - if (ierror != MPI_SUCCESS) - { - MrBayesPrint ("%s Problem broadcasting run ID seed\n", spacer); - } - -# else - curTime = time(NULL); - globalSeed = (RandLong)curTime; - if (globalSeed < 0) - globalSeed = -globalSeed; - - /* Note: swapSeed will often be the same as globalSeed */ - curTime = time(NULL); - swapSeed = (RandLong)curTime; - if (swapSeed < 0) - swapSeed = -swapSeed; - - /* Note: runIDSeed will often be the same as globalSeed */ - curTime = time(NULL); - runIDSeed = (RandLong)curTime; - if (runIDSeed < 0) - runIDSeed = -runIDSeed; - -# endif -} - - -int InitializeMrBayes (void) -{ - /* this function initializes the program; only call it at the start of execution */ - - int i, j, growthFxn[6]; - - nBitsInALong = sizeof(BitsLong) * 8; /* global variable: number of bits in a BitsLong */ - userLevel = STANDARD_USER; /* default user level */ - - readWord = NO; /* should we read a word next ? */ - readComment = NO; /* should we read comments? (used by tree cmd) */ - fileNameChanged = NO; /* file name changed ? (used by a few commands) */ - echoMB = YES; /* flag used by Manual to control printing */ - -# if defined (MPI_ENABLED) - sprintf (manFileName, "commref_mb%sp.txt", VERSION_NUMBER); /* name of command reference file */ -# else - sprintf (manFileName, "commref_mb%s.txt", VERSION_NUMBER); /* name of command reference file */ -# endif - - for (i=0; i\" for information\n"); - MrBayesPrint (" on the commands that are available.\n\n"); - MrBayesPrint (" Type \"about\" for authorship and general\n"); - MrBayesPrint (" information about the program.\n\n\n"); -} - - -int ReinitializeMrBayes (void) -{ - /* this function resets everything dependent on a matrix */ - - int i; - - /* reinitialize indentation */ - strcpy (spacer, ""); /* holds blanks for indentation */ - - /* reset all taxa flags */ - ResetTaxaFlags(); - - /* reset all characters flags */ - ResetCharacterFlags(); - - /* chain parameters */ - chainParams.numGen = 1000000; /* number of MCMC cycles */ - chainParams.sampleFreq = 500; /* frequency to sample chain */ - chainParams.printFreq = 1000; /* frequency to print chain */ - chainParams.swapFreq = 1; /* frequency of attempting swap of states */ - chainParams.numSwaps = 1; /* number of swaps to try each time */ - chainParams.isSS = NO; - chainParams.startFromPriorSS = NO; - chainParams.numStepsSS = 50; - chainParams.burninSS = -1; - chainParams.alphaSS = 0.4; - chainParams.backupCheckSS = 0; - chainParams.mcmcDiagn = YES; /* write MCMC diagnostics to file ? */ - chainParams.diagnFreq = 5000; /* diagnostics frequency */ - chainParams.minPartFreq = 0.10; /* min partition frequency for diagnostics */ - chainParams.allChains = NO; /* calculate diagnostics for all chains ? */ - chainParams.allComps = NO; /* do not calc diagn for all run comparisons */ - chainParams.relativeBurnin = YES; /* use relative burnin? */ - chainParams.burninFraction = 0.25; /* default burnin fraction */ - chainParams.stopRule = NO; /* should stopping rule be used? */ - chainParams.stopVal = 0.05; /* convergence diagnostic value to reach */ - chainParams.numRuns = 2; /* number of runs */ - chainParams.numChains = 4; /* number of chains */ - chainParams.chainTemp = 0.1; /* chain temperature */ - chainParams.redirect = NO; /* should printf be to stdout */ - strcpy(chainParams.chainFileName, "temp"); /* chain file name for output */ - chainParams.chainBurnIn = 0; /* chain burn in length */ - chainParams.numStartPerts = 0; /* number of perturbations to starting tree */ - strcpy(chainParams.startTree, "Current"); /* starting tree for chain (random/current) */ - strcpy(chainParams.startParams, "Current"); /* starting params for chain (reset/current) */ - chainParams.saveBrlens = YES; /* should branch lengths be saved */ - chainParams.weightScheme[0] = 0.0; /* percent chars to decrease in weight */ - chainParams.weightScheme[1] = 0.0; /* percent chars to increase in weight */ - chainParams.weightScheme[2] = 1.0; /* weight increment */ - chainParams.calcPbf = NO; /* should we calculate the pseudo-BF? */ - chainParams.pbfInitBurnin = 100000; /* initial burnin for pseudo BF */ - chainParams.pbfSampleFreq = 10; /* sample frequency for pseudo BF */ - chainParams.pbfSampleTime = 2000; /* how many cycles to calcualate site prob. */ - chainParams.pbfSampleBurnin = 2000; /* burnin period for each site for pseudo BF */ - chainParams.userDefinedTemps = NO; /* should we use the users temperatures? */ - for (i=0; i -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef USECONFIG_H -# include "config.h" -#elif !defined (XCODE_VERSION) /* some defaults that would otherwise be guessed by configure */ -# define PACKAGE_NAME "mrbayes" -# define PACKAGE_VERSION "3.2" -# undef HAVE_LIBREADLINE -# define UNIX_VERSION 1 -# define SSE_ENABLED 1 -# undef MPI_ENABLED -# undef BEAGLE_ENABLED -# undef FAST_LOG -#endif - -#if defined (MPI_ENABLED) -#include "mpi.h" -#endif - -#if defined (BEAGLE_ENABLED) -#include "libhmsbeagle/beagle.h" -#endif - -/* uncomment the following line when releasing, also modify the VERSION_NUMBER below */ -/* #define RELEASE */ -#ifdef RELEASE -#define VERSION_NUMBER "3.2.5" -#else -#define VERSION_NUMBER "3.2.5-svn" -#endif - -#if !defined (UNIX_VERSION) && !defined (WIN_VERSION) && !defined (MAC_VERSION) -# ifdef __MWERKS__ -# define MAC_VERSION -# elif defined __APPLE__ -# define MAC_VERSION -# else -# define WIN_VERSION -# endif -#endif - -#if defined (WIN_VERSION) -# include -# include -#endif - -/* Previous problems with bitfield operations may have been caused by several things. One potential - problem has been that MrBayes has used signed ints or signed longs for the bit operations, and - not all compilers perform bitfield operations on signed ints and longs in the expected manner - for unsigned ints and longs. Actually, the ANSI standard does not specify how to implement - bit operations on signed operands. - - Another problem is that some bitshift operations in MrBayes have been performed on an integer - constant "1". This is probably interpreted by most compilers as a signed int and the result of - the bitshift operation is therefore also a signed int. When a signed int has had a different - number of bits than the type specified as SafeLong, this may also have resulted in errors on - some systems. - - Both of these problems are fixed now by using unsigned longs for the bitfield operations and - by setting the "1" value needed by some bitfield functions using a variable defined as the same - type as the bitfield containers themselves. Furthermore, I have separated out the cases where - a signed long is required or is more appropriate than the container type of bitfields. - - FR 2013-07-06 - */ -typedef unsigned long BitsLong; -typedef long RandLong; - -#define MRBFLT_MAX DBL_MAX /* maximum possible value that can be stored in MrBFlt */ -#define MRBFLT_MIN DBL_MIN /* minimum possible value that can be stored in MrBFlt */ -#define MRBFLT_NEG_MAX (-DBL_MAX) /* maximum possible negative value that can be stored in MrBFlt */ -typedef double MrBFlt; /* double used for parameter values and generally for floating point values, - if set to float MPI would not work becouse of use MPI_DOUBLE */ -typedef float CLFlt; /* single-precision float used for cond likes (CLFlt) to increase speed and reduce memory requirement */ - /* set CLFlt to double if you want increased precision */ - /* NOTE: CLFlt = double not compatible with SSE_ENABLED */ - -/* Define a compiler and vector size for the SSE code */ -#if defined (SSE_ENABLED) -# define FLOATS_PER_VEC 4 -# if defined (WIN_VERSION) -# define MS_VCPP_SSE -# include -# else -# define GCC_SSE -# undef ICC_SSE -# include -# endif -#endif - -/* For comparing floating points: two values are the same if the absolute difference is less then - this value. -*/ -#ifndef ETA -#define ETA (1E-30) -#endif - -/* This defined DEBUG() is not used anywhere -#if defined (DEBUGOUTPUT) -#define DEBUG(fmt, arg) printf("%s:%d ",__FILE__,__LINE__); printf(fmt,arg); -#endif -*/ - -/* TEMPSTRSIZE determines size of temporary sprintf buffer (for SafeSprintf) */ -/* A patch was sent in by Allen Smith for SafeSprintf, but I could not get - it compiled on SGI IRIX 6.5 (too old?) with _xpg5_vsnprintf undefined. - The code below is a hack so SafeSprintf never has to reallocate memory. -*/ -#ifdef __sgi -#define TEMPSTRSIZE 1000 -#else -#define TEMPSTRSIZE 200 -#endif - -/* NO_ERROR is defined in bayes.h (as 0) and also in WinError.h (as 0L) - ERROR is defined in bayes.h (as 1) and also in WinGDI.h (as 0). we use the bayes.h value */ -#undef NO_ERROR -#undef ERROR -#define NO_ERROR 0 -#define ERROR 1 -#define NO_ERROR_QUIT 2 -#define ABORT 3 -#define SKIP_COMMAND 4 - -#undef FALSE -#undef TRUE -#define FALSE 0 -#define TRUE 1 - -#define NO 0 -#define YES 1 - -#define UP 0 -#define DOWN 1 - -#define UPPER 0 -#define MIDDLE 1 -#define LOWER 2 - -#define NONINTERACTIVE 0 -#define INTERACTIVE 1 - -#define STANDARD_USER 1 -#define DEVELOPER 3 - -#define DIFFERENT 0 -#define SAME 1 -#define CONSISTENT_WITH 2 - -#define LINETERM_UNIX 0 -#define LINETERM_MAC 1 -#define LINETERM_DOS 2 - -#define SCREENWIDTH 60 -#define SCREENWIDTH2 61 - -#define AVGSTDDEV 0 -#define MAXSTDDEV 1 - -#define NONE 0 -#define DNA 1 -#define RNA 2 -#define PROTEIN 3 -#define RESTRICTION 4 -#define STANDARD 5 -#define MIXED 6 -#define CONTINUOUS 7 - -#define AAMODEL_POISSON 0 -#define AAMODEL_JONES 1 -#define AAMODEL_DAY 2 -#define AAMODEL_MTREV 3 -#define AAMODEL_MTMAM 4 -#define AAMODEL_WAG 5 -#define AAMODEL_RTREV 6 -#define AAMODEL_CPREV 7 -#define AAMODEL_VT 8 -#define AAMODEL_BLOSUM 9 -#define AAMODEL_LG 10 -#define AAMODEL_EQ 11 -#define AAMODEL_GTR 12 /* aa models with free parameters must be listed last */ - -#define NUCMODEL_4BY4 0 -#define NUCMODEL_DOUBLET 1 -#define NUCMODEL_CODON 2 -#define NUCMODEL_AA 3 - -#define NST_MIXED -1 /* anything other than 1, 2, or 6 */ - -#define MISSING 10000000 -#define GAP 10000001 - -#define UNORD 0 -#define ORD 1 -#define DOLLO 2 -#define IRREV 3 - -#define IN_CMD 0 -#define IN_FILE 1 - -#define NOTHING 0 -#define COMMAND 1 -#define PARAMETER 2 -#define EQUALSIGN 3 -#define COLON 4 -#define SEMICOLON 5 -#define COMMA 6 -#define POUNDSIGN 7 -#define QUESTIONMARK 8 -#define DASH 9 -#define LEFTPAR 10 -#define RIGHTPAR 11 -#define LEFTCOMMENT 12 -#define RIGHTCOMMENT 13 -#define ALPHA 14 -#define NUMBER 15 -#define RETURNSYMBOL 16 -#define ASTERISK 17 -#define BACKSLASH 18 -#define FORWARDSLASH 19 -#define EXCLAMATIONMARK 20 -#define PERCENT 21 -#define QUOTATIONMARK 22 -#define WEIRD 23 -#define UNKNOWN_TOKEN_TYPE 24 -#define LEFTCURL 25 -#define RIGHTCURL 26 -#define DOLLAR 27 -#define AMPERSAND 28 - -#define MAX_Q_RATE 100.0f -#define MIN_SHAPE_PARAM 0.0001f -#define MAX_SHAPE_PARAM 200.0f -#define MAX_SITE_RATE 10.0f -#define MAX_GAMMA_CATS 20 -#define MAX_GAMMA_CATS_SQUARED 400 -#define BRLENS_MIN 0.00000001f // 1E-8f -#define BRLENS_MAX 100.0f -/* BRLENS_MIN must be bigger than TIME_MIN */ -#define TIME_MIN 1.0E-11f -#define TIME_MAX 100.0f -#define RELBRLENS_MIN 0.00000001f // 1E-8f -#define RELBRLENS_MAX 100.0f -#define KAPPA_MIN 0.001f -#define KAPPA_MAX 1000.0f -#define GROWTH_MIN 0.000001f -#define GROWTH_MAX 1000000.0f -#define RATE_MIN 0.000001f -#define RATE_MAX 100.0f -#define CPPRATEMULTIPLIER_MIN 0.001f -#define CPPRATEMULTIPLIER_MAX 1000.0f -#define SYMPI_MIN 0.000001f -#define SYMPI_MAX 100.0f -#define ALPHA_MIN 0.0001f -#define ALPHA_MAX 10000.0f -#define DIR_MIN 0.000001f -#define PI_MIN 0.000001f -#define OFFSETEXPLAMBDA_MIN 0.000001f -#define OFFSETEXPLAMBDA_MAX 100000.0f -#define TREEHEIGHT_MIN 0.00000001f -#define TREEHEIGHT_MAX 1000.0f -#define TREEAGE_MIN 0.00000001f -#define TREEAGE_MAX 1000000.0f -#define CPPLAMBDA_MIN 0.00001f -#define CPPLAMBDA_MAX 100.0f -#define TK02VAR_MIN 0.000001f -#define TK02VAR_MAX 10000.0f -#define IGRVAR_MIN 0.000001f -#define IGRVAR_MAX 10000.0f -#define MIXEDVAR_MIN 0.000001f -#define MIXEDVAR_MAX 10000.0f -#define OMEGA_MIN 0.001f -#define OMEGA_MAX 1000.0f - -#define POS_MIN 1E-25f -#define POS_MAX 1E25f -#define POS_INFINITY 1E25f -#define NEG_INFINITY -1000000.0f -#define POSREAL_MIN 1E-25f -#define POSREAL_MAX 1E25f - -#define CMD_STRING_LENGTH 100000 - -#define pos(i,j,n) ((i)*(n)+(j)) - -#define NUM_ALLOCS 100 - -#define ALLOC_MATRIX 0 -#define ALLOC_CHARINFO 2 -#define ALLOC_CHARSETS 3 -#define ALLOC_TAXA 4 -#define ALLOC_TMPSET 5 -#define ALLOC_PARTITIONS 6 -#define ALLOC_PARTITIONVARS 7 -#define ALLOC_TAXASETS 8 -#define ALLOC_CONSTRAINTS 9 -#define ALLOC_USERTREE 10 -#define ALLOC_SUMTPARAMS 11 -#define ALLOC_TERMSTATE 12 -#define ALLOC_ISPARTAMBIG 13 -#define ALLOC_AVAILNODES 25 -#define ALLOC_AVAILINDICES 26 -#define ALLOC_CURLNL 28 -#define ALLOC_CURLNPR 29 -#define ALLOC_CHAINID 30 -#define ALLOC_PARAMS 31 -#define ALLOC_TREE 32 -#define ALLOC_NODES 33 -#define ALLOC_LOCTAXANAMES 34 -#define ALLOC_COMPMATRIX 39 -#define ALLOC_NUMSITESOFPAT 40 -#define ALLOC_COMPCOLPOS 41 -#define ALLOC_COMPCHARPOS 42 -#define ALLOC_ORIGCHAR 43 -#define ALLOC_PARAMVALUES 46 -#define ALLOC_MCMCTREES 47 -#define ALLOC_MOVES 48 -#define ALLOC_PRELIKES 52 -#define ALLOC_SITEJUMP 54 -#define ALLOC_MARKOVTIS 55 -#define ALLOC_RATEPROBS 56 -#define ALLOC_STDTYPE 57 -#define ALLOC_PACKEDTREES 58 -#define ALLOC_SUMPSTRING 62 -#define ALLOC_SUMPINFO 63 -#define ALLOC_SWAPINFO 64 -#define ALLOC_SYMPIINDEX 65 -#define ALLOC_POSSELPROBS 66 -#define ALLOC_PBF 68 -#define ALLOC_LOCALTAXONCALIBRATION 69 -#define ALLOC_SPR_PARSSETS 72 -#define ALLOC_PFCOUNTERS 74 -#define ALLOC_FILEPOINTERS 75 -#define ALLOC_STATS 76 -#define ALLOC_DIAGNTREE 77 -#define ALLOC_USEDMOVES 82 -#define ALLOC_MODEL 83 -#define ALLOC_STDSTATEFREQS 84 -#define ALLOC_PRINTPARAM 85 -#define ALLOC_TREELIST 86 -#define ALLOC_TFILEPOS 87 -#define ALLOC_BEST 88 -#define ALLOC_SPECIESPARTITIONS 89 -#define ALLOC_SS 90 -#define ALLOC_SAMPLEFOSSILSLICE 91 - -#define LINKED 0 -#define UNLINKED 1 - -/*paramType*/ -#define NUM_LINKED 31 -#define P_TRATIO 0 -#define P_REVMAT 1 -#define P_OMEGA 2 -#define P_PI 3 -#define P_SHAPE 4 -#define P_PINVAR 5 -#define P_CORREL 6 -#define P_SWITCH 7 -#define P_RATEMULT 8 -#define P_TOPOLOGY 9 -#define P_BRLENS 10 -#define P_SPECRATE 11 -#define P_EXTRATE 12 -#define P_FOSLRATE 13 -#define P_POPSIZE 14 -#define P_AAMODEL 15 -#define P_BRCORR 16 -#define P_BRSIGMA 17 -#define P_GROWTH 18 -#define P_CPPMULTDEV 19 -#define P_CPPRATE 20 -#define P_CPPEVENTS 21 -#define P_TK02VAR 22 -#define P_TK02BRANCHRATES 23 -#define P_IGRVAR 24 -#define P_IGRBRANCHRATES 25 -#define P_CLOCKRATE 26 -#define P_SPECIESTREE 27 -#define P_GENETREERATE 28 -#define P_MIXEDVAR 29 -#define P_MIXEDBRCHRATES 30 -/* NOTE: If you add another parameter, change NUM_LINKED */ - -// #define CPPm 0 /* CPP rate multipliers */ -// #define CPPi 1 /* CPP independent rates */ -#define RCL_TK02 0 -#define RCL_IGR 1 /* type of mixed relaxed clock model */ - -#define MAX_NUM_USERTREES 200 /* maximum number of user trees MrBayes will read */ -#define MAX_CHAINS 256 /* maximum numbder of chains you can run actually only half of it becouse of m->lnLike[MAX_CHAINS] */ - -// #define PARAM_NAME_SIZE 400 - -typedef void * VoidPtr; -typedef int (*CmdFxn)(void); -typedef int (*ParmFxn)(char *, char *); - -/* typedef for a ln prior prob fxn */ -typedef MrBFlt (*LnPriorProbFxn)(MrBFlt val, MrBFlt *priorParams); - -/* typedef for a ln prior prob ratio fxn */ -typedef MrBFlt (*LnPriorRatioFxn)(MrBFlt newVal, MrBFlt oldVal, MrBFlt *priorParams); - -typedef struct - { - MrBFlt sum; /* sum of standard deviations */ - MrBFlt max; /* maximum standard deviation */ - MrBFlt numPartitions; - MrBFlt numSamples; - MrBFlt avgStdDev; - MrBFlt **pair; - } STATS; - -/* enumeration for calibration prior type */ -enum CALPRIOR - { - unconstrained, - fixed, - uniform, - offsetExponential, - truncatedNormal, - logNormal, - offsetLogNormal, - standardGamma, - offsetGamma - }; - -enum ConstraintType - { - PARTIAL, - NEGATIVE, - HARD - }; - -/* typedef for calibration */ -typedef struct calibration - { - char name[100]; - enum CALPRIOR prior; - MrBFlt priorParams[3]; - LnPriorProbFxn LnPriorProb; - LnPriorRatioFxn LnPriorRatio; - MrBFlt min; - MrBFlt max; - } - Calibration; - -/* typedef for tree (topology) list element */ -typedef struct element - { - struct element *next; - int *order; - } TreeListElement; - -/* typedef for list of trees (topologies) */ -typedef struct - { - TreeListElement *first; - TreeListElement *last; - } TreeList; - -/* typedef for packed tree */ -typedef struct - { - int *order; - MrBFlt *brlens; - } PackedTree; - -/* typedef for binary tree node */ -/* NOTE: Any variable added here must also be copied in CopyTrees */ -typedef struct node - { - char *label; /*!< name of node if tip */ - struct node *left, *right, *anc; /*!< pointers to adjacent nodes */ - int memoryIndex; /*!< memory index (do not change) */ - int index; /*!< index to node (0 to numLocalTaxa for tips) */ - int upDateCl; /*!< cond likes need update? */ - int upDateTi; /*!< transition probs need update? */ - int scalerNode; /*!< is node scaling cond likes? */ - int isLocked; /*!< is node locked? */ - int lockID; /*!< id of lock */ - int isDated; /*!< is node dated (calibrated)? */ - int marked, x, y; /*!< scratch variables */ - MrBFlt d; /*!< scratch variable */ - BitsLong *partition; /*!< pointer to bitfield describing splits */ - MrBFlt length; /*!< length of pending branch */ - MrBFlt nodeDepth; /*!< node depth (height) */ - MrBFlt age; /*!< age of node */ - Calibration *calibration; /*!< pointer to calibration data */ - } - TreeNode; - -/* typedef for binary tree */ -typedef struct - { - char name[100]; /*!< name of tree */ - int memNodes; /*!< number of allocated nodes (do not exceed!) */ - int nNodes; /*!< number of nodes in tree (including lower root in rooted trees) */ - int nIntNodes; /*!< number of interior nodes in tree (excluding lower root in rooted trees) */ - int isRooted; /*!< is tree rooted? */ - int isClock; /*!< is tree clock? */ - int isCalibrated; /*!< is tree calibrated? */ - int nRelParts; /*!< number of relevant partitions */ - int *relParts; /*!< pointer to relevant partitions */ - int checkConstraints; /*!< does tree have constraints? */ - int nConstraints; /*!< number of constraints */ - int *constraints; /*!< pointer to constraints */ - int nLocks; /*!< number of constrained (locked) nodes */ - TreeNode **allDownPass; /*!< downpass array of all nodes */ - TreeNode **intDownPass; /*!< downpass array of interior nodes (including upper but excluding lower root in rooted trees) */ - TreeNode *root; /*!< pointer to root (lower root in rooted trees) */ - TreeNode *nodes; /*!< array containing the nodes */ - BitsLong *bitsets; /*!< pointer to bitsets describing splits */ - BitsLong *flags; /*!< pointer to cond like flags */ - int fromUserTree; /*!< YES is set for the trees whoes branch lengthes are set from user tree(as start tree or fix branch length prior), NO otherwise */ - } - Tree; - -/* typedef for node in polytomous tree */ -typedef struct pNode - { - char label[100]; /*!< name of node if terminal */ - struct pNode *left, *sib, *anc; /*!< pointers to adjacent nodes */ - int x, y, mark; /*!< scratch variables */ - int partitionIndex; /*!< partition index in sumt (scratch) */ - int index; /*!< index of node (if < numLocalTaxa = local taxon index) */ - int memoryIndex; /*!< immutable index of memory position */ - int isLocked; /*!< is the node locked? */ - int lockID; /*!< id of lock */ - int isDated; /*!< is node dated? */ - MrBFlt length; /*!< age of node */ - MrBFlt depth; /*!< depth (height) of node */ - MrBFlt age; /*!< age of node */ - MrBFlt support, f; /*!< scratch variables */ - BitsLong *partition; /*!< pointer to partition (split) bitset */ - Calibration *calibration; /*!< pointer to dating of node */ - } - PolyNode; - -/* typedef for polytomous tree */ -typedef struct - { - char name[100]; /*!< name of tree */ - int memNodes; /*!< number of allocated nodes; do not exceed! */ - int nNodes; /*!< number of nodes in tree */ - int nIntNodes; /*!< number of interior nodes in tree */ - PolyNode **allDownPass; /*!< downpass array over all nodes */ - PolyNode **intDownPass; /*!< downpass array over interior nodes */ - PolyNode *root; /*!< pointer to root (lower for rooted trees */ - PolyNode *nodes; /*!< array holding the tree nodes */ - BitsLong *bitsets; /*!< bits describing partitions (splits) */ - int nBSets; /*!< number of effective branch length sets */ - int nESets; /*!< number of breakpoint rate sets */ - char **bSetName; /*!< names of effective branch length sets */ - char **eSetName; /*!< names of breakpoint rate sets */ - int **nEvents; /*!< number of branch events of bp rate set */ - MrBFlt ***position; /*!< position of branch events */ - MrBFlt ***rateMult; /*!< parameter of branch events */ - MrBFlt **effectiveBrLen; /*!< effective branch lengths of ebl set */ - int brlensDef; /*!< are brlens defined ? */ - int isRooted; /*!< is tree rooted? */ - int isClock; /*!< is tree clock? */ - int isCalibrated; /*!< is tree calibrated? */ - int isRelaxed; /*!< is tree relaxed? */ - MrBFlt clockRate; /*!< clock rate */ - int popSizeSet; /*!< does tree have a population size set? */ - MrBFlt *popSize; /*!< the population size */ - char *popSizeSetName; /*!< name of the population size set */ - } - PolyTree; - -/* struct for holding model parameter info for the mcmc run */ -typedef struct param - { - int index; /* index to the parameter (0, 1, 2, ...) */ - int paramType; /* the type of the parameter */ - int paramId; /* unique ID for parameter x prior combination */ - MrBFlt *values; /* main values of parameter */ - MrBFlt *subValues; /* subvalues of parameter */ - int *intValues; /* integer values (model index/growth fxn) */ - int nValues; /* number of values */ - int nSubValues; /* number of subvalues */ - int nIntValues; /* number of intvalues */ - MrBFlt min; /* minimum value of parameter */ - MrBFlt max; /* maximum value of parameter */ - int *relParts; /* pointer to relevant divisions */ - int nRelParts; /* number of relevant divisions */ - int upDate; /* update flag (for copying) */ - struct param **subParams; /* pointers to subparams (for topology) */ - int nSubParams; /* number of subparams */ - Tree **tree; /* pointer to tree ptrs (for brlens & topology) */ - int treeIndex; /* index to first tree in mcmcTree */ - int hasBinaryStd; /* has binary standard chars */ - int *sympiBsIndex; /* pointer to sympi bsIndex (std chars) */ - int *sympinStates; /* pointer to sympi nStates (std chars) */ - int *sympiCType; /* pointer to sympi cType (std chars) */ - int nSympi; /* number of sympis */ - int printParam; /* whether parameter should be printed */ - int nPrintSubParams; /* number of subparams that should be printed */ - char *paramHeader; /* a string holding header for param values */ - char *name; /* string holding name of parameter */ - char *paramTypeName; /* pointer to description of parameter type */ - int checkConstraints; /* is tree parameter constrained? */ - int fill; /* flags whether the parameter should be filled */ - int nStdStateFreqs; /* number of std state frequencies */ - MrBFlt *stdStateFreqs; /* pointer to std state frequencies */ - int **nEvents; /* number of branch events for Cpp model */ - /* nEvents[0..2*numCains][0..numNodes=2*numTaxa] */ - MrBFlt ***position; /* event positions for Cpp relaxed clock model */ - MrBFlt ***rateMult; /* rate multipliers for Cpp relaxed clock model */ - int affectsLikelihood; /* does parameter directly influence likelihood? */ - MrBFlt* priorParams; /* pointer to the prior parameters */ - LnPriorProbFxn LnPriorProb; /* ln prior prob function */ - LnPriorRatioFxn LnPriorRatio; /* ln prior prob ratio function */ - } Param; - -#if defined(THREADS_ENABLED) -#include - -typedef struct s_launch_struct - { - int chain; - int division; - MrBFlt* lnL; - } LaunchStruct; -#endif - -/* parameter ID values */ -/* identifies unique model parameter x prior combinations */ -#define TRATIO_DIR 1 -#define TRATIO_FIX 2 -#define REVMAT_DIR 3 -#define REVMAT_FIX 4 -#define OMEGA_DIR 5 -#define OMEGA_FIX 6 -#define SYMPI_UNI 7 -#define SYMPI_UNI_MS 8 -#define SYMPI_EXP 9 -#define SYMPI_EXP_MS 10 -#define SYMPI_FIX 11 -#define SYMPI_FIX_MS 12 -#define SYMPI_EQUAL 13 -#define PI_DIR 14 -#define PI_USER 15 -#define PI_EMPIRICAL 16 -#define PI_EQUAL 17 -#define PI_FIXED 18 -#define SHAPE_UNI 19 -#define SHAPE_EXP 20 -#define SHAPE_FIX 21 -#define PINVAR_UNI 22 -#define PINVAR_FIX 23 -#define CORREL_UNI 24 -#define CORREL_FIX 25 -#define SWITCH_UNI 26 -#define SWITCH_EXP 27 -#define SWITCH_FIX 28 -#define RATEMULT_DIR 29 -#define RATEMULT_FIX 30 -#define TOPOLOGY_NCL_UNIFORM 31 -#define TOPOLOGY_NCL_CONSTRAINED 32 -#define TOPOLOGY_NCL_FIXED 33 -#define TOPOLOGY_NCL_UNIFORM_HOMO 34 -#define TOPOLOGY_NCL_UNIFORM_HETERO 35 -#define TOPOLOGY_NCL_CONSTRAINED_HOMO 36 -#define TOPOLOGY_NCL_CONSTRAINED_HETERO 37 -#define TOPOLOGY_NCL_FIXED_HOMO 38 -#define TOPOLOGY_NCL_FIXED_HETERO 39 -#define TOPOLOGY_CL_UNIFORM 40 -#define TOPOLOGY_CL_CONSTRAINED 41 -#define TOPOLOGY_CL_FIXED 42 -#define TOPOLOGY_CCL_UNIFORM 43 -#define TOPOLOGY_CCL_CONSTRAINED 44 -#define TOPOLOGY_CCL_FIXED 45 -#define TOPOLOGY_PARSIMONY_UNIFORM 46 -#define TOPOLOGY_PARSIMONY_CONSTRAINED 47 -#define TOPOLOGY_PARSIMONY_FIXED 48 -#define BRLENS_UNI 49 -#define BRLENS_EXP 50 -#define BRLENS_GamDir 51 -#define BRLENS_iGmDir 52 -#define BRLENS_twoExp 53 -#define BRLENS_FIXED 54 -#define BRLENS_CLOCK_UNI 55 -#define BRLENS_CLOCK_COAL 56 -#define BRLENS_CLOCK_BD 57 -#define BRLENS_CLOCK_FIXED 58 -#define BRLENS_CLOCK_SPCOAL 59 -#define BRLENS_CLOCK_FOSSIL 60 -#define BRLENS_PARSIMONY 61 -#define SPECRATE_UNI 62 -#define SPECRATE_EXP 63 -#define SPECRATE_FIX 64 -#define EXTRATE_BETA 65 -#define EXTRATE_FIX 66 -#define FOSLRATE_BETA 67 -#define FOSLRATE_FIX 68 -#define POPSIZE_UNI 69 -#define POPSIZE_GAMMA 70 -#define POPSIZE_FIX 71 -#define POPSIZE_NORMAL 72 -#define POPSIZE_LOGNORMAL 73 -#define AAMODEL_FIX 74 -#define AAMODEL_MIX 75 -#define GROWTH_UNI 76 -#define GROWTH_EXP 77 -#define GROWTH_FIX 78 -#define GROWTH_NORMAL 79 -#define OMEGA_BUD 80 -#define OMEGA_BUF 81 -#define OMEGA_BED 82 -#define OMEGA_BEF 83 -#define OMEGA_BFD 84 -#define OMEGA_BFF 85 -#define OMEGA_FUD 86 -#define OMEGA_FUF 87 -#define OMEGA_FED 88 -#define OMEGA_FEF 89 -#define OMEGA_FFD 90 -#define OMEGA_FFF 91 -#define OMEGA_ED 92 -#define OMEGA_EF 93 -#define OMEGA_FD 94 -#define OMEGA_FF 95 -#define OMEGA_10UUB 96 -#define OMEGA_10UUF 97 -#define OMEGA_10UEB 98 -#define OMEGA_10UEF 99 -#define OMEGA_10UFB 100 -#define OMEGA_10UFF 101 -#define OMEGA_10EUB 102 -#define OMEGA_10EUF 103 -#define OMEGA_10EEB 104 -#define OMEGA_10EEF 105 -#define OMEGA_10EFB 106 -#define OMEGA_10EFF 107 -#define OMEGA_10FUB 108 -#define OMEGA_10FUF 109 -#define OMEGA_10FEB 110 -#define OMEGA_10FEF 111 -#define OMEGA_10FFB 112 -#define OMEGA_10FFF 113 -#define CPPRATE_FIX 114 -#define CPPRATE_EXP 115 -#define CPPMULTDEV_FIX 116 -#define TK02VAR_FIX 117 -#define TK02VAR_EXP 118 -#define TK02VAR_UNI 119 -#define TOPOLOGY_RCL_UNIFORM 120 -#define TOPOLOGY_RCL_CONSTRAINED 121 -#define TOPOLOGY_RCL_FIXED 122 -#define TOPOLOGY_RCCL_UNIFORM 123 -#define TOPOLOGY_RCCL_CONSTRAINED 124 -#define TOPOLOGY_RCCL_FIXED 125 -#define TOPOLOGY_SPECIESTREE 126 -#define CPPEVENTS 127 -#define TK02BRANCHRATES 128 -#define TOPOLOGY_FIXED 129 -#define IGRVAR_FIX 130 -#define IGRVAR_EXP 131 -#define IGRVAR_UNI 132 -#define IGRBRANCHRATES 133 -#define CLOCKRATE_FIX 134 -#define CLOCKRATE_NORMAL 135 -#define CLOCKRATE_LOGNORMAL 136 -#define CLOCKRATE_GAMMA 137 -#define CLOCKRATE_EXP 138 -#define SPECIESTREE_UNIFORM 139 -#define GENETREERATEMULT_DIR 140 -#define GENETREERATEMULT_FIX 141 -#define REVMAT_MIX 142 -#define MIXEDVAR_FIX 143 -#define MIXEDVAR_EXP 144 -#define MIXEDVAR_UNI 145 -#define MIXEDBRCHRATES 146 - -#if defined (BEAGLE_ENABLED) -#define MB_BEAGLE_SCALE_ALWAYS 0 -#define MB_BEAGLE_SCALE_DYNAMIC 1 -#if defined (_DEBUG) -#define MB_PRINT_DYNAMIC_RESCALE_FAIL_STAT -#endif -#endif - -/* typedef for a MoveFxn */ -typedef int (MoveFxn)(Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp); - -/* typedef for an ApplicFxn */ -typedef int (ApplicFxn)(Param *param); - -/* typedef for an AutotuneFxn */ -typedef void (AutotuneFxn)(MrBFlt acceptanceRate, MrBFlt targetRate, int batch, MrBFlt *tuningParameter, MrBFlt minTuning, MrBFlt maxTuning); - -/* struct holding info on each move type that the program handles */ -typedef struct - { - MoveFxn *moveFxn; /* pointer to the move function */ - ApplicFxn *isApplicable; /* pointer to function determining whether move is applicable to a parameter */ - int nApplicable; /* number of relevant params */ - int applicableTo[40]; /* pointer to ID of relevant params */ - char *name; /* name of the move type */ - char *shortName; /* abbreviated name of the move type */ - char *paramName; /* name of subparameter if complex parameter */ - int subParams; /* are we changing subparams (brlens of topol.) */ - char *tuningName[5]; /* name of tuning params */ - char *shortTuningName[5];/* short name of tuning params */ - MrBFlt relProposalProb; /* default relative proposal probability */ - int numTuningParams; /* number of tuning parameters */ - MrBFlt tuningParam[5]; /* default tuning parameters for the proposal */ - MrBFlt minimum[5]; /* minimum values for tuning params */ - MrBFlt maximum[5]; /* maximum values for tuning params */ - int parsimonyBased; /* this move is based on parsimony (YES/NO) */ - int level; /* user level of this move */ - AutotuneFxn *Autotune; /* pointer to the autotuning function */ - MrBFlt targetRate; /* default target acceptance rate for autotuning */ - } MoveType; - -/* max number of move types */ -#define NUM_MOVE_TYPES 100 - -/* struct holding info on each move */ -/* Note: This allows several different moves to affect the same parameter */ -/* It also allows the same move to affect different parameters as before */ -/* This is also a good place to keep the proposal probs */ -typedef struct - { - char *name; /* name of the move */ - MoveType *moveType; /* pointer to the move type */ - MoveFxn *moveFxn; /* pointer to the move function */ - Param *parm; /* ptr to parameter the move applies to */ - MrBFlt *relProposalProb; /* the relative proposal probability */ - MrBFlt *cumProposalProb; /* the cumulative proposal probability */ - int *nAccepted; /* number of accepted moves */ - int *nTried; /* number of tried moves */ - int *nBatches; /* counter for autotuning rounds */ - int *nTotAccepted; /* total number of accepted moves */ - int *nTotTried; /* total number of tried moves */ - MrBFlt *targetRate; /* target acceptance rate for autotuning */ - MrBFlt *lastAcceptanceRate;/* acceptance rate in last complete batch */ - MrBFlt **tuningParam; /* tuning parameters for the move */ - } MCMCMove; - -typedef int (*LikeDownFxn)(TreeNode *, int, int); -typedef int (*LikeRootFxn)(TreeNode *, int, int); -typedef int (*LikeScalerFxn)(TreeNode *, int, int); -typedef int (*LikeFxn)(TreeNode *, int, int, MrBFlt *, int); -typedef int (*TiProbFxn)(TreeNode *, int, int); -typedef int (*LikeUpFxn)(TreeNode *, int, int); -typedef int (*PrintAncStFxn)(TreeNode *, int, int); -typedef int (*StateCodeFxn) (int); -typedef int (*PrintSiteRateFxn) (TreeNode *, int, int); -typedef int (*PosSelProbsFxn) (TreeNode *, int, int); -typedef int (*SiteOmegasFxn) (TreeNode *, int, int); - -typedef struct cmdtyp - { - int cmdNumber; - char *string; - int specialCmd; - CmdFxn cmdFxnPtr; - short numParms; - short parmList[50]; - int expect; - char *cmdDescription; - int cmdUse; - int hiding; - } - CmdType; - -typedef struct parm - { - char *string; /* parameter name */ - char *valueList; /* list of values that could be input */ - ParmFxn fp; /* function pointer */ - } - ParmInfo, *ParmInfoPtr; - -typedef struct model - { - int dataType; /* data type for partition */ - int nStates; /* number of states for this type of data */ - int codon[64]; /* gives protein ID for each codon */ - int codonNucs[64][3]; /* gives triplet for each codon */ - int codonAAs[64]; /* gives protein ID for implemented code */ - - char nucModel[100]; /* nucleotide model used */ - char nst[100]; /* number of substitution types */ - char parsModel[100]; /* use the (so-called) parsimony model */ - char geneticCode[100]; /* genetic code used */ - char coding[100]; /* type of patterns encoded */ - char ploidy[100]; /* ploidy level */ - char omegaVar[100]; /* type of omega variation model */ - char ratesModel[100]; /* rates across sites model */ - int numGammaCats; /* number of categories for gamma approximation */ - char useGibbs[100]; /* flags whether Gibbs sampling of discrete gamma is used */ - int gibbsFreq; /* frequency of Gibbs resampling of discrete gamma */ - - int numBetaCats; /* number of categories for beta approximation */ - int numM10GammaCats; /* number of cats for gamma approx (M10 model) */ - int numM10BetaCats; /* number of cats for beta approx (M10 model) */ - char covarionModel[100];/* use covarion model? (yes/no) */ - char augmentData[100]; /* should data be augmented */ - - char tRatioPr[100]; /* prior for ti/tv rate ratio */ - MrBFlt tRatioFix; - MrBFlt tRatioDir[2]; - char revMatPr[100]; /* prior for GTR model */ - MrBFlt revMatFix[6]; - MrBFlt revMatDir[6]; - MrBFlt revMatSymDir; /* prior for mixed GTR subspace model */ - char aaModelPr[100]; /* prior for amino acid model */ - char aaModel[100]; - MrBFlt aaModelPrProbs[10]; - char aaRevMatPr[100]; /* prior for aa GTR model */ - MrBFlt aaRevMatFix[190]; - MrBFlt aaRevMatDir[190]; - char omegaPr[100]; /* prior for omega */ - MrBFlt omegaFix; - MrBFlt omegaDir[2]; - char ny98omega1pr[100]; /* prior for class 1 omega (Ny98 model) */ - MrBFlt ny98omega1Fixed; - MrBFlt ny98omega1Beta[2]; - char ny98omega3pr[100]; /* prior for class 3 omega (Ny98 model) */ - MrBFlt ny98omega3Fixed; - MrBFlt ny98omega3Uni[2]; - MrBFlt ny98omega3Exp; - char m3omegapr[100]; /* prior for all three omegas (M3 model) */ - MrBFlt m3omegaFixed[3]; - char m10betapr[100]; /* prior for omega variation (M10 model) */ - char m10gammapr[100]; - MrBFlt m10betaExp; - MrBFlt m10betaUni[2]; - MrBFlt m10betaFix[2]; - MrBFlt m10gammaExp; - MrBFlt m10gammaUni[2]; - MrBFlt m10gammaFix[2]; - char codonCatFreqPr[100]; /* prior for selection cat frequencies */ - MrBFlt codonCatFreqFix[3]; - MrBFlt codonCatDir[3]; - char stateFreqPr[100]; /* prior for character state frequencies */ - MrBFlt stateFreqsFix[200]; - MrBFlt stateFreqsDir[200]; - char stateFreqsFixType[100]; - int numDirParams; - char shapePr[100]; /* prior for gamma shape parameter */ - MrBFlt shapeFix; - MrBFlt shapeUni[2]; - MrBFlt shapeExp; - char pInvarPr[100]; /* prior for proportion of invariable sites */ - MrBFlt pInvarFix; - MrBFlt pInvarUni[2]; - char adGammaCorPr[100]; /* prior for correlation param of adGamma model */ - MrBFlt corrFix; - MrBFlt corrUni[2]; - char covSwitchPr[100]; /* prior for switching rates of covarion model */ - MrBFlt covswitchFix[2]; - MrBFlt covswitchUni[2]; - MrBFlt covswitchExp; - char symPiPr[100]; /* prior for pi when unidentifiable states used */ - MrBFlt symBetaFix; - MrBFlt symBetaUni[2]; - MrBFlt symBetaExp; - char ratePr[100]; /* prior on rate for a partition */ - MrBFlt ratePrDir; - char generatePr[100]; /* prior on rate for a gene (one or more partitions) */ - MrBFlt generatePrDir; - char brownCorPr[100]; /* prior for correlation of Brownian model */ - MrBFlt brownCorrFix; - MrBFlt brownCorrUni[2]; - char brownScalesPr[100]; /* prior for scales of Brownian model */ - MrBFlt brownScalesFix; - MrBFlt brownScalesUni[2]; - MrBFlt brownScalesGamma[2]; - MrBFlt brownScalesGammaMean; - - char topologyPr[100]; /* prior for tree topology */ - int topologyFix; /* user tree index for fixed topology */ - int *activeConstraints; /* which constraints are active? */ - int numActiveConstraints; - int numActiveLocks; - char brlensPr[100]; /* prior on branch lengths */ - int brlensFix; /* user tree index for fixed brlens */ - MrBFlt brlensUni[2]; - MrBFlt brlensExp; - MrBFlt brlens2Exp[2]; - MrBFlt brlensDir[4]; - MrBFlt brlensGamma[2]; - char speciesTreeBrlensPr[100]; /* prior on branch lengths of species tree */ - char unconstrainedPr[100]; /* prior on branch lengths if unconstrained */ - char clockPr[100]; /* prior on branch if clock enforced */ - char clockVarPr[100]; /* prior on clock rate variation (strict, cpp, tk02, igr, ...) */ - char nodeAgePr[100]; /* prior on node depths (unconstrained, constraints) */ - char speciationPr[100]; /* prior on speciation rate (net diversification) */ - MrBFlt speciationFix; - MrBFlt speciationUni[2]; - MrBFlt speciationExp; - char extinctionPr[100]; /* prior on relative extinction rate (turnover) */ - MrBFlt extinctionFix; - MrBFlt extinctionBeta[2]; - char fossilizationPr[100]; /* prior on fossilization rate (sampling proportion) */ - MrBFlt fossilizationFix; - MrBFlt fossilizationBeta[2]; - char sampleStrat[100]; /* taxon sampling strategy (for b-d process) */ - int sampleFSNum; /* number of fossil slice sampling events (s) */ - MrBFlt *sampleFSTime; /* fossil slice sampling times (t_i, i=1,..,s) */ - MrBFlt *sampleFSProb; /* fossil slice sampling probs (rho_i, i=1,..,s) */ - MrBFlt sampleProb; /* extant taxon sampling fraction (rho) */ - Calibration treeAgePr; /* prior on tree age for uniform clock trees */ - char clockRatePr[100]; /* prior on base substitution rate of tree for clock trees */ - MrBFlt clockRateNormal[2]; - MrBFlt clockRateLognormal[2]; - MrBFlt clockRateGamma[2]; - MrBFlt clockRateExp; - MrBFlt clockRateFix; - char popSizePr[100]; /* prior on population size */ - MrBFlt popSizeFix; - MrBFlt popSizeUni[2]; - MrBFlt popSizeLognormal[2]; - MrBFlt popSizeGamma[2]; - MrBFlt popSizeNormal[2]; - char popVarPr[100]; /* prior on pop. size variation across tree */ - char growthPr[100]; /* prior on coalescence growth rate */ - MrBFlt growthFix; - MrBFlt growthUni[2]; - MrBFlt growthExp; - MrBFlt growthNorm[2]; - char cppRatePr[100]; /* prior on CPP rate */ - MrBFlt cppRateFix; - MrBFlt cppRateExp; - char cppMultDevPr[100]; /* prior on CPP rate multiplier Lognormal variance */ - MrBFlt cppMultDevFix; - char tk02varPr[100]; /* prior on TK02 lognormal rate variance */ - MrBFlt tk02varFix; - MrBFlt tk02varUni[2]; - MrBFlt tk02varExp; - char igrvarPr[100]; /* prior on IGR gamma distribution variance */ - MrBFlt igrvarFix; - MrBFlt igrvarUni[2]; - MrBFlt igrvarExp; - char mixedvarPr[100]; /* prior on mixed relaxed clock rate variance */ - MrBFlt mixedvarFix; - MrBFlt mixedvarUni[2]; - MrBFlt mixedvarExp; - - char tratioFormat[30]; /* format used to report tratio */ - char revmatFormat[30]; /* format used to report revmat */ - char ratemultFormat[30]; /* format used to report ratemult */ - char treeFormat[30]; /* format used to report trees/topologies */ - char inferAncStates[5]; /* should ancestral states be inferred (Yes/No)? */ - char inferSiteOmegas[5]; /* should site omega vals be inferred (Yes/No)? */ - char inferSiteRates[5]; /* should site rates be inferred (Yes/No)? */ - char inferPosSel[5]; /* should site selection be inferred (Yes/No)? */ - } Model, ModelParams; - -typedef struct chain - { - int numGen; /* number of MCMC cycles */ - int sampleFreq; /* frequency to sample chain */ - int printFreq; /* frequency to print chain */ - int swapFreq; /* frequency to attempt swap of states */ - int numRuns; /* number of runs */ - int numChains; /* number of chains */ - int isSS; /* do we do Steppingstone Sampling */ - int startFromPriorSS; /* If Yes SS is moving from Prior to Posterior */ - int numStepsSS; /* Number of steps in SS */ - int burninSS; /* Fixed burnin for SS */ - MrBFlt alphaSS; /* Beta values are distributed according to quantiles of Beta(alphaSS,1.0) distribution */ - int backupCheckSS; /* Frequency of checkpoints backup */ - MrBFlt chainTemp; /* chain temperature */ - int userDefinedTemps; /* should we use the users temperatures? */ - MrBFlt userTemps[MAX_CHAINS]; /* user-defined chain temperatures */ - char chainFileName[100]; /* chain file name for output */ - int chainBurnIn; /* chain burn in length */ - int numStartPerts; /* number of perturbations to starting tree */ - char startTree[100]; /* starting tree for chain (current/random) */ - char startParams[100]; /* starting values for chain (current/reset) */ - int saveBrlens; /* should branch lengths be saved */ - MrBFlt weightScheme[3]; /* percent chars to increase/decrease in weight */ - int calcPbf; /* should we calculate the pseudo Bayes factor */ - int pbfInitBurnin; /* initial burnin when calculating pseudo BF */ - int pbfSampleFreq; /* sample frequency for pseudo BF */ - int pbfSampleTime; /* how many cycles to calcualate site prob. */ - int pbfSampleBurnin; /* burnin period for each site for pseudo BF */ - int swapAdjacentOnly; /* whether we only swap adjacent temperatures */ - int redirect; /* should output go to stdout */ - int allChains; /* should stats be output for all chains? */ - int numSwaps; /* number of swaps to try each time */ - int mcmcDiagn; /* should mcmc diagnostics be output? */ - int diagnFreq; /* mcmc diagnostics frequency */ - int diagnStat; /* statistic to use for mcmc diagnostics */ - int relativeBurnin; /* should a relative burnin be used ? */ - MrBFlt burninFraction; /* the sample fraction to discard as burnin */ - int allComps; /* top conv diagnosis for all pairs? */ - MrBFlt minPartFreq; /* minimum partition frequency for conv diagn */ - MrBFlt stopVal; /* top conv diagn value to reach before stopping */ - int stopRule; /* use stop rule? */ - STATS *stat; /* ptr to structs with mcmc diagnostics info */ - Tree *dtree; /* pointing to tree used for conv diagnostics */ - TreeList *treeList; /* vector of tree lists for saving trees */ - int saveTrees; /* save tree samples for later removal? */ - int stopTreeGen; /* generation after which no trees need be saved */ - fpos_t *tFilePos; /* position for reading trees for removal */ - int printMax; /* maximum number of chains to print */ - int printAll; /* whether to print all or only cold chains */ - int checkPoint; /* should we use check-pointing? */ - int checkFreq; /* check-pointing frequency */ - int runWithData; /* should we run with or without data? */ - int orderTaxa; /* order taxa before printing tree to file? */ - int append; /* order taxa before printing tree to file? */ - int autotune; /* autotune tuning parameters of proposals ? */ - int tuneFreq; /* autotuning frequency */ - } Chain; - -typedef struct modelinfo - { - /* General model information */ - int dataType; /* data type for partition */ - int nucModelId; /* structure of nucleotide model */ - int nst; /* # substitution types */ - int aaModelId; /* amino acid model type */ - int parsModelId; /* is parsimony model used YES/NO */ - - /* Specific model information */ - int numGammaCats; /* number of gamma cats (1 if inapplic.) */ - int numBetaCats; /* number of beta cats (1 if inapplic.) */ - int numOmegaCats; /* number of omega cats (1 if inapplic.) */ - int numTiCats; /* number of cats needing different tis */ - int numModelStates; /* number of states including hidden ones */ - int numStates; /* number of observable discrete states */ - - /* Model parameter pointers */ - Param *tRatio; /* ptr to tRatio used in model */ - Param *revMat; /* ptr to revMat used in model */ - Param *omega; /* ptr to omega used in model */ - Param *stateFreq; /* ptr to statFreq used in model */ - Param *shape; /* ptr to shape used in model */ - Param *pInvar; /* ptr to pInvar used in model */ - Param *correlation; /* ptr to correlation used in model */ - Param *switchRates; /* ptr to switchRates (off<->on) */ - Param *rateMult; /* ptr to parition rateMult used in model */ - Param *geneTreeRateMult; /* ptr to gene tree rateMult used in model */ - Param *speciationRates; /* ptr to speciationRates used in model */ - Param *extinctionRates; /* ptr to extinctionRates used in model */ - Param *fossilizationRates; /* ptr to fossilizationRates */ - Param *popSize; /* ptr to population size used in model */ - Param *growthRate; /* ptr to growth rate used in model */ - Param *topology; /* ptr to topology used in model */ - Param *brlens; /* ptr to brlens (and tree) used in model */ - Param *speciesTree; /* ptr to species tree used in model */ - Param *aaModel; /* ptr to amino acid matrix used */ - Param *cppMultDev; /* ptr to cpp ratemult lognormal variance */ - Param *cppRate; /* ptr to CPP rate used in model */ - Param *cppEvents; /* ptr to CPP events */ - Param *tk02var; /* ptr to variance for TK02 relaxed clock */ - Param *tk02BranchRates; /* ptr to branch rates for TK02 relaxed clock */ - Param *igrvar; /* ptr to gamma var for IGR relaxed clock */ - Param *igrBranchRates; /* ptr to branch rates for IGR relaxed clock*/ - Param *mixedvar; /* ptr to var for mixed relaxed clock */ - Param *mixedBrchRates; /* ptr to branch rates for mixed relaxed clock */ - Param *clockRate; /* ptr to clock rate parameter */ - - /* Information about characters and transformations */ - int numChars; /* number of compressed characters */ - int numUncompressedChars; /* number of uncompressed characters */ - int numDummyChars; /* number of dummy characters */ - int compMatrixStart; /* start column in compressed matrix */ - int compMatrixStop; /* stop column in compressed matrix */ - int compCharStart; /* start char among compressed chars */ - int compCharStop; /* stop char among compressed chars */ - int parsMatrixStart; /* start column in parsimony matrix */ - int parsMatrixStop; /* stop collumn in parsimony matrix */ - int nParsIntsPerSite; /* # parsimony ints per character */ - int nCharsPerSite; /* number chars per site (eg 3 for codon) */ - int rateProbStart; /* start of rate probs (for adgamma) */ - - /* Variables for eigen decompositions */ - int cijkLength; /* stores length of cijk vector */ - int nCijkParts; /* stores number of cijk partitions (1 except for omega/covarion models) */ - int upDateCijk; /* whether cijk vector needs to be updated */ - - /* Variables for standard model */ - int *tiIndex; /* index to trans probs for each compressed char*/ - int *bsIndex; /* index to stat freqs for each compressed char */ - int *nStates; /* # states of each compressed char */ - int *cType; /* whether char is ord, unord or irrev */ - int *weight; /* prior weight of each compressed char */ - int isTiNeeded[20]; /* marks whether a trans prob matrix is needed */ - - /* Gibbs sampling of gamma site rate parameters */ - CLFlt ***catLike; /* likelihood for Gibbs sampling of gamma */ - CLFlt ***catLnScaler; /* scaler for Gibbs sampling of gamma */ - int gibbsGamma; /* flags whether Gibbs sampling of discrete gamma is used */ - int gibbsFreq; /* frequency of Gibbs resampling of discrete gamma */ - - /* Variables for parsimony sets and parsimony calculations */ - MrBFlt parsTreeLength[MAX_CHAINS*2]; /* parsimony tree lengths for chains */ - BitsLong **parsSets; /* parsimony sets */ - int numParsSets; /* number of parsimony sets */ - CLFlt *parsNodeLens; /* parsimony node lengths */ - int numParsNodeLens; /* number of parsimony node lengths */ - - /* Miscellaneous parameters */ - int mark; /* scratch parameter */ - int parsimonyBasedMove; /* is parsimony-based move used (YES/NO) */ - - /* Variables for conditional likelihoods */ - int upDateCl; /* flags whether update of cond likes needed */ - int upDateAll; /* flags whether update of entire tree is needed*/ - int *isPartAmbig; /* is tip partially ambiguous? */ - int **termState; /* index arrays for terminal branch shortcuts */ - CLFlt *invCondLikes; /* space for the invariable cond likes */ - CLFlt **condLikes; /* space for the cond likes */ - CLFlt **tiProbs; /* space for the ti probs */ - CLFlt **scalers; /* space for the node and site scalers */ - CLFlt **clP; /* handy pointers to cond likes for ti cats */ -#if defined (SSE_ENABLED) - __m128 **clP_SSE; /* handy pointers to cond likes, SSE version */ - int numSSEChars; /* number of compact SSE character groups */ - CLFlt *lnL_SSE; /* temp storage for log site likes */ - CLFlt *lnLI_SSE; /* temp storage for log site invariable likes */ -#endif - MrBFlt **cijks; /* space for cijks */ - int **condLikeIndex; /* index to cond like space for nodes & chains */ - int *condLikeScratchIndex; /* index to scratch space for node cond likes */ - int **nodeScalerIndex; /* index to scaler space for nodes & chains */ - int *nodeScalerScratchIndex; /* index to scratch space for node scalers */ - int **scalersSet; /* flags whether scalers are set */ - int *scalersSetScratch; /* scratch flag for whether scalers are set */ - int *siteScalerIndex; /* index to site scaler space for chains */ - int siteScalerScratchIndex; /* index to scratch space for site scalers */ - int **tiProbsIndex; /* index to ti probs for branches & chains */ - int *tiProbsScratchIndex; /* index to scratch space for branch ti probs */ - int *cijkIndex; /* index to cijks for chains */ - int cijkScratchIndex; /* index to scratch space for cijks */ - int numCondLikes; /* number of cond like arrays */ - int numScalers; /* number of scaler arrays */ - int numTiProbs; /* number of ti prob arrays */ - int condLikeLength; /* length of cond like array (incl. ti cats) */ - int tiProbLength; /* length of ti prob array */ - MrBFlt lnLike[MAX_CHAINS]; /* log like for chain */ - CLFlt *ancStateCondLikes; /* ancestral state cond like array */ - - /* Likelihood function pointers */ - LikeDownFxn CondLikeDown; /* function for calculating partials */ - LikeRootFxn CondLikeRoot; /* function for calculating partials at root */ - LikeScalerFxn CondLikeScaler; /* function for scaling partials */ - LikeFxn Likelihood; /* function for getting cond likes for tree */ - TiProbFxn TiProbs; /* function for calculating transition probs */ - LikeUpFxn CondLikeUp; /* final-pass calculation of cond likes */ - PrintAncStFxn PrintAncStates; /* function for sampling ancestral states */ - StateCodeFxn StateCode; /* function for getting states from codes */ - PrintSiteRateFxn PrintSiteRates; /* function for samling site rates */ - PosSelProbsFxn PosSelProbs; /* function for sampling pos. selection probs */ - SiteOmegasFxn SiteOmegas; /* function for sampling site omega values */ - - /* Report variables */ - int printAncStates; /* should ancestral states be printed (YES/NO) */ - int printSiteRates; /* should site rates be printed (YES/NO) */ - int printPosSel; /* should selection be printed (YES/NO) */ - int printSiteOmegas; /* should site omegas be printed (YES/NO) */ - - /* likelihood calculator flags */ - int useBeagle; /* use Beagle for this partition? */ - int useSSE; /* use SSE for this partition? */ - -#if defined (BEAGLE_ENABLED) - /* Beagle variables */ - int useBeagleResource; /* try to use this BEAGLE resource number */ - MrBFlt* branchLengths; /* array of branch lengths for Beagle */ - MrBFlt* inRates; /* array of category rates for Beagle */ - int* tiProbIndices; /* array of trans prob indices for Beagle */ - MrBFlt* logLikelihoods; /* array of log likelihoods from Beagle */ - int beagleInstance; /* beagle instance for division */ - MrBFlt* inWeights; /* array of weights for Beagle root likelihood */ - int* bufferIndices; /* array of partial indices for root likelihood */ - int* eigenIndices; /* array of eigen indices for root likelihood */ - int* childBufferIndices; /* array of child partial indices (unrooted) */ - int* childTiProbIndices; /* array of child ti prob indices (unrooted) */ - int* cumulativeScaleIndices; /* array of cumulative scale indices */ - int rescaleBeagleAll; /* set to rescale all nodes */ - int* rescaleFreq; /* rescale frequency for each chain's tree */ - int rescaleFreqOld; /* holds rescale frequency of current state */ - int recalculateScalers; /* shoud we recalculate scalers for current state YES/NO */ - int* succesCount; /* count number of succesful computation since last reset of scalers */ - int** isScalerNode; /* for each node and chain set to YES if scaled node */ - int* isScalerNodeScratch; /* scratch space to hold isScalerNode of proposed state*/ - long* beagleComputeCount; /* count of number of calls to likelihood */ -#endif - - } ModelInfo; - -typedef struct sumt - { - int *absentTaxa; /* information on absent taxa */ - int brlensDef; /* branch lengths defined? */ - char sumtFileName[100]; /* name of input file */ - char sumtOutfile[120]; /* name of output file */ - char curFileName[120]; /* name of file being processed */ - int burnin; /* actual burnin when parsing tree files */ - char sumtConType[100]; /* consensus tree type */ - int calcTreeprobs; /* should the individual tree probs be calculated*/ - int showSumtTrees; /* should the individual tree probs be shown */ - int printBrlensToFile; /* should branch lengths be printed to file */ - MrBFlt brlensFreqDisplay; /* threshold for printing branch lengths to file */ - int numRuns; /* number of independent analyses to summarize */ - int numTrees; /* number of tree params to summarize */ - int orderTaxa; /* order taxa in trees? */ - MrBFlt minPartFreq; /* minimum part. freq. for overall diagnostics */ - int table; /* show table of partition frequencies? */ - int summary; /* show summary diagnostics ? */ - int showConsensus; /* show consensus trees ? */ - int consensusFormat; /* format of consensus tree */ - PolyTree *tree; /* for storing tree read from file */ - int *order; /* for storing topology read from file */ - int orderLen; /* length of order array */ - int numTreesInLastBlock; /* number of trees in last block */ - int numTreesEncountered; /* number of trees encounted in total */ - int numTreesSampled; /* number of sampled trees in total */ - int isRooted; /* is sumt tree rooted ? */ - int isRelaxed; /* is sumt tree a relaxed clock tree ? */ - int isClock; /* is sumt tree a clock tree ? */ - int isCalibrated; /* is sumt tree calibrated ? */ - int nESets; /* number of event sets */ - int nBSets; /* number of branch rate sets */ - char **bSetName; /* name of effective branch length sets */ - char **eSetName; /* name of event sets */ - int popSizeSet; /* do sumt trees have population size set? */ - char *popSizeSetName; /* name of population size set */ - int BitsLongsNeeded; /* number of safe longs needed for taxon bits */ - int runId; /* id of run being processed */ - int numTaxa; /* number of sumt taxa */ - char **taxaNames; /* names of sumt taxa */ - int *numFileTrees; /* number of trees per file */ - int *numFileTreesSampled; /* number of trees sampled per file */ - int HPD; /* use highest posterior density? */ - } Sumt; - -/* formats for consensus trees */ -#define SIMPLE 0 -#define FIGTREE 1 - -typedef struct comptree - { - char comptFileName1[120]; /* name of first input file */ - char comptFileName2[120]; /* name of second input file */ - char comptOutfile[120]; /* name of output file */ - int burnin; /* actual burnin used when parsing tree files */ - MrBFlt minPartFreq; /* use partitions with frequency >= minPartFreq */ - } Comptree; - -typedef struct sump - { - char sumpFileName[100]; /* name of input file */ - char sumpOutfile[120]; /* name of output file */ - //int plot; /* output plot (y/n)? */ - int table; /* output table (y/n)? */ - int margLike; /* output marginal likelihood (y/n)? */ - int numRuns; /* number of independent analyses to summarize */ - int allRuns; /* should data for all runs be printed (yes/no)? */ - int HPD; /* use highest posterior density? */ - MrBFlt minProb; /* cut-off for model probabilities to show */ - } Sump; - -typedef struct sumss - { - //int plot; /* output plot (y/n)? */ - int numRuns; /* number of independent analyses to summarize */ - int allRuns; /* should data for all runs be printed (yes/no)? */ - int stepToPlot; /* Which step to plot in the step plot */ - int askForMorePlots; /* Should user be asked to plot for different discardfraction (y/n)? */ - int smoothing; /* An integer indicating number of neighbors to average over when dooing smoothing of curvs on plots */ - MrBFlt discardFraction; /* Proportion of samples discarded when ploting step plot.*/ - } Sumss; - -typedef struct plot - { - char plotFileName[120]; /* name of input file */ - char parameter[100]; /* parameter(s) to be plotted */ - char match[100]; /* whether the match needs to be perfect */ - } Plot; - -typedef struct - { - int numTrees; /* number of trees to reassemble */ - int numRuns; /* number of runs to reassemble */ - } ReassembleInfo; - -typedef struct doublet - { - BitsLong first, second; - } Doublet; - -typedef struct matrix - { - BitsLong *origin; - int rowSize; - int nRows; - int column; - int row; - } Matrix; - -typedef struct charinfo - { - int dType; - int cType; - int nStates; - int constant[10]; - int variable; - int informative; - } CharInfo; - -typedef struct - { - int isExcluded; /* is the character excluded */ - int numStates; /* number of observed states for the character */ - int charType; /* type of character */ - int isMissAmbig; /* is the character missing or ambiguous */ - int ctype; /* ordering of character */ - int charId; /* char ID index for doublet and codon models */ - int pairsId; /* char ID for doublets */ - int bigBreakAfter; /* is there a large break after this character */ - } - CharInformation; - -typedef struct - { - int isDeleted; /* is the taxon deleted */ - int charCount; /* count holder */ - } - TaxaInformation; - -typedef struct - { - MrBFlt curScore; - MrBFlt minScore; - MrBFlt totalScore; - MrBFlt stopScore; - MrBFlt warp; - TreeNode **leaf; - TreeNode **vertex; - } - TreeInfo; - -typedef struct - { - int allavailable; - } - ShowmovesParams; - -typedef struct - { - int numNames; - char **names; - } - NameSet; - -/* global variables */ -extern int abortMove; /* flag determining whether to abort move */ -extern int *activeParams[NUM_LINKED]; /* a table holding the parameter status */ -extern int *activeParts; /* partitions changes should apply to */ -extern int autoClose; /* autoclose */ -extern int autoOverwrite; /* Overwrite or append outputfiles when nowarnings=yes */ -extern int chainHasAdgamma; /* indicates if chain has adgamma HMMs */ -extern Chain chainParams; /* holds parameters for Markov chain */ -extern CharInformation *charInfo; /* holds critical information about characters */ -extern char **charSetNames; /* holds names of character sets */ -extern int *compCharPos; /* char position in compressed matrix */ -extern int *compColPos; /* column position in compressed matrix */ -extern BitsLong *compMatrix; /* compressed character matrix */ -extern int compMatrixRowSize; /* row size of compressed matrix */ -extern Comptree comptreeParams; /* holds parameters for comparetree command */ -extern char **constraintNames; /* holds names of constraints */ -extern BitsLong **definedConstraint; /* holds information about defined constraints */ -extern BitsLong **definedConstraintTwo; /* bitfields representing second taxa sets of defined constraints (used for PARTIAL constraints) */ -extern BitsLong **definedConstraintPruned; /* bitfields representing taxa sets of defined constraints after delited taxa are removed */ -extern BitsLong **definedConstraintTwoPruned; /* bitfields representing second taxa sets of defined constraints after delited taxa are removed(used for PARTIAL constraints) */ -extern int dataType; /* type of data */ -extern Calibration defaultCalibration; /* default model settings */ -extern ModelParams defaultModel; /* default model settings */ -extern int defChars; /* flag for whether number of characters is known*/ -extern int defMatrix; /* flag for whether matrix is successfull read */ -extern int defPairs; /* flag for whether constraints on tree are read */ -extern int defPartition; /* flag for whether character partition is read */ -extern int defTaxa; /* are taxon labels defined ? */ -extern Doublet doublet[16]; /* holds information on states for doublets */ -extern int echoMB; /* flag used by Manual to prevent echoing */ -extern BitsLong expecting; /* variable denoting expected token type */ -extern int fileNameChanged; /* has file name been changed? */ -extern int foundNewLine; /* whether a new line has been found */ -extern char gapId; /* gap character Id */ -extern RandLong globalSeed; /* seed that is initialized at start up */ -extern char **headerNames; /* string to hold headers in sump and plot */ -extern int inComment; /* flag for whether input stream is commented */ -extern int inferAncStates; /* should ancestral states be inferred (y/n) */ -extern int inferSiteOmegas; /* should site omega values be inferred (y/n) */ -extern int inferSiteRates; /* should site rates be inferred (y/n) */ -extern int inferPosSel; /* should positive selection be inferred (y/n) */ -extern char inputFileName[100]; /* input (NEXUS) file name */ -extern int inTreesBlock; /* are we in the sumt block */ -extern int inValidCommand; /* a useful flag set whenever you enter a cmd */ -extern int isInAmbig, isInPoly; /* flags whether we are within () or {} */ -extern int isMixed; /* flags whether dataset is mixed */ -extern int inMrbayesBlock; /* flag for whether we are in a mrbayes block */ -extern int *intValues; /* integer values of parameters */ -extern int isTaxsetDef; /* is a taxon set defined */ -extern int isTranslateDef; /* is a translation block defined */ -extern int isTranslateDiff; /* is translate different from current taxaset? */ -extern int *linkTable[NUM_LINKED]; /* how parameters are linked across parts */ -extern int localOutGroup; /* outgroup for non-excluded taxa */ -extern char **localTaxonNames; /* points to names of non-excluded taxa */ -extern FILE *logFileFp; /* file pointer to log file */ -extern char logFileName[100]; /* name of the log file */ -extern int logToFile; /* should screen output be logged to a file */ -extern char manFileName[100]; /* name of man file */ -extern char matchId; /* mach character Id */ -extern int *matrix; /* matrix containing original data */ -extern int matrixHasPoly; /* flag for whether matrix has polymorphisms */ -extern int memAllocs[NUM_ALLOCS]; /* allocated memory flags */ -extern int mode; /* mode of program (interactive/noninteractive) */ -extern char **modelIndicatorParams; /* model indicator params */ -extern char ***modelElementNames; /* names for component models */ -extern MCMCMove **moves; /* vector of applicable moves */ -extern MoveType moveTypes[NUM_MOVE_TYPES]; /* holds information on the move types */ -extern char missingId; /* missing character Id */ -extern Tree **mcmcTree; /* pointers to mcmc trees */ -extern Model *modelParams; /* holds model params for partitions */ -extern ModelInfo *modelSettings; /* stores important info on model params */ -extern int nBitsInALong; /* number of bits in a BitsLong */ -extern Calibration *nodeCalibration; /* holds information about node calibrations */ -extern int noWarn; /* no warnings on overwriting files */ -extern int nPThreads; /* number of pthreads to use */ -extern int numActiveLocks; /* number of active, locked nodes */ -extern int numApplicableMoves; /* number of moves applicable to parameters */ -extern int numChar; /* number of characters in character matrix */ -extern int numCharSets; /* holds number of character sets */ -extern int numComments; /* number of nested comments */ -extern int numCompressedChars; /* number of compressed characters */ -extern int numCurrentDivisions; /* number of partitions of data */ -extern int numDefinedConstraints; /* number of constraints defined */ -extern enum ConstraintType *definedConstraintsType; /* Store type of constraint */ -extern int numDefinedPartitions; /* number of partitions defined */ -extern int numDefinedSpeciespartitions; /* number of species partitions defined */ -extern int numGlobalChains; /* number of global chains */ -extern int numLocalTaxa; /* number of non-excluded taxa */ -extern int numLocalChar; /* number of non-excluded characters */ -extern int numMoveTypes; /* the number of move types */ -extern int numOpenExeFiles; /* number of execute files open */ -extern int numParams; /* number of parameters in model */ -extern int numDivisions; /* number of current divisions */ -extern int numPrintParams; /* number of substitution model parameters to print */ -extern int numPrintTreeParams; /* number of tree model parameters to print */ -extern CLFlt *numSitesOfPat; /* no. sites of each pattern */ -extern int numSpecies; /* number of species in current speciespartition */ -extern int numTaxa; /* number of taxa in character matrix */ -extern int numTaxaSets; /* holds number of taxa sets */ -extern int numTopologies; /* number of topologies for one chain and state */ -extern int numTranslates; /* number of taxa in active translate block */ -extern int numTrees; /* number of trees for one chain and state */ -extern int numUserTrees; /* number of defined user trees */ -extern int *numVars; /* number of variables in setting arrays */ -extern int *origChar; /* index from compressed char to original char */ -extern int outGroupNum; /* number of outgroup taxon */ -extern ParmInfo paramTable[]; /* information on parameters */ -extern MrBFlt *paramValues; /* values of parameters */ -extern int **partitionId; /* holds information about defined partitions */ -extern char **partitionNames; /* hold names of partitions (first is "default") */ -extern MrBFlt *parameterValues; /* vector holding sump or plot parameters */ -extern Param *params; /* vector of parameters in model */ -extern int partitionNum; /* index of current partition */ -extern Plot plotParams; /* holds parameters for plot command */ -extern int precision; /* precision of samples and summary stats */ -extern int *printAncStates; /* divisions to print anc states for */ -extern int quitOnError; /* quit on error? */ -extern int readComment; /* should we read comment (looking for &)? */ -extern int readWord; /* should we read a word next? */ -extern ReassembleInfo reassembleParams; /* holds parameters for reassemble command */ -extern int replaceLogFile; /* should logfile be replace/appended to */ -extern RandLong runIDSeed; /* seed used only for generating run ID [stamp] */ -extern BitsLong bitsLongWithAllBitsSet; /* a BitsLong with all bits set, for bit ops */ -extern int setUpAnalysisSuccess; /* Set to YES if analysis is set without error */ -extern int scientific; /* use scientific format for samples ? */ -extern ShowmovesParams showmovesParams; /* holds parameters for Showmoves command */ -extern char spacer[10]; /* holds blanks for printing indentations */ -extern NameSet *speciesNameSets; /* hold species name sets, one for each speciespartition */ -extern int **speciespartitionId; /* holds info about defined speciespartitions */ -extern char **speciespartitionNames; /* hold names of speciespartitions (first is "default") */ -extern int speciespartitionNum; /* index of current species partition */ -extern char stamp[11]; /* holds a unique identifier for each analysis */ -extern RandLong swapSeed; /* seed used only for determining which to swap */ -extern int state[MAX_CHAINS]; /* state of chain */ -extern MrBFlt *stdStateFreqs; /* std char state frequencies */ -extern int *stdType; /* compressed std char type: ord, unord, irrev */ -extern Sump sumpParams; /* holds parameters for sump command */ -extern char sumpToken[]; /* string holding a .p file token */ -extern char *sumpTokenP; /* pointer to a .p file token */ -extern Sumt sumtParams; /* holds parameters for sumt command */ -extern Sumss sumssParams; /* holds parameters for sumss command */ -extern int stdStateFreqsRowSize; /* row size for stdStateFreqs */ -extern int *sympiIndex; /* sympi state freq index for multistate chars */ -extern TaxaInformation *taxaInfo; /* holds critical information about taxa */ -extern char **taxaNames; /* holds name of taxa */ -extern char **taxaSetNames; /* holds names of taxa sets */ -extern BitsLong **taxaSet; /* holds information about defined taxasets */ -extern int *tempActiveConstraints; /* info on the active constraints in prset */ -extern int *tempLinkUnlink[NUM_LINKED]; /* for changing parameter linkage */ -extern int *tempLinkUnlinkVec; /* for changing parameter linkage */ -extern MrBFlt *tempNum; /* vector of numbers used for setting arrays */ -extern int *tempSet; /* temporarily holds defined character set */ -extern int theAmbigChar; /* int containing ambiguous character */ -extern int *tiIndex; /* compressed std char ti index */ -extern Calibration *tipCalibration; /* holds tip calibrations */ -extern char **transFrom; /* translation block information */ -extern char **transTo; /* translation block information */ -extern int userBrlensDef; /* are the branch lengths on user tree defined */ -extern int userLevel; /* the level of the user */ -extern PolyTree *userTree[]; /* array of user trees */ -extern char workingDir[100]; /* working directory */ -#if defined (BEAGLE_ENABLED) -extern int tryToUseBEAGLE; /* try to use the BEAGLE library */ -extern long beagleFlags; /* BEAGLE requirement flags */ -extern int beagleResourceNumber; /* BEAGLE resource number */ -extern int* beagleResource; /* BEAGLE resource list */ -extern int beagleResourceCount; /* BEAGLE resource list length */ -extern int beagleInstanceCount; /* total number of BEAGLE instances */ -extern int beagleScalingScheme; /* BEAGLE dynamic scaling */ -extern int beagleScalingFrequency; /* BEAGLE rescaling frequency */ -extern int recalcScalers; /* shoud we recalculate scalers for one of divisions for current state YES/NO */ -#endif -#if defined (THREADS_ENABLED) -extern int tryToUseThreads; /* try to use pthreads with BEAGLE library */ -#endif - -/* Aamodel parameters */ -extern MrBFlt aaJones[20][20]; /* rates for Jones model */ -extern MrBFlt aaDayhoff[20][20]; /* rates for Dayhoff model */ -extern MrBFlt aaMtrev24[20][20]; /* rates for mtrev24 model */ -extern MrBFlt aaMtmam[20][20]; /* rates for mtmam model */ -extern MrBFlt aartREV[20][20]; /* rates for rtREV model */ -extern MrBFlt aaWAG[20][20]; /* rates for WAG model */ -extern MrBFlt aacpREV[20][20]; /* rates for aacpREV model */ -extern MrBFlt aaVt[20][20]; /* rates for VT model */ -extern MrBFlt aaBlosum[20][20]; /* rates for Blosum62 model */ -extern MrBFlt aaLG[20][20]; /* rates for LG model */ -extern MrBFlt jonesPi[20]; /* stationary frequencies for Jones model */ -extern MrBFlt dayhoffPi[20]; /* stationary frequencies for Dayhoff model */ -extern MrBFlt mtrev24Pi[20]; /* stationary frequencies for mtrev24 model */ -extern MrBFlt mtmamPi[20]; /* stationary frequencies for mtmam model */ -extern MrBFlt rtrevPi[20]; /* stationary frequencies for rtREV model */ -extern MrBFlt wagPi[20]; /* stationary frequencies for WAG model */ -extern MrBFlt cprevPi[20]; /* stationary frequencies for aacpREV model */ -extern MrBFlt vtPi[20]; /* stationary frequencies for VT model */ -extern MrBFlt blosPi[20]; /* stationary frequencies for Blosum62 model */ -extern MrBFlt lgPi[20]; /* stationary frequencies for LG model */ - -#if defined (PRINT_RATEMULTIPLIERS_CPP) -extern FILE *rateMultfp; -#endif - -#if defined (MPI_ENABLED) -extern int proc_id; /* process ID (0, 1, ..., num_procs-1) */ -extern int num_procs; /* number of active processors */ -extern MrBFlt myStateInfo[7]; /* likelihood/prior/heat/ran/moveInfo vals of me */ -extern MrBFlt partnerStateInfo[7]; /* likelihood/prior/heat/ran/moveInfo vals of partner */ -#endif - -#if defined (FAST_LOG) -extern CLFlt scalerValue[]; -extern CLFlt logValue[]; -#endif - -#endif /* __BAYES_H__ */ diff --git a/src/best.c b/src/best.c deleted file mode 100644 index 15c8c6fe..00000000 --- a/src/best.c +++ /dev/null @@ -1,1810 +0,0 @@ -/* - * Best 2.2 - * - * This file contains the functions - * for calculating the probability of - * gene trees given the species tree - * and the prior probability of the - * species tree - * - * Liang Liu - * Department of Statistics - * The Ohio State University - * Columbus, Ohio - * - * liuliang@stat.ohio-state.edu - */ - -#include "bayes.h" -#include "best.h" -#include "command.h" -#include "mcmc.h" -#include "model.h" -#include "proposal.h" -#include "utils.h" - -const char* const svnRevisionBestC = "$Rev$"; /* Revision keyword which is expended/updated by svn on each commit/update */ - -/****************************** Local functions converted by Fredrik from BEST code *****************************/ -int CompareDepths (const void *x, const void *y); -int CompareDoubles (const void *x, const void *y); -int CompareNodes (const void *x, const void *y); -int CompareNodesByX (const void *x, const void *y); -int GetSpeciesTreeFromMinDepths (Tree* speciesTree, double *depthMatrix); -int GetDepthMatrix(Tree * speciesTree, double *depthMatrix); -int GetMeanDist (Tree *speciesTree, double *depthMatrix, double *mean); -int GetMinDepthMatrix (Tree **geneTrees, int numGeneTrees, double *depthMatrix); -void LineagesIn (TreeNode* geneTreeNode, TreeNode* speciesTreeNode); -double LnPriorProbGeneTree (Tree *geneTree, double mu, Tree *speciesTree, double *popSizePtr); -double LnProposalProbSpeciesTree (Tree *speciesTree, double *depthMatrix, double expRate); -void MapGeneTreeToSpeciesTree (Tree *geneTree, Tree *speciesTree); -int ModifyDepthMatrix (double expRate, double *depthMatrix, RandLong *seed); - -/* Global BEST variables */ -BitsLong **speciesPairSets; -double *depthMatrix; - -/* Allocate variables used by best code during mcmc */ -void AllocateBestChainVariables (void) -{ - int i, j, index, numUpperTriang, nLongsNeeded; - - // Free if by mistake variables are already allocated - if (memAllocs[ALLOC_BEST] == YES) - FreeBestChainVariables (); - - // Allocate space for upper triangular pair sets - numUpperTriang = (numSpecies * (numSpecies-1)) / 2; - nLongsNeeded = ((numSpecies - 1) / nBitsInALong) + 1; - speciesPairSets = (BitsLong **) SafeCalloc (numUpperTriang, sizeof(BitsLong *)); - speciesPairSets[0] = (BitsLong *) SafeCalloc (numUpperTriang*nLongsNeeded, sizeof(BitsLong)); - for (i=1; i (*((Depth *)(y))).depth) - return 1; - else - return 0; -} - - -/** Compare function (doubles) for qsort */ -int CompareDoubles (const void *x, const void *y) { - - if (*((double *)(x)) < *((double *)(y))) - return -1; - else if (*((double *)(x)) > *((double *)(y))) - return 1; - else - return 0; -} - - -/** Compare function (TreeNode struct) for qsort */ -int CompareNodes (const void *x, const void *y) { - - if ((*((TreeNode **)(x)))->nodeDepth < (*((TreeNode**)(y)))->nodeDepth) - return -1; - else if ((*((TreeNode **)(x)))->nodeDepth > (*((TreeNode**)(y)))->nodeDepth) - return 1; - else - return 0; -} - - -/** Compare function (TreeNode struct; sort by x, then by nodeDepth) for qsort */ -int CompareNodesByX (const void *x, const void *y) { - - if ((*((TreeNode **)(x)))->x < (*((TreeNode**)(y)))->x) - return -1; - else if ((*((TreeNode **)(x)))->x > (*((TreeNode**)(y)))->x) - return 1; - else { - if ((*((TreeNode **)(x)))->nodeDepth < (*((TreeNode**)(y)))->nodeDepth) - return -1; - else if ((*((TreeNode **)(x)))->nodeDepth > (*((TreeNode**)(y)))->nodeDepth) - return 1; - else - return 0; - } -} - - -/**----------------------------------------------------------------- -| -| FillSpeciesTreeParams: Fill in species trees (start value) -| -------------------------------------------------------------------*/ -int FillSpeciesTreeParams (RandLong *seed, int fromChain, int toChain) -{ - int i, k, chn, numGeneTrees, freeBestChainVars; - Param *p; - Tree *speciesTree, **geneTrees; - - // Allocate space for global best model variables used in this function, in case they are not allocated - if (memAllocs[ALLOC_BEST] == NO) - { - freeBestChainVars = YES; - AllocateBestChainVariables(); - } - else - freeBestChainVars = NO; - - // Use global variable numTopologies to calculate number of gene trees - // There is one topology for the species tree, the other ones are gene trees - // The number of current divisions is not safe because one gene tree can have - // several partitions, for instance if we assign the different genes on the - // mitochondrion different substitution models, or if we assign different rates - // to the codon site positions in a sequence - numGeneTrees = numTopologies - 1; - geneTrees = (Tree **) SafeCalloc (numGeneTrees, sizeof(Tree*)); - - // Build species trees for state 0 - for (chn=fromChain; chnparamType == P_SPECIESTREE) - { - // Find species tree and gene trees - speciesTree = GetTree(p, chn, 0); - for (i=0; inSubParams; i++) - geneTrees[i] = GetTree(p->subParams[i], chn, 0); - - // Get minimum depth matrix for species tree - GetMinDepthMatrix (geneTrees, numGeneTrees, depthMatrix); - - // Get a species tree from min depth matrix - GetSpeciesTreeFromMinDepths(speciesTree, depthMatrix); - - assert (IsSpeciesTreeConsistent(speciesTree, chn) == YES); - - // Label the tips - if (LabelTree (speciesTree, speciesNameSets[speciespartitionNum].names) == ERROR) - { - FreeBestChainVariables(); - return (ERROR); - } - } - } - } - - // Free gene trees - free (geneTrees); - - // Free best model variables if appropriate - if (freeBestChainVars == YES) - FreeBestChainVariables(); - - return (NO_ERROR); - MrBayesPrint ("%lf", *seed); /* just because I am tired of seeing the unused parameter error msg */ -} - - -/**----------------------------------------------------------------- -| -| FreeBestChainVariables: Free best variables used during an mcmc -| run. -| -------------------------------------------------------------------*/ -void FreeBestChainVariables(void) -{ - if (memAllocs[ALLOC_BEST] == YES) { - free (speciesPairSets[0]); - free (speciesPairSets); - speciesPairSets = NULL; - } - - free (depthMatrix); - depthMatrix = NULL; - - memAllocs[ALLOC_BEST] = NO; -} - - -/**--------------------------------------------------------------------- -| -| GetDepthMatrix: -| -| This algorithm calculates the upper triangular depth matrix for the -| species tree. Time complexity O(n^2). -| -| @param speciesTree The species tree (in) -| @param depthMatrix The minimum depth matrix, upper triangular array (out) -| @returns Returns ERROR or NO_ERROR -----------------------------------------------------------------------*/ -int GetDepthMatrix (Tree *speciesTree, double *depthMatrix) { - - int i, left, right, numUpperTriang, index, nLongsNeeded, freeBitsets; - double maxDepth; - TreeNode *p; - - // Make sure we have bitfields allocated and set - freeBitsets = NO; - if (speciesTree->bitsets == NULL) - { - AllocateTreePartitions(speciesTree); - freeBitsets = YES; - } - else - { - ResetTreePartitions(speciesTree); // just in case - freeBitsets = NO; - } - - // Calculate number of values in the upper triangular matrix - numUpperTriang = numSpecies * (numSpecies - 1) / 2; - - // Number of longs needed in a bitfield representing a species set - nLongsNeeded = ((numSpecies -1) / nBitsInALong) + 1; - - // Set all cells to max - maxDepth = speciesTree->root->left->nodeDepth; // root depth - for (i=0; inIntNodes; i++) - { - p = speciesTree->intDownPass[i]; - for (left = FirstTaxonInPartition(p->left->partition, nLongsNeeded); left < numSpecies; left = NextTaxonInPartition(left, p->left->partition, nLongsNeeded)) - { - for (right = FirstTaxonInPartition(p->right->partition, nLongsNeeded); right < numSpecies; right = NextTaxonInPartition(right, p->right->partition, nLongsNeeded)) - { - index = UpperTriangIndex(left, right, numSpecies); - depthMatrix[index] = p->nodeDepth; - } - } - } - - // Free partitions if appropriate - if (freeBitsets == YES) - FreeTreePartitions(speciesTree); - - return (NO_ERROR); -} - - -/**--------------------------------------------------------------------- -| -| GetMeanDist -| -| This algorithm calculates the mean distance between a distance matrix -| and the minimum depths that define a species tree. -| -| @param speciesTree The species tree (in) -| @param minDepthMatrix The minimum depth matrix, upper triangular array (in) -| @param mean The mean distance (out) -| @returns Returns ERROR or NO_ERROR -----------------------------------------------------------------------*/ -int GetMeanDist (Tree *speciesTree, double *minDepthMatrix, double *mean) { - - int i, left, right, index, nLongsNeeded, freeBitsets; - double dist, minDist=0.0, distSum; - TreeNode *p; - - // Make sure we have bitfields allocated and set - freeBitsets = NO; - if (speciesTree->bitsets == NULL) - { - AllocateTreePartitions(speciesTree); - freeBitsets = YES; - } - else - { - ResetTreePartitions(speciesTree); // just in case - freeBitsets = NO; - } - - // Number of longs needed in a bitfield representing a species set - nLongsNeeded = ((numSpecies -1) / nBitsInALong) + 1; - - // Loop over interior nodes - distSum = 0.0; - for (i=0; inIntNodes; i++) - { - p = speciesTree->intDownPass[i]; - p->x = 0; - while ((left=FirstTaxonInPartition(p->left->partition, nLongsNeeded)) < numSpecies) - { - while ((right=FirstTaxonInPartition(p->right->partition, nLongsNeeded)) < numSpecies) - { - p->x++; - index = UpperTriangIndex(left, right, numSpecies); - dist = depthMatrix[index] - p->nodeDepth; - if (p->x == 1) - minDist = dist; - else if (dist < minDist) - minDist = dist; - ClearBit(right, p->right->partition); - } - ClearBit(left, p->left->partition); - } - distSum += minDist; - } - - (*mean) = distSum / speciesTree->nIntNodes; - - // Reset partitions that were destroyed above or free partitions, as appropriate - if (freeBitsets == YES) - FreeTreePartitions(speciesTree); - else - ResetTreePartitions(speciesTree); - - return (NO_ERROR); - MrBayesPrint ("%lf", *minDepthMatrix); /* just because I am tired of seeing the unused parameter error msg */ -} - - -/**--------------------------------------------------------------------- -| -| GetMinDepthMatrix: converted from GetMinDists. -| -| This algorithm scans the gene trees and calculates the minimum depth -| (height) separating species across gene trees. The complexity of the -| original algorithm was O(mn^3), where m is the number of gene trees and -| n is the number of taxa in each gene tree. I think this algorithm has -| complexity that is better on average, but the difference is small. -| -| I have rewritten the algorithm also to show alternative techniques that -| could be used in this and other BEST algorithms. -| -| @param geneTrees The gene trees (in) -| @param depthMatrix The minimum depth matrix, upper triangular array (out) -| @returns Returns ERROR or NO_ERROR -----------------------------------------------------------------------*/ -int GetMinDepthMatrix (Tree **geneTrees, int numGeneTrees, double *depthMatrix) { - - int i, j, w, nLongsNeeded, numUpperTriang, index, trace=0; - double maxDepth; - TreeNode *p; - BitsLong **speciesSets; - - // Allocate space for species partitions - nLongsNeeded = ((numSpecies -1) / nBitsInALong) + 1; // number of longs needed in a bitfield representing a species set - speciesSets = (BitsLong **) SafeCalloc (2*numLocalTaxa-1, sizeof(BitsLong *)); - speciesSets[0] = (BitsLong *) SafeCalloc ((2*numLocalTaxa-1)*nLongsNeeded, sizeof(BitsLong)); - for (i=1; i<2*numLocalTaxa-1; i++) - speciesSets[i] = speciesSets[0] + i*nLongsNeeded; - - // Set tip species partitions once and for all - for (i=0; iroot->left->nodeDepth; - for (i=0; inIntNodes; i++) { - p = geneTrees[w]->intDownPass[i]; - for (j=0; jindex][j] = speciesSets[p->left->index][j] | speciesSets[p->right->index][j]; - } - - // Now order the interior nodes in terms of node depth. We rely on the fact that the - // ordered sequence is a valid downpass sequence. O(log n). - qsort((void *)(geneTrees[w]->intDownPass), (size_t) geneTrees[w]->nIntNodes, sizeof(TreeNode *), CompareNodes); - - // Finally find the minimum for each cell in the upper triangular matrix - // This is the time critical step with complexity O(n^3) in the simplest - // algorithm version. This algorithm should do a little better in most cases. - for (i=0; inIntNodes; j++) { - p = geneTrees[w]->intDownPass[j]; - - // Because nodes are ordered in time, if this test is true then we cannot beat the minimum - if (p->nodeDepth > depthMatrix[i]) - break; - - // Check whether the node is a candidate minimum for the species pair - // If the test is true, we know from the test above that p->nodeDepth is - // either a tie or the new minimum - if (IsPartNested(speciesPairSets[i], speciesSets[p->index], nLongsNeeded) == YES) { - depthMatrix[i] = p->nodeDepth; - break; - } - } - } - } // Next gene tree - - if (trace) - { - index = 0; - printf ("Mindepth matrix\n"); - for (i=0;iisRooted = YES; - polyTree->isClock = YES; - polyTree->root = &polyTree->nodes[2*numSpecies-2]; - for (i=0; inodes[i]; - p->index = i; - p->depth = 0.0; - p->left = NULL; - if (isib = &polyTree->nodes[i+1]; - else - p->sib = NULL; - p->anc = polyTree->root; - } - p = polyTree->root; - p->index = 2*numSpecies - 2; - p->left = &polyTree->nodes[0]; - p->sib = NULL; - p->anc = NULL; - p->depth = -1.0; - polyTree->nNodes = numSpecies + 1; - polyTree->nIntNodes = 1; - GetPolyDownPass(polyTree); - ResetPolyTreePartitions(polyTree); /* set bitsets (partitions) for initial tree */ - - // Resolve bush using sorted depth structs - nextNodeIndex = numSpecies; - for (i=0; inodes[FirstTaxonInPartition(minDepth[i].pairSet, nLongsNeeded)]; - - // Descend tree until we find a node within which the pair set is nested - do { - p = p->anc; - } - while (!IsPartNested(minDepth[i].pairSet, p->partition, nLongsNeeded)); - - if (p->left->sib->sib != NULL) { - // This node is still a polytomy - - // Find left and right descendants of new node - qPrev = NULL; - for (q=p->left; IsSectionEmpty(q->partition, minDepth[i].pairSet, nLongsNeeded); q=q->sib) - qPrev = q; - rPrev = q; - for (r=q->sib; IsSectionEmpty(r->partition, minDepth[i].pairSet, nLongsNeeded); r=r->sib) - rPrev = r; - - // Introduce the new node - u = &polyTree->nodes[nextNodeIndex]; - u->index = nextNodeIndex; - nextNodeIndex++; - polyTree->nIntNodes++; - polyTree->nNodes++; - u->left = q; - u->anc = p; - if (p->left == q) - p->left = u; - else - qPrev->sib = u; - // former upstream sibling to r should point to r->sib - if (rPrev == q) - u->sib = r->sib; - else - rPrev->sib = r->sib; - if (q->sib == r) - u->sib = r->sib; - else - u->sib = q->sib; - u->depth = minDepth[i].depth; // because minDepth structs are sorted, we know this is the min depth - assert (u->depth > 0.0); - - // Create new taxon set with bitfield operations - for (j=0; jpartition[j] = q->partition[j] | r->partition[j]; - - // Patch the tree together with the new node added - q->sib = r; - r->sib = NULL; - q->anc = u; - r->anc = u; - } - else if (p == polyTree->root && p->depth < 0.0) { - // This is the first time we hit the root of the tree && it is resolved - p->depth = minDepth[i].depth; - assert (p->depth > 0.0); - } - // other cases should not be added to tree - } - - // Make sure we have a complete species tree - assert (polyTree->nIntNodes == numSpecies - 1); - - // Set traversal sequences - GetPolyDownPass(polyTree); - - // Set branch lengths from node depths (not done automatically for us) - // Make sure all branch lengths are nonnegative (we can have 0.0 brlens, they - // should not be problematic in a species tree; they occur when there are - // ties in the min depth matrix that have not been modified by the move) - for (i=0; inNodes; i++) { - p = polyTree->allDownPass[i]; - if (p->anc == NULL) - p->length = 0.0; - else - p->length = p->anc->depth - p->depth; - if (p->length < 0.0) { - FreePolyTree(polyTree); - free (minDepth); - return (ERROR); - } - } - - // Copy to species tree from polytomous tree - CopyToSpeciesTreeFromPolyTree (speciesTree, polyTree); - - // Free locally allocated variables - FreePolyTree(polyTree); - free (minDepth); - - return(NO_ERROR); -} - - -/**--------------------------------------------------------------------------------------- -| -| IsSpeciesTreeConsistent: Called when user tries to set a species tree or when -| attempting to use a species tree from a check point as starting value. -| ------------------------------------------------------------------------------------------*/ -int IsSpeciesTreeConsistent (Tree *speciesTree, int chain) -{ - int i, answer, numGeneTrees, numUpperTriang, freeBestVars; - double *speciesTreeDepthMatrix; - Tree **geneTrees; - - answer = NO; - - freeBestVars = NO; - if (memAllocs[ALLOC_BEST] == NO) - { - AllocateBestChainVariables(); - freeBestVars = YES; - } - - numGeneTrees = numTrees - 1; - geneTrees = (Tree **) SafeCalloc (numGeneTrees, sizeof(Tree *)); - for (i=0; iroot, 0, YES); - - if (freeBestVars == YES) - FreeBestChainVariables(); - - free (speciesTreeDepthMatrix); - free (geneTrees); - - return answer; -} - - -/**--------------------------------------------------------------------------------------- -| -| LineagesIn: Recursive function to get number of gene tree lineages coming into each -| branch of the species tree (in ->x of speciestree nodes). We also assign each gene -| tree lineage to the corresponding species tree lineage (in ->x of genetree nodes). -| Finally, number of coalescent events is recorded (in ->y of speciestree nodes). -| Time complexity is O(n). -| ------------------------------------------------------------------------------------------*/ -void LineagesIn (TreeNode *geneTreeNode, TreeNode *speciesTreeNode) -{ - int nLongsNeeded; - - if (geneTreeNode->nodeDepth < speciesTreeNode->nodeDepth) { - // climb up species tree - if (speciesTreeNode->left == NULL) { - assert (geneTreeNode->left == NULL); - speciesTreeNode->x++; - } - else { - nLongsNeeded = (numSpecies - 1) / nBitsInALong + 1; - speciesTreeNode->x++; - if (IsPartNested(geneTreeNode->partition, speciesTreeNode->left->partition, nLongsNeeded) == YES) - LineagesIn (geneTreeNode, speciesTreeNode->left); - else if (IsPartNested(geneTreeNode->partition, speciesTreeNode->right->partition, nLongsNeeded) == YES) - LineagesIn (geneTreeNode, speciesTreeNode->right); - } - } - else { - // climb up gene tree - if (geneTreeNode->left != NULL) - LineagesIn(geneTreeNode->left, speciesTreeNode); - if (geneTreeNode->right != NULL) - LineagesIn(geneTreeNode->right, speciesTreeNode); - if (geneTreeNode->left == NULL) { - speciesTreeNode->x++; - assert (speciesTreeNode->left == NULL); - } - else { - speciesTreeNode->y++; - } - geneTreeNode->x = speciesTreeNode->index; - } -} - - -/**----------------------------------------------------------------- -| -| LnSpeciesTreeProb: Wrapper for LnJointGeneTreeSpeciesTreePr to -| free calling functions from retrieving gene and species trees. -| -------------------------------------------------------------------*/ -double LnSpeciesTreeProb(int chain) -{ - int i, numGeneTrees; - double lnProb; - Tree **geneTrees, *speciesTree; - ModelInfo *m; - - m = &modelSettings[0]; - - speciesTree = GetTree(m->speciesTree, chain, state[chain]); - - numGeneTrees = m->speciesTree->nSubParams; - geneTrees = (Tree **) SafeCalloc (numGeneTrees, sizeof(Tree *)); - - for (i=0; ispeciesTree->nSubParams; i++) - geneTrees[i] = GetTree(m->speciesTree->subParams[i], chain, state[chain]); - - lnProb = LnJointGeneTreeSpeciesTreePr(geneTrees, numGeneTrees, speciesTree, chain); - - free (geneTrees); - - return lnProb; -} - - -/**----------------------------------------------------------------- -| -| LnJointGeneTreeSpeciesTreePr: Converted from LnJointGenetreePr, -| SPLogLike, SPLogPrior. -| -| In this function we calculate the entire probability of the species -| tree, including its probability given its priors, and the probability -| of the gene trees given the species tree. -| -------------------------------------------------------------------*/ -double LnJointGeneTreeSpeciesTreePr(Tree **geneTrees, int numGeneTrees, Tree *speciesTree, int chain) -{ - double lnPrior, lnLike, clockRate, mu, *popSizePtr, sR, eR, sF; - int i; - ModelInfo *m; - ModelParams *mp; - - // Get model info for species tree - m = &modelSettings[speciesTree->relParts[0]]; - - // Get model params for species tree - mp = &modelParams[speciesTree->relParts[0]]; - - // Get popSize ptr - popSizePtr = GetParamVals(m->popSize, chain, state[chain]); - - // Get clock rate - if (speciesTree->isCalibrated == YES) - clockRate = *GetParamVals(m->clockRate, chain, state[chain]); - else - clockRate = 1.0; - - // Calculate probability of gene trees given species tree - // ShowNodes(speciesTree->root, 0, YES); - lnLike = 0.0; - mu = clockRate; - for (i=0; ispeciesTreeBrlensPr, "Birthdeath") == 0) { - sR = *GetParamVals(m->speciationRates, chain, state[chain]); - eR = *GetParamVals(m->extinctionRates, chain, state[chain]); - sF = mp->sampleProb; - lnPrior = 0.0; - LnBirthDeathPriorPr(speciesTree, clockRate, &lnPrior, sR, eR, mp->sampleStrat, sF); - } - else - lnPrior = 0.0; - - // The population size is taken care of elsewhere - - return lnLike + lnPrior; -} - - -/**----------------------------------------------------------------- -| -| LnPriorProbGeneTree: Calculate the prior probability of a gene -| tree. -| -------------------------------------------------------------------*/ -double LnPriorProbGeneTree (Tree *geneTree, double mu, Tree *speciesTree, double *popSizePtr) -{ - int i, k, index, nEvents, trace=0; - double N, lnProb, ploidyFactor, theta, timeInterval; - TreeNode *p, *q=NULL, *r; - ModelParams *mp; - - // Get model params - mp = &modelParams[speciesTree->relParts[0]]; - - // Find ploidy setting - if (strcmp(mp->ploidy, "Diploid") == 0) - ploidyFactor = 4.0; - else if (strcmp(mp->ploidy, "Haploid") == 0) - ploidyFactor = 2.0; - else /* if (strcmp(mp->ploidy, "Zlinked") == 0) */ - ploidyFactor = 3.0; - - // Initialize species tree with theta in d - for (i=0; inNodes-1; i++) { - p = speciesTree->allDownPass[i]; - if (strcmp(mp->popVarPr, "Equal") != 0) - N = popSizePtr[p->index]; - else - N = popSizePtr[0]; - p->d = ploidyFactor * N * mu; - } - - // Map gene tree to species tree - MapGeneTreeToSpeciesTree(geneTree, speciesTree); - - // Sort gene tree interior nodes first by speciestree branch on which they coalesce, then in time order - qsort((void *)(geneTree->intDownPass), (size_t) geneTree->nIntNodes, sizeof(TreeNode *), CompareNodesByX); - - // Debug output of qsort result - if (trace) { - printf ("index -- x -- nodeDepth for gene tree\n"); - for (i=0; inIntNodes; i++) - printf ("%d -- %d -- %e\n", geneTree->intDownPass[i]->index, geneTree->intDownPass[i]->x, geneTree->intDownPass[i]->nodeDepth); - } - - // Now calculate probability after making sure species tree nodes appear in index order - // (the order does not have to be a correct downpass sequence) - for (i=0; imemNodes; i++) - { - p = &(speciesTree->nodes[i]); - speciesTree->allDownPass[p->index] = p; - } - index = 0; - lnProb = 0.0; - for (i=0; inNodes-1; i++) { - - p = speciesTree->allDownPass[i]; - - // Get theta - theta = p->d; - - // Get number of events - nEvents = p->y; - - // Calculate probability - lnProb += nEvents * log (2.0 / theta); - - for (k=p->x; k > p->x - p->y; k--) { - - q = geneTree->intDownPass[index]; - assert (q->x == p->index); - - if (k == p->x) - timeInterval = q->nodeDepth - p->nodeDepth; - else { - r = geneTree->intDownPass[index-1]; - timeInterval = q->nodeDepth - r->nodeDepth; - } - - lnProb -= (k * (k - 1) * timeInterval) / theta; - index++; - } - - if (p->x - p->y > 1) { - - if (nEvents == 0) - timeInterval = p->anc->nodeDepth - p->nodeDepth; - else - timeInterval = p->anc->nodeDepth - q->nodeDepth; - - assert (p->anc->anc != NULL); - assert (timeInterval >= 0.0); - - k = p->x - p->y; - lnProb -= (k * (k - 1) * timeInterval) / theta; - } - } - - // Restore downpass sequences (probably not necessary for gene tree, but may be if some - // code relies on intDownPass and allDownPass to be in same order) - GetDownPass(speciesTree); - GetDownPass(geneTree); - - // Free space - FreeTreePartitions(speciesTree); - FreeTreePartitions(geneTree); - - return lnProb; -} - - -/**--------------------------------------------------------------------- -| -| LnProposalProbSpeciesTree: -| -| This algorithm calculates the probability of proposing a particular -| species tree given a distance matrix modified using a scheme based on -| truncated exponential distributions with rate expRate. -| -| @param speciesTree The species tree (in) -| @param depthMatrix The minimum depth matrix, upper triangular array (in) -| @param expRate Rate of truncated exponential distribution -| @returns Returns probability of proposing the species tree -----------------------------------------------------------------------*/ -double LnProposalProbSpeciesTree (Tree *speciesTree, double *depthMatrix, double expRate) -{ - int i, left, right, index, nLongsNeeded, freeBitsets; - double dist, normConst=1.0, negLambdaX=0.0, eNegLambdaX, density, prob, - sumDensRatio, prodProb, lnProb; - TreeNode *p; - - // Make sure we have bitfields allocated and set - freeBitsets = NO; - if (speciesTree->bitsets == NULL) - freeBitsets = YES; - else - freeBitsets = NO; - AllocateTreePartitions(speciesTree); - - // Number of longs needed in a bitfield representing a species set - nLongsNeeded = ((numSpecies -1) / nBitsInALong) + 1; - - // Loop over interior nodes - lnProb = 0.0; - for (i=0; inIntNodes; i++) - { - p = speciesTree->intDownPass[i]; - p->x = 0; - sumDensRatio = 0.0; - prodProb = 1.0; - for (left = FirstTaxonInPartition(p->left->partition, nLongsNeeded); left < numSpecies; left = NextTaxonInPartition(left, p->left->partition, nLongsNeeded)) - { - for (right = FirstTaxonInPartition(p->right->partition, nLongsNeeded); right < numSpecies; right = NextTaxonInPartition(right, p->right->partition, nLongsNeeded)) - { - p->x++; - index = UpperTriangIndex(left, right, numSpecies); assert (index < numSpecies*(numSpecies - 1) / 2); - dist = depthMatrix[index] - p->nodeDepth; // distance between depth matrix entry and actual species-tree node - normConst = 1.0 - exp(-expRate * depthMatrix[index]); // normalization constant because of truncation of exp distribution - negLambdaX = - expRate * dist; - eNegLambdaX = exp(negLambdaX); - density = expRate * eNegLambdaX / normConst; // density for x == dist, f(dist) - prob = (1.0 - eNegLambdaX) / normConst; // cumulative prob for x <= dist, F(dist) - sumDensRatio += density / prob; // warning: if dist==0, prob is ZERO! - prodProb *= prob; - } - } - if (p->x == 1) - lnProb += log(expRate) + negLambdaX - log(normConst); - else - lnProb += log(sumDensRatio * prodProb); - } - - // to avoid lnProposalProb is NaN at initial steps - if (lnProb != lnProb) lnProb = 0.0; - - // Free partitions if appropriate - if (freeBitsets == YES) - FreeTreePartitions(speciesTree); - - return (lnProb); -} - - -/**----------------------------------------------------------------- -| -| MapGeneTreeToSpeciesTree: Fold gene tree into species tree. We -| are going to use ->x of gene tree to give index of the -| corresponding node in the species tree. ->x in the species -| tree will give the number of lineages into the corresponding -| branch, and ->y will give the number of coalescent events on -| that branch. -| -------------------------------------------------------------------*/ -void MapGeneTreeToSpeciesTree (Tree *geneTree, Tree *speciesTree) -{ - int i, j, nLongsNeeded, trace=0; - TreeNode *p; - - // Initialize species partitions for both gene tree and species tree - // This will set the partitions to reflect the partitions in the tree itself, - // which is OK for the species tree, but we want the gene tree partitions to - // reflect the species partitions and not the gene partitions, so we need to - // set them here - AllocateTreePartitions(geneTree); - AllocateTreePartitions(speciesTree); - nLongsNeeded = (numSpecies - 1) / nBitsInALong + 1; - for (i=0; inNodes-1; i++) { - p = geneTree->allDownPass[i]; - ClearBits(p->partition, nLongsNeeded); - if (p->left == NULL) - SetBit(speciespartitionId[p->index][speciespartitionNum]-1, p->partition); - else { - for (j=0; jpartition[j] = p->left->partition[j] | p->right->partition[j]; - } - } - // Species tree partitions already set by call to AllocateTreePartitions - - // Reset ->x and ->y of species tree (->x of gene tree does not need to be initialized) - for (i=0; inNodes; i++) - { - p = speciesTree->allDownPass[i]; - p->x = 0; - p->y = 0; - } - - // Call recursive function to match gene tree and species tree - LineagesIn(geneTree->root->left, speciesTree->root->left); - - if (trace) { - printf ("index -- x -- y for species tree\n"); - for (i=0; inNodes-1; i++) - printf ("%-2d -- %d -- %d\n", speciesTree->allDownPass[i]->index, speciesTree->allDownPass[i]->x, speciesTree->allDownPass[i]->y); - } - - if (trace) { - printf ("index -- x -- nodeDepth for gene tree\n"); - for (i=0; inIntNodes; i++) - printf ("%-2d -- %d -- %e\n", geneTree->intDownPass[i]->index, geneTree->intDownPass[i]->x, geneTree->intDownPass[i]->nodeDepth); - } - - // Free space - FreeTreePartitions(speciesTree); - FreeTreePartitions(geneTree); -} - - -/**--------------------------------------------------------------------- -| -| ModifyDepthMatrix: -| -| This algorithm uses a truncated exponential distribution to modify -| a depth matrix. -| -| @param expRate The rate of the exponential distribution (in) -| @param depthMatrix The minimum depth matrix to be modified, upper triangular array (in/out) -| @param seed Pointer to seed for random number generator (in/ut) -| @returns Returns ERROR or NO_ERROR -----------------------------------------------------------------------*/ -int ModifyDepthMatrix (double expRate, double *depthMatrix, RandLong *seed) -{ - int i, numUpperTriang; - double u, interval, delta; - - numUpperTriang = numSpecies * (numSpecies - 1) / 2; - for (i=0; irelParts[0]]; - - // Get species tree (this trick is possible because we always copy tree params) - newSpeciesTree = GetTree (m->speciesTree, chain, state[chain]); - oldSpeciesTree = GetTree (m->speciesTree, chain, state[chain] ^ 1); - - // Get gene trees - geneTrees = (Tree **) SafeCalloc (2*numGeneTrees, sizeof(Tree *)); - for (i=0; ispeciesTree->nSubParams; i++) { - geneTrees[i] = GetTree(m->speciesTree->subParams[i], chain, state[chain]); - } - - // Allocate space for depth matrix copy - numUpperTriang = numSpecies * (numSpecies - 1) / 2; - oldMinDepths = (double *) SafeCalloc (2*numUpperTriang, sizeof(double)); - modMinDepths = oldMinDepths + numUpperTriang; - - // Get min depth matrix for old gene trees - GetMinDepthMatrix(geneTrees, numTopologies-1, depthMatrix); - - // Save a copy - for (i=0; irelParts[0]]; - - // Get species tree (this trick is possible because we always copy tree params) - newSpeciesTree = GetTree (m->speciesTree, chain, state[chain]); - oldSpeciesTree = GetTree (m->speciesTree, chain, state[chain] ^ 1); - - // Get gene trees - geneTrees = (Tree **) SafeCalloc (2*numGeneTrees, sizeof(Tree *)); - for (i=0; ispeciesTree->nSubParams; i++) { - geneTrees[i] = GetTree(m->speciesTree->subParams[i], chain, state[chain]); - } - - // Allocate space for depth matrix copy - numUpperTriang = numSpecies * (numSpecies - 1) / 2; - oldMinDepths = (double *) SafeCalloc (2*numUpperTriang, sizeof(double)); - modMinDepths = oldMinDepths + numUpperTriang; - - // Get min depth matrix for old gene trees - GetMinDepthMatrix(geneTrees, numTopologies-1, depthMatrix); - - // Save a copy - for (i=0; irelParts[0]]; - - // Get species tree (this trick is possible because we always copy tree params) - newSpeciesTree = GetTree (m->speciesTree, chain, state[chain]); - oldSpeciesTree = GetTree (m->speciesTree, chain, state[chain] ^ 1); - - // Get gene trees - geneTrees = (Tree **) SafeCalloc (2*numGeneTrees, sizeof(Tree *)); - for (i=0; ispeciesTree->nSubParams; i++) { - geneTrees[i] = GetTree(m->speciesTree->subParams[i], chain, state[chain]); - } - - // Allocate space for depth matrix copy - numUpperTriang = numSpecies * (numSpecies - 1) / 2; - oldMinDepths = (double *) SafeCalloc (2*numUpperTriang, sizeof(double)); - modMinDepths = oldMinDepths + numUpperTriang; - - // Get min depth matrix for old gene trees - GetMinDepthMatrix(geneTrees, numTopologies-1, depthMatrix); - - // Save a copy - for (i=0; irelParts[0]]; - - /* get gene tree and species tree */ - geneTree = GetTree (param, chain, state[chain]); - speciesTree = GetTree (m->speciesTree, chain, state[chain]); - - /* get population size(s) */ - popSizePtr = GetParamVals(m->popSize, chain, state[chain]); - - /* get clock rate */ - if (m->clockRate == NULL) - clockRate = 1.0; - else - clockRate = *GetParamVals(m->clockRate, chain, state[chain]); - - /* pick a node to be changed */ - p = geneTree->intDownPass[(int)(RandomNumber(seed)*geneTree->nIntNodes)]; - -# if defined (DEBUG_CSLIDER) - printf ("Before node slider (gene tree):\n"); - printf ("Picked branch with index %d and depth %f\n", p->index, p->nodeDepth); - if (p->anc->anc == NULL) - printf ("Old clock rate: %f\n", clockRate); - ShowNodes (t->root, 0, t->isRooted); - getchar(); -# endif - - /* get gene tree prior prob before move */ - (*lnPriorRatio) -= LnPriorProbGeneTree(geneTree, clockRate, speciesTree, popSizePtr); - - /* store values needed later for prior calculation (relaxed clocks) */ - oldPLength = p->length; - if (p->left != NULL) - { - oldLeftLength = p->left->length; - oldRightLength = p->right->length; - } - else - oldLeftLength = oldRightLength = 0.0; - - /* find species tree branch to which the gene tree node belongs */ - MapGeneTreeToSpeciesTree(geneTree, speciesTree); - q = NULL; - for (i=0; inNodes-1; i++) - { - q = speciesTree->allDownPass[i]; - if (p->x == q->index) - break; - } - assert (q != NULL && p->x == q->index); - - /* determine lower and upper bound */ - minDepth = p->left->nodeDepth + POS_MIN; - if (p->right->nodeDepth + POS_MIN > minDepth) - minDepth = p->right->nodeDepth + POS_MIN; - if (q->nodeDepth + POS_MIN > minDepth) - minDepth = q->nodeDepth + POS_MIN; - if (p->anc->anc == NULL) - maxDepth = TREEHEIGHT_MAX; - else - maxDepth = p->anc->nodeDepth - POS_MIN; - - /* abort if impossible */ - if (minDepth >= maxDepth) - { - abortMove = YES; - return (NO_ERROR); - } - - if (maxDepth-minDepth < window) - { - window = maxDepth-minDepth; - } - - /* pick the new node depth */ - oldDepth = p->nodeDepth; - newDepth = oldDepth + (RandomNumber(seed) - 0.5) * window; - - /* reflect the new node depth */ - while (newDepth < minDepth || newDepth > maxDepth) - { - if (newDepth < minDepth) - newDepth = 2.0 * minDepth - newDepth; - if (newDepth > maxDepth) - newDepth = 2.0 * maxDepth - newDepth; - } - p->nodeDepth = newDepth; - - /* determine new branch lengths around p and set update of transition probabilities */ - if (p->left != NULL) - { - p->left->length = p->nodeDepth - p->left->nodeDepth; - assert (p->left->length >= POS_MIN); - p->left->upDateTi = YES; - p->right->length = p->nodeDepth - p->right->nodeDepth; - assert (p->right->length >= POS_MIN); - p->right->upDateTi = YES; - } - if (p->anc->anc != NULL) - { - p->length = p->anc->nodeDepth - p->nodeDepth; - assert (p->length >= POS_MIN); - p->upDateTi = YES; - } - - /* set flags for update of cond likes from p and down to root */ - q = p; - while (q->anc != NULL) - { - q->upDateCl = YES; - q = q->anc; - } - - /* calculate proposal ratio */ - (*lnProposalRatio) = 0.0; - - /* calculate prior ratio */ - (*lnPriorRatio) += LnPriorProbGeneTree (geneTree, clockRate, speciesTree, popSizePtr); - - /* adjust proposal and prior ratio for relaxed clock models */ - for (i=0; inSubParams; i++) - { - subParm = param->subParams[i]; - if (subParm->paramType == P_CPPEVENTS) - { - nEvents = subParm->nEvents[2*chain+state[chain]]; - lambda = *GetParamVals (modelSettings[subParm->relParts[0]].cppRate, chain, state[chain]); - - /* proposal ratio */ - if (p->left != NULL) - { - (*lnProposalRatio) += nEvents[p->left->index ] * log (p->left->length / oldLeftLength); - (*lnProposalRatio) += nEvents[p->right->index] * log (p->right->length / oldRightLength); - } - if (p->anc->anc != NULL) - (*lnProposalRatio) += nEvents[p->index] * log (p->length / oldPLength); - - /* prior ratio */ - if (p->anc->anc == NULL) // two branches changed in same direction - (*lnPriorRatio) += lambda * (2.0 * (oldDepth - newDepth)); - else if (p->left != NULL) // two branches changed in one direction, one branch in the other direction - (*lnPriorRatio) += lambda * (oldDepth - newDepth); - else /* if (p->left == NULL) */ // one branch changed - (*lnPriorRatio) += lambda * (newDepth - oldDepth); - - /* update effective evolutionary lengths */ - if (UpdateCppEvolLengths (subParm, p, chain) == ERROR) - { - abortMove = YES; - return (NO_ERROR); - } - } - else if ( subParm->paramType == P_TK02BRANCHRATES || - (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_TK02)) - { - if (subParm->paramType == P_TK02BRANCHRATES) - nu = *GetParamVals (modelSettings[subParm->relParts[0]].tk02var, chain, state[chain]); - else - nu = *GetParamVals (modelSettings[subParm->relParts[0]].mixedvar, chain, state[chain]); - tk02Rate = GetParamVals (subParm, chain, state[chain]); - brlens = GetParamSubVals (subParm, chain, state[chain]); - - /* no proposal ratio effect */ - - /* prior ratio */ - if (p->left != NULL) - { - (*lnPriorRatio) -= LnProbTK02LogNormal (tk02Rate[p->index], nu*oldLeftLength, tk02Rate[p->left->index]); - (*lnPriorRatio) -= LnProbTK02LogNormal (tk02Rate[p->index], nu*oldRightLength, tk02Rate[p->right->index]); - (*lnPriorRatio) += LnProbTK02LogNormal (tk02Rate[p->index], nu*p->left->length, tk02Rate[p->left->index]); - (*lnPriorRatio) += LnProbTK02LogNormal (tk02Rate[p->index], nu*p->right->length, tk02Rate[p->right->index]); - } - if (p->anc->anc != NULL) - { - (*lnPriorRatio) -= LnProbTK02LogNormal (tk02Rate[p->anc->index], nu*oldPLength, tk02Rate[p->index]); - (*lnPriorRatio) += LnProbTK02LogNormal (tk02Rate[p->anc->index], nu*p->length, tk02Rate[p->index]); - } - - /* update effective evolutionary lengths */ - if (p->left != NULL) - { - brlens[p->left->index] = p->left->length * (tk02Rate[p->left->index]+tk02Rate[p->index])/2.0; - brlens[p->right->index] = p->right->length * (tk02Rate[p->right->index]+tk02Rate[p->index])/2.0; - if (brlens[p->left->index] < RELBRLENS_MIN || brlens[p->left->index] > RELBRLENS_MAX || - brlens[p->right->index] < RELBRLENS_MIN || brlens[p->right->index] > RELBRLENS_MAX) - { - abortMove = YES; - return (NO_ERROR); - } - } - if (p->anc->anc != NULL) - { - brlens[p->index] = p->length * (tk02Rate[p->index]+tk02Rate[p->anc->index])/2.0; - if (brlens[p->index] < RELBRLENS_MIN || brlens[p->index] > RELBRLENS_MAX) - { - abortMove = YES; - return (NO_ERROR); - } - } - } - else if ( subParm->paramType == P_IGRBRANCHRATES || - (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_IGR)) - { - if (subParm->paramType == P_IGRBRANCHRATES) - igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].igrvar, chain, state[chain]); - else - igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].mixedvar, chain, state[chain]); - igrRate = GetParamVals (subParm, chain, state[chain]); - brlens = GetParamSubVals (subParm, chain, state[chain]); - - if (p->left != NULL) - { - (*lnPriorRatio) -= LnProbGamma (oldLeftLength/igrvar, oldLeftLength/igrvar, igrRate[p->left->index ]); - (*lnPriorRatio) -= LnProbGamma (oldRightLength/igrvar, oldRightLength/igrvar, igrRate[p->right->index]); - (*lnPriorRatio) += LnProbGamma (p->left->length/igrvar, p->left->length/igrvar, igrRate[p->left->index ]); - (*lnPriorRatio) += LnProbGamma (p->right->length/igrvar, p->right->length/igrvar, igrRate[p->right->index]); - } - if (p->anc->anc != NULL) - { - (*lnPriorRatio) -= LnProbGamma (oldPLength/igrvar, oldPLength/igrvar, igrRate[p->index]); - (*lnPriorRatio) += LnProbGamma (p->length /igrvar, p->length /igrvar, igrRate[p->index]); - } - - if (p->left != NULL) - { - brlens[p->left->index ] = igrRate[p->left->index ] * p->left->length; - brlens[p->right->index] = igrRate[p->right->index] * p->right->length; - if (brlens[p->left->index] < RELBRLENS_MIN || brlens[p->left->index] > RELBRLENS_MAX || - brlens[p->right->index] < RELBRLENS_MIN || brlens[p->right->index] > RELBRLENS_MAX) - { - abortMove = YES; - return (NO_ERROR); - } - } - if (p->anc->anc != NULL) - { - brlens[p->index] = igrRate[p->index] * p->length; - if (brlens[p->index] < RELBRLENS_MIN || brlens[p->index] > RELBRLENS_MAX) - { - abortMove = YES; - return (NO_ERROR); - } - } - } - } - -# if defined (DEBUG_CSLIDER) - printf ("After node slider (gene tree):\n"); - printf ("Old depth: %f -- New depth: %f -- LnPriorRatio %f -- LnProposalRatio %f\n", - oldDepth, newDepth, (*lnPriorRatio), (*lnProposalRatio)); - ShowNodes (t->root, 0, t->isRooted); - getchar(); -# endif - - return (NO_ERROR); - -} - - -/*------------------------------------------------------------------ -| -| Move_SpeciesTree: Propose a new species tree -| -------------------------------------------------------------------*/ -int Move_SpeciesTree (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp) -{ - int i, numGeneTrees, numUpperTriang; - double newLnProb, oldLnProb, backwardLnProposalProb, forwardLnProposalProb, *modMinDepths, - forwardLambda, backwardLambda, lambdaDiv, mean; - Tree *newSpeciesTree, *oldSpeciesTree, **geneTrees; - ModelInfo *m; - - /* get tuning parameter (lambda divider) */ - lambdaDiv = mvp[0]; - - /* calculate number of gene trees */ - numGeneTrees = param->nSubParams; - - /* get model settings */ - m = &modelSettings[param->relParts[0]]; - - /* get new and old species trees */ - newSpeciesTree = GetTree (m->speciesTree, chain, state[chain]); - oldSpeciesTree = GetTree (m->speciesTree, chain, state[chain] ^ 1); - - /* get gene trees */ - geneTrees = (Tree **) SafeCalloc (numGeneTrees, sizeof(Tree*)); - for (i=0; inSubParams; i++) - geneTrees[i] = GetTree(param->subParams[i], chain, state[chain]); - - /* get minimum depth matrix */ - GetMinDepthMatrix(geneTrees, numGeneTrees, depthMatrix); - - /* get forward lambda */ - GetMeanDist(oldSpeciesTree, depthMatrix, &mean); - forwardLambda = 1.0 / (mean * lambdaDiv); - - /* make a copy for modification */ - numUpperTriang = numSpecies * (numSpecies - 1) / 2; - modMinDepths = (double *) SafeCalloc (numUpperTriang, sizeof(double)); - for (i=0; istring = s; \ - p->fp = f; \ - p->valueList = l; \ - p++; -#define HIDE 0 -#define SHOW 1 - -/* Debugging options */ -#undef SHOW_TOKENS -#undef ECHO_PROCESSED_COMMANDS - -/* Local function prototypes */ -int AddNameSet(NameSet **nameSetList, int numNameSets, char **nameSet, int numNames); -int AddToSet (int i, int j, int k, int id); -int AllocCharacters (void); -int AllocMatrix (void); -int AllocTaxa (void); -char ChangeCase (char c); -int CharacterCode (char ch, int *charCode, int chType); -int CharacterNumber (int charCode, int chType); -int CheckInitialPartitions (void); -int Dex (TreeNode *p); -int DoAbout (void); -int DoAcknowledgments (void); -int DoBeginParm (char *parmName, char *tkn); -int DoBreaks (void); -int DoBreaksParm (char *parmName, char *tkn); -int DoCalibrate (void); -int DoCalibrateParm (char *parmName, char *tkn); -int DoCharset (void); -int DoCharsetParm (char *parmName, char *tkn); -int DoCharStat (void); -int DoCitations (void); -int DoConstraint (void); -int DoConstraintParm (char *parmName, char *tkn); -int DoCtype (void); -int DoCtypeParm (char *parmName, char *tkn); -int DoDelete (void); -int DoDeleteParm (char *parmName, char *tkn); -int DoDimensions (void); -int DoDimensionsParm (char *parmName, char *tkn); -int DoDisclaimer (void); -int DoEndBlock (void); -int DoExecuteParm (char *parmName, char *tkn); -int DoExclude (void); -int DoExcludeParm (char *parmName, char *tkn); -int DoFormat (void); -int DoFormatParm (char *parmName, char *tkn); -int DoHelp (void); -int DoHelpParm (char *parmName, char *tkn); -int DoInclude (void); -int DoIncludeParm (char *parmName, char *tkn); -int DoLog (void); -int DoLogParm (char *parmName, char *tkn); -int DoManual (void); -int DoManualParm (char *parmName, char *tkn); -int DoMatrix (void); -int DoMatrixParm (char *parmName, char *tkn); -int DoNexusParm (char *parmName, char *tkn); -int DoOutgroup (void); -int DoOutgroupParm (char *parmName, char *tkn); -int DoPairs (void); -int DoPairsParm (char *parmName, char *tkn); -int DoPartition (void); -int DoPartitionParm (char *parmName, char *tkn); -int DoRestore (void); -int DoRestoreParm (char *parmName, char *tkn); -int DoSet (void); -int DoSetParm (char *parmName, char *tkn); -int DoShowBeagle (void); -int DoShowMatrix (void); -int DoShowUserTrees (void); -int DoSpeciespartition (void); -int DoSpeciespartitionParm (char *parmName, char *tkn); -int DoTaxaset (void); -int DoTaxasetParm (char *parmName, char *tkn); -int DoTaxaStat (void); -int DoTaxlabels (void); -int DoTaxlabelsParm (char *parmName, char *tkn); -int DoTranslate (void); -int DoTranslateParm (char *parmName, char *tkn); -int DoTree (void); -int DoTreeParm (char *parmName, char *tkn); -int DoUserTree (void); -int DoUserTreeParm (char *parmName, char *tkn); -int DoVersion (void); -int FindValidParam (char *tk, int *numMatches); -int FreeCharacters (void); -int FreeMatrix (void); -int FreeTaxa (void); -int GetNumPartDivisions (int n); -int GetUserHelp (char *helpTkn); -int IsAmbig (int charCode, int dType); -int IsMissing (int charCode, int dType); -int MBResID (char nuc); -int NucID (char nuc); -void PrintSettings (char *command); -void PrintYesNo (int yn, char s[4]); -int ProtID (char aa); -int SetPartition (int part); -int SetSpeciespartition (int part); -int SetTaxaFromTranslateTable (void); -int StandID (char nuc); -void WhatVariableExp (BitsLong exp, char *st); -MrBFlt WhichCont (int x); - -/* globals */ -int autoClose; /* autoclose */ -int autoOverwrite; /* Overwrite or append outputfiles when nowarnings=yes */ -Calibration *calibrationPtr; /* ptr to calibration being set */ -CharInformation *charInfo; /* holds critical information about characters */ -BitsLong **charSet; /* holds information about defined charsets */ -char **charSetNames; /* holds names of character sets */ -Comptree comptreeParams; /* holds parameters for comparetree command */ -char **constraintNames; /* holds names of constraints */ -int dataType; /* type of data */ -Calibration defaultCalibration; /* default calibration */ -BitsLong **definedConstraint; /* bitfields representing taxa sets of defined constraints */ -BitsLong **definedConstraintTwo; /* bitfields representing second taxa sets of defined constraints (used for PARTIAL constraints) */ -BitsLong **definedConstraintPruned; /* bitfields representing taxa sets of defined constraints after delited taxa are removed */ -BitsLong **definedConstraintTwoPruned; /* bitfields representing second taxa sets of defined constraints for PARTIAL constraints after delited*/ - /* taxa are removed and for NEGATIVE constraint it contains complements of definedConstraintPruned */ -int echoMB; /* flag used by Manual to prevent echoing */ -BitsLong expecting; /* variable denoting expected token type */ -int foundNewLine; /* whether a new line has been found */ -int inComment; /* flag for whether input stream is commented */ -int inComparetreeCommand; /* flag set whenever you enter comparetree cmd */ -int inferAncStates; /* should ancestral states be inferred (y/n) */ -int inferSiteOmegas; /* should site omegas be inferred (y/n) */ -int inferSiteRates; /* should site rates be inferred (y/n) */ -int inMrbayesBlock; /* flag for whether we are in a mrbayes block */ -int inSumtCommand; /* flag set whenever you enter sumt cmd */ -int inTreesBlock; /* flag for whether we are in a trees block */ -int inValidCommand; /* a useful flag set whenever you enter a cmd */ -int isInAmbig, isInPoly; /* flags whether we are within () or {} */ -int isTaxsetDef; /* is a taxon set defined */ -int isTranslateDef; /* is a translation block defined */ -int isTranslateDiff; /* is translate different from current taxaset? */ -char logFileName[100]; /* name of the log file */ -int logToFile; /* should screen output be logged to a file */ -FILE *logFileFp; /* file pointer to log file */ -int longIntegerSize; /* size of an unsigned integer */ -char manFileName[100]; /* name of the file for the command help info */ -int *matrix; /* matrix containing original data */ -int matrixHasPoly; /* flag for whether matrix has polymorphisms */ -int memAllocs[NUM_ALLOCS]; /* allocated memory flags */ -int mode; /* mode of program (interactive/noninteractive) */ -Calibration *nodeCalibration; /* holds information about node calibrations */ -int noWarn; /* no warnings on overwriting files */ -int numChar; /* number of characters in character matrix */ -int numCharSets; /* number of character sets */ -int numComments; /* counts how deeply nested a comment is */ -int numDefinedConstraints; /* number of constraints defined */ -int numDefinedPartitions; /* number of partitions defined */ -int numDefinedSpeciespartitions; /* number of speciespartitions defined */ -int numNamedTaxa; /* number of named taxa during parsing of cmd */ -int numOpenExeFiles; /* number of execute files open */ -int numSpecies; /* number of species in current speciespartition */ -int numTaxa; /* number of taxa in character matrix */ -int numTaxaSets; /* number of taxa sets */ -int numTranslates; /* number of taxa in active translate block */ -int outGroupNum; /* number of outgroup taxon */ -ParmInfo paramTable[NUMPARAMS]; /* information on parameters */ -char **partitionNames; /* hold names of partitions (first is "default") */ -int **partitionId; /* holds information about defined partitions */ -int partitionNum; /* index of current partition */ -Plot plotParams; /* holds parameters for plot command */ -int precision; /* precision of samples and summary stats */ -int quitOnError; /* quit on error? */ -int replaceLogFile; /* should logfile be replace/appended to */ -int scientific; /* use scientific format for samples ? */ -char spacer[10]; /* holds blanks for printing indentations */ -NameSet *speciesNameSets; /* hold species name sets, one for each speciespartition */ -int **speciespartitionId; /* holds info about defined speciespartitions */ -char **speciespartitionNames; /* hold names of speciespartitions (first is "default") */ -int speciespartitionNum; /* index of current speciespartition */ -Sump sumpParams; /* holds parameters for sump command */ -Sumt sumtParams; /* holds parameters for sumt command */ -Sumss sumssParams; /* holds parameters for sumss command */ -TaxaInformation *taxaInfo; /* holds critical information about taxa */ -char **taxaNames; /* holds name of taxa */ -BitsLong **taxaSet; /* holds information about defined taxasets */ -char **taxaSetNames; /* holds names of taxa sets */ -int *tempActiveConstraints;/* temporarily holds active constraints size allcated */ -enum ConstraintType *definedConstraintsType; /* Store type of constraint */ -int *tempSet; /* temporarily holds defined set */ -int *tempSetNeg; /* holds bitset of negative set of taxa for partial constraint*/ -int theAmbigChar; /* int containing ambiguous character */ -Calibration *tipCalibration; /* holds information about node calibrations */ -char **transFrom; /* translation block information */ -char **transTo; /* translation block information */ -int userBrlensDef; /* are the branch lengths on user tree defined */ - -#if defined (BEAGLE_ENABLED) -int tryToUseBEAGLE; /* try to use the BEAGLE library */ -int beagleScalingScheme; /* BEAGLE dynamic scaling */ -int beagleScalingFrequency;/* BEAGLE dynamic scaling frequency */ -long beagleFlags; /* BEAGLE required resource flags */ -int beagleResourceNumber; /* BEAGLE resource number */ -int *beagleResource; /* BEAGLE resource choice list */ -int beagleResourceCount; /* BEAGLE resource choice list length */ -int beagleInstanceCount; /* total number of BEAGLE instances */ -#endif - -#if defined (THREADS_ENABLED) -int tryToUseThreads; /* try to use pthreads with BEAGLE library */ -#endif - -/* local (to this file) */ -char *tokenP, token[CMD_STRING_LENGTH], *cmdStr=NULL; -Calibration defaultCalibration = { - "Unconstrained", /* name */ - unconstrained, /* prior */ - { -1.0, -1.0, -1.0 }, /* priorParams */ - NULL, /* LnPriorProb */ - NULL, /* LnPriorRatio */ - -1.0, /* min */ - -1.0 /* max */ - }; - -CmdType commands[] = - { - /* Information on commands initialization: - - 1 = Command number (cmdNumber) - 2 = Command name (string) - 3 = Special command (YES/NO) (specialCmd) - 4 = Pointer to finishing function (fp) - 5 = Number of valid parameters (numParms) - 6 = List of valid parameters (parmList) - 7 = Expecting (2^TokenType) (expect) (PARAMETER = 4; SEMICOLON = 32; ALPHA = 16384; - ALPHA | QUESTIONMARK | DASH | NUMBER | ASTERISK | EXCLAMATIONMARK | PERCENT | WEIRD | SEMICOLON = 11715360; - ALPHA | QUESTIONMARK | DASH | NUMBER | ASTERISK | EXCLAMATIONMARK | PERCENT | WEIRD | SEMICOLON | LEFTPAR | RIGHTPAR | LEFTCURL | RIGHTCURL = 112381728; - PARAMETER | SEMICOLON = 36; NUMBER | ALPHA = 49152; ALPHA | SEMICOLON = 16416; EQUALSIGN = 8; NUMBER = 32768) - 8 = Description of the command (cmdDescription) - 9 = Where should the command be used (cmdUse) (IN_CMD = used from command line or mrbayes block; IN_FILE = used in data block or in tree block) - 10 = Should the command be shown when "help" is typed (hiding). - - #1 #2 #3 #4 #5 #6 #7 #8 #9 #10 - -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */ - { 0, "#", NO, NULL, 1, {0}, 4, "", IN_FILE, HIDE }, - { 1, "About", NO, DoAbout, 0, {-1}, 32, "Describes the program", IN_CMD, SHOW }, - { 2, "Acknowledgments", NO, DoAcknowledgments, 0, {-1}, 32, "Shows program acknowledgments", IN_CMD, SHOW }, - { 3, "Begin", NO, NULL, 6, {1,2,3,201,226,227}, 4, "Denotes beginning of block in file", IN_FILE, SHOW }, - { 4, "Calibrate", NO, DoCalibrate, 1, {119}, 4, "Assigns dates to terminals or interior nodes", IN_CMD, SHOW }, - { 5, "Charset", NO, DoCharset, 1, {15}, 4, "Assigns a group of sites to a set", IN_CMD, SHOW }, - { 6, "Charstat", NO, DoCharStat, 0, {-1}, 32, "Shows status of characters", IN_CMD, SHOW }, - { 7, "Citations", NO, DoCitations, 0, {-1}, 32, "Citation of program, models, and methods", IN_CMD, SHOW }, - { 8, "Comparetree", NO, DoCompareTree, 7, {127,128,129,130,221,222,223}, 36, "Compares the trees from two tree files", IN_CMD, SHOW }, - { 9, "Constraint", NO, DoConstraint, 1, {66}, 4, "Defines a constraint on tree topology", IN_CMD, SHOW }, - { 10, "Ctype", NO, DoCtype, 1, {65}, 4, "Assigns ordering for the characters", IN_CMD, SHOW }, - { 11, "Databreaks", YES, DoBreaks, 1, {93}, 32768, "Defines data breaks for autodiscrete gamma model", IN_CMD, SHOW }, - { 12, "Delete", YES, DoDelete, 1, {47}, 49152, "Deletes taxa from the analysis", IN_CMD, SHOW }, - { 13, "Dimensions", NO, DoDimensions, 2, {4,5}, 4, "Defines size of character matrix", IN_FILE, SHOW }, - { 14, "Disclaimer", NO, DoDisclaimer, 0, {-1}, 32, "Describes program disclaimer", IN_CMD, SHOW }, - { 15, "End", NO, DoEndBlock, 0, {-1}, 32, "Denotes end of a block in file", IN_FILE, SHOW }, - { 16, "Endblock", NO, DoEndBlock, 0, {-1}, 32, "Alternative way of denoting end of a block", IN_FILE, SHOW }, - { 17, "Exclude", YES, DoExclude, 1, {45}, 49152, "Excludes sites from the analysis", IN_CMD, SHOW }, - { 18, "Execute", YES, DoExecute, 1, {12}, 16384, "Executes a file", IN_CMD, SHOW }, - { 19, "Format", NO, DoFormat, 7, {6,7,8,9,10,219,220}, 4, "Defines character format in data block", IN_FILE, SHOW }, - { 20, "Help", YES, DoHelp, 1, {50}, 16416, "Provides detailed description of commands", IN_CMD, SHOW }, - { 21, "Include", YES, DoInclude, 1, {46}, 49152, "Includes sites", IN_CMD, SHOW }, - { 22, "Link", NO, DoLink, 30, {55,56,57,58,59,60,61,62,63,72,73,74,75,76,105,118,193,194,195,196,197,242,243,252,253,255,256, - 270,273,274}, 4, "Links parameters across character partitions", IN_CMD, SHOW }, - { 23, "Log", NO, DoLog, 5, {85,86,87,88,89}, 4, "Logs screen output to a file", IN_CMD, SHOW }, - { 24, "Lset", NO, DoLset, 16, {28,29,30,31,32,33,34,40,51,52,53,90,91,131,188,189}, 4, "Sets the parameters of the likelihood model", IN_CMD, SHOW }, - { 25, "Manual", NO, DoManual, 1, {126}, 36, "Prints a command reference to a text file", IN_CMD, SHOW }, - { 26, "Matrix", YES, DoMatrix, 1, {11},112381728, "Defines matrix of characters in data block", IN_FILE, SHOW }, - { 27, "Mcmc", NO, DoMcmc, 46, {17,18,19,20,21,22,23,24,25,26,27,84,98,112,113,114,115,116,132,142,143,144,148,149,150,151,152, - 153,154,155,156,157,158,159,160,166,169,190,191,198,199,200,202,213,214,215}, 36, "Starts Markov chain Monte Carlo analysis", IN_CMD, SHOW }, - { 28, "Mcmcp", NO, DoMcmcp, 46, {17,18,19,20,21,22,23,24,25,26,27,84,98,112,113,114,115,116,132,142,143,144,148,149,150,151,152, - 153,154,155,156,157,158,159,160,166,169,190,191,198,199,200,202,213,214,215}, 4, "Sets parameters of a chain (without starting analysis)", IN_CMD, SHOW }, - { 29, "Outgroup", YES, DoOutgroup, 1, {78}, 49152, "Changes outgroup taxon", IN_CMD, SHOW }, - { 30, "Pairs", YES, DoPairs, 1, {92}, 32768, "Defines nucleotide pairs (doublets) for stem models", IN_CMD, SHOW }, - { 31, "Partition", NO, DoPartition, 1, {16}, 4, "Assigns a character partition", IN_CMD, SHOW }, - { 32, "Plot", NO, DoPlot, 6, {106,107,108,109,224,225}, 36, "Plots parameters from MCMC analysis", IN_CMD, SHOW }, - { 33, "Prset", NO, DoPrset, 43, {35,36,37,38,39,41,42,43,44,54,64,67,68,69,70,71,77,100,101,102,103,104,110,111,117,120,121,133, - 168,172,173,174,183,184,185,218,241,246,247,251,254,269,271,272}, 4, "Sets the priors for the parameters", IN_CMD, SHOW }, - { 34, "Propset", NO, DoPropset, 1, {186}, 4, "Sets proposal probabilities and tuning parameters", IN_CMD, SHOW }, - { 35, "Quit", NO, DoQuit, 0, {-1}, 32, "Quits the program", IN_CMD, SHOW }, - { 36, "Report", NO, DoReport, 9, {122,123,124,125,134,135,136,192,217}, 4, "Controls how model parameters are reported", IN_CMD, SHOW }, - { 37, "Restore", YES, DoRestore, 1, {48}, 49152, "Restores taxa", IN_CMD, SHOW }, - { 38, "Set", NO, DoSet, 22, {13,14,94,145,170,171,179,181,182,216,229,233,234,235,236,237,238,239,240,245,268,275}, 4, "Sets run conditions and defines active data partition", IN_CMD, SHOW }, - { 39, "Showbeagle", NO, DoShowBeagle, 0, {-1}, 32, "Show available BEAGLE resources", IN_CMD, SHOW }, - { 40, "Showmatrix", NO, DoShowMatrix, 0, {-1}, 32, "Shows current character matrix", IN_CMD, SHOW }, - { 41, "Showmcmctrees", NO, DoShowMcmcTrees, 0, {-1}, 32, "Shows trees used in mcmc analysis", IN_CMD, SHOW }, - { 42, "Showmodel", NO, DoShowModel, 0, {-1}, 32, "Shows model settings", IN_CMD, SHOW }, - { 43, "Showmoves", NO, DoShowMoves, 1, {180}, 36, "Shows moves for current model", IN_CMD, SHOW }, - { 44, "Showparams", NO, DoShowParams, 0, {-1}, 32, "Shows parameters in current model", IN_CMD, SHOW }, - { 45, "Showusertrees", NO, DoShowUserTrees, 0, {-1}, 32, "Shows user-defined trees", IN_CMD, SHOW }, - { 46,"Speciespartition", NO,DoSpeciespartition, 1, {244}, 4, "Defines a partition of tips into species", IN_CMD, SHOW }, - { 47, "Ss", NO, DoSs, 50, {17,18,19,20,21,22,23,24,25,26,27,84,98,112,113,114,115,116,132,142,143,144,148,149,150,151,152, - 153,154,155,156,157,158,159,160,166,169,190,191,198,199,200,202,213,214,215,248,249,250,257}, 36, "Starts stepping-stone sampling", IN_CMD, SHOW }, - { 48, "Ssp", NO, DoSsp, 50, {17,18,19,20,21,22,23,24,25,26,27,84,98,112,113,114,115,116,132,142,143,144,148,149,150,151,152, - 153,154,155,156,157,158,159,160,166,169,190,191,198,199,200,202,213,214,215,248,249,250,257}, 36,"Sets parameters of stepping-stone analysis (without starting)",IN_CMD, SHOW }, - { 49, "Startvals", NO, DoStartvals, 1, {187}, 4, "Sets starting values of parameters", IN_CMD, SHOW }, - { 50, "Sump", NO, DoSump, 13, {96,97,137,138,139,140,141,161,162,178,211,212,231}, 36, "Summarizes parameters from MCMC analysis", IN_CMD, SHOW }, - { 51, "Sumss", NO, DoSumSs, 10, {258,259,260,261,262,263,264,265,266,267}, 36, "Summarizes parameters from stepping-stone analysis", IN_CMD, SHOW }, - { 52, "Sumt", NO, DoSumt, 21, {80,81,82,95,146,147,163,164,165,167,175,177,204,205,206,207,208,209,210,230,232}, 36, "Summarizes trees from MCMC analysis", IN_CMD, SHOW }, - { 53, "Taxastat", NO, DoTaxaStat, 0, {-1}, 32, "Shows status of taxa", IN_CMD, SHOW }, - { 54, "Taxset", NO, DoTaxaset, 1, {49}, 4, "Assigns a group of taxa to a set", IN_CMD, SHOW }, - { 55, "Taxlabels", YES, DoTaxlabels, 1, {228}, 49152, "Defines taxon labels", IN_FILE, SHOW }, - { 56, "Translate", YES, DoTranslate, 1, {83}, 49152, "Defines alternative names for taxa", IN_FILE, SHOW }, - { 57, "Tree", NO, DoTree, 1, {79}, 4, "Defines a tree", IN_FILE, SHOW }, - { 58, "Unlink", NO, DoUnlink, 30, {55,56,57,58,59,60,61,62,63,72,73,74,75,76,105,118,193,194,195,196,197,242,243,252,253,255,256, - 270,273,274}, 4, "Unlinks parameters across character partitions", IN_CMD, SHOW }, - { 59, "Usertree", YES, DoUserTree, 1, {203}, 8, "Defines a single user tree", IN_CMD, HIDE }, - { 60, "Version", NO, DoVersion, 0, {-1}, 32, "Shows program version", IN_CMD, SHOW }, - /* NOTE: If you add a command here, make certain to change NUMCOMMANDS (above, in this file) appropriately! */ - { 999, NULL, NO, NULL, 0, {-1}, 32, "", IN_CMD, HIDE } - }; -int inDataBlock, inForeignBlock, isInterleaved, isFirstMatrixRead, isFirstInterleavedBlock, - taxonCount, fromI, toJ, everyK, foundDash, foundSlash, foundFirst, isMixed, whichPartition, - isNegative, numDivisions, charOrdering, foundExp, foundColon, isFirstNode, nextAvailableNode, - pairId, firstPair, inTaxaBlock, inCharactersBlock, foundEqual; -char gapId, missingId, matchId, tempSetName[100], **tempNames; -CmdType *commandPtr; /*Points to the commands array entery which corresponds to currently processed command*/ -ParmInfoPtr paramPtr; /*Points to paramTable table array entery which corresponds to currently processed parameter of current command*/ -TreeNode *pPtr, *qPtr; - -enum ConstraintType consrtainType; /* Used only in processing of constraine command to indicate what is the type of constrain */ - - -int AddToGivenSet (int i, int j, int k, int id, int *Set) -{ - int m, n; - - if (id <= 0) - { - MrBayesPrint ("%s The id for a temporary set should be greater than 0\n", spacer); - return (ERROR); - } - - if (i < 0 && j < 0) - return (ERROR); - else if (i < 0 && j >= 0) - return (ERROR); - else if (i >= 0 && j < 0) - { - if (k >= 0) - return (ERROR); - else - { - if (Set[i] != 0) - { - MrBayesPrint ("%s Character %d defined more than once\n", spacer, i+1); - return (ERROR); - } - Set[i] = id; - } - } - else if (i >= 0 && j >= 0) - { - if (k < 0) - { - for (m=i; m<=j; m++) - { - if (Set[m] != 0) - { - MrBayesPrint ("%s Character %d defined more than once\n", spacer, m+1); - return (ERROR); - } - Set[m] = id; - } - } - else - { - n = k; - for (m=i; m<=j; m++) - { - if (n % k == 0) - { - if (Set[m] != 0) - { - MrBayesPrint ("%s Character %d defined more than once\n", spacer, m+1); - return (ERROR); - } - Set[m] = id; - } - n++; - } - } - } - - return (NO_ERROR); - -} - - -int AddToSet (int i, int j, int k, int id) -{ - return AddToGivenSet (i, j, k,id, tempSet); -} - - -/* AddNameSet: Push a name set onto the end of a list of name sets, with reallocation - of list to hold the extra element. The calling function needs to keep track of - the counter holding the length of the list. */ -int AddNameSet (NameSet **nameSetList, int numNameSets, char **nameSet, int numNames) -{ - int i; - - (*nameSetList) = (NameSet*) SafeRealloc ((void*)(*nameSetList), (size_t)(((numNameSets+1)*sizeof(NameSet)))); - - (*nameSetList)[numNameSets].names = NULL; - (*nameSetList)[numNameSets].numNames = numNames; - - for (i=0; i numTaxa) - tempSetSize = numChar; - else - tempSetSize = numTaxa; - tempSet = (int *)SafeRealloc((void *)tempSet, (size_t) (tempSetSize * sizeof(int))); - tempSetNeg = (int *)SafeRealloc((void *)tempSetNeg, (size_t) (tempSetSize * sizeof(int))); - if (!tempSet || !tempSetNeg) - { - MrBayesPrint ("%s Problem reallocating tempSet (%d)\n", spacer, tempSetSize * sizeof(int)); - goto errorExit; - } - - MrBayesPrint ("%s Allocated matrix\n", spacer); - return (NO_ERROR); - - errorExit: - MrBayesPrint ("%s Problem allocating matrix\n", spacer); - FreeMatrix(); - return (ERROR); -} - - -int AllocMatrix (void) -{ - if (memAllocs[ALLOC_TAXA] == NO && AllocTaxa() == ERROR) - return ERROR; - else - return (AllocCharacters()); -} - - -int AllocTaxa (void) -{ - int i; - - if (defTaxa==NO) - { - MrBayesPrint ("%s Number of taxa not defined\n", spacer); - return (ERROR); - } - if (numTaxa == 0) - { - MrBayesPrint ("%s Number of taxa is 0\n", spacer); - return (ERROR); - } - - /* allocate space for taxa */ - if (memAllocs[ALLOC_TAXA] == YES) - goto errorExit; - taxaNames = NULL; /* This variable is allocated in AddString */ - taxaInfo = (TaxaInformation *)SafeMalloc((size_t) (numTaxa * sizeof(TaxaInformation))); - if (!taxaInfo) - { - goto errorExit; - } - tipCalibration = (Calibration *)SafeMalloc((size_t) (numTaxa * sizeof(Calibration))); - if (!tipCalibration) - { - free (taxaInfo); - taxaInfo = NULL; - goto errorExit; - } - for (i=0; i 0) - { - MrBayesPrint ("%s Previous user trees not freed\n", spacer); - goto errorExit; - } - - MrBayesPrint ("%s Allocated taxon set\n", spacer); - return NO_ERROR; - -errorExit: - MrBayesPrint ("%s Problem allocating taxon set\n", spacer); - FreeTaxa(); - return ERROR; -} - - -char ChangeCase (char c) -{ - int x; - - x = tolower(c); - return (x); -} - - -int CharacterCode (char ch, int *charCode, int chType) -{ - if (chType == DNA || chType == RNA) - { - if ((*charCode = NucID (ch)) == -1) - { - MrBayesPrint ("%s Unrecognized DNA/RNA character '%c'\n", spacer, ch); - return (ERROR); - } - } - else if (chType == PROTEIN) - { - if ((*charCode = ProtID (ch)) == -1) - { - MrBayesPrint ("%s Unrecognized Protein character '%c'\n", spacer, ch); - return (ERROR); - } - } - else if (chType == RESTRICTION) - { - if ((*charCode = MBResID (ch)) == -1) - { - MrBayesPrint ("%s Unrecognized Restriction character '%c'\n", spacer, ch); - return (ERROR); - } - } - else if (chType == STANDARD) - { - if ((*charCode = StandID (ch)) == -1) - { - MrBayesPrint ("%s Unrecognized Standard character '%c'\n", spacer, ch); - return (ERROR); - } - } - else if (chType == CONTINUOUS) - { - MrBayesPrint ("%s CharacterCode function cannot check continuous characters\n", spacer); - } - else - { - MrBayesPrint ("%s Unrecognized character type (%d)\n", spacer, chType); - return (ERROR); - } - - return (NO_ERROR); -} - - -int CharacterNumber (int charCode, int chType) -{ - int i, x = charCode; - - if (chType == CONTINUOUS) - return 0; - - for (i=0; x!=0; i++) - x >>= 1; - - return (i); -} - - -int CheckInitialPartitions (void) -{ - int i; - - for (i=0; i numDivisions) - { - MrBayesPrint ("%s The partition for site %d is incorrect\n", spacer, i+1); - return (ERROR); - } - } - - return (NO_ERROR); -} - - -int CheckStringValidity (char *s) -{ - int i, numUnknownChars, tempNumComments, tempInComment; - char temp[100]; - - i = 0; - numUnknownChars = 0; - tempNumComments = numComments; - tempInComment = inComment; - - while (s[i] != '\0') - { - if (tempInComment == NO) - { - if (!IsIn(s[i],"=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789.;:,#()[]?-*/'\\'!%\"&~+^$@|{}`>< ")) - { - if (IsWhite(s[i]) == 1 || IsWhite(s[i]) == 2) - { - - } - else - { - if (commandPtr == NULL) - return (ERROR); - MrBayesPrint ("%s Unknown character \"%c\" (ASCII code %d)\n", spacer, s[i], s[i]); - if (!strcmp(commandPtr->string,"Matrix")) - { - if (foundNewLine == NO) - { - MrBayesPrint ("%s The error is in character %d for taxon %s\n", spacer, taxaInfo[taxonCount-1].charCount+i+1, "???"); /* bug? */ - } - else - { - if (taxonCount == 0) - MrBayesPrint ("%s The error is in the first taxon name\n", spacer); - else - { - strcpy(temp, taxaNames[taxonCount]); - if (isInterleaved == NO) - MrBayesPrint ("%s The error is in the name of the taxon following taxon %s\n", spacer, temp); - else - { - MrBayesPrint ("%s The error is in the name of the taxon following taxon %s\n", spacer, temp); - MrBayesPrint ("%s in one of the interleaved data blocks\n", spacer); - } - } - } - } - else if (!strcmp(commandPtr->string,"Execute")) - { - MrBayesPrint ("%s Assuming irrelevant characters at beginning of file; processing continues\n", spacer); - return (NO_ERROR); - } - return (ERROR); - } - } - if (s[i]=='[') - { - tempInComment = YES; - tempNumComments++; - } - } - else if (tempInComment == YES) - { - if (s[i]==']') - { - tempNumComments--; - if (tempNumComments == 0) - tempInComment = NO; - } - } - i++; - } - - if (numUnknownChars > 0) - return (ERROR); - else - return (NO_ERROR); -} - - -/* CheckString: This function simply checks a vector of strings for a match against token. - Upon return, matchIndex contains the index of the matched string. An - ERROR is returned if there are no matches. */ -int CheckString (char **list, int len, char *token, int *matchIndex) -{ - int i; - - *matchIndex = -1; - for (i=0; iindex; -} - - -int DoAbout (void) -{ - MrBayesPrint (" --------------------------------------------------------------------------- \n"); - MrBayesPrint (" About the program \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" MrBayes is a program for the Bayesian estimation of phylogeny. Bayesian \n"); - MrBayesPrint (" inference of phylogeny is based upon the posterior probability distribution \n"); - MrBayesPrint (" of trees. Trees are labelled T1, T2, ..., Tn, where n is the number of \n"); - MrBayesPrint (" possible trees. The posterior probability of the i-th tree is calculated \n"); - MrBayesPrint (" using Bayes\'s formula as \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" Pr[Ti | X] = Pr[X | Ti] X Pr[Ti] / Pr[X] \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" where X is a character matrix. Here, \"Pr[Ti | X]\" is the posterior \n"); - MrBayesPrint (" probability of the i-th tree, \"Pr[X | Ti]\" is the likelihood of the \n"); - MrBayesPrint (" i-th tree, and \"Pr[Ti]\" is the prior probability of the i-th tree. The \n"); - MrBayesPrint (" denominator of Bayes\'s formula (\"Pr[X]\") is a normalizing constant that \n"); - MrBayesPrint (" involves a summation over all possible trees. The likelihood, as described \n"); - MrBayesPrint (" above, cannot be calculated with knowledge of only the tree\'s topology. You \n"); - MrBayesPrint (" also need to have information on the lenths of the branches and on the \n"); - MrBayesPrint (" mechanism of character change. Hence, the likelihood (\"Pr[X | Ti]\") \n"); - MrBayesPrint (" involves a multidimensional integral over all possible combinations of \n"); - MrBayesPrint (" branch lengths and substitution model parameters. \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" In practice, it is impossible to calculate the posterior probability dist- \n"); - MrBayesPrint (" ribution of trees analytically. Instead, the posterior probability \n"); - MrBayesPrint (" of trees must be approximated. MrBayes uses a method called Markov chain \n"); - MrBayesPrint (" Monte Carlo (MCMC) to approximate the posterior probability of trees. \n"); - MrBayesPrint (" The object of MCMC is to construct a Markov chain that has as its state \n"); - MrBayesPrint (" space the parameters of the phylogenetic model and a stationary distribution \n"); - MrBayesPrint (" that is the posterior probability distribution of trees. MCMC takes valid, \n"); - MrBayesPrint (" albeit dependent, samples from the posterior probability distribution of \n"); - MrBayesPrint (" trees. The fraction of the time any tree appears in this sample is a \n"); - MrBayesPrint (" valid approximation of the posterior probability of the tree. MrBayes keeps \n"); - MrBayesPrint (" track of all the parameters of the phylogenetic model. The trees (with branch \n"); - MrBayesPrint (" lengths) that were sampled by the MCMC procedure are saved in one file \n"); - MrBayesPrint (" (a file with a \".t\" extension) whereas the parameters of the model of \n"); - MrBayesPrint (" character change are saved in another file (a file with a \".p\" ext- \n"); - MrBayesPrint (" ension). You can summarize the results in the \".t\" and \".p\" files \n"); - MrBayesPrint (" using the \"sumt\" and \"sump\" commands, respectively. \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" MrBayes was originally written by John Huelsenbeck in August of 2000 and was \n"); - MrBayesPrint (" intended to be distributed to a small number of people. In March of 2001, \n"); - MrBayesPrint (" Fredrik Ronquist started making contributions to the program. The contribu- \n"); - MrBayesPrint (" tions were of such a significant nature that he was made a coauthor of the \n"); - MrBayesPrint (" program. Version 3 of MrBayes was a fully joint effort, started in the summer \n"); - MrBayesPrint (" of 2002 when JPH visited Sweden on a grant from the Wenner-Gren Foundations. \n"); - MrBayesPrint (" Several others have contributed to the MrBayes code since then, most notably \n"); - MrBayesPrint (" Paul van der Mark and Maxim Teslenko, both postdocs/programmers in Fredrik's \n"); - MrBayesPrint (" lab. A large number of users and students, too many to list here, have also \n"); - MrBayesPrint (" contributed importantly to the project (type 'Acknowledgments' for a list of \n"); - MrBayesPrint (" some of them). \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" Since 2003, MrBayes has been distributed from SourceForge. Bugs can be repor- \n"); - MrBayesPrint (" ted to the MrBayes site on SourceForge or by contacting Maxim Teslenko \n"); - MrBayesPrint (" (maxim.teslenko@nrm.se) directly. \n"); - MrBayesPrint (" --------------------------------------------------------------------------- \n"); - - return (NO_ERROR); -} - - -int DoAcknowledgments (void) -{ - MrBayesPrint (" --------------------------------------------------------------------------- \n"); - MrBayesPrint (" Acknowledgments \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" JPH and FR would like to thank Gautam Altekar, Andrea Betancourt, Jon \n"); - MrBayesPrint (" Bollback, Barry Hall, Jimmy McGuire, Rasmus Nielsen, David Swofford, \n"); - MrBayesPrint (" Johan Nylander, Mikael Thollesson, and Derrick Zwickl for help during the \n"); - MrBayesPrint (" initial development of this program. Gautam Altekar, especially, was instru- \n"); - MrBayesPrint (" mental in getting the parallel version of the program working. Important bug- \n"); - MrBayesPrint (" fixes and additional functionality was contributed by Clemens Lakner, Sebas- \n"); - MrBayesPrint (" tian Hoehna, Paul Lewis, Mark Holder, Julian Catchen and Bret Larget. Marc \n"); - MrBayesPrint (" Suchard, Daniel Ayres and Aaron Darling got mrbayes working with beagle and \n"); - MrBayesPrint (" contributed a lot of related functionality and bug fixes. Aaron Darling was \n"); - MrBayesPrint (" instrumental in getting the Windows installer set up. Liu Liang and Dennis \n"); - MrBayesPrint (" Pearl helped integrate MrBayes with BEST. \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" Bug fixes and user support was provided by Paul van der Mark (2005-2007) and \n"); - MrBayesPrint (" from 2010 by Maxim Teslenko (maxim.teslenko@nrm.se). \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" Our wives -- Edna Huelsenbeck and Eva Ronquist -- showed extraordinary \n"); - MrBayesPrint (" patience with us while we spent many late nights programming. \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" JPH was supported by NSF grants DEB-007540 and MCB-0075404 and a Wenner- \n"); - MrBayesPrint (" Gren scholarship while writing this program. FR was supported by grants \n"); - MrBayesPrint (" from the Swedish Natural Science Research Council and the Swedish Research \n"); - MrBayesPrint (" Council. \n"); - MrBayesPrint (" --------------------------------------------------------------------------- \n"); - - return (NO_ERROR); -} - - -int DoBeginParm (char *parmName, char *tkn) -{ - if (expecting == Expecting(PARAMETER)) - { - /* set Data (inDataBlock) *************************************************************/ - if (!strcmp(parmName, "Data")) - { - if (FreeModel () == ERROR) - return (ERROR); - if (FreeMatrix () == ERROR) - return (ERROR); - MrBayesPrint (" Reading data block\n"); - inDataBlock = YES; - expecting = Expecting(SEMICOLON); - strcpy (spacer, " "); - } - /* set Characters (inCharactersBlock) *************************************************************/ - else if (!strcmp(parmName, "Characters")) - { - if (FreeModel () == ERROR) - return (ERROR); - if (FreeCharacters () == ERROR) - return (ERROR); - MrBayesPrint (" Reading characters block\n"); - inCharactersBlock = YES; - expecting = Expecting(SEMICOLON); - strcpy (spacer, " "); - } - /* set Taxa (inTaxaBlock) *************************************************************/ - else if (!strcmp(parmName, "Taxa")) - { - if (FreeModel () == ERROR) - return (ERROR); - if (FreeMatrix () == ERROR) - return (ERROR); - MrBayesPrint (" Reading taxa block\n"); - inTaxaBlock = YES; - expecting = Expecting(SEMICOLON); - strcpy (spacer, " "); - } - /* set Mrbayes (inMrbayesBlock) *******************************************************/ - else if (!strcmp(parmName, "Mrbayes")) - { - MrBayesPrint (" Reading mrbayes block\n"); - inMrbayesBlock = YES; - expecting = Expecting(SEMICOLON); - strcpy (spacer, " "); - } - /* set Trees (inTreesBlock) *******************************************************/ - else if (!strcmp(parmName, "Trees")) - { - MrBayesPrint (" Reading trees block\n"); - inTreesBlock = YES; - expecting = Expecting(SEMICOLON); - strcpy (spacer, " "); - } - /* set Foreign (inForeignBlock) *******************************************************/ - else - { - MrBayesPrint (" Skipping \"%s\" block\n", tkn); - inForeignBlock = YES; - expecting = Expecting(SEMICOLON); - strcpy (spacer, ""); - } - } - else - return (ERROR); - - return (NO_ERROR); -} - - -int DoBreaks (void) -{ - int i, numBreaks; - - numBreaks = 0; - for (i=0; i 0) - { - if (numBreaks == 1) - MrBayesPrint ("%s One data break found after character ", spacer, numBreaks); - else - MrBayesPrint ("%s %d data breaks found after characters: ", spacer, numBreaks); - for (i=0; i numChar) - { - MrBayesPrint ("%s Character number %d is out of range (should be between %d and %d)\n", spacer, tempInt, 1, numChar); - for (i=0; i 1) - { - MrBayesPrint ("%s Both a taxon and a constraint named ""%s"" encountered -- please rename one\n", spacer, tkn); - return (ERROR); - } - - /* get ready to find the equal sign */ - expecting = Expecting(EQUALSIGN); - } - - else if (expecting == Expecting(EQUALSIGN)) - { - /* get ready to find the calibration prior */ - expecting = Expecting(ALPHA); - } - - else if (expecting == Expecting(ALPHA)) - { - /* set the calibration prior type */ - if (IsArgValid(tkn,tempStr) == NO_ERROR) - { - if (!strcmp (tempStr, "Unconstrained")) - calPrior = unconstrained; - else if (!strcmp (tempStr, "Fixed")) - calPrior = fixed; - else if (!strcmp (tempStr, "Uniform")) - calPrior = uniform; - else if (!strcmp (tempStr, "Offsetexponential")) - calPrior = offsetExponential; - else if (!strcmp (tempStr, "Truncatednormal")) - calPrior = truncatedNormal; - else if (!strcmp (tempStr, "Lognormal")) - calPrior = logNormal; - else if (!strcmp (tempStr, "Offsetlognormal")) - calPrior = offsetLogNormal; - else if (!strcmp (tempStr, "Gamma")) - calPrior = standardGamma; - else if (!strcmp (tempStr, "Offsetgamma")) - calPrior = offsetGamma; - - if (calPrior == unconstrained) - { - /* reset the values of the calibration */ - MrBayesPrint ("%s Resetting previous calibration for ""%s""\n", spacer, nodeName); - - calibrationPtr->prior = defaultCalibration.prior; - calibrationPtr->priorParams[0] = defaultCalibration.priorParams[0]; - calibrationPtr->priorParams[1] = defaultCalibration.priorParams[1]; - calibrationPtr->priorParams[2] = defaultCalibration.priorParams[2]; - calibrationPtr->LnPriorProb = defaultCalibration.LnPriorProb; - calibrationPtr->LnPriorRatio = defaultCalibration.LnPriorRatio; - calibrationPtr->min = defaultCalibration.min; - calibrationPtr->max = defaultCalibration.max; - strcpy(calibrationPtr->name, defaultCalibration.name); - - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - { - strcpy (calName, tempStr); - paramIndex = 0; - priorParams[0] = priorParams[1] = priorParams[2] = -1.0; - expecting = Expecting(LEFTPAR); - } - } - else - { - MrBayesPrint ("%s Invalid calibration prior argument \n", spacer); - return (ERROR); - } - } - else if (expecting == Expecting(LEFTPAR)) - { - strcat (calName, "("); - expecting = Expecting(NUMBER); - } - else if (expecting == Expecting(NUMBER)) - { - sscanf (tkn, "%lf", &tempD); - if (paramIndex == 0) - { - if (calPrior == logNormal) - { - if (tempD < 0.0) - { - MrBayesPrint ("%s Mean age must be nonnegative\n", spacer); - MrBayesPrint ("%s Parameters of the lognormal distribution used for dating are mean age\n", spacer); - MrBayesPrint ("%s and standard deviation, both specified on the linear scale, not as log values.\n", spacer); - return (ERROR); - } - } - else if (calPrior == standardGamma) - { - if (tempD <= 0.0) - { - MrBayesPrint ("%s Mean parameter must be positive\n", spacer); - MrBayesPrint ("%s Parameters of the gamma distribution used for dating are mean age and\n", spacer); - MrBayesPrint ("%s standard deviation. In terms of the common shape (alpha) and rate (beta)\n", spacer); - MrBayesPrint ("%s parameterization, the expected mean is alpha/beta and the standard\n", spacer); - MrBayesPrint ("%s deviation is the square root of (alpha / beta^2).\n", spacer); - return (ERROR); - } - } - else - { - if (tempD < 0.0) - { - if (calPrior == fixed) - MrBayesPrint ("%s Fixed age must be nonnegative\n", spacer); - else if (calPrior == uniform) - { - MrBayesPrint ("%s Minimum age must be nonnegative\n", spacer); - MrBayesPrint ("%s Parameters of the uniform are minimum age and maximum age.\n", spacer); - } - else if (calPrior == truncatedNormal) - { - MrBayesPrint ("%s Offset (minimum or truncation) age must be nonnegative.\n", spacer); - MrBayesPrint ("%s Parameters of the truncated normal distribution are offset (minimum\n", spacer); - MrBayesPrint ("%s or truncation) age, mean age and standard deviation.\n", spacer); - } - else if (calPrior == offsetGamma) - { - MrBayesPrint ("%s Offset age must be nonnegative\n", spacer); - MrBayesPrint ("%s Parameters of the offset gamma distribution used for dating are offset age,\n", spacer); - MrBayesPrint ("%s mean age, and standard deviation. In terms of the common shape (alpha) and\n", spacer); - MrBayesPrint ("%s rate (beta) parameterization, the expected mean is alpha/beta and the standard\n", spacer); - MrBayesPrint ("%s deviation is the square root of (alpha / beta^2).\n", spacer); - } - else if (calPrior == offsetExponential) - { - MrBayesPrint ("%s Offset age must be nonnegative\n", spacer); - MrBayesPrint ("%s Parameters of the offset exponential are offset age and mean age.\n", spacer); - } - else if (calPrior == offsetLogNormal) - { - MrBayesPrint ("%s Offset age must be nonnegative\n", spacer); - MrBayesPrint ("%s Parameters of the offset lognormal distribution are offset age, mean age,\n", spacer); - MrBayesPrint ("%s and standard deviation. All values are specified on the linear scale, not\n", spacer); - MrBayesPrint ("%s as log values.\n", spacer); - } - return (ERROR); - } - } - priorParams[0] = tempD; - if (calPrior == fixed) - expecting = Expecting(RIGHTPAR); - else - expecting = Expecting(COMMA); - } - else if (paramIndex == 1) - { - if (calPrior == uniform) - { - if (tempD <= priorParams[0]) - { - MrBayesPrint ("%s Maximum age of uniform distribution must be larger than minimum age\n", spacer); - return (ERROR); - } - } - else if (calPrior == offsetExponential) - { - if (tempD <= priorParams[0]) - { - MrBayesPrint ("%s Mean age must be larger than offset age.\n", spacer); - MrBayesPrint ("%s MrBayes now uses offset and mean rather than offset and rate\n", spacer); - MrBayesPrint ("%s as the parameters for the offset exponential distribution.\n", spacer); - return (ERROR); - } - } - else if (calPrior == truncatedNormal) - { - if (tempD <= priorParams[0]) - { - MrBayesPrint ("%s Mean age must be larger than offset (truncation) age.\n", spacer); - MrBayesPrint ("%s Parameters of the truncated normal distribution are offset (minimum\n", spacer); - MrBayesPrint ("%s or truncation) age, mean age and standard deviation\n", spacer); - return (ERROR); - } - } - else if (calPrior == logNormal) - { - if (tempD <= 0.0) - { - MrBayesPrint ("%s Standard deviation must be positive.\n", spacer); - MrBayesPrint ("%s Parameters of the lognormal distribution used for dating are mean age\n", spacer); - MrBayesPrint ("%s and standard deviation, both specified on the linear scale, not as log values.\n", spacer); - return (ERROR); - } - } - else if (calPrior == offsetLogNormal) - { - if (tempD <= priorParams[0]) - { - MrBayesPrint ("%s Mean age must be larger than offset age.\n", spacer); - MrBayesPrint ("%s Parameters of the offset lognormal distribution are offset age, mean age,\n", spacer); - MrBayesPrint ("%s and standard deviation. All values are specified on the linear scale, not\n", spacer); - MrBayesPrint ("%s as log values.\n", spacer); - return (ERROR); - } - } - else if (calPrior == standardGamma) - { - if (tempD <= 0.0) - { - MrBayesPrint ("%s Standard deviation must be positive.\n", spacer); - MrBayesPrint ("%s Parameters of the gamma distribution used for dating are mean age and\n", spacer); - MrBayesPrint ("%s standard deviation. In terms of the common shape (alpha) and rate (beta)\n", spacer); - MrBayesPrint ("%s parameterization, the expected mean is alpha/beta and the standard\n", spacer); - MrBayesPrint ("%s deviation is the square root of (alpha / beta^2).\n", spacer); - return (ERROR); - } - } - else if (calPrior == offsetGamma) - { - if (tempD <= 0.0) - { - MrBayesPrint ("%s Mean age must be positive.\n", spacer); - MrBayesPrint ("%s Parameters of the offset gamma distribution used for dating are offset age,\n", spacer); - MrBayesPrint ("%s mean age, and standard deviation. In terms of the common shape (alpha) and\n", spacer); - MrBayesPrint ("%s rate (beta) parameterization, the expected mean is alpha/beta and the standard\n", spacer); - MrBayesPrint ("%s deviation is the square root of (alpha / beta^2).\n", spacer); - return (ERROR); - } - } - - priorParams[1] = tempD; - if (calPrior == uniform || calPrior == standardGamma || calPrior == logNormal || calPrior == offsetExponential) - expecting = Expecting(RIGHTPAR); - else - expecting = Expecting(COMMA); - } - else /* if (paramIndex == 2) */ - { - if (calPrior == offsetGamma) - { - if (tempD <= 0.0) - { - MrBayesPrint ("%s Standard deviation must be positive.\n", spacer); - MrBayesPrint ("%s Parameters of the offset gamma distribution used for dating are offset age,\n", spacer); - MrBayesPrint ("%s mean age, and standard deviation. In terms of the common shape (alpha) and\n", spacer); - MrBayesPrint ("%s rate (beta) parameterization, the expected mean is alpha/beta and the standard\n", spacer); - MrBayesPrint ("%s deviation is the square root of (alpha / beta^2).\n", spacer); - return (ERROR); - } - } - else if (calPrior == offsetLogNormal) - { - if (tempD <= 0.0) - { - MrBayesPrint ("%s Standard deviation must be positive.\n", spacer); - MrBayesPrint ("%s Parameters of the offset lognormal distribution are offset age, mean age,\n", spacer); - MrBayesPrint ("%s and standard deviation. All values are specified on the linear scale, not\n", spacer); - MrBayesPrint ("%s as log values.\n", spacer); - return (ERROR); - } - } - priorParams[2] = tempD; - expecting = Expecting(RIGHTPAR); - } - sprintf (s, "%1.2lf", tempD); - strcat (calName, s); - } - else if (expecting == Expecting(COMMA)) - { - strcat (calName, ","); - paramIndex++; - expecting = Expecting(NUMBER); - } - else if (expecting == Expecting(RIGHTPAR)) - { - strcat (calName, ")"); - if (isTaxon == YES) - MrBayesPrint ("%s Setting age of taxon '%s' to %s\n", spacer, nodeName, calName); - else - MrBayesPrint ("%s Setting age of constraint node '%s' to %s\n", spacer, nodeName, calName); - - /* set calibration based on collected values and settings */ - strcpy(calibrationPtr->name, calName); - calibrationPtr->priorParams[0] = priorParams[0]; - calibrationPtr->priorParams[1] = priorParams[1]; - calibrationPtr->priorParams[2] = priorParams[2]; - calibrationPtr->prior = calPrior; - if (calPrior == fixed) - { - calibrationPtr->LnPriorProb = &LnPriorProbFix; - calibrationPtr->LnPriorRatio = &LnProbRatioFix; - calibrationPtr->min = priorParams[0]; - calibrationPtr->max = priorParams[0]; - } - else if (calPrior == uniform) - { - calibrationPtr->LnPriorProb = &LnPriorProbUniform; - calibrationPtr->LnPriorRatio = &LnProbRatioUniform; - calibrationPtr->min = priorParams[0]; - calibrationPtr->max = priorParams[1]; - } - else if (calPrior == offsetExponential) - { - calibrationPtr->LnPriorProb = &LnPriorProbOffsetExponential_Param_Offset_Mean; - calibrationPtr->LnPriorRatio = &LnProbRatioOffsetExponential_Param_Offset_Mean; - calibrationPtr->min = priorParams[0]; - calibrationPtr->max = POS_INFINITY; - } - else if (calPrior == truncatedNormal) - { - calibrationPtr->LnPriorProb = &LnPriorProbTruncatedNormal_Param_Trunc_Mean_Sd; - calibrationPtr->LnPriorRatio = &LnProbRatioTruncatedNormal_Param_Trunc_Mean_Sd; - calibrationPtr->min = priorParams[0]; - calibrationPtr->max = POS_INFINITY; - } - else if (calPrior == logNormal) - { - calibrationPtr->LnPriorProb = &LnPriorProbLognormal_Param_Mean_Sd; - calibrationPtr->LnPriorRatio = &LnProbRatioLognormal_Param_Mean_Sd; - calibrationPtr->min = 0.0; - calibrationPtr->max = POS_INFINITY; - } - else if (calPrior == offsetLogNormal) - { - calibrationPtr->LnPriorProb = &LnPriorProbOffsetLognormal_Param_Offset_Mean_Sd; - calibrationPtr->LnPriorRatio = &LnProbRatioOffsetLognormal_Param_Offset_Mean_Sd; - calibrationPtr->min = priorParams[0]; - calibrationPtr->max = POS_INFINITY; - } - else if (calPrior == standardGamma) - { - calibrationPtr->LnPriorProb = &LnPriorProbGamma_Param_Mean_Sd; - calibrationPtr->LnPriorRatio = &LnProbRatioGamma_Param_Mean_Sd; - calibrationPtr->min = 0.0; - calibrationPtr->max = POS_INFINITY; - } - else if (calPrior == offsetGamma) - { - calibrationPtr->LnPriorProb = &LnPriorProbOffsetGamma_Param_Offset_Mean_Sd; - calibrationPtr->LnPriorRatio = &LnProbRatioOffsetGamma_Param_Offset_Mean_Sd; - calibrationPtr->min = priorParams[0]; - calibrationPtr->max = POS_INFINITY; - } - - /* get ready to find more calibrated nodes or taxa, if present */ - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - - return (NO_ERROR); -} - - -int DoCharset (void) -{ - /* first add set to tempSet */ - if (fromI >= 0 && toJ < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - } - else if (fromI >= 0 && toJ >= 0 && everyK < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - } - else if (fromI >= 0 && toJ >= 0 && everyK >= 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - } - - /* add name to charSetNames */ - if (AddString (&charSetNames, numCharSets, tempSetName) == ERROR) - { - MrBayesPrint ("%s Problem adding charset %s to list\n", spacer, tempSetName); - return (ERROR); - } - - /* store charset */ - AddBitfield (&charSet, numCharSets, tempSet, numChar); - - /* increment number of char sets */ - numCharSets++; - - return (NO_ERROR); -} - - -int DoCharsetParm (char *parmName, char *tkn) -{ - int i, index, tempInt, allDigit; - - if (defMatrix == NO) - { - MrBayesPrint ("%s A matrix must be specified before charsets can be defined\n", spacer); - return (ERROR); - } - - if (expecting == Expecting(PARAMETER)) - { - if (!strcmp(parmName, "Xxxxxxxxxx")) - { - /* check that the name of the charset is not a number */ - allDigit = YES; - for (i=0; i<(int)strlen(tkn); i++) - { - if (tkn[i] == '0' || tkn[i] == '1' || tkn[i] == '2' || tkn[i] == '3' || tkn[i] == '4' || - tkn[i] == '5' || tkn[i] == '6' || tkn[i] == '7' || tkn[i] == '8' || tkn[i] == '9' || tkn[i] == '.') - {} - else - allDigit = NO; - } - if (allDigit == YES) - { - MrBayesPrint ("%s Charset name may not be a number\n", spacer); - return (ERROR); - } - - /* check size of charset name */ - if (strlen(tkn) > 99) - { - MrBayesPrint ("%s Charset name is too long\n", spacer); - return (ERROR); - } - - /* check to see if the name has already been used as a charset */ - if (numCharSets > 1) - { - if (CheckString (charSetNames, numCharSets, tkn, &index) == ERROR) - { - /* if the charset name has not been used, then we should have an ERROR returned */ - /* we _want_ to be here */ - - } - else - { - MrBayesPrint ("%s Charset name has been used previously\n", spacer); - return (ERROR); - } - } - - /* add the name to the character set */ - strcpy (tempSetName, tkn); - - /* clear tempSet */ - for (i=0; i numChar) - { - MrBayesPrint ("%s Character number %d is out of range (should be between %d and %d)\n", spacer, tempInt, 1, numChar); - return (ERROR); - } - tempInt--; - if (foundDash == YES) - { - if (fromI >= 0) - toJ = tempInt; - else - { - MrBayesPrint ("%s Improperly formatted charset\n", spacer); - return (ERROR); - } - foundDash = NO; - } - else if (foundSlash == YES) - { - tempInt++; - if (tempInt <= 1) - { - MrBayesPrint ("%s Improperly formatted charset\n", spacer); - return (ERROR); - } - if (fromI >= 0 && toJ >= 0 && fromI < toJ) - everyK = tempInt; - else - { - MrBayesPrint ("%s Improperly formatted charset\n", spacer); - return (ERROR); - } - foundSlash = NO; - } - else - { - if (fromI >= 0 && toJ < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - fromI = tempInt; - } - else if (fromI < 0 && toJ < 0) - { - fromI = tempInt; - } - else if (fromI >= 0 && toJ >= 0 && everyK < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - fromI = tempInt; - toJ = everyK = -1; - } - else if (fromI >= 0 && toJ >= 0 && everyK >= 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - fromI = tempInt; - toJ = everyK = -1; - } - else - { - MrBayesPrint ("%s Improperly formatted charset\n", spacer); - { - return (ERROR); - } - } - - } - - - expecting = Expecting(ALPHA); - expecting |= Expecting(NUMBER); - expecting |= Expecting(SEMICOLON); - expecting |= Expecting(DASH); - expecting |= Expecting(BACKSLASH); - } - else if (expecting == Expecting(DASH)) - { - foundDash = YES; - expecting = Expecting(NUMBER); - } - else if (expecting == Expecting(BACKSLASH)) - { - foundSlash = YES; - expecting = Expecting(NUMBER); - } - else - return (ERROR); - - return (NO_ERROR); -} - - -int DoCharStat (void) -{ - int i, j, numDivs; - char tempName[100]; - - if (defMatrix == NO) - { - MrBayesPrint ("%s A character matrix must be defined first\n", spacer); - return (ERROR); - } - - if (numDefinedPartitions == 1) - MrBayesPrint ("%s 1 character partition defined:\n", spacer, numDefinedPartitions); - else - MrBayesPrint ("%s %d character partitions defined:\n", spacer, numDefinedPartitions); - for (i=0; i 0) - { - /* find paired character */ - for (j=0; j= 0 && toJ < 0) - { - if (AddToGivenSet (fromI, toJ, everyK, 1, tset) == ERROR) - return (ERROR); - } - else if (fromI >= 0 && toJ >= 0 && everyK < 0) - { - if (AddToGivenSet (fromI, toJ, everyK, 1, tset) == ERROR) - return (ERROR); - } - else if (fromI >= 0 && toJ >= 0 && everyK >= 0) - { - if (AddToGivenSet (fromI, toJ, everyK, 1, tset) == ERROR) - return (ERROR); - } - - /* check that this is not a stupid constraint */ - howMany = 0; - for (i=0; i 99) - { - MrBayesPrint ("%s Constraint name is too long\n", spacer); - return (ERROR); - } - - /* check to see if the name has already been used as a constraint */ - if (numDefinedConstraints > 0) - { - if (CheckString (constraintNames, numDefinedConstraints, tkn, &index) == ERROR) - { - /* if the constraint name has not been used, then we should have an ERROR returned */ - /* we _want_ to be here */ - } - else - { - MrBayesPrint ("%s Constraint name '%s' has been used previously\n", spacer, tkn); - return (ERROR); - } - } - - /* copy the name to the temporary constraint names string */ - strcpy (tempSetName, tkn); - - /* clear tempSet */ - for (i=0; i numTaxa) - { - MrBayesPrint ("%s Taxon number %d is out of range (should be between %d and %d)\n", spacer, tempInt, 1, numTaxa); - return (ERROR); - } - } - tempInt--; - if (foundDash == YES) - { - if (fromI >= 0) - toJ = tempInt; - else - { - MrBayesPrint ("%s Improperly formatted constraint\n", spacer); - return (ERROR); - } - foundDash = NO; - } - else if (foundSlash == YES) - { - tempInt++; - if (tempInt <= 1) - { - MrBayesPrint ("%s Improperly formatted constraint\n", spacer); - return (ERROR); - } - if (fromI >= 0 && toJ >= 0 && fromI < toJ) - everyK = tempInt; - else - { - MrBayesPrint ("%s Improperly formatted constraint\n", spacer); - return (ERROR); - } - foundSlash = NO; - } - else - { - if (fromI >= 0 && toJ < 0) - { - if (AddToGivenSet (fromI, toJ, everyK, 1, tempSetCurrent) == ERROR) - return (ERROR); - fromI = tempInt; - } - else if (fromI < 0 && toJ < 0) - { - fromI = tempInt; - } - else if (fromI >= 0 && toJ >= 0 && everyK < 0) - { - if (AddToGivenSet (fromI, toJ, everyK, 1, tempSetCurrent) == ERROR) - return (ERROR); - fromI = tempInt; - toJ = everyK = -1; - } - else if (fromI >= 0 && toJ >= 0 && everyK >= 0) - { - if (AddToGivenSet (fromI, toJ, everyK, 1, tempSetCurrent) == ERROR) - return (ERROR); - fromI = tempInt; - toJ = everyK = -1; - } - else - { - MrBayesPrint ("%s Improperly formatted constraint\n", spacer); - { - return (ERROR); - } - } - } - - expecting = Expecting(ALPHA); - expecting |= Expecting(NUMBER); - expecting |= Expecting(DASH); - expecting |= Expecting(BACKSLASH); - if (consrtainType != PARTIAL || foundColon == YES) - expecting |= Expecting(SEMICOLON); - else - expecting |= Expecting(COLON); - } - } - else if (expecting == Expecting(BACKSLASH)) - { - foundSlash = YES; - expecting = Expecting(NUMBER); - } - else if (expecting == Expecting(COLON)) - { - if (foundColon == YES) - { - MrBayesPrint ("%s Improperly formatted constraint: two colon charactors in constraint command.\n", spacer); - return (ERROR); - } - - /* add set to tempSet */ - if (fromI >= 0 && toJ < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - } - else if (fromI >= 0 && toJ >= 0 && everyK < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - } - else if (fromI >= 0 && toJ >= 0 && everyK >= 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - } - fromI = toJ = everyK = -1; - foundDash = foundSlash = NO; - - foundColon = YES; - tempSetCurrent = tempSetNeg; - expecting = Expecting(ALPHA); - expecting |= Expecting(NUMBER); - } - else - return (ERROR); - - return (NO_ERROR); -} - - -int DoCtype (void) -{ - int i, foundIllegal, marks[5], numAppliedTo; - - /* add set to tempSet */ - if (fromI >= 0 && toJ < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - } - else if (fromI >= 0 && toJ >= 0 && everyK < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - } - else if (fromI >= 0 && toJ >= 0 && everyK >= 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - } - - /* merge tempSet with ctype */ - numAppliedTo = 0; - for (i=0; i<5; i++) - marks[i] = NO; - for (i=0; i 0) - { - MrBayesPrint ("%s Ctype was applied to %d standard characters\n", spacer, numAppliedTo); - } - else - { - MrBayesPrint ("%s No standard characters found to apply ctype to\n", spacer); - } - -# if 0 - for (i=0; i numChar) - { - MrBayesPrint ("%s Character number %d is out of range (should be between %d and %d)\n", spacer, tempInt, 1, numChar); - return (ERROR); - } - tempInt--; - if (foundDash == YES) - { - if (fromI >= 0) - toJ = tempInt; - else - { - MrBayesPrint ("%s Improperly formatted ctype\n", spacer); - return (ERROR); - } - foundDash = NO; - } - else if (foundSlash == YES) - { - tempInt++; - if (tempInt <= 1) - { - MrBayesPrint ("%s Improperly formatted ctype\n", spacer); - return (ERROR); - } - if (fromI >= 0 && toJ >= 0 && fromI < toJ) - everyK = tempInt; - else - { - MrBayesPrint ("%s Improperly formatted ctype\n", spacer); - return (ERROR); - } - foundSlash = NO; - } - else - { - if (fromI >= 0 && toJ < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - fromI = tempInt; - } - else if (fromI < 0 && toJ < 0) - { - fromI = tempInt; - } - else if (fromI >= 0 && toJ >= 0 && everyK < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - fromI = tempInt; - toJ = everyK = -1; - } - else if (fromI >= 0 && toJ >= 0 && everyK >= 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - fromI = tempInt; - toJ = everyK = -1; - } - else - { - MrBayesPrint ("%s Improperly formatted ctype\n", spacer); - { - return (ERROR); - } - } - - } - - - expecting = Expecting(ALPHA); - expecting |= Expecting(NUMBER); - expecting |= Expecting(SEMICOLON); - expecting |= Expecting(DASH); - expecting |= Expecting(BACKSLASH); - } - else if (expecting == Expecting(DASH)) - { - foundDash = YES; - expecting = Expecting(NUMBER); - } - else if (expecting == Expecting(BACKSLASH)) - { - foundSlash = YES; - expecting = Expecting(NUMBER); - } - else - return (ERROR); - - return (NO_ERROR); -} - - -int DoDelete (void) -{ - int i, alreadyDone; - - MrBayesPrint ("%s Excluding taxa\n", spacer); - - /* add set to tempSet */ - if (fromI >= 0 && toJ < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - } - else if (fromI >= 0 && toJ >= 0 && everyK < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - } - else if (fromI >= 0 && toJ >= 0 && everyK >= 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - } - - /* merge tempSet with taxaset */ - alreadyDone = NO; - for (i=0; i= 0 && toJ < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - } - else if (fromI >= 0 && toJ >= 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - } - - tempSet[index] = 1; - } - } - foundDash = NO; - fromI = toJ = everyK = -1; - - expecting = Expecting(ALPHA); - expecting |= Expecting(NUMBER); - expecting |= Expecting(SEMICOLON); - } - else if (expecting == Expecting(NUMBER)) - { - if (strlen(tkn) == 1 && !strcmp(tkn, ".")) - tempInt = numTaxa; - else - { - sscanf (tkn, "%d", &tempInt); - if (tempInt <= 0 || tempInt > numTaxa) - { - MrBayesPrint ("%s Taxon number %d is out of range (should be between %d and %d)\n", spacer, tempInt, 1, numTaxa); - return (ERROR); - } - } - tempInt--; - if (foundDash == YES) - { - if (fromI >= 0) - toJ = tempInt; - else - { - MrBayesPrint ("%s Improperly formatted delete set\n", spacer); - return (ERROR); - } - foundDash = NO; - } - else - { - if (fromI >= 0 && toJ < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - fromI = tempInt; - } - else if (fromI < 0 && toJ < 0) - { - fromI = tempInt; - } - else if (fromI >= 0 && toJ >= 0 && everyK < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - fromI = tempInt; - toJ = everyK = -1; - } - else if (fromI >= 0 && toJ >= 0 && everyK >= 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - fromI = tempInt; - toJ = everyK = -1; - } - else - { - MrBayesPrint ("%s Improperly formatted delete set\n", spacer); - { - return (ERROR); - } - } - } - expecting = Expecting(ALPHA); - expecting |= Expecting(NUMBER); - expecting |= Expecting(SEMICOLON); - expecting |= Expecting(DASH); - } - else if (expecting == Expecting(DASH)) - { - foundDash = YES; - expecting = Expecting(NUMBER); - } - else - return (ERROR); - - return (NO_ERROR); - MrBayesPrint ("%s", parmName); /* just because I am tired of seeing the unused parameter error msg */ -} - - -int DoDimensions (void) -{ - if (inDataBlock == NO && inTaxaBlock == NO && inCharactersBlock == NO) - { - MrBayesPrint ("%s Dimensions can only be defined in a data, characters or taxa block\n", spacer); - return (ERROR); - } - - /* other problems are detected already when reading in DoDimensionsParm */ - if (inDataBlock == YES && (defTaxa == NO || defChars == NO)) - { - MrBayesPrint ("%s Expecting both Ntax and Nchar to be defined in a data block\n", spacer); - return (ERROR); - } - - /* allocate matrix */ - if (inTaxaBlock == YES) - { - if (AllocTaxa () == ERROR) - return ERROR; - MrBayesPrint ("%s Defining new set of %d taxa\n", spacer, numTaxa); - } - - if (inCharactersBlock == YES) - { - if (AllocMatrix() == ERROR) - return (ERROR); - MrBayesPrint ("%s Defining new character matrix with %d characters\n", spacer, numChar); - } - - if (inDataBlock == YES) - { - if (AllocMatrix() == ERROR) - return (ERROR); - MrBayesPrint ("%s Defining new matrix with %d taxa and %d characters\n", spacer, numTaxa, numChar); - } - - return (NO_ERROR); -} - - -int DoDimensionsParm (char *parmName, char *tkn) -{ - if (expecting == Expecting(PARAMETER)) - { - expecting = Expecting(EQUALSIGN); - } - else - { - /* set Ntax (numTaxa) *****************************************************************/ - if (!strcmp(parmName, "Ntax")) - { - if (inCharactersBlock == YES) - { - MrBayesPrint ("%s You cannot define ntax in a characters block\n"); - return (ERROR); - } - if (expecting == Expecting(EQUALSIGN)) - expecting = Expecting(NUMBER); - else if (expecting == Expecting(NUMBER)) - { - sscanf (tkn, "%d", &numTaxa); - defTaxa = YES; - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } - /* set Nchar (numChar) ****************************************************************/ - else if (!strcmp(parmName, "Nchar")) - { - if (inTaxaBlock == YES) - { - MrBayesPrint ("%s You cannot define nchar in a taxa block\n"); - return (ERROR); - } - if (expecting == Expecting(EQUALSIGN)) - expecting = Expecting(NUMBER); - else if (expecting == Expecting(NUMBER)) - { - sscanf (tkn, "%d", &numChar); - defChars = YES; - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } - else - return (ERROR); - } - - return (NO_ERROR); -} - - -int DoDisclaimer (void) -{ - MrBayesPrint (" --------------------------------------------------------------------------- \n"); - MrBayesPrint (" Disclaimer \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" Copyright 2003 by John P. Huelsenbeck and Fredrik Ronquist \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" This software package is provided \"as is\" and without a warranty of any \n"); - MrBayesPrint (" kind. In no event shall the authors be held responsible for any damage \n"); - MrBayesPrint (" resulting from the use of this software. The program--including source code, \n"); - MrBayesPrint (" example data sets, and executables--is distributed free of charge for \n"); - MrBayesPrint (" academic use only. \n"); - MrBayesPrint (" --------------------------------------------------------------------------- \n"); - - return (NO_ERROR); -} - - -int DoEndBlock (void) -{ - if (inMrbayesBlock == YES) - { - MrBayesPrint (" Exiting mrbayes block\n"); - inMrbayesBlock = NO; - } - else if (inDataBlock == YES) - { - MrBayesPrint (" Exiting data block\n"); - inDataBlock = NO; - } - else if (inCharactersBlock == YES) - { - MrBayesPrint (" Exiting characters block\n"); - inCharactersBlock = NO; - } - else if (inTaxaBlock == YES) - { - MrBayesPrint (" Exiting taxa block\n"); - if (numNamedTaxa < numTaxa) - { - MrBayesPrint ("%s Leaving taxa block without taxon labels being defined\n", spacer); - FreeTaxa(); - } - inTaxaBlock = NO; - } - else if (inTreesBlock == YES) - { - MrBayesPrint (" Exiting trees block\n"); - inTreesBlock = NO; - ResetTranslateTable(); - } - else if (inForeignBlock == YES) - { - MrBayesPrint (" Exiting foreign block\n"); - inForeignBlock = NO; - } - else - { - MrBayesPrint (" Unknown \"end\" statement\n"); - return (ERROR); - } - - strcpy(spacer,""); /* reset indentation */ - return (NO_ERROR); -} - - -int DoExecute (void) -{ - int c, i, rc, cmdLine, lineTerm, longestLineLength, nErrors; - char *s, exeFileName[100]; - FILE *fp; - CmdType *oldCommandPtr; -# if defined (MPI_ENABLED) - int sumErrors; -# endif - - nErrors = 0; - cmdLine = 0; - numOpenExeFiles++; - s = NULL; - strncpy (exeFileName, inputFileName, 98); - - if (numOpenExeFiles > 1) - MrBayesPrint ("\n%s Executing file \"%s\"...\n\n", spacer, inputFileName); - else - MrBayesPrint ("%s Executing file \"%s\"\n", spacer, inputFileName); - - /* Save old command ptr */ - oldCommandPtr = commandPtr; - - /* open binary file */ - if ((fp = OpenBinaryFileR(inputFileName)) == NULL) - nErrors++; - - /* set indentation to 0 */ - strcpy (spacer, ""); - -# if defined (MPI_ENABLED) - MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); - if (sumErrors > 0) - { - MrBayesPrint ("%s There was an error on at least one processor\n", spacer); - goto errorExit; - } -# else - if (nErrors > 0) - goto errorExit; -# endif - - /* find out what type of line termination is used */ - lineTerm = LineTermType (fp); - if (lineTerm == LINETERM_MAC) - MrBayesPrint ("%s Macintosh line termination\n", spacer); - else if (lineTerm == LINETERM_DOS) - MrBayesPrint ("%s DOS line termination\n", spacer); - else if (lineTerm == LINETERM_UNIX) - MrBayesPrint ("%s UNIX line termination\n", spacer); - else - { - MrBayesPrint ("%s Unknown line termination\n", spacer); - nErrors++; - } -# if defined (MPI_ENABLED) - MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); - if (sumErrors > 0) - { - MrBayesPrint ("%s There was an error on at least one processor\n", spacer); - goto errorExit; - } -# else - if (nErrors > 0) - goto errorExit; -# endif - - /* find length of longest line */ - longestLineLength = LongestLine (fp); - MrBayesPrint ("%s Longest line length = %d\n", spacer, longestLineLength); - longestLineLength += 50; - - /* check that longest line is not longer than CMD_STRING_LENGTH */ - if (longestLineLength >= CMD_STRING_LENGTH - 100) - { - /*MrBayesPrint ("%s A maximum of %d characters is allowed on a single line\n", spacer, CMD_STRING_LENGTH - 100);*/ - MrBayesPrint ("%s The longest line of the file %s\n", spacer, inputFileName); - MrBayesPrint ("%s contains at least one line with %d characters.\n", spacer, longestLineLength); - } - /* -# if defined (MPI_ENABLED) - MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); - if (sumErrors > 0) - { - MrBayesPrint ("%s There was an error on at least one processor\n", spacer); - goto errorExit; - } -# else - if (nErrors > 0) - goto errorExit; -# endif - */ - - /* allocate a string long enough to hold a line */ - s = (char *)SafeMalloc((size_t) (longestLineLength * sizeof(char))); - if (!s) - { - MrBayesPrint ("%s Problem allocating string for reading file\n", spacer); - nErrors++; - } -# if defined (MPI_ENABLED) - MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); - if (sumErrors > 0) - { - MrBayesPrint ("%s There was an error on at least one processor\n", spacer); - goto errorExit; - } -# else - if (nErrors > 0) - goto errorExit; -# endif - - /* close binary file */ - SafeFclose (&fp); - - /* open text file */ - if ((fp = OpenTextFileR(inputFileName)) == NULL) - { - nErrors++; - } -# if defined (MPI_ENABLED) - MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); - if (sumErrors > 0) - { - MrBayesPrint ("%s There was an error on at least one processor\n", spacer); - goto errorExit; - } -# else - if (nErrors > 0) - goto errorExit; -# endif - - /* parse file, reading each line in turn */ - MrBayesPrint ("%s Parsing file\n", spacer); - - inMrbayesBlock = inDataBlock = inForeignBlock = inTreesBlock = NO; - foundNewLine = NO; - expecting = Expecting(COMMAND); - cmdLine = 0; - - do { - /* read in a new line into s */ - i = 0; - do { - c = fgetc(fp); - if (c == '\r' || c == '\n' || c == EOF) - s[i++] = '\n'; - else - s[i++] = c; - } while (s[i-1] != '\n'); - s[i] = '\0'; - foundNewLine = YES; - cmdLine++; - - /* process string if not empty */ - if (strlen(s) > 1) - { - /* check that all characters in the string are valid */ - if (CheckStringValidity (s) == ERROR) - { - nErrors++; - } -# if defined (MPI_ENABLED) - MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); - if (sumErrors > 0) - { - MrBayesPrint ("%s There was an error on at least one processor\n", spacer); - goto errorExit; - } -# else - if (nErrors > 0) - goto errorExit; -# endif - - /* interpret commands on line */ - rc = ParseCommand (s); - if (rc == ERROR) - nErrors++; -# if defined (MPI_ENABLED) - MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); - if (sumErrors > 0) - { - MrBayesPrint ("%s There was an error on at least one processor\n", spacer); - goto errorExit; - } -# else - if (nErrors > 0) - goto errorExit; -# endif - if (rc == NO_ERROR_QUIT) - nErrors++; -# if defined (MPI_ENABLED) - MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); - if (sumErrors > 0) - goto quitExit; -# else - if (nErrors > 0) - goto quitExit; -# endif - } - } while (c != EOF); - - MrBayesPrint ("%s Reached end of file\n", spacer); - - if (inComment == YES) - nErrors++; - -# if defined (MPI_ENABLED) - MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); - if (sumErrors > 0) - { - MrBayesPrint ("%s There was an error on at least one processor\n", spacer); - goto errorExit; - } -# else - if (nErrors > 0) - goto errorExit; -# endif - - if (s) - free (s); - SafeFclose (&fp); - numOpenExeFiles--; - - if (numOpenExeFiles > 0) - { - inMrbayesBlock = YES; - MrBayesPrint ("\n Returning execution to calling file ...\n\n"); - strcpy (spacer, " "); - } - else - strcpy (spacer, ""); - - commandPtr = oldCommandPtr; - - return (NO_ERROR); - - quitExit: - if (s) - free (s); - SafeFclose (&fp); - numOpenExeFiles--; - if (numOpenExeFiles > 0) - { - inMrbayesBlock = YES; - strcpy (spacer, " "); - } - else - strcpy (spacer, ""); - - commandPtr = oldCommandPtr; - - return (NO_ERROR_QUIT); - - errorExit: - if (inComment == YES) - { - MrBayesPrint ("%s ERROR: Reached end of file while in comment.\n", spacer); - inComment = NO; - numComments = 0; - } - if (fp) - { - MrBayesPrint ("%s The error occurred when reading char. %d on line %d\n", spacer, tokenP-cmdStr-strlen(token)+1, cmdLine); - MrBayesPrint ("%s in the file '%s'\n", spacer, exeFileName); - } - if (s) - free (s); - SafeFclose (&fp); - numOpenExeFiles--; /* we increase the value above even if no file is successfully opened */ - - /* make sure we exit the block we were reading from correctly */ - if (inMrbayesBlock == YES) - inMrbayesBlock = NO; - else if (inDataBlock == YES) - inDataBlock = NO; - else if (inTreesBlock == YES) - { - inTreesBlock = NO; - ResetTranslateTable(); - } - else if (inForeignBlock == YES) - inForeignBlock = NO; - - /* make sure correct return if we came from mrbayes block in another execute file */ - if (numOpenExeFiles > 0) - { - inMrbayesBlock = YES; - MrBayesPrint ("\n Returning execution to calling file ...\n\n"); - strcpy (spacer, " "); - commandPtr = oldCommandPtr; - return (ERROR); - } - else - strcpy (spacer, ""); - - commandPtr = oldCommandPtr; - - return (ERROR); -} - - -int DoExecuteParm (char *parmName, char *tkn) -{ - if (strlen(tkn)>99) - { - MrBayesPrint ("%s Maximum allowed length of file name is 99 characters. The given name:\n", spacer); - MrBayesPrint ("%s '%s'\n", spacer,tkn); - MrBayesPrint ("%s has %d characters.\n", spacer,strlen(tkn)); - return (ERROR); - } - strcpy (inputFileName, tkn); - - expecting = Expecting (SEMICOLON); - - return (NO_ERROR); - MrBayesPrint ("%s", parmName); /* just because I am tired of seeing the unused parameter error msg */ -} - - -int DoExclude (void) -{ - int i, alreadyDone; - - MrBayesPrint ("%s Excluding character(s)\n", spacer); - - /* add set to tempSet */ - if (fromI >= 0 && toJ < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - } - else if (fromI >= 0 && toJ >= 0 && everyK < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - } - else if (fromI >= 0 && toJ >= 0 && everyK >= 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - } - - /* merge tempSet with charset */ - alreadyDone = NO; - for (i=0; i numChar) - { - MrBayesPrint ("%s Character number %d is out of range (should be between %d and %d)\n", spacer, tempInt, 1, numChar); - return (ERROR); - } - tempInt--; - if (foundDash == YES) - { - if (fromI >= 0) - toJ = tempInt; - else - { - MrBayesPrint ("%s Improperly formatted exclude set\n", spacer); - return (ERROR); - } - foundDash = NO; - } - else if (foundSlash == YES) - { - tempInt++; - if (tempInt <= 1) - { - MrBayesPrint ("%s Improperly formatted exclude set\n", spacer); - return (ERROR); - } - if (fromI >= 0 && toJ >= 0 && fromI < toJ) - everyK = tempInt; - else - { - MrBayesPrint ("%s Improperly formatted exclude set\n", spacer); - return (ERROR); - } - foundSlash = NO; - } - else - { - if (fromI >= 0 && toJ < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - fromI = tempInt; - } - else if (fromI < 0 && toJ < 0) - { - fromI = tempInt; - } - else if (fromI >= 0 && toJ >= 0 && everyK < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - fromI = tempInt; - toJ = everyK = -1; - } - else if (fromI >= 0 && toJ >= 0 && everyK >= 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - fromI = tempInt; - toJ = everyK = -1; - } - else - { - MrBayesPrint ("%s Improperly formatted exclude set\n", spacer); - { - return (ERROR); - } - } - } - expecting = Expecting(ALPHA); - expecting |= Expecting(NUMBER); - expecting |= Expecting(SEMICOLON); - expecting |= Expecting(DASH); - expecting |= Expecting(BACKSLASH); - } - else if (expecting == Expecting(DASH)) - { - foundDash = YES; - expecting = Expecting(NUMBER); - } - else if (expecting == Expecting(BACKSLASH)) - { - foundSlash = YES; - expecting = Expecting(NUMBER); - } - else - return (ERROR); - - return (NO_ERROR); - MrBayesPrint ("%s", parmName); /* just because I am tired of seeing the unused parameter error msg */ -} - - -int DoFormat (void) -{ - if (inDataBlock == NO && inCharactersBlock == NO) - { - MrBayesPrint ("%s Formats can only be defined in a data or characters block\n", spacer); - return (ERROR); - } - - return CheckInitialPartitions(); -} - - -int DoFormatParm (char *parmName, char *tkn) -{ - int i, tempInt; - char tempStr[100]; - - if (inDataBlock == NO && inCharactersBlock == NO) - { - MrBayesPrint ("%s Formats can only be defined in a data or characters block\n", spacer); - return (ERROR); - } - if (defTaxa == NO || defChars == NO) - { - MrBayesPrint ("%s The dimensions of the matrix must be defined before the format\n", spacer); - return (ERROR); - } - - if (expecting == Expecting(PARAMETER)) - { - expecting = Expecting(EQUALSIGN); - if (!strcmp(parmName, "Interleave")) - { - expecting = Expecting(EQUALSIGN) | Expecting(PARAMETER) | Expecting(SEMICOLON); - isInterleaved = YES; - } - } - else - { - /* set Datatype (dataType) ************************************************************/ - if (!strcmp(parmName, "Datatype")) - { - if (expecting == Expecting(EQUALSIGN)) - expecting = Expecting(ALPHA); - else if (expecting == Expecting(ALPHA)) - { - if (IsArgValid(tkn, tempStr) == NO_ERROR) - { - if (isMixed == NO) - { - if (!strcmp(tempStr, "Dna")) - dataType = DNA; - else if (!strcmp(tempStr, "Rna")) - dataType = RNA; - else if (!strcmp(tempStr, "Protein")) - dataType = PROTEIN; - else if (!strcmp(tempStr, "Restriction")) - dataType = RESTRICTION; - else if (!strcmp(tempStr, "Standard")) - dataType = STANDARD; - else if (!strcmp(tempStr, "Continuous")) - dataType = CONTINUOUS; - else if (!strcmp(tempStr, "Mixed")) - { - dataType = MIXED; - isMixed = YES; - for (i=0; i numChar) - { - MrBayesPrint ("%s Character number %d is out of range (should be between %d and %d)\n", spacer, tempInt, 1, numChar); - return (ERROR); - } - tempInt--; - if (foundDash == YES) - { - if (fromI >= 0) - toJ = tempInt; - else - { - MrBayesPrint ("%s Improperly formatted partition\n", spacer); - return (ERROR); - } - foundDash = NO; - } - else if (foundSlash == YES) - { - tempInt++; - if (tempInt <= 1) - { - MrBayesPrint ("%s Improperly formatted partition\n", spacer); - return (ERROR); - } - if (fromI >= 0 && toJ >= 0 && fromI < toJ) - everyK = tempInt; - else - { - MrBayesPrint ("%s Improperly formatted partition\n", spacer); - return (ERROR); - } - foundSlash = NO; - } - else - { - if (fromI >= 0 && toJ < 0) - { - if (AddToSet (fromI, toJ, everyK, numDivisions+1) == ERROR) - return (ERROR); - fromI = tempInt; - } - else if (fromI < 0 && toJ < 0) - { - fromI = tempInt; - } - else if (fromI >= 0 && toJ >= 0 && everyK < 0) - { - if (AddToSet (fromI, toJ, everyK, numDivisions+1) == ERROR) - return (ERROR); - fromI = tempInt; - toJ = everyK = -1; - } - else if (fromI >= 0 && toJ >= 0 && everyK >= 0) - { - if (AddToSet (fromI, toJ, everyK, numDivisions+1) == ERROR) - return (ERROR); - fromI = tempInt; - toJ = everyK = -1; - } - else - { - MrBayesPrint ("%s Improperly formatted partition\n", spacer); - { - return (ERROR); - } - } - - } - expecting = Expecting(NUMBER); - expecting |= Expecting(DASH); - expecting |= Expecting(BACKSLASH); - expecting |= Expecting(COMMA); - expecting |= Expecting(RIGHTPAR); - } - else if (expecting == Expecting(DASH)) - { - foundDash = YES; - expecting = Expecting(NUMBER); - } - else if (expecting == Expecting(BACKSLASH)) - { - foundSlash = YES; - expecting = Expecting(NUMBER); - } - else if (expecting == Expecting(COMMA)) - { - /* add set to tempSet */ - if (fromI >= 0 && toJ < 0) - { - if (AddToSet (fromI, toJ, everyK, numDivisions+1) == ERROR) - return (ERROR); - } - else if (fromI >= 0 && toJ >= 0 && everyK < 0) - { - if (AddToSet (fromI, toJ, everyK, numDivisions+1) == ERROR) - return (ERROR); - } - else if (fromI >= 0 && toJ >= 0 && everyK >= 0) - { - if (AddToSet (fromI, toJ, everyK, numDivisions+1) == ERROR) - return (ERROR); - } - for (i=0; i= 0 && toJ < 0) - { - if (AddToSet (fromI, toJ, everyK, numDivisions+1) == ERROR) - return (ERROR); - } - else if (fromI >= 0 && toJ >= 0 && everyK < 0) - { - if (AddToSet (fromI, toJ, everyK, numDivisions+1) == ERROR) - return (ERROR); - } - else if (fromI >= 0 && toJ >= 0 && everyK >= 0) - { - if (AddToSet (fromI, toJ, everyK, numDivisions+1) == ERROR) - return (ERROR); - } - - /* merge tempSet */ - for (i=0; i 1) - MrBayesPrint ("%s There are a total of %d default data divisions\n", spacer, numDivisions); - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } - /* set Interleave (isInterleaved) *****************************************************/ - else if (!strcmp(parmName, "Interleave")) - { - if (expecting == Expecting(EQUALSIGN)) - expecting = Expecting(ALPHA); - else if (expecting == Expecting(ALPHA)) - { - if (IsArgValid(tkn, tempStr) == NO_ERROR) - { - if (!strcmp(tempStr, "Yes")) - isInterleaved = YES; - else - isInterleaved = NO; - } - else - { - MrBayesPrint ("%s Invalid argument for interleaved data\n", spacer); - return (ERROR); - } - if (isInterleaved == YES) - MrBayesPrint ("%s Data matrix is interleaved\n", spacer); - else - MrBayesPrint ("%s Data matrix is not interleaved\n", spacer); - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } - /* set Gap (gapId) ********************************************************************/ - else if (!strcmp(parmName, "Gap")) - { - if (expecting == Expecting(EQUALSIGN)) - { - expecting = Expecting(ALPHA); - expecting |= Expecting(QUESTIONMARK); - expecting |= Expecting(DASH); - expecting |= Expecting(NUMBER); - expecting |= Expecting(ASTERISK); - expecting |= Expecting(EXCLAMATIONMARK); - expecting |= Expecting(PERCENT); - expecting |= Expecting(WEIRD); - } - else if (((expecting & Expecting(ALPHA)) == Expecting(ALPHA)) || - ((expecting & Expecting(QUESTIONMARK)) == Expecting(QUESTIONMARK)) || - ((expecting & Expecting(DASH)) == Expecting(DASH)) || - ((expecting & Expecting(NUMBER)) == Expecting(NUMBER)) || - ((expecting & Expecting(ASTERISK)) == Expecting(ASTERISK)) || - ((expecting & Expecting(EXCLAMATIONMARK)) == Expecting(EXCLAMATIONMARK)) || - ((expecting & Expecting(PERCENT)) == Expecting(PERCENT)) || - ((expecting & Expecting(WEIRD)) == Expecting(WEIRD))) - { - if (strlen(tkn) == 1) - { - if (tkn[0] == matchId || tkn[0] == missingId) - { - MrBayesPrint ("%s Gap character matches matching or missing characters\n", spacer); - return (ERROR); - } - gapId = tkn[0]; - } - else - { - MrBayesPrint ("%s Invalid gap argument %s\n", spacer, tkn); - return (ERROR); - } - MrBayesPrint ("%s Gaps coded as %s\n", spacer, tkn); - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } - /* set Missing (missingId) ************************************************************/ - else if (!strcmp(parmName, "Missing")) - { - if (expecting == Expecting(EQUALSIGN)) - { - expecting = Expecting(ALPHA); - expecting |= Expecting(QUESTIONMARK); - expecting |= Expecting(DASH); - expecting |= Expecting(NUMBER); - expecting |= Expecting(ASTERISK); - expecting |= Expecting(EXCLAMATIONMARK); - expecting |= Expecting(PERCENT); - expecting |= Expecting(WEIRD); - } - else if (((expecting & Expecting(ALPHA)) == Expecting(ALPHA)) || - ((expecting & Expecting(QUESTIONMARK)) == Expecting(QUESTIONMARK)) || - ((expecting & Expecting(DASH)) == Expecting(DASH)) || - ((expecting & Expecting(NUMBER)) == Expecting(NUMBER)) || - ((expecting & Expecting(ASTERISK)) == Expecting(ASTERISK)) || - ((expecting & Expecting(EXCLAMATIONMARK)) == Expecting(EXCLAMATIONMARK)) || - ((expecting & Expecting(PERCENT)) == Expecting(PERCENT)) || - ((expecting & Expecting(WEIRD)) == Expecting(WEIRD))) - { - if (strlen(tkn) == 1) - { - if (tkn[0] == gapId || tkn[0] == matchId) - { - MrBayesPrint ("%s Missing character matches matching or gap characters\n", spacer); - return (ERROR); - } - missingId = tkn[0]; - } - else - { - MrBayesPrint ("%s Invalid missing argument %s\n", spacer, tkn); - return (ERROR); - } - MrBayesPrint ("%s Missing data coded as %s\n", spacer, tkn); - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } - /* set Matchchar (matchId) ************************************************************/ - else if (!strcmp(parmName, "Matchchar")) - { - if (expecting == Expecting(EQUALSIGN)) - { - expecting = Expecting(ALPHA); - expecting |= Expecting(QUESTIONMARK); - expecting |= Expecting(DASH); - expecting |= Expecting(NUMBER); - expecting |= Expecting(ASTERISK); - expecting |= Expecting(EXCLAMATIONMARK); - expecting |= Expecting(PERCENT); - expecting |= Expecting(WEIRD); - } - else if (((expecting & Expecting(ALPHA)) == Expecting(ALPHA)) || - ((expecting & Expecting(QUESTIONMARK)) == Expecting(QUESTIONMARK)) || - ((expecting & Expecting(DASH)) == Expecting(DASH)) || - ((expecting & Expecting(NUMBER)) == Expecting(NUMBER)) || - ((expecting & Expecting(ASTERISK)) == Expecting(ASTERISK)) || - ((expecting & Expecting(EXCLAMATIONMARK)) == Expecting(EXCLAMATIONMARK)) || - ((expecting & Expecting(PERCENT)) == Expecting(PERCENT)) || - ((expecting & Expecting(WEIRD)) == Expecting(WEIRD))) - { - if (strlen(tkn) == 1) - { - if (tkn[0] == gapId || tkn[0] == missingId) - { - MrBayesPrint ("%s Matching character matches gap or missing characters\n", spacer); - return (ERROR); - } - matchId = tkn[0]; - } - else - { - MrBayesPrint ("%s Invalid matchchar argument %s\n", spacer, tkn); - return (ERROR); - } - MrBayesPrint ("%s Matching characters coded as %s\n", spacer, tkn); - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } - /* skip Symbols ***************************************************************/ - else if (!strcmp(parmName, "Symbols")) - { - if (expecting == Expecting(EQUALSIGN)) - { - MrBayesPrint ("%s WARNING: MrBayes does not support 'symbols' specification; default symbols assumed\n", spacer); - readWord=YES; - expecting = Expecting(ALPHA); - } - else if (expecting == Expecting(ALPHA)) - { - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } - /* on Equate return ERROR ***************************************************************/ - else if (!strcmp(parmName, "Equate")) - { - MrBayesPrint ("%s ERROR: MrBayes does not support 'Equate' macros; please remove or comment out\n", spacer); - return (ERROR); - } - else - return (ERROR); - } - - return (NO_ERROR); -} - - -int DoHelp (void) -{ - int i, j, longestDescription; - CmdType *p; - - if (foundFirst == NO) - { - longestDescription = 0; - for (i=1; istring) > longestDescription) - longestDescription = (int) strlen(p->string); - } - - MrBayesPrint (" --------------------------------------------------------------------------- \n"); - MrBayesPrint (" Commands that are available from the command \n"); - MrBayesPrint (" line or from a MrBayes block include: \n"); - MrBayesPrint (" \n"); - for (i=1; icmdUse == IN_CMD && p->hiding == SHOW) - { - MrBayesPrint (" %s", p->string); - for (j=0; jstring); j++) - MrBayesPrint (" "); - MrBayesPrint (" -- %s\n", p->cmdDescription); - } - } - MrBayesPrint (" \n"); - MrBayesPrint (" Commands that should be in a NEXUS file (data \n"); - MrBayesPrint (" block, trees block or taxa block) include: \n"); - MrBayesPrint (" \n"); - for (i=1; icmdUse == IN_FILE && p->hiding == SHOW) - { - MrBayesPrint (" %s", p->string); - for (j=0; jstring); j++) - MrBayesPrint (" "); - MrBayesPrint (" -- %s\n", p->cmdDescription); - } - } - MrBayesPrint (" \n"); - MrBayesPrint (" Note that this program supports the use of the shortest unambiguous \n"); - MrBayesPrint (" spelling of the above commands (e.g., \"exe\" instead of \"execute\"). \n"); - MrBayesPrint (" --------------------------------------------------------------------------- \n"); - } - foundFirst = NO; - - return (NO_ERROR); -} - - -int DoHelpParm (char *parmName, char *tkn) -{ - int i, j, tkLen, targetLen, numDiff, numMatches; - CmdType *p, *q=NULL; - - if (expecting == Expecting(ALPHA)) - { - p = commands + 0; - tkLen = (int) strlen(tkn); - numMatches = 0; - for (i=0; istring); - if (tkLen <= targetLen) - { - for (j=0, numDiff=0; jstring[j])) - numDiff++; - } - if (numDiff == 0) - { - numMatches++; - q = p; - if (tkLen == targetLen) - break; - } - } - p++; - } - if (numMatches == 0) - { - MrBayesPrint ("%s Could not find command \"%s\"\n", spacer, tkn); - return (ERROR); - } - else if (numMatches == 1) - { - if (GetUserHelp (q->string) == ERROR) - { - MrBayesPrint ("%s Problem getting help for command \"%s\"\n", spacer, q->string); - } - } - else - { - MrBayesPrint ("%s Ambiguous command \"%s\"\n", spacer, tkn); - return (ERROR); - } - - expecting = Expecting(SEMICOLON); - foundFirst = YES; - } - else - return (ERROR); - - return (NO_ERROR); - MrBayesPrint ("%s", parmName); /* just because I am tired of seeing the unused parameter error msg */ -} - - -int DoInclude (void) -{ - int i, alreadyDone; - - MrBayesPrint ("%s Including character(s)\n", spacer); - - /* add set to tempSet */ - if (fromI >= 0 && toJ < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - } - else if (fromI >= 0 && toJ >= 0 && everyK < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - } - else if (fromI >= 0 && toJ >= 0 && everyK >= 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - } - - /* merge tempSet with excludedChars */ - alreadyDone = NO; - for (i=0; i numChar) - { - MrBayesPrint ("%s Character number %d is out of range (should be between %d and %d)\n", spacer, tempInt, 1, numChar); - return (ERROR); - } - tempInt--; - if (foundDash == YES) - { - if (fromI >= 0) - toJ = tempInt; - else - { - MrBayesPrint ("%s Improperly formatted include set\n", spacer); - return (ERROR); - } - foundDash = NO; - } - else if (foundSlash == YES) - { - tempInt++; - if (tempInt <= 1) - { - MrBayesPrint ("%s Improperly formatted include set\n", spacer); - return (ERROR); - } - if (fromI >= 0 && toJ >= 0 && fromI < toJ) - everyK = tempInt; - else - { - MrBayesPrint ("%s Improperly formatted include set\n", spacer); - return (ERROR); - } - foundSlash = NO; - } - else - { - if (fromI >= 0 && toJ < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - fromI = tempInt; - } - else if (fromI < 0 && toJ < 0) - { - fromI = tempInt; - } - else if (fromI >= 0 && toJ >= 0 && everyK < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - fromI = tempInt; - toJ = everyK = -1; - } - else if (fromI >= 0 && toJ >= 0 && everyK >= 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - fromI = tempInt; - toJ = everyK = -1; - } - else - { - MrBayesPrint ("%s Improperly formatted include set\n", spacer); - { - return (ERROR); - } - } - } - expecting = Expecting(ALPHA); - expecting |= Expecting(NUMBER); - expecting |= Expecting(SEMICOLON); - expecting |= Expecting(DASH); - expecting |= Expecting(BACKSLASH); - } - else if (expecting == Expecting(DASH)) - { - foundDash = YES; - expecting = Expecting(NUMBER); - } - else if (expecting == Expecting(BACKSLASH)) - { - foundSlash = YES; - expecting = Expecting(NUMBER); - } - else - return (ERROR); - - return (NO_ERROR); - MrBayesPrint ("%s", parmName); /* just because I am tired of seeing the unused parameter error msg */ -} - - -int DoLog (void) -{ - if (logToFile == YES) - { - SafeFclose (&logFileFp); - if (replaceLogFile == YES) - { - if ((logFileFp = OpenTextFileW (logFileName)) == NULL) - { - logToFile = NO; - return (ERROR); - } - } - else - { - if ((logFileFp = OpenTextFileA (logFileName)) == NULL) - { - logToFile = NO; - return (ERROR); - } - } - MrBayesPrint ("%s Logging screen output to file \"%s\"\n", spacer, logFileName); - } - else - { - SafeFclose (&logFileFp); - MrBayesPrint ("%s Terminating log output\n", spacer); - } - - return (NO_ERROR); -} - - -int DoLogParm (char *parmName, char *tkn) -{ - if (expecting == Expecting(PARAMETER)) - { - if (!strcmp(parmName, "Start")) - { - if (logToFile == YES) - MrBayesPrint ("%s Logging to file is already on\n", spacer, logFileName); - else - logToFile = YES; - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else if (!strcmp(parmName, "Stop")) - { - if (logToFile == NO) - MrBayesPrint ("%s Logging to file is already off\n", spacer, logFileName); - else - logToFile = NO; - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else if (!strcmp(parmName, "Replace")) - { - replaceLogFile = YES; - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else if (!strcmp(parmName, "Append")) - { - replaceLogFile = NO; - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - expecting = Expecting(EQUALSIGN); - } - else - { - if (!strcmp(parmName, "Filename")) - { - if (expecting == Expecting(EQUALSIGN)) - { - expecting = Expecting(ALPHA); - readWord = YES; - } - else if (expecting == Expecting(ALPHA)) - { - strcpy (logFileName, tkn); - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } - else - { - MrBayesPrint ("%s Unknown parameter in Log\n", spacer); - return (ERROR); - } - } - - return (NO_ERROR); -} - - -int DoManual (void) -{ - int i, j, logSetting; - char title[100]; - FILE *fp, *logfp; - CmdType *p; - - /* try to open file, return error if present */ - if ((fp = OpenTextFileRQuait(manFileName)) != NULL) - { - MrBayesPrint ("%s File \"%s\" already exists \n", spacer, manFileName); - SafeFclose(&fp); - return (ERROR); - } - - /* try to open file for writing, return error if not possible */ - if ((fp = OpenTextFileW(manFileName)) == NULL) - return (ERROR); - - /* print message */ - MrBayesPrint ("%s Producing command reference file \"%s\"\n", spacer, manFileName); - - /* temporarily disable normal logging and switch echoing off */ - logSetting = logToFile; - logfp = logFileFp; - echoMB = NO; - logToFile = YES; - logFileFp = fp; - - /* produce command reference file */ - /* header */ - strcpy (title, "Command Reference for MrBayes ver. "); - strcat (title, VERSION_NUMBER); - - i = (70 - (int) strlen (title)) / 2; - j = 70 - i - (int) strlen(title); - - MrBayesPrint (" \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" %*c%s%*c \n", i, ' ', title, j, ' '); - MrBayesPrint (" \n"); - MrBayesPrint (" (c) John P. Huelsenbeck, Fredrik Ronquist \n"); - MrBayesPrint (" and Maxim Teslenko \n"); - MrBayesPrint (" \n"); - - /* summary */ - MrBayesPrint (" \n"); - MrBayesPrint (" *************************************************************************** \n"); - MrBayesPrint (" * * \n"); - MrBayesPrint (" * 1. Command summary * \n"); - MrBayesPrint (" * * \n"); - MrBayesPrint (" *************************************************************************** \n"); - MrBayesPrint (" \n"); - foundFirst = NO; - if (DoHelp() == ERROR) - { - MrBayesPrint ("%s Could not produce command reference summary\n", spacer); - goto errorExit; - } - - /* list of MrBayes commands */ - MrBayesPrint (" \n"); - MrBayesPrint (" *************************************************************************** \n"); - MrBayesPrint (" * * \n"); - MrBayesPrint (" * 2. MrBayes commands * \n"); - MrBayesPrint (" * * \n"); - MrBayesPrint (" *************************************************************************** \n"); - MrBayesPrint (" \n"); - for (i=1; icmdUse == IN_CMD && p->hiding == SHOW) - { - if (GetUserHelp(p->string)==ERROR) - goto errorExit; - } - } - - /* list of data or tree block commands */ - MrBayesPrint (" \n"); - MrBayesPrint (" *************************************************************************** \n"); - MrBayesPrint (" * * \n"); - MrBayesPrint (" * 3. 'Data' or 'tree' block commands (in #NEXUS file) * \n"); - MrBayesPrint (" * * \n"); - MrBayesPrint (" *************************************************************************** \n"); - MrBayesPrint (" \n"); - for (i=1; icmdUse == IN_FILE && p->hiding == SHOW) - { - if (GetUserHelp(p->string) == ERROR) - goto errorExit; - } - } - - /* return logging to previous setings and switch echoing on */ - SafeFclose (&fp); - logToFile = logSetting; - logFileFp = logfp; - echoMB = YES; - - MrBayesPrint ("%s Successfully produced command reference file \"%s\"\n", spacer, manFileName); - - return (NO_ERROR); - - errorExit: - SafeFclose (&fp); - logToFile = logSetting; - logFileFp = logfp; - echoMB = YES; - - return (ERROR); -} - - -int DoManualParm (char *parmName, char *tkn) -{ - if (expecting == Expecting(PARAMETER)) - { - expecting = Expecting(EQUALSIGN); - } - else - { - if (!strcmp(parmName, "Filename")) - { - if (expecting == Expecting(EQUALSIGN)) - { - expecting = Expecting(ALPHA); - readWord = YES; - } - else if (expecting == Expecting(ALPHA)) - { - strcpy (manFileName, tkn); - expecting = Expecting(SEMICOLON); - } - else - return (ERROR); - } - else - { - MrBayesPrint ("%s Unknown parameter in Manual\n", spacer); - return (ERROR); - } - } - - return (NO_ERROR); -} - - -int DoMatrix (void) -{ - int i, j, hasMissingAmbig; - - if (taxonCount != numTaxa) - { - MrBayesPrint ("%s Problem with number of taxa read in (%d taxa read in, while expecting %d)\n", spacer, taxonCount, numTaxa); - FreeMatrix(); - return (ERROR); - } - for (i=0; i 1) */ - { - sprintf (comptreeParams.comptFileName1, "%s.run1.t", inputFileName); - sprintf (comptreeParams.comptFileName2, "%s.run2.t", inputFileName); - } - - if (chainParams.numRuns == 1) - sprintf (plotParams.plotFileName, "%s.p", inputFileName); - else /* if (chainParams.numRuns > 1) */ - sprintf (plotParams.plotFileName, "%s.run1.p", inputFileName); - - strcpy (chainParams.chainFileName, inputFileName); - - if (chainParams.numRuns > 1) - MrBayesPrint ("%s Setting output file names to \"%s.run.\"\n", spacer, chainParams.chainFileName); - else - MrBayesPrint ("%s Setting output file names to \"%s.\"\n", spacer, chainParams.chainFileName); - -# if 0 - for (i=0; i 0) - { - if (taxaInfo[taxonCount-1].charCount < numChar) - foundNewLine = NO; - } - } - - if (taxonCount >= numTaxa && foundNewLine == YES) - { - if (isInterleaved == YES) - { - taxonCount = 0; - isFirstInterleavedBlock = NO; - } - else - { - MrBayesPrint ("%s Too many taxa in matrix\n", spacer); - goto errorExit; - } - } - - if (taxaInfo[0].charCount > 4010) - i = 1; - - if (foundNewLine == YES) - { - /* Should be a taxon. */ - if (isFirstInterleavedBlock == YES) - { - /* If this is the first interleaved block, then we need to add the taxon - to the set of taxon names unless there is already a defined taxon set. */ - if (strlen(tkn)>99) - { - MrBayesPrint ("%s Taxon name %s is too long. Maximun 99 characters is allowed.\n", spacer, tkn); - goto errorExit; - } - if (isTaxsetDef == NO && AddString (&taxaNames, taxonCount, tkn) == ERROR) - { - MrBayesPrint ("%s Problem adding taxon %s to taxon set\n", spacer, tkn); - goto errorExit; - } - if (numTaxa < 10) - MrBayesPrint ("%s Taxon %d -> %s\n", spacer, taxonCount+1, tkn); - else if (numTaxa < 100 && numTaxa >= 10) - MrBayesPrint ("%s Taxon %2d -> %s\n", spacer, taxonCount+1, tkn); - else if (numTaxa < 1000 && numTaxa >= 100) - MrBayesPrint ("%s Taxon %3d -> %s\n", spacer, taxonCount+1, tkn); - else - MrBayesPrint ("%s Taxon %4d -> %s\n", spacer, taxonCount+1, tkn); - } - else - { - /* If this is not the first interleaved block, then we need to - check to see if taxon name is present and in correct place. */ - if (CheckString (taxaNames, numTaxa, tkn, &index) == ERROR) - { - MrBayesPrint ("%s Could not find taxon %s in list of taxa\n", spacer, tkn); - goto errorExit; - } - if (index != taxonCount) - { - MrBayesPrint ("%s Could not find taxon %s in correct position in list of taxa\n", spacer, tkn); - goto errorExit; - } - } - foundNewLine = NO; - isNegative = NO; - taxonCount++; - } - else - { - /* Should be a character (either continuous or otherwise). */ - if (charInfo[taxaInfo[taxonCount-1].charCount].charType == CONTINUOUS) - { - /* If we have a CONTINUOUS character, then the entire token should either be - a number or a dash (for a negative sign). */ - if (!strcmp(tkn, "-")) - { - /* Dealing with a negative number. We will multiply the next tkn, which - had better be a number, by -1. */ - isNegative = YES; - } - else - { - /* We have a number, we hope. */ - if (tkn[0] == matchId) - { - /* If the token is a matchchar, then things are simple. */ - if (taxonCount == 1) - { - MrBayesPrint ("%s Matching characters cannot be in first taxon\n", spacer); - goto errorExit; - } - charCode = matrix[pos(0,taxaInfo[taxonCount-1].charCount,numChar)]; - matrix[pos(taxonCount-1,taxaInfo[taxonCount-1].charCount,numChar)] = charCode; - } - else - { - /* Otherwise, we have a number. Check that it is a valid number first... */ - if (!IsIn(tkn[0],"0123456789.")) - { - MrBayesPrint ("%s Expecting a number for the continuous character\n", spacer); - goto errorExit; - } - /* ... and then put the character into the matrix. Note that matrix - is defined as an integer, but we may have floating precision continuous - characters. To get around this, we multiply the value of the character - by 1000 before putting it into matrix. We will divide by 1000 later on - when/if we use the characters. */ - sscanf (tkn, "%lf", &charValue); - charValue *= 1000.0; - if (isNegative == YES) - { - charValue *= -1.0; - isNegative = NO; - } - /*MrBayesPrint ("%d \n", (int)charValue);*/ - matrix[pos(taxonCount-1,taxaInfo[taxonCount-1].charCount++,numChar)] = (int)charValue; - } - } - } - else - { - /* Otherwise, we are dealing with a run-of-the-mill character, and we - cannot expect the entire token to contain only a single character. We - must, therefore, go through the token character-by-character. */ - i = 0; - while (tkn[i] != '\0') - { - /*MrBayesPrint ("%c", tkn[i]);*/ - if (tkn[i] == matchId) - { - if (taxonCount == 1) - { - MrBayesPrint ("%s Matching characters cannot be in first taxon\n", spacer); - goto errorExit; - } - charCode = matrix[pos(0,taxaInfo[taxonCount-1].charCount,numChar)]; - matrix[pos(taxonCount-1,taxaInfo[taxonCount-1].charCount++,numChar)] = charCode; - } - else - { - if ((tkn[i] == ')' && isInAmbig == YES) || (tkn[i] == '}' && isInPoly == YES)) - { - isInAmbig = isInPoly = NO; - charCode = theAmbigChar; - j = CharacterNumber (charCode, charInfo[taxaInfo[taxonCount-1].charCount].charType); - if (j > charInfo[taxaInfo[taxonCount-1].charCount].numStates) - charInfo[taxaInfo[taxonCount-1].charCount].numStates = j; - matrix[pos(taxonCount-1,taxaInfo[taxonCount-1].charCount++,numChar)] = charCode; - theAmbigChar = 0; - } - else if ((tkn[i] == '(' && isInAmbig == YES) || (tkn[i] == '{' && isInPoly == YES)) - { - if (isInAmbig == YES) - MrBayesPrint ("%s Found an inappropriate \"(\"\n", spacer); - else - MrBayesPrint ("%s Found an inappropriate \"{\"\n", spacer); - goto errorExit; - } - else if (isInAmbig == YES || isInPoly == YES) - { - if (tkn[i] == ',') - expecting |= Expecting (COMMA); - else - { - if (CharacterCode(tkn[i], &charCode, charInfo[taxaInfo[taxonCount-1].charCount].charType) == ERROR) - goto errorExit; - if (charCode == MISSING || charCode == GAP) - goto errorExit; - theAmbigChar |= charCode; - expecting ^= Expecting (COMMA); - } - } - else if (tkn[i] == '{' && isInPoly == NO && isInAmbig == NO) - { - isInPoly = YES; - matrixHasPoly = YES; - theAmbigChar = 0; - } - else if (tkn[i] == '(' && isInPoly == NO && isInAmbig == NO) - { - isInAmbig = YES; - theAmbigChar = 0; - } - else if (tkn[i] == '(' && isInPoly == NO && isInAmbig == NO) - { - isInAmbig = YES; - theAmbigChar = 0; - } - else - { - if (CharacterCode(tkn[i], &charCode, charInfo[taxaInfo[taxonCount-1].charCount].charType) == ERROR) - { - MrBayesPrint ("%s Error while reading character position %d (charCode %d)\n", spacer, taxaInfo[taxonCount-1].charCount+1, charCode); - goto errorExit; - } - if (charCode != MISSING && charCode != GAP) - { - j = CharacterNumber (charCode, charInfo[taxaInfo[taxonCount-1].charCount].charType); - if (j > charInfo[taxaInfo[taxonCount-1].charCount].numStates) - charInfo[taxaInfo[taxonCount-1].charCount].numStates = j; - } - matrix[pos(taxonCount-1,taxaInfo[taxonCount-1].charCount++,numChar)] = charCode; - } - } - i++; - } - } - } - - return (NO_ERROR); - MrBayesPrint ("%s", parmName); /* just because I am tired of seeing the unused parameter error msg */ - errorExit: - numTaxa=taxonCount; - FreeMatrix(); - return (ERROR); -} - - -int DoNexusParm (char *parmName, char *tkn) -{ - if (!strcmp(parmName, "NEXUS")) - { - MrBayesPrint ("%s Expecting NEXUS formatted file\n", spacer); - expecting = Expecting(COMMAND); - } - else - { - MrBayesPrint ("%s Found %s\n", spacer, tkn); - return (ERROR); - } - - return (NO_ERROR); -} - - -int DoOutgroup (void) -{ - MrBayesPrint ("%s Setting outgroup to taxon \"%s\"\n", spacer, taxaNames[outGroupNum]); - return (NO_ERROR); -} - - -int DoOutgroupParm (char *parmName, char *tkn) -{ - int index, tempInt; - - if (expecting == Expecting(ALPHA)) - { - if (CheckString (taxaNames, numTaxa, tkn, &index) == ERROR) - { - MrBayesPrint ("%s Could not find taxon %s in list of taxa\n", spacer, tkn); - return (ERROR); - } - outGroupNum = index; - - expecting = Expecting(SEMICOLON); - } - else if (expecting == Expecting(NUMBER)) - { - if (CheckString (taxaNames, numTaxa, tkn, &index) == ERROR) - { - /* OK, as we expect, the taxon is not a digit. So, now we assume that - the user is assigning the outgroup by its number */ - sscanf (tkn, "%d", &tempInt); - if (tempInt < 1 || tempInt > numTaxa) - { - MrBayesPrint ("%s Taxon number %d is out of range\n", spacer, tempInt); - return (ERROR); - } - outGroupNum = tempInt - 1; - } - else - { - outGroupNum = index; - } - - expecting = Expecting(SEMICOLON); - } - else - return (ERROR); - - return (NO_ERROR); - MrBayesPrint ("%s", parmName); /* just because I am tired of seeing the unused parameter error msg */ -} - - -int DoPairs (void) -{ - MrBayesPrint ("\n"); - MrBayesPrint ("%s Successfully defined character pairings\n", spacer); - - defPairs = YES; - foundFirst = NO; - - return (NO_ERROR); -} - - -int DoPairsParm (char *parmName, char *tkn) -{ - int i, tempInt; - - if (defMatrix == NO) - { - MrBayesPrint ("%s A matrix must be specified before you can define pairs of characters\n", spacer); - return (ERROR); - } - - if (defPairs == YES) - { - MrBayesPrint ("%s Character pairs have been previously defined \n", spacer); - MrBayesPrint ("%s Now overwriting old pairings\n", spacer); - for (i=0; i numChar) - { - MrBayesPrint ("\n"); - MrBayesPrint ("%s Character number %d is out of range (should be between %d and %d)\n", spacer, tempInt, 1, numChar); - for (i=0; i= 0) - if (AddToSet (fromI, toJ, everyK, whichPartition+1) == ERROR) - return (ERROR); - - /* check that all characters are included */ - for (i=0; i 99) - { - MrBayesPrint ("%s Partition name is too long. Max 100 characters\n", spacer); - return (ERROR); - } - - /* check to see if the name has already been used as a partition */ - if (numDefinedPartitions > 1) - { - if (CheckString (partitionNames, numDefinedPartitions, tkn, &index) == ERROR) - { - /* if the partition name has not been used, then we should have an ERROR returned */ - /* we _want_ to be here */ - - } - else - { - MrBayesPrint ("%s Partition name '%s' has been used previously\n", spacer, tkn); - return (ERROR); - } - } - - /* add the name temporarily to tempSetName */ - strcpy (tempSetName, tkn); - - /* clear tempSet */ - for (i=0; i numChar) - { - MrBayesPrint ("%s Character number %d is out of range (should be between %d and %d)\n", spacer, tempInt, 1, numChar); - return (ERROR); - } - tempInt--; - if (foundDash == YES) - { - if (fromI >= 0) - toJ = tempInt; - else - { - MrBayesPrint ("%s Improperly formatted partition\n", spacer); - return (ERROR); - } - foundDash = NO; - } - else if (foundSlash == YES) - { - tempInt++; - if (tempInt <= 1) - { - MrBayesPrint ("%s Improperly formatted charset\n", spacer); - return (ERROR); - } - if (fromI >= 0 && toJ >= 0 && fromI < toJ) - everyK = tempInt; - else - { - MrBayesPrint ("%s Improperly formatted charset\n", spacer); - return (ERROR); - } - foundSlash = NO; - } - else - { - if (fromI >= 0 && toJ < 0) - { - if (AddToSet (fromI, toJ, everyK, whichPartition+1) == ERROR) - return (ERROR); - fromI = tempInt; - } - else if (fromI < 0 && toJ < 0) - { - fromI = tempInt; - } - else if (fromI >= 0 && toJ >= 0 && everyK < 0) - { - if (AddToSet (fromI, toJ, everyK, whichPartition+1) == ERROR) - return (ERROR); - fromI = tempInt; - toJ = everyK = -1; - } - else if (fromI >= 0 && toJ >= 0 && everyK >= 0) - { - if (AddToSet (fromI, toJ, everyK, whichPartition+1) == ERROR) - return (ERROR); - fromI = tempInt; - toJ = everyK = -1; - } - else - { - MrBayesPrint ("%s Improperly formatted charset\n", spacer); - { - return (ERROR); - } - } - } - - expecting = Expecting(ALPHA); - expecting |= Expecting(NUMBER); - expecting |= Expecting(SEMICOLON); - expecting |= Expecting(DASH); - expecting |= Expecting(BACKSLASH); - expecting |= Expecting(COMMA); - } - } - else if (expecting == Expecting(COMMA)) - { - /* add set to tempSet */ - if (fromI >= 0) - if (AddToSet (fromI, toJ, everyK, whichPartition+1) == ERROR) - return (ERROR); - - fromI = toJ = everyK = -1; - foundDash = foundSlash = NO; - whichPartition++; - if (whichPartition > numDivisions) - { - MrBayesPrint ("%s Too many partitions of the data (expecting %d)\n", spacer, numDivisions); - return (ERROR); - } - expecting = Expecting(NUMBER); - expecting |= Expecting(ALPHA); - } - else if (expecting == Expecting(COLON)) - { - expecting = Expecting(NUMBER); - expecting |= Expecting(ALPHA); - } - else if (expecting == Expecting(DASH)) - { - foundDash = YES; - expecting = Expecting(NUMBER); - } - else if (expecting == Expecting(BACKSLASH)) - { - foundSlash = YES; - expecting = Expecting(NUMBER); - } - else - return (ERROR); - - return (NO_ERROR); -} - - -int DoRestore (void) -{ - int i, alreadyDone; - - MrBayesPrint ("%s Restore taxa\n", spacer); - - /* add set to tempSet */ - if (fromI >= 0 && toJ < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - } - else if (fromI >= 0 && toJ >= 0 && everyK < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - } - else if (fromI >= 0 && toJ >= 0 && everyK >= 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - } - - /* merge tempSet with excludedTaxa */ - alreadyDone = NO; - for (i=0; i= 0 && toJ < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - } - else if (fromI >= 0 && toJ >= 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - } - tempSet[index] = 1; - } - fromI = toJ = everyK = -1; - } - - expecting = Expecting(ALPHA); - expecting |= Expecting(NUMBER); - expecting |= Expecting(SEMICOLON); - } - else if (expecting == Expecting(NUMBER)) - { - if (strlen(tkn) == 1 && !strcmp(tkn, ".")) - { - tempInt = numTaxa; - } - else - { - sscanf (tkn, "%d", &tempInt); - if (tempInt <= 0 || tempInt > numTaxa) - { - MrBayesPrint ("%s Taxon number %d is out of range (should be between %d and %d)\n", spacer, tempInt, 1, numTaxa); - return (ERROR); - } - } - tempInt--; - if (foundDash == YES) - { - if (fromI >= 0) - toJ = tempInt; - else - { - MrBayesPrint ("%s Improperly formatted restore set\n", spacer); - return (ERROR); - } - foundDash = NO; - } - else - { - if (fromI >= 0 && toJ < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - fromI = tempInt; - } - else if (fromI < 0 && toJ < 0) - { - fromI = tempInt; - } - else if (fromI >= 0 && toJ >= 0 && everyK < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - fromI = tempInt; - toJ = everyK = -1; - } - else if (fromI >= 0 && toJ >= 0 && everyK >= 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - fromI = tempInt; - toJ = everyK = -1; - } - else - { - MrBayesPrint ("%s Improperly formatted restore set\n", spacer); - { - return (ERROR); - } - } - } - expecting = Expecting(ALPHA); - expecting |= Expecting(NUMBER); - expecting |= Expecting(SEMICOLON); - expecting |= Expecting(DASH); - } - else if (expecting == Expecting(DASH)) - { - foundDash = YES; - expecting = Expecting(NUMBER); - } - else - return (ERROR); - - return (NO_ERROR); - MrBayesPrint ("%s", parmName); /* just because I am tired of seeing the unused parameter error msg */ -} - - -int DoSet (void) -{ - return (NO_ERROR); -} - - -int DoSetParm (char *parmName, char *tkn) -{ - int index; - char tempStr[100]; - int tempI; - - if (expecting == Expecting(PARAMETER)) - { - expecting = Expecting(EQUALSIGN); - } - else - { - /* set Autoclose (autoClose) **********************************************************/ - if (!strcmp(parmName, "Autoclose")) - { - if (expecting == Expecting(EQUALSIGN)) - expecting = Expecting(ALPHA); - else if (expecting == Expecting(ALPHA)) - { - if (IsArgValid(tkn, tempStr) == NO_ERROR) - { - if (!strcmp(tempStr, "Yes")) - autoClose = YES; - else - autoClose = NO; - } - else - { - MrBayesPrint ("%s Invalid argument for autoclose\n", spacer); - return (ERROR); - } - if (autoClose == YES) - MrBayesPrint ("%s Setting autoclose to yes\n", spacer); - else - MrBayesPrint ("%s Setting autoclose to no\n", spacer); - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } - /* set Nowarnings (noWarn) **********************************************************/ - else if (!strcmp(parmName, "Nowarnings")) - { - if (expecting == Expecting(EQUALSIGN)) - expecting = Expecting(ALPHA); - else if (expecting == Expecting(ALPHA)) - { - if (IsArgValid(tkn, tempStr) == NO_ERROR) - { - if (!strcmp(tempStr, "Yes")) - noWarn = YES; - else - noWarn = NO; - } - else - { - MrBayesPrint ("%s Invalid argument for nowarnings\n", spacer); - return (ERROR); - } - if (noWarn == YES) - MrBayesPrint ("%s Setting nowarnings to yes\n", spacer); - else - MrBayesPrint ("%s Setting nowarnings to no\n", spacer); - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } - /* set Quitonerror (quitOnError) **************************************************/ - else if (!strcmp(parmName, "Quitonerror")) - { - if (expecting == Expecting(EQUALSIGN)) - expecting = Expecting(ALPHA); - else if (expecting == Expecting(ALPHA)) - { - if (IsArgValid(tkn, tempStr) == NO_ERROR) - { - if (!strcmp(tempStr, "Yes")) - quitOnError = YES; - else - quitOnError = NO; - } - else - { - MrBayesPrint ("%s Invalid argument for quitonerror\n", spacer); - return (ERROR); - } - if (quitOnError == YES) - MrBayesPrint ("%s Setting quitonerror to yes\n", spacer); - else - MrBayesPrint ("%s Setting quitonerror to no\n", spacer); - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } - /* set Autoreplace (autoOverwrite) **************************************************/ - else if (!strcmp(parmName, "Autoreplace")) - { - if (expecting == Expecting(EQUALSIGN)) - expecting = Expecting(ALPHA); - else if (expecting == Expecting(ALPHA)) - { - if (IsArgValid(tkn, tempStr) == NO_ERROR) - { - if (!strcmp(tempStr, "Yes")) - { - autoOverwrite = YES; - MrBayesPrint ("%s Setting autoreplace to yes\n", spacer); - } - else - { - autoOverwrite = NO; - MrBayesPrint ("%s Setting autoreplace to no\n", spacer); - } - } - else - { - MrBayesPrint ("%s Invalid argument for autoreplace\n", spacer); - return (ERROR); - } - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } - /* set Scientific (scientific) *********************************************/ - else if (!strcmp(parmName, "Scientific")) - { - if (expecting == Expecting(EQUALSIGN)) - expecting = Expecting(ALPHA); - else if (expecting == Expecting(ALPHA)) - { - if (IsArgValid(tkn, tempStr) == NO_ERROR) - { - if (!strcmp(tempStr, "Yes")) - scientific = YES; - else - scientific = NO; - } - else - { - MrBayesPrint ("%s Invalid argument for Scientific\n", spacer); - return (ERROR); - } - if (scientific == YES) - MrBayesPrint ("%s Setting Scientific to Yes\n", spacer); - else - MrBayesPrint ("%s Setting Scientific to No\n", spacer); - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } - /* set Userlevel (userLevel) **********************************************************/ - else if (!strcmp(parmName, "Userlevel")) - { - if (expecting == Expecting(EQUALSIGN)) - expecting = Expecting(ALPHA); - else if (expecting == Expecting(ALPHA)) - { - if (IsArgValid(tkn, tempStr) == NO_ERROR) - { - if (!strcmp(tempStr, "Standard")) - userLevel = STANDARD_USER; - else if (!strcmp (tempStr,"Developer")) - userLevel = DEVELOPER; - } - else - { - MrBayesPrint ("%s Invalid argument for userlevel\n", spacer); - return (ERROR); - } - MrBayesPrint ("%s Setting userlevel to %s\n", spacer, tempStr); - if (defMatrix == YES && SetUpAnalysis(&globalSeed) == ERROR) - return ERROR; - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } - /* set Npthreads (number of pthreads) ****************************************************/ - else if (!strcmp(parmName, "Npthreads")) - { - if (expecting == Expecting(EQUALSIGN)) - expecting = Expecting(NUMBER); - else if (expecting == Expecting(NUMBER)) - { - sscanf (tkn, "%d", &tempI); - nPThreads = tempI; - MrBayesPrint ("%s Setting Npthreads to %d\n", spacer, nPThreads); - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } - /* set Precision (number of decimals) ****************************************************/ - else if (!strcmp(parmName, "Precision")) - { - if (expecting == Expecting(EQUALSIGN)) - expecting = Expecting(NUMBER); - else if (expecting == Expecting(NUMBER)) - { - sscanf (tkn, "%d", &tempI); - if (tempI < 3 || tempI > 15) - { - MrBayesPrint ("%s Precision must be in the range 3 to 15\n", spacer); - return ERROR; - } - precision = tempI; - MrBayesPrint ("%s Setting Precision to %d\n", spacer, precision); - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } - /* set Partition (partitionNum) *******************************************************/ - else if (!strcmp(parmName, "Partition")) - { - if (defMatrix == NO) - { - MrBayesPrint ("%s A character matrix must be defined first\n", spacer); - return (ERROR); - } - if (expecting == Expecting(EQUALSIGN)) - expecting = Expecting(ALPHA) | Expecting(NUMBER); - else if (expecting == Expecting(ALPHA)) - { - /* first check to see if name is there */ - if (CheckString (partitionNames, numDefinedPartitions, tkn, &index) == ERROR) - { - MrBayesPrint ("%s Could not find \"%s\" as a defined partition\n", spacer, tkn); - return (ERROR); - } - if (SetPartition (index) == ERROR) - return ERROR; - if (numCurrentDivisions == 1) - MrBayesPrint ("%s Setting %s as the partition (does not divide up characters).\n", spacer, tkn); - else - MrBayesPrint ("%s Setting %s as the partition, dividing characters into %d parts.\n", spacer, tkn, numCurrentDivisions); - if (SetModelDefaults () == ERROR) - return (ERROR); - if (SetUpAnalysis (&globalSeed) == ERROR) - return (ERROR); - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else if (expecting == Expecting(NUMBER)) - { - sscanf (tkn, "%d", &index); - if (index > numDefinedPartitions) - { - MrBayesPrint ("%s Partition number %d is not a valid partition. Only %d partitions\n", spacer, index, numDefinedPartitions); - MrBayesPrint ("%s have been defined.\n", spacer); - return (ERROR); - } - if (index < 1) - { - MrBayesPrint ("%s Partition number %d is not a valid partition. Must be between 1 and %d.\n", spacer, index+1, numDefinedPartitions); - return (ERROR); - } - if (SetPartition (index) == ERROR) - return ERROR; - if (numCurrentDivisions == 1) - MrBayesPrint ("%s Setting %s as the partition (does not divide up characters).\n", spacer, partitionNames[index]); - else - MrBayesPrint ("%s Setting %s as the partition, dividing characters into %d parts.\n", spacer, partitionNames[index], numCurrentDivisions); - if (SetModelDefaults () == ERROR) - return (ERROR); - if (SetUpAnalysis (&globalSeed) == ERROR) - return (ERROR); - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } - /* set Speciespartition (speciespartitionNum) *******************************************************/ - else if (!strcmp(parmName, "Speciespartition")) - { - if (defTaxa == NO) - { - MrBayesPrint ("%s A taxaset must be defined first\n", spacer); - return (ERROR); - } - if (expecting == Expecting(EQUALSIGN)) - expecting = Expecting(ALPHA) | Expecting(NUMBER); - else if (expecting == Expecting(ALPHA)) - { - /* first check to see if name is there */ - if (CheckString (speciespartitionNames, numDefinedSpeciespartitions, tkn, &index) == ERROR) - { - MrBayesPrint ("%s Could not find \"%s\" as a defined speciespartition\n", spacer, tkn); - return (ERROR); - } - if (SetSpeciespartition (index) == ERROR) - return ERROR; - MrBayesPrint ("%s Setting %s as the speciespartition, dividing taxa into %d species.\n", spacer, tkn, numSpecies); - if (SetModelDefaults () == ERROR) - return (ERROR); - if (SetUpAnalysis (&globalSeed) == ERROR) - return (ERROR); - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else if (expecting == Expecting(NUMBER)) - { - sscanf (tkn, "%d", &index); - if (index > numDefinedSpeciespartitions) - { - MrBayesPrint ("%s Speciespartition number %d is not valid. Only %d speciespartitions\n", spacer, index, numDefinedSpeciespartitions); - MrBayesPrint ("%s have been defined.\n", spacer); - return (ERROR); - } - if (index < 1) - { - MrBayesPrint ("%s Speciespartition number %d is not valid. Must be between 1 and %d.\n", spacer, index, numDefinedSpeciespartitions); - return (ERROR); - } - if (SetSpeciespartition (index-1) == ERROR) - return ERROR; - MrBayesPrint ("%s Setting %s as the speciespartition, dividing taxa into %d species.\n", spacer, speciespartitionNames[index-1], numSpecies); - if (SetModelDefaults () == ERROR) - return (ERROR); - if (SetUpAnalysis (&globalSeed) == ERROR) - return (ERROR); - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } - /* set Seed (global variable globalSeed) ****************************************************/ - else if (!strcmp(parmName, "Seed")) - { - if (expecting == Expecting(EQUALSIGN)) - expecting = Expecting(NUMBER); - else if (expecting == Expecting(NUMBER)) - { - sscanf (tkn, "%d", &tempI); - if (tempI == 0 || tempI == 2147483647) - { - MrBayesPrint ("%s Error: Seed can be any natural number except 0 and 2147483647\n", spacer); - return (ERROR); - } - globalSeed = tempI; - MrBayesPrint ("%s Setting seed to %ld\n", spacer, globalSeed); - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } - /* set Swapseed (global variable swapSeed) ***************************************************************/ - else if (!strcmp(parmName, "Swapseed")) - { - if (expecting == Expecting(EQUALSIGN)) - expecting = Expecting(NUMBER); - else if (expecting == Expecting(NUMBER)) - { - sscanf (tkn, "%d", &tempI); - if (tempI == 0 || tempI == 2147483647) - { - MrBayesPrint ("%s Error: Swapseed can be any natural number except 0 and 2147483647\n", spacer); - return (ERROR); - } - swapSeed = tempI; - MrBayesPrint ("%s Setting swapseed to %ld\n", spacer, swapSeed); - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } - /* set Dir (global variable workingDir) ***************************************************************/ - else if (!strcmp(parmName, "Dir")) - { - if (expecting == Expecting(EQUALSIGN)) - { - expecting = Expecting(ALPHA); - readWord = YES; - } - else if (expecting == Expecting(ALPHA)) - { - if (strlen(tkn)>99) - { - MrBayesPrint ("%s Maximum allowed length of working directory name is 99 characters. The given name:\n", spacer); - MrBayesPrint ("%s '%s'\n", spacer,tkn); - MrBayesPrint ("%s has %d characters.\n", spacer,strlen(tkn)); - return (ERROR); - } - strcpy (workingDir, tkn); -# if defined (WIN_VERSION) - /* Reformat to Windows with trailing '\' */ - for (index=0; index<(int)strlen(workingDir); index++) - { - if (workingDir[index] == '/') - workingDir[index] = '\\'; - } - if (strlen(workingDir) > 0 && workingDir[strlen(workingDir)-1] != '\\') - strcat(workingDir,"\\"); -# else - /* Reformat to Unix with trailing '/' */ - for (index=0; index<(int)strlen(workingDir); index++) - { - if (workingDir[index] == '\\') - workingDir[index] = '/'; - } - if (strlen(workingDir) > 0 && workingDir[strlen(workingDir)-1] != '/') - strcat(workingDir,"/"); -# endif - MrBayesPrint ("%s Setting working directory to \"%s\"\n", spacer, workingDir); - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } - /* set Usebeagle (global variable BEAGLE usage) ***************************************************************/ - else if (!strcmp(parmName, "Usebeagle")) - { - if (expecting == Expecting(EQUALSIGN)) - expecting = Expecting(ALPHA); - else if (expecting == Expecting(ALPHA)) - { -# if defined (BEAGLE_ENABLED) - if (IsArgValid(tkn, tempStr) == NO_ERROR) - { - if (!strcmp(tempStr, "Yes")) - tryToUseBEAGLE = YES; - else - tryToUseBEAGLE = NO; - } - else - { - MrBayesPrint ("%s Invalid argument for usebeagle\n", spacer); - return (ERROR); - } - if (tryToUseBEAGLE == YES) - MrBayesPrint ("%s Setting usebeagle to yes\n", spacer); - else - MrBayesPrint ("%s Setting usebeagle to no\n", spacer); -# else - BeagleNotLinked(); -# endif - if (defMatrix == YES && SetUpAnalysis(&globalSeed) == ERROR) - return ERROR; - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } - /* set Beagle resource number (global variable BEAGLE flag) ****************************************/ - else if (!strcmp(parmName, "Beagleresource")) - { - if (expecting == Expecting(EQUALSIGN)) - expecting = Expecting(NUMBER); - else if (expecting == Expecting(NUMBER)) - { -# if defined (BEAGLE_ENABLED) - sscanf (tkn, "%d", &tempI); - if (tempI < 0) - { - MrBayesPrint ("%s Beagleresource must be a valid resource number or 99 to disable resource selection\n", spacer); - return ERROR; - } - beagleResourceNumber = tempI; - if (beagleResourceNumber == 99) - MrBayesPrint ("%s Setting Beagleresource to %d (auto)\n", spacer, beagleResourceNumber); - else - MrBayesPrint ("%s Setting Beagleresource to %d\n", spacer, beagleResourceNumber); -# else - BeagleNotLinked(); -# endif - if (defMatrix == YES && SetUpAnalysis(&globalSeed) == ERROR) - return ERROR; - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } - /* set Beagle resources requirements (global variable BEAGLE flag) ****************************************/ - else if (!strcmp(parmName, "Beagledevice")) - { - if (expecting == Expecting(EQUALSIGN)) - expecting = Expecting(ALPHA); - else if (expecting == Expecting(ALPHA)) - { -# if defined (BEAGLE_ENABLED) - if (IsArgValid(tkn, tempStr) == NO_ERROR) - { - long oldFlags = beagleFlags; - if (!strcmp(tempStr, "Gpu")) - { - beagleFlags &= ~BEAGLE_FLAG_PROCESSOR_CPU; - beagleFlags |= BEAGLE_FLAG_PROCESSOR_GPU; - BeagleAddGPUDevicesToList(&beagleResource, &beagleResourceCount); - } - else - { - beagleFlags &= ~BEAGLE_FLAG_PROCESSOR_GPU; - beagleFlags |= BEAGLE_FLAG_PROCESSOR_CPU; - BeagleRemoveGPUDevicesFromList(&beagleResource, &beagleResourceCount); - } - if (BeagleCheckFlagCompatability(beagleFlags) == NO) { - beagleFlags = oldFlags; - } - else { - if (beagleFlags & BEAGLE_FLAG_PROCESSOR_GPU) - MrBayesPrint ("%s Setting beagledevice to GPU\n", spacer); - else - MrBayesPrint ("%s Setting beagledevice to CPU\n", spacer); - } - } - else - { - MrBayesPrint ("%s Invalid argument for beagledevice\n", spacer); - return (ERROR); - } -# else - BeagleNotLinked(); -# endif - if (defMatrix == YES && SetUpAnalysis(&globalSeed) == ERROR) - return ERROR; - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } - else if (!strcmp(parmName, "Beagleprecision")) - { - if (expecting == Expecting(EQUALSIGN)) - expecting = Expecting(ALPHA); - else if (expecting == Expecting(ALPHA)) - { -# if defined (BEAGLE_ENABLED) - if (IsArgValid(tkn, tempStr) == NO_ERROR) - { - long oldFlags = beagleFlags; - if (!strcmp(tempStr, "Single")) - { - beagleFlags &= ~BEAGLE_FLAG_PRECISION_DOUBLE; - beagleFlags |= BEAGLE_FLAG_PRECISION_SINGLE; - } - else - { - beagleFlags &= ~BEAGLE_FLAG_PRECISION_SINGLE; - beagleFlags |= BEAGLE_FLAG_PRECISION_DOUBLE; - } - if (BeagleCheckFlagCompatability(beagleFlags) == NO) { - beagleFlags = oldFlags; - } - else { - if (beagleFlags & BEAGLE_FLAG_PRECISION_DOUBLE) - MrBayesPrint ("%s Setting beagleprecision to double\n", spacer); - else - MrBayesPrint ("%s Setting beagleprecision to single\n", spacer); - } - } - else - { - MrBayesPrint ("%s Invalid argument for beagleprecision\n", spacer); - return (ERROR); - } -# else - BeagleNotLinked(); -# endif - if (defMatrix == YES && SetUpAnalysis(&globalSeed) == ERROR) - return ERROR; - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } - else if (!strcmp(parmName, "Beagleopenmp")) - { - if (expecting == Expecting(EQUALSIGN)) - expecting = Expecting(ALPHA); - else if (expecting == Expecting(ALPHA)) - { -# if defined (BEAGLE_ENABLED) - if (IsArgValid(tkn, tempStr) == NO_ERROR) - { - long oldFlags = beagleFlags; - if (!strcmp(tempStr, "Yes")) - { - beagleFlags |= BEAGLE_FLAG_THREADING_OPENMP; - } - else - { - beagleFlags &= ~BEAGLE_FLAG_THREADING_OPENMP; - } - if (BeagleCheckFlagCompatability(beagleFlags) == NO) { - beagleFlags = oldFlags; - } - else { - if (beagleFlags & BEAGLE_FLAG_THREADING_OPENMP) - MrBayesPrint ("%s Setting beagleopenmp to Yes\n", spacer); - else - MrBayesPrint ("%s Setting beagleopenmp to No\n", spacer); - } - } - else - { - MrBayesPrint ("%s Invalid argument for beagleopenmp\n", spacer); - return (ERROR); - } -# else - BeagleNotLinked(); -# endif - if (defMatrix == YES && SetUpAnalysis(&globalSeed) == ERROR) - return ERROR; - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } - else if (!strcmp(parmName, "Beaglefreq")) - { - if (expecting == Expecting(EQUALSIGN)) - expecting = Expecting(NUMBER); - else if (expecting == Expecting(NUMBER)) - { -# if defined (BEAGLE_ENABLED) - sscanf (tkn, "%d", &tempI); - if (tempI < 0) - { - MrBayesPrint ("%s Beaglefreq must be greater than 0\n", spacer); - return ERROR; - } - beagleScalingFrequency= tempI; - MrBayesPrint ("%s Setting Beaglefreq to %d\n", spacer, beagleScalingFrequency); -# else - BeagleNotLinked(); -# endif - if (defMatrix == YES && SetUpAnalysis(&globalSeed) == ERROR) - return ERROR; - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } - else if (!strcmp(parmName, "Beaglesse")) - { - if (expecting == Expecting(EQUALSIGN)) - expecting = Expecting(ALPHA); - else if (expecting == Expecting(ALPHA)) - { -# if defined (BEAGLE_ENABLED) - if (IsArgValid(tkn, tempStr) == NO_ERROR) - { - long oldFlags = beagleFlags; - if (!strcmp(tempStr, "Yes")) - { - beagleFlags |= BEAGLE_FLAG_VECTOR_SSE; - } - else - { - beagleFlags &= ~BEAGLE_FLAG_VECTOR_SSE; - } - if (BeagleCheckFlagCompatability(beagleFlags) == NO) { - beagleFlags = oldFlags; - } - else { - if (beagleFlags & BEAGLE_FLAG_VECTOR_SSE) - MrBayesPrint ("%s Setting beaglesse to Yes\n", spacer); - else - MrBayesPrint ("%s Setting beaglesse to No\n", spacer); - } - } - else - { - MrBayesPrint ("%s Invalid argument for beagleopenmp\n", spacer); - return (ERROR); - } -# else - BeagleNotLinked(); -# endif - if (defMatrix == YES && SetUpAnalysis(&globalSeed) == ERROR) - return ERROR; - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } -#if 0 - else if (!strcmp(parmName, "Beaglevec")) - { - if (expecting == Expecting(EQUALSIGN)) - expecting = Expecting(ALPHA); - else if (expecting == Expecting(ALPHA)) - { -# if defined (BEAGLE_ENABLED) - if (IsArgValid(tkn, tempStr) == NO_ERROR) - { - long oldFlags = beagleFlags; - if (!strcmp(tempStr, "Sse")) - { - beagleFlags |= BEAGLE_FLAG_VECTOR_SSE; - beagleFlags &= ~BEAGLE_FLAG_VECTOR_AVX; - } - else if (!strcmp(tempStr, "Avx")) - { - beagleFlags |= ~BEAGLE_FLAG_VECTOR_AVX; - beagleFlags &= ~BEAGLE_FLAG_VECTOR_SSE; - } - else if (!strcmp(tempStr, "None")) - { - beagleFlags &= ~BEAGLE_FLAG_VECTOR_SSE; - beagleFlags &= ~BEAGLE_FLAG_VECTOR_AVX; - } - else - { - MrBayesPrint("%s Unrecognized argument for beaglevec\n", spacer); - } - MrBayesPrint ("%s Setting beaglevec to %s\n", spacer, tempStr); - } - else - { - MrBayesPrint ("%s Invalid argument for beagleopenmp\n", spacer); - return (ERROR); - } -# else - BeagleNotLinked(); -# endif - if (defMatrix == YES && SetUpAnalysis(&globalSeed) == ERROR) - return ERROR; - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } -#endif - else if (!strcmp(parmName, "Beaglethreads")) - { - if (expecting == Expecting(EQUALSIGN)) - expecting = Expecting(ALPHA); - else if (expecting == Expecting(ALPHA)) - { -# if defined (BEAGLE_ENABLED) && defined (THREADS_ENABLED) - if (IsArgValid(tkn, tempStr) == NO_ERROR) - { - if (!strcmp(tempStr, "Yes")) - { - tryToUseThreads = YES; - } - else - { - tryToUseThreads = NO; - } - - if (tryToUseThreads == YES) - MrBayesPrint ("%s Setting beaglethreads to Yes\n", spacer); - else - MrBayesPrint ("%s Setting beaglethreads to No\n", spacer); - } - else - { - MrBayesPrint ("%s Invalid argument for beaglethreads\n", spacer); - return (ERROR); - } -# else - BeagleThreadsNotLinked(); -# endif - if (defMatrix == YES && SetUpAnalysis(&globalSeed) == ERROR) - return ERROR; - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - } - else if (!strcmp(parmName, "Beaglescaling")) - { - if (expecting == Expecting(EQUALSIGN)) - expecting = Expecting(ALPHA); - else if (expecting == Expecting(ALPHA)) - { -# if defined (BEAGLE_ENABLED) - if (IsArgValid(tkn, tempStr) == NO_ERROR) - { - if (!strcmp(tempStr, "Always")) - { - beagleScalingScheme = MB_BEAGLE_SCALE_ALWAYS; - } - else - { - beagleScalingScheme = MB_BEAGLE_SCALE_DYNAMIC; - } - - if (beagleScalingScheme == MB_BEAGLE_SCALE_ALWAYS) - MrBayesPrint ("%s Setting beaglescaling to Always\n", spacer); - else - MrBayesPrint ("%s Setting beaglescaling to Dynamic\n", spacer); - } - else - { - MrBayesPrint ("%s Invalid argument for beaglescaling\n", spacer); - return (ERROR); - } -# else - BeagleThreadsNotLinked(); -# endif - if (defMatrix == YES && SetUpAnalysis(&globalSeed) == ERROR) - return ERROR; - expecting = Expecting(PARAMETER) | Expecting(SEMICOLON); - } - else - return (ERROR); - } - else - return (ERROR); - } - - return (NO_ERROR); -} - - -int DoShowMatrix (void) -{ - int i, j, nameLen, start, finish, ct, longestName; - char tempStr[100], stride; - - if (defMatrix == NO) - { - MrBayesPrint ("%s A character matrix must be defined first\n", spacer); - return (ERROR); - } - - longestName = 0; - for (i=0; i longestName) - longestName = nameLen; - } - - stride = 50; - start = finish = 0; - do - { - finish += stride; - if (finish > numChar) - finish = numChar; - - MrBayesPrint ("%s ", spacer); - for (j=0; j= longestName) - { - for (j=0; jname); - ShowConTree (stdout, userTree[i], 70, NO); - MrBayesPrint ("\n"); - } - } - - return (NO_ERROR); -} - - -int DoShowBeagle (void) -{ -# if defined (BEAGLE_ENABLED) - BeaglePrintResources(); -# else - BeagleNotLinked(); -# endif - return (NO_ERROR); -} - - -int DoTaxlabels (void) -{ - isTaxsetDef = YES; - - /* add default speciespartition name to list of valid speciespartitions */ - if (AddString (&speciespartitionNames, 0, "Default") == ERROR) - { - MrBayesPrint ("%s Problem adding Default speciespartition to list\n", spacer); - return (ERROR); - } - - /* add default species name set */ - AddNameSet(&speciesNameSets, 0, taxaNames, numTaxa); - - /* set number of defined speciespartitions to 1 */ - numDefinedSpeciespartitions = 1; - - return (NO_ERROR); -} - - -int DoTaxlabelsParm (char *parmName, char *tkn) -{ - int index; - - if (inTaxaBlock == NO) - { - MrBayesPrint ("%s You must be in a taxa block to read a taxlabels command\n", spacer); - return (ERROR); - } - - if (defTaxa == NO) - { - MrBayesPrint ("%s The number of taxa must be given before a set of taxon labels can be read\n", spacer); - return ERROR; - } - - if (isTaxsetDef == YES) - { - MrBayesPrint ("%s A set of taxon labels has already been defined\n", spacer); - if (defMatrix == NO) - if (WantTo ("Do you want to delete the current set of taxon labels") == NO) - return (SKIP_COMMAND); - else - FreeTaxa(); - else - if (WantTo ("Do you want to delete the current character matrix") == NO) - return (SKIP_COMMAND); - else - FreeMatrix(); - } - - if (expecting == Expecting(ALPHA) || - expecting == Expecting(NUMBER)) - { - if (CheckString (taxaNames, numNamedTaxa, tkn, &index) == ERROR) - { - if (strlen(tkn)>99) - { - MrBayesPrint ("%s Taxon name %s is too long. Maximun 99 characters is allowed.\n", spacer, tkn); - return (ERROR); - } - if (AddString (&taxaNames, numNamedTaxa, tkn) == ERROR) - { - MrBayesPrint ("%s Problem adding label %s to list of taxon labels\n", spacer, tkn); - return (ERROR); - } - numNamedTaxa++; - } - else - { - MrBayesPrint ("%s Taxon label '%s' is included twice in list of taxon labels\n", spacer, tkn); - return (ERROR); - } - if (numNamedTaxa < numTaxa) - { - expecting = Expecting(ALPHA); - expecting |= Expecting(NUMBER); - } - else - expecting |= Expecting(SEMICOLON); - } - - return (NO_ERROR); - MrBayesPrint ("%s", parmName); /* just because I am tired of seeing the unused parameter error msg */ - MrBayesPrint ("%s", tkn); -} - - -int DoSpeciespartition (void) -{ - int i, *partCount; - - /* add set to tempSet */ - if (fromI >= 0) - if (AddToSet (fromI, toJ, everyK, whichPartition+1) == ERROR) - { - for (i=0; i numTaxa) - { - MrBayesPrint ("%s Speciespartition index for tip %d out of bound (%d)\n", spacer, i+1, tempSet[i]); - free (partCount); - for (i=0; i 99) - { - MrBayesPrint ("%s Partition name is too long. Max 100 characters\n", spacer); - return (ERROR); - } - - /* check to see if the name has already been used as a partition */ - if (numDefinedSpeciespartitions > 0) - { - if (CheckString (speciespartitionNames, numDefinedSpeciespartitions, tkn, &index) == ERROR) - { - /* if the partition name has not been used, then we should have an ERROR returned */ - /* we _want_ to be here */ - - } - else - { - MrBayesPrint ("%s Speciespartition name '%s' has been used previously\n", spacer, tkn); - return (ERROR); - } - } - - /* add the name temporarily to tempSetName */ - strcpy (tempSetName, tkn); - - /* clear tempSet */ - for (i=0; i numTaxa) - { - MrBayesPrint ("%s Tip number %d is out of range (should be between %d and %d)\n", spacer, tempInt, 1, numTaxa); - for (i=0; i= 0) - toJ = tempInt; - else - { - MrBayesPrint ("%s Improperly formatted speciespartition\n", spacer); - for (i=0; i= 0 && toJ >= 0 && fromI < toJ) - everyK = tempInt; - else - { - MrBayesPrint ("%s Improperly formatted speciespartition\n", spacer); - for (i=0; i= 0 && toJ < 0) - { - if (AddToSet (fromI, toJ, everyK, whichPartition+1) == ERROR) - { - for (i=0; i= 0 && toJ >= 0 && everyK < 0) - { - if (AddToSet (fromI, toJ, everyK, whichPartition+1) == ERROR) - return (ERROR); - fromI = tempInt; - toJ = everyK = -1; - } - else if (fromI >= 0 && toJ >= 0 && everyK >= 0) - { - if (AddToSet (fromI, toJ, everyK, whichPartition+1) == ERROR) - return (ERROR); - fromI = tempInt; - toJ = everyK = -1; - } - else - { - MrBayesPrint ("%s Improperly formatted speciespartition\n", spacer); - { - for (i=0; i= 0) - if (AddToSet (fromI, toJ, everyK, whichPartition+1) == ERROR) - { - for (i=0; i numTaxa) - { - MrBayesPrint ("%s Too many speciespartitions (expecting maximum %d speciespartitions)\n", spacer, numTaxa); - for (i=0; i= 0 && toJ < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - } - else if (fromI >= 0 && toJ >= 0 && everyK < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - } - else if (fromI >= 0 && toJ >= 0 && everyK >= 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - } - - /* add name to taxaSetNames */ - if (AddString (&taxaSetNames, numTaxaSets, tempSetName) == ERROR) - { - MrBayesPrint ("%s Problem adding taxset %s to list\n", spacer, tempSetName); - return (ERROR); - } - - /* merge tempSet with taxaSet */ - AddBitfield (&taxaSet, numTaxaSets, tempSet, numTaxa); - - /* increment number of char sets */ - numTaxaSets++; - - /* show taxset (for debugging) */ -# if 0 - for (i=0; i 99) - { - MrBayesPrint ("%s Taxset name is too long\n", spacer); - return (ERROR); - } - - /* check to see if the name has already been used as a taxset */ - if (numTaxaSets > 0) - { - if (CheckString (taxaSetNames, numTaxaSets, tkn, &index) == ERROR) - { - /* if the taxset name has not been used, then we should have an ERROR returned */ - /* we _want_ to be here */ - - } - else - { - MrBayesPrint ("%s Taxset name has been used previously\n", spacer); - return (ERROR); - } - } - else if (numTaxaSets > 30) - { - MrBayesPrint ("%s You cannot define more than 30 taxsets\n", spacer); - return (ERROR); - } - - /* add the name to the taxa set */ - strcpy (tempSetName, tkn); - - /* clear tempSet */ - for (i=0; i numTaxa) - { - MrBayesPrint ("%s Taxon number %d is out of range (should be between %d and %d)\n", spacer, tempInt, 1, numTaxa); - return (ERROR); - } - } - tempInt--; - if (foundDash == YES) - { - if (fromI >= 0) - toJ = tempInt; - else - { - MrBayesPrint ("%s Improperly formatted taxset\n", spacer); - return (ERROR); - } - foundDash = NO; - } - else if (foundSlash == YES) - { - tempInt++; - if (tempInt <= 1) - { - MrBayesPrint ("%s Improperly formatted taxset\n", spacer); - return (ERROR); - } - if (fromI >= 0 && toJ >= 0 && fromI < toJ) - everyK = tempInt; - else - { - MrBayesPrint ("%s Improperly formatted taxset\n", spacer); - return (ERROR); - } - foundSlash = NO; - } - else - { - if (fromI >= 0 && toJ < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - fromI = tempInt; - } - else if (fromI < 0 && toJ < 0) - { - fromI = tempInt; - } - else if (fromI >= 0 && toJ >= 0 && everyK < 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - fromI = tempInt; - toJ = everyK = -1; - } - else if (fromI >= 0 && toJ >= 0 && everyK >= 0) - { - if (AddToSet (fromI, toJ, everyK, 1) == ERROR) - return (ERROR); - fromI = tempInt; - toJ = everyK = -1; - } - else - { - MrBayesPrint ("%s Improperly formatted taxset\n", spacer); - { - return (ERROR); - } - } - } - - expecting = Expecting(ALPHA); - expecting |= Expecting(NUMBER); - expecting |= Expecting(SEMICOLON); - expecting |= Expecting(DASH); - expecting |= Expecting(BACKSLASH); - } - else if (expecting == Expecting(DASH)) - { - foundDash = YES; - expecting = Expecting(NUMBER); - } - else if (expecting == Expecting(BACKSLASH)) - { - foundSlash = YES; - expecting = Expecting(NUMBER); - } - else - return (ERROR); - - return (NO_ERROR); -} - - -int DoTaxaStat (void) -{ - int i, j, maxLen, nameLen, nIncludedTaxa; - char tempName[100]; - - if (defMatrix == NO) - { - MrBayesPrint ("%s A character matrix must be defined first\n", spacer); - return (ERROR); - } - - /* find maximum length of taxon name */ - maxLen = nIncludedTaxa = 0; - for (i=0; i maxLen) - maxLen = (int) strlen(tempName); - if (taxaInfo[i].isDeleted == NO) - nIncludedTaxa++; - } - - MrBayesPrint ("%s Showing taxon status:\n\n", spacer); - if (nIncludedTaxa == numTaxa) - MrBayesPrint ("%s Number of taxa = %d (all of which are included)\n", spacer, numTaxa); - else - MrBayesPrint ("%s Number of taxa = %d (of which %d are included)\n", spacer, numTaxa, nIncludedTaxa); - MrBayesPrint ("%s Number of constraints = %d\n\n", spacer, numDefinedConstraints); - - if (numDefinedConstraints > 0) - { - for (j=0; j 0) - { - MrBayesPrint ("----"); - for (j=0; j%4d (%s) ", spacer, i+1, tempName); - else - MrBayesPrint ("%s %4d (%s) ", spacer, i+1, tempName); - for (j=0; j<(maxLen-nameLen); j++) - MrBayesPrint (" "); - MrBayesPrint (" -- "); - - if (taxaInfo[i].isDeleted == YES) - MrBayesPrint ("Deleted "); - else - MrBayesPrint ("Included"); - - MrBayesPrint (" "); - - for (j=0; j = [&R] ; - tree = [&U] ; - tree [&E CppEvents] = [&R] [&clockrate = 1.23] ((1:0.021[&E CppEvents 2: (0.10 1.11,0.83 3.17)],... - tree [&B TK02Brlens] = [&R] [&clockrate = 1.23] ((1:0.021[&B TK02Brlens 0.019],... - tree [&B IgrBrlens] = [&R] [&clockrate = 1.23] ((1:0.021[&B IgrBrlens 0.019],... - - Values will be stored in event sets that go with the tree and that are used to initialize the relaxed clock - parameters before a run is started. Note that several sets of events can be stored with each tree. - */ - - if (isTaxsetDef == NO) - { - MrBayesPrint ("%s Taxon labels must be specified before a tree could be red in\n", spacer); - return (ERROR); - } - if (inTreesBlock == NO) - { - MrBayesPrint ("%s You must be in a trees block to read a tree\n", spacer); - return (ERROR); - } - - if (expecting == Expecting(PARAMETER)) - { - /* this is the name of the tree */ - if (inSumtCommand==YES || inComparetreeCommand == YES) - { - /* we are reading in a tree to sumt or comparetree counters */ - t = sumtParams.tree; - ResetPolyTree (t); - } - else - { - /* we are reading in a user tree */ - /* check if the tree exists */ - treeIndex = 0; - for (i=0; iname) == 0) - break; - treeIndex = i; - if (treeIndex < numUserTrees) - { - MrBayesPrint ("%s Overwriting tree '%s'.\n", spacer, userTree[treeIndex]); - FreePolyTree (userTree[treeIndex]); - } - if ((userTree[treeIndex] = AllocatePolyTree (numTaxa)) == NULL) - return (ERROR); - t = userTree[treeIndex]; - } - strncpy (t->name, tkn, 99); - foundColon = foundAmpersand = foundEqual = foundComment = NO; - foundE = foundB = foundN = foundFirst = foundClockrate = foundName = NO; - eSetIndex = bSetIndex = eventIndex = 0; - nextAvailableNode = 0; - if (isTranslateDef == YES && isTranslateDiff == YES) - nextIntNodeIndex = numTranslates; - else - nextIntNodeIndex = numTaxa; - pp = &t->nodes[nextAvailableNode++]; - t->root = pp; - t->isRooted = NO; /* expect unrooted tree */ - t->isClock = NO; /* expect nonclock tree */ - t->isCalibrated = NO; /* expect uncalibrated tree */ - t->isRelaxed = NO; /* expect strict clock if clock tree */ - t->clockRate = 0.0; /* expect no clock rate */ - t->popSizeSet = NO; - readComment = YES; - expecting = Expecting(EQUALSIGN) | Expecting(LEFTCOMMENT); - lastExpecting = expecting; - } - else if (expecting == Expecting(EQUALSIGN)) - { - if (foundClockrate == YES) - expecting = Expecting(NUMBER); - else - { - for (i=0; i= 2*numTaxa) - { - MrBayesPrint ("%s Too many nodes on tree '%s'\n", spacer, t->name); - if (inSumtCommand == NO && inComparetreeCommand == NO) - FreePolyTree (userTree[treeIndex]); - return (ERROR); - } - qq = &t->nodes[nextAvailableNode++]; - qq->anc = pp; - pp->left = qq; - pp->index = nextIntNodeIndex++; - pp = qq; - expecting = Expecting(LEFTPAR); - expecting |= Expecting(ALPHA); - expecting |= Expecting(NUMBER); - expecting |= Expecting(LEFTCOMMENT); - lastExpecting = expecting; - } - } - else if (expecting == Expecting(ALPHA)) - { - if (foundAmpersand == YES) - { - if (strcmp(tkn,"E") == 0) - { - foundE = YES; - expecting = Expecting(ALPHA); - } - else if (strcmp(tkn,"B") == 0) - { - foundB = YES; - expecting = Expecting(ALPHA); - } - else if (strcmp(tkn,"N") == 0) - { - foundN = YES; - expecting = Expecting(ALPHA); - } - else if (strcmp(tkn, "R") == 0) - { - t->isRooted = YES; - t->isClock = YES; /* assume clock if rooted */ - expecting = Expecting(RIGHTCOMMENT); - } - else if (strcmp(tkn, "U") == 0) - { - t->isRooted = NO; - expecting = Expecting(RIGHTCOMMENT); - } - else if (strcmp(tkn, "clockrate") == 0) - { - t->isCalibrated = YES; - foundClockrate = YES; - expecting = Expecting(EQUALSIGN); - } - else - { - inComment = YES; - numComments++; - expecting = lastExpecting; - } - foundAmpersand = NO; - } - else if (foundName == YES && foundCurly == YES) - { - if (strcmp("all",tkn) == 0) - { - SafeStrcat (&tempNameString,tkn); - expecting = Expecting(RIGHTCURL); - } - else - { - MrBayesPrint ("%s Urecognized argument '%s'\n", spacer, tkn); - return (ERROR); - } - } - else if (foundE == YES) /* We have seen &E */ - { - if (foundEqual == NO) /* We have not seen name before and we are in header */ - { - t->nESets++; - t->isRelaxed = YES; - t->nEvents = (int **) SafeRealloc ((void *)t->nEvents, t->nESets*sizeof(int *)); - t->position = (MrBFlt ***) SafeRealloc ((void *)t->position, t->nESets*sizeof(MrBFlt **)); - t->rateMult = (MrBFlt ***) SafeRealloc ((void *)t->rateMult, t->nESets*sizeof(MrBFlt **)); - t->nEvents[t->nESets-1] = (int *) SafeCalloc ((size_t)(2*numTaxa), sizeof(int)); - t->position[t->nESets-1] = (MrBFlt **) SafeCalloc ((size_t)(2*numTaxa), sizeof(MrBFlt *)); - t->rateMult[t->nESets-1] = (MrBFlt **) SafeCalloc ((size_t)(2*numTaxa), sizeof(MrBFlt *)); - t->eSetName = (char **) SafeRealloc ((void *)t->eSetName, t->nESets*sizeof(char **)); - } - SafeStrcpy (&tempNameString,tkn); - foundName = YES; - expecting = Expecting(LEFTCURL); - if (foundEqual == YES) - expecting |= Expecting(NUMBER); - else - expecting |= Expecting(RIGHTCOMMENT); - } - else if (foundB == YES) - { - if (foundEqual == NO) - { - t->nBSets++; - t->isRelaxed = YES; - t->effectiveBrLen = (MrBFlt **) SafeRealloc ((void *)t->effectiveBrLen, (size_t)(t->nBSets*sizeof(MrBFlt *))); - t->effectiveBrLen[t->nBSets-1] = (MrBFlt *) SafeCalloc ((size_t)(2*numTaxa),sizeof(MrBFlt)); - for (i=0; i<2*numTaxa; i++) - t->effectiveBrLen[t->nBSets-1][i] = 1.0; - t->bSetName = (char **) SafeRealloc ((void *)t->bSetName, t->nBSets*sizeof(char **)); - t->bSetName[t->nBSets-1] = (char *) SafeCalloc (strlen(tkn)+1,sizeof(char)); - } - SafeStrcpy (&tempNameString,tkn); - foundName = YES; - expecting = Expecting(LEFTCURL); - if (foundEqual == YES) - expecting |= Expecting(NUMBER); - else - expecting |= Expecting(RIGHTCOMMENT); - } - else if (foundN == YES) - { - if (foundEqual == NO) - { - if (t->popSizeSet == YES) - { - MrBayesPrint ("%s Cannot hold more than one population size set\n", spacer); - if (inSumtCommand == NO && inComparetreeCommand == NO) - FreePolyTree (userTree[treeIndex]); - return (ERROR); - } - t->popSizeSet = YES; - if (isTranslateDef == YES && isTranslateDiff == YES) - t->popSize = (MrBFlt *) SafeCalloc (2*numTranslates, sizeof(MrBFlt)); - else - t->popSize = (MrBFlt *) SafeCalloc (2*numLocalTaxa, sizeof(MrBFlt)); - } - SafeStrcpy (&tempNameString,tkn); - foundName = YES; - expecting = Expecting(LEFTCURL); - if (foundEqual == YES) - expecting |= Expecting(NUMBER); - else - expecting |= Expecting(RIGHTCOMMENT); - } - else /* taxon name */ - { - if (isTranslateDef == YES) - { - /* we are using the translation table */ - if (CheckString (transTo, numTranslates, tkn, &index) == ERROR) - { - MrBayesPrint ("%s Could not find token '%s' in taxon translation table\n", spacer, tkn); - if (inSumtCommand == NO && inComparetreeCommand == NO) - FreePolyTree (userTree[treeIndex]); - return (ERROR); - } - strcpy (tempName, transFrom[index]); - if (isTranslateDiff == NO && CheckString (taxaNames, numTaxa, tempName, &index) == ERROR) - { - MrBayesPrint ("%s Could not find taxon '%s' in list of taxa\n", spacer, tkn); - if (inSumtCommand == NO && inComparetreeCommand == NO) - FreePolyTree (userTree[treeIndex]); - return (ERROR); - } - if (tempSet[index] == YES) - { - MrBayesPrint ("%s Taxon name '%s' already used in tree\n", spacer, tkn); - if (inSumtCommand == NO && inComparetreeCommand == NO) - FreePolyTree (userTree[treeIndex]); - return (ERROR); - } - tempSet[index] = YES; - strcpy (pp->label, tempName); - pp->index = index; - } - else - { - /* Check to see if the name is in the list of taxon names. */ - if (CheckString (taxaNames, numTaxa, tkn, &index) == ERROR) - { - MrBayesPrint ("%s Could not find taxon '%s' in list of taxa\n", spacer, tkn); - if (inSumtCommand == NO && inComparetreeCommand == NO) - FreePolyTree (userTree[treeIndex]); - return (ERROR); - } - if (tempSet[index] == YES) - { - MrBayesPrint ("%s Taxon name '%s' already used in tree\n", spacer, tkn); - if (inSumtCommand == NO && inComparetreeCommand == NO) - FreePolyTree (userTree[treeIndex]); - return (ERROR); - } - tempSet[index] = YES; - strcpy (pp->label, tkn); - pp->index = index; - } - expecting = Expecting(COMMA); - expecting |= Expecting(COLON); - expecting |= Expecting(RIGHTPAR); - } - } - else if (expecting == Expecting(RIGHTPAR)) - { - if (foundE == YES) - expecting = Expecting(RIGHTCOMMENT); - else - { - if (pp->anc == NULL) - { - MrBayesPrint ("%s Incorrect tree format: cannot go down\n", spacer);//, tkn - if (inSumtCommand == NO && inComparetreeCommand == NO) - FreePolyTree (userTree[treeIndex]); - return (ERROR); - } - if (pp->anc->left == pp) - { - MrBayesPrint ("%s Incorrect tree format: all nodes except tips should have more then one child. Either a single\n", spacer); - MrBayesPrint ("%s taxon is surrounded with brackets or there is a clade surrounded by double brackets.\n", spacer); - if (inSumtCommand == NO && inComparetreeCommand == NO) - FreePolyTree (userTree[treeIndex]); - return (ERROR); - } - pp = pp->anc; - if (pp->anc == NULL) - { - /* finish up tree */ - t->nNodes = nextAvailableNode; - t->nIntNodes = t->nNodes; - for (i=0; inNodes; i++) - { - if (t->nodes[i].left == NULL) - t->nIntNodes--; - } - GetPolyDownPass(t); - - /* check that number of taxa is correct */ - if (t->isRooted == NO && t->nNodes-t->nIntNodes == t->nIntNodes + 1) - t->isRooted = YES; - if ((t->isRooted == YES && t->nNodes-t->nIntNodes != t->nIntNodes + 1) || - (t->isRooted == NO && t->nNodes-t->nIntNodes != t->nIntNodes + 2)) - { - /* we are protected from adding too many taxa by taxon-matching code above */ - if (t->isRooted == YES && t->nNodes-t->nIntNodes == t->nIntNodes + 2) - { - MrBayesPrint ("%s The tree is declared as rooted (by comment [&R]) but\n", spacer); - MrBayesPrint ("%s the given tree has unrooted structure.\n", spacer); - } - else - MrBayesPrint ("%s Taxa missing in tree, or NOT a binary tree\n", spacer); - - return (ERROR); - } - - /* check other properties */ - if (t->isClock == YES && t->isRooted == NO) - { - MrBayesPrint ("%s Tree has clock rate but is not rooted\n", spacer); - return (ERROR); - /* Note: any deviation from an ultrametric tree must be assumed to be due to dated - tips at this point */ - } - if (t->isRelaxed == YES && t->isClock == NO) - { - MrBayesPrint ("%s Tree has relaxed clock rates but is not a clock tree\n", spacer); - return (ERROR); - } - if (inSumtCommand == NO && inComparetreeCommand == NO) - { - if (treeIndex == numUserTrees) - numUserTrees++; - MrBayesPrint ("%s Successfully read tree '%s'\n", spacer, userTree[treeIndex]->name); - } - if (t->popSize == NULL) - { - readComment = NO; - expecting = Expecting(SEMICOLON); - } - else - { - readComment = YES; - expecting = Expecting(LEFTCOMMENT); - lastExpecting = expecting; - } - } - else - { - expecting = Expecting(COMMA); - expecting |= Expecting(COLON); - expecting |= Expecting(RIGHTPAR); - } - } - } - else if (expecting == Expecting(COLON)) - { - foundColon = YES; - if (foundE == YES) - expecting = Expecting(LEFTPAR); - else - expecting = Expecting(NUMBER); - expecting |= Expecting(LEFTCOMMENT); - lastExpecting = expecting; - } - else if (expecting == Expecting(COMMA)) - { - if (foundName == YES) - { - SafeStrcat (&tempNameString,","); - expecting = Expecting(NUMBER); - } - else if (foundE == YES) - { - expecting = Expecting(NUMBER); - } - else - { - if (nextAvailableNode >= 2*numTaxa) - { - MrBayesPrint ("%s Too many nodes on tree '%s'\n", spacer, t->name); - if (inSumtCommand == NO && inComparetreeCommand == NO) - FreePolyTree (userTree[treeIndex]); - return (ERROR); - } - qq = &t->nodes[nextAvailableNode++]; - pp->sib = qq; - qq->anc = pp->anc; - pp = qq; - expecting = Expecting(LEFTPAR); - expecting |= Expecting(ALPHA); - expecting |= Expecting(NUMBER); - expecting |= Expecting(LEFTCOMMENT); - lastExpecting = expecting; - } - } - else if (expecting == Expecting(NUMBER)) - { - if (foundClockrate == YES) - { - sscanf (tkn, "%lf", &tempD); - t->clockRate = tempD; - foundClockrate = NO; - expecting = Expecting(RIGHTCOMMENT); - } - else if (foundName == YES && foundCurly == YES) - { - /* still assembling name of a param set */ - SafeStrcat (&tempNameString,tkn); - expecting = Expecting(RIGHTCURL) | Expecting(COMMA); - } - else if (foundN == YES) - { - /* we only know now that name is complete if it does not have curlies in it */ - foundName = NO; - - if (strcmp(tempNameString,t->popSizeSetName) != 0) - { - MrBayesPrint ("%s Could not find population size set '%s'\n", spacer, tempNameString); - if (inSumtCommand == NO && inComparetreeCommand == NO) - FreePolyTree (userTree[treeIndex]); - return (ERROR); - } - - sscanf (tkn, "%lf", &tempD); - t->popSize[pp->index] = tempD; - foundN = NO; - expecting = Expecting(RIGHTCOMMENT); - } - else if (foundB == YES) - { - /* we only know now that name is complete if it does not have curlies in it */ - foundName = NO; - - /* find the right effective branch length set */ - for (i=0; inBSets; i++) - if (strcmp(t->bSetName[i],tempNameString) == 0) - break; - if (i == t->nBSets) - { - MrBayesPrint ("%s Could not find effective branch length set '%s'\n", spacer, tempNameString); - if (inSumtCommand == NO && inComparetreeCommand == NO) - FreePolyTree (userTree[treeIndex]); - return (ERROR); - } - bSetIndex = i; - - sscanf (tkn, "%lf", &tempD); - t->effectiveBrLen[bSetIndex][pp->index] = tempD; - foundB = NO; - expecting = Expecting(RIGHTCOMMENT); - } - else if (foundE == YES) - { - if (foundColon == NO) - { - /* we only know now that name is complete if it does not have curlies in it */ - foundName = NO; - - /* find the right event set */ - for (i=0; inESets; i++) - if (strcmp(t->eSetName[i],tempNameString) == 0) - break; - if (i == t->nESets) - { - MrBayesPrint ("%s Could not find event set '%s'\n", spacer, tempNameString); - if (inSumtCommand == NO && inComparetreeCommand == NO) - FreePolyTree (userTree[treeIndex]); - return (ERROR); - } - eSetIndex = i; - - sscanf (tkn, "%d", &tempInt); - if (tempInt < 0) - { - MrBayesPrint ("%s Wrong number of events (%d) for event set '%s'\n", spacer, tempInt, t->eSetName[eSetIndex]); - if (inSumtCommand == NO && inComparetreeCommand == NO) - FreePolyTree (userTree[treeIndex]); - return (ERROR); - } - t->nEvents[eSetIndex][pp->index] = tempInt; - if (tempInt > 0) - { - t->position[eSetIndex][pp->index] = (MrBFlt *) SafeCalloc (tempInt, sizeof(MrBFlt)); - t->rateMult[eSetIndex][pp->index] = (MrBFlt *) SafeCalloc (tempInt, sizeof(MrBFlt)); - expecting = Expecting (COLON); - if (inSumtCommand == YES || inComparetreeCommand == YES) - expecting |= Expecting (RIGHTCOMMENT); /* we allow empty event specifications in sumt and comparetree */ - } - else - expecting = Expecting (RIGHTCOMMENT); - eventIndex = 0; - } - else if (foundFirst == NO) - { - /* processing the first number in the cpp event pair */ - sscanf (tkn, "%lf", &tempD); - t->position[eSetIndex][pp->index][eventIndex] = tempD; - expecting = Expecting(NUMBER); - foundFirst = YES; - } - else - { - /* processing the second number in the cpp event pair */ - foundFirst = NO; - sscanf (tkn, "%lf", &tempD); - t->rateMult[eSetIndex][pp->index][eventIndex] = tempD; - eventIndex++; - if (eventIndex == t->nEvents[eSetIndex][pp->index]) - { - expecting = Expecting(RIGHTPAR); - foundColon = NO; - } - else - expecting = Expecting(COMMA); - } - } - else if (foundColon == YES) - { - /* branch length */ - sscanf (tkn, "%lf", &tempD); - pp->length = tempD; - foundColon = NO; - t->brlensDef = YES; - expecting = Expecting(COMMA); - expecting |= Expecting(RIGHTPAR); - expecting |= Expecting(LEFTCOMMENT); - lastExpecting = expecting; - } - else /* taxon identifier */ - { - if (isTranslateDef == YES) - { - /* we are using the translation table */ - if (CheckString (transTo, numTranslates, tkn, &index) == ERROR) - { - MrBayesPrint ("%s Could not find token '%s' in taxon translation table\n", spacer, tkn); - if (inSumtCommand == NO && inComparetreeCommand == NO) - FreePolyTree (userTree[treeIndex]); - return (ERROR); - } - strcpy (tempName, transFrom[index]); - if (isTranslateDiff == NO && CheckString (taxaNames, numTaxa, tempName, &index) == ERROR) - { - MrBayesPrint ("%s Could not find taxon '%s' in list of taxa\n", spacer, tkn); - if (inSumtCommand == NO && inComparetreeCommand == NO) - FreePolyTree (userTree[treeIndex]); - return (ERROR); - } - if (tempSet[index] == YES) - { - MrBayesPrint ("%s Taxon name '%s' already used in tree\n", spacer, tkn); - if (inSumtCommand == NO && inComparetreeCommand == NO) - FreePolyTree (userTree[treeIndex]); - return (ERROR); - } - tempSet[index] = YES; - strcpy (pp->label, tempName); - pp->index = index; - } - else - { - /* Simply use taxon number; first check to see if the name is in the list of taxon names. */ - if (CheckString (taxaNames, numTaxa, tkn, &index) == ERROR) - { - /* The number could not be found as a taxon name in the list of taxon names. We will - assume that the user has then input taxa as numbers and not the names. */ - sscanf (tkn, "%d", &index); - if (index < 1 || index > numTaxa) - { - MrBayesPrint ("%s Taxon number %d is out of range\n", spacer, index); - if (inSumtCommand == NO && inComparetreeCommand == NO) - FreePolyTree (userTree[treeIndex]); - return (ERROR); - } - index--; - if (tempSet[index] == YES) - { - MrBayesPrint ("%s Taxon name %d has already been used in tree '%s'\n", spacer, index+1, t->name); - if (inSumtCommand == NO && inComparetreeCommand == NO) - FreePolyTree (userTree[treeIndex]); - return (ERROR); - } - } - else - { - /* The number is in the list of taxon names */ - if (index < 0 || index >= numTaxa) - { - MrBayesPrint ("%s Taxon name %s could not be found\n", spacer, tkn); - if (inSumtCommand == NO && inComparetreeCommand == NO) - FreePolyTree (userTree[treeIndex]); - return (ERROR); - } - if (tempSet[index] == YES) - { - MrBayesPrint ("%s Taxon %d has already been used in tree '%s'\n", spacer, index+1, t->name); - if (inSumtCommand == NO && inComparetreeCommand == NO) - FreePolyTree (userTree[treeIndex]); - return (ERROR); - } - } - tempSet[index] = YES; - strcpy (pp->label, taxaNames[index]); - pp->index = index; - } - expecting = Expecting(COMMA); - expecting |= Expecting(COLON); - expecting |= Expecting(RIGHTPAR); - expecting |= Expecting(LEFTCOMMENT); - lastExpecting = expecting; - } - } - else if (expecting == Expecting(LEFTCOMMENT)) - { - expecting = Expecting(AMPERSAND); - foundComment = YES; - } - else if (expecting == Expecting(RIGHTCOMMENT)) - { - if (foundEqual == NO) - { - /* We may have a complete name of a set of branch parameters, which needs to be recorded */ - if (foundName == YES) - { - if (foundE == YES) - { - t->eSetName[t->nESets-1] = (char *) SafeCalloc (strlen(tempNameString)+1,sizeof(char)); - strcat(t->eSetName[t->nESets-1],tempNameString); - } - else if (foundB == YES) - { - t->bSetName[t->nBSets-1] = (char *) SafeCalloc (strlen(tempNameString)+1,sizeof(char)); - strcat(t->bSetName[t->nBSets-1],tempNameString); - } - else if (foundN == YES) - { - t->popSizeSetName = (char *) SafeCalloc (strlen(tempNameString)+1,sizeof(char)); - strcpy(t->popSizeSetName,tempNameString); - } - foundName = NO; - } - expecting = Expecting(EQUALSIGN); - } - else - { - if (pp->anc == NULL) - { - if (pp->left == NULL) - expecting = Expecting(LEFTPAR); - else - expecting = Expecting(SEMICOLON); - } - else if (pp == pp->anc->left) - expecting = Expecting(COMMA); - else - expecting = Expecting(RIGHTPAR); - } - foundE = foundB = foundN = NO; - expecting |= Expecting(LEFTCOMMENT); - } - else if (expecting == Expecting(AMPERSAND)) - { - foundAmpersand = YES; - foundComment = NO; - expecting = Expecting (ALPHA); - } - else if (foundComment == YES) - { - numComments++; - foundComment = NO; - } - else if (expecting == Expecting(LEFTCURL)) - { - if (foundName == YES) - { - foundCurly=YES; - SafeStrcat (&tempNameString,"{"); - expecting = Expecting(NUMBER) | Expecting(ALPHA); - } - else - return(ERROR); - } - else if (expecting == Expecting(RIGHTCURL)) - { - if (foundName == YES) - { - SafeStrcat (&tempNameString,"}"); - foundCurly=NO; - if (foundEqual == NO) - { - /* We are processing a name of a set of branch params in the header of a tree. */ - expecting = Expecting(RIGHTCOMMENT); - } - else - { - /* We are processing a param value of a branch param set */ - expecting = Expecting(NUMBER); - } - } - else - return(ERROR); - } - - return (NO_ERROR); - MrBayesPrint ("%s", parmName); /* just because I am tired of seeing the unused parameter error msg */ -} - - -int DoUserTree (void) -{ - MrBayesPrint ("%s Usertree command deprecated. Define the tree in a treeblock and use 'Startvals' instead.\n", spacer); - return (ERROR); -} - - -int DoUserTreeParm (char *parmName, char *tkn) -{ - if (expecting == Expecting(EQUALSIGN)) - { - expecting = Expecting(LEFTPAR); - expecting |= Expecting(RIGHTPAR); - expecting |= Expecting(COLON); - expecting |= Expecting(NUMBER); - expecting |= Expecting(ALPHA); - expecting |= Expecting(SEMICOLON); - } - else if (expecting == Expecting(LEFTPAR)) - { - expecting = Expecting(LEFTPAR); - expecting |= Expecting(ALPHA); - expecting |= Expecting(NUMBER); - } - else if (expecting == Expecting(ALPHA)) - { - expecting = Expecting(COLON); - expecting |= Expecting(COMMA); - expecting |= Expecting(RIGHTPAR); - } - else if (expecting == Expecting(NUMBER)) - { - expecting = Expecting(COLON); - expecting |= Expecting(COMMA); - expecting |= Expecting(RIGHTPAR); - } - else if (expecting == Expecting(COLON)) - { - expecting = Expecting(NUMBER); - } - else if (expecting == Expecting(COMMA)) - { - expecting = Expecting(LEFTPAR); - expecting |= Expecting(ALPHA); - expecting |= Expecting(NUMBER); - } - else if (expecting == Expecting(RIGHTPAR)) - { - expecting = Expecting(RIGHTPAR); - expecting |= Expecting(COMMA); - expecting |= Expecting(COLON); - expecting |= Expecting(SEMICOLON); - } - else - return (ERROR); - - return (NO_ERROR); - MrBayesPrint ("%s", parmName); /* just because I am tired of seeing the unused parameter error msg */ - MrBayesPrint ("%s", tkn); -} - - -int DoVersion (void) -{ - MrBayesPrint (" --------------------------------------------------------------------------- \n"); - MrBayesPrint (" Version \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" MrBayes v%s \n", VERSION_NUMBER); - MrBayesPrint (" --------------------------------------------------------------------------- \n"); - - return (NO_ERROR); -} - - -BitsLong Expecting (int y) -{ - BitsLong x; - - x = (BitsLong) pow (2.0, (MrBFlt)y); - - return (x); -} - - -#ifdef HAVE_LIBREADLINE -/* This function is for commandline substitution: first word is always a command */ -char *command_generator(const char *text, int state) -{ - static int list_index, len; - char *command; - - if (state==0) - { - list_index=0; - len= (int) strlen(text); - } - while ((command=commands[list_index].string)!=NULL) - { - list_index++; - if (strncasecmp(command,text,len)==0) - /* memory is freed by the readline library so we need a strdup here */ - return strdup(command); - } - return (char *)NULL; -} -#endif - - -int FindValidCommand (char *tk, int *numMatches) -{ - int i, j, tkLen, targetLen, numDiff; - CmdType *p; - - p = commands + 0; - tkLen = (int) strlen(tk); - - (*numMatches) = 0; - for (i=0; istring); - if (tkLen <= targetLen) - { - for (j=0, numDiff=0; jstring[j])) - numDiff++; - } - if (numDiff == 0) - { - (*numMatches)++; - commandPtr = p; - if (tkLen == targetLen) - break; - } - } - p++; - } - - inValidCommand = NO; - if (*numMatches == 1) - { - inValidCommand = YES; - return (NO_ERROR); - } - else - return (ERROR); -} - - -int FindValidParam (char *tk, int *numMatches) -{ - int i, j, tkLen, targetLen, numDiff; - CmdType *p; - ParmInfoPtr q; - - if (commandPtr) - p = commandPtr; - else - { - MrBayesPrint ("%s Command pointer is NULL\n", spacer); - return (ERROR); - } - tkLen = (int) strlen(tk); - - *numMatches = 0; - for (i=0; inumParms; i++) - { - q = paramTable + (p->parmList[i]); - targetLen = (int) strlen(q->string); - /* printf ("%s %d (%s %d)\n", q->string, targetLen, tk, p->numParms); */ - if (!strcmp(q->string, "Xxxxxxxxxx")) - { - (*numMatches)++; - paramPtr = q; - } - else if (tkLen <= targetLen) - { - for (j=0, numDiff=0; jstring[j])) - numDiff++; - } - if (numDiff == 0) - { - (*numMatches)++; - paramPtr = q; - if (tkLen == targetLen) - break; - } - } - } - - if (*numMatches == 1) - return (NO_ERROR); - else - return (ERROR); -} - - -int FreeCharacters (void) -{ - int i, memoryLetFree; - - memoryLetFree = NO; - - if (memAllocs[ALLOC_TMPSET] == YES) - { - if (numChar > numTaxa) - tempSet = (int *) SafeRealloc ((void *) tempSet, (size_t)(numTaxa*sizeof(int))); - tempSetNeg = (int *) SafeRealloc ((void *) tempSetNeg, (size_t)(numTaxa*sizeof(int))); - } - if (memAllocs[ALLOC_MATRIX] == YES) - { - free (matrix); - matrix = NULL; - defMatrix = NO; - memAllocs[ALLOC_MATRIX] = NO; - memoryLetFree = YES; - } - if (memAllocs[ALLOC_CHARINFO] == YES) - { - free (charInfo); - charInfo = NULL; - memAllocs[ALLOC_CHARINFO] = NO; - memoryLetFree = YES; - } - if (memAllocs[ALLOC_CHARSETS] == YES) - { - for (i=0; i 0) - { - MrBayesPrint ("%s Deleting user trees\n", spacer); - for (i=0; i maxDiv) - maxDiv = partitionId[i][n]; - - divFound = (int *) SafeCalloc (maxDiv, sizeof(int)); - - for (i=0; i tempMax) - { - *tokenType = NOTHING; - token[20]='\0'; - MrBayesPrint ("%s Error while parsing a string. Token \"%s...[followed by at least %d more charectors]\" is too long.\n", spacer,token,tempMax-token-20); - MrBayesPrint ("%s Maximum allowed lenght of a token is %d\n", spacer,tempMax-token); - return (ERROR); - } - *temp++ = *(*sourceH)++; - } - *tokenType = ALPHA; - } - *temp = '\0'; - readWord = NO; - return (NO_ERROR);; - } - - *tokenType = UNKNOWN_TOKEN_TYPE; - if (IsIn(**sourceH,"=")) - { - *temp++ = *(*sourceH)++; - *tokenType = EQUALSIGN; - } - else if (IsIn(**sourceH,";")) - { - *temp++ = *(*sourceH)++; - *tokenType = SEMICOLON; - } - else if (IsIn(**sourceH,":")) - { - *temp++ = *(*sourceH)++; - *tokenType = COLON; - } - else if (IsIn(**sourceH,",")) - { - *temp++ = *(*sourceH)++; - *tokenType = COMMA; - } - else if (IsIn(**sourceH,"#")) - { - *temp++ = *(*sourceH)++; - *tokenType = POUNDSIGN; - } - else if (IsIn(**sourceH,"(")) - { - *temp++ = *(*sourceH)++; - *tokenType = LEFTPAR; - } - else if (IsIn(**sourceH,")")) - { - *temp++ = *(*sourceH)++; - *tokenType = RIGHTPAR; - } - else if (IsIn(**sourceH,"{")) - { - *temp++ = *(*sourceH)++; - *tokenType = LEFTCURL; - } - else if (IsIn(**sourceH,"}")) - { - *temp++ = *(*sourceH)++; - *tokenType = RIGHTCURL; - } - else if (IsIn(**sourceH,"[")) - { - *temp++ = *(*sourceH)++; - *tokenType = LEFTCOMMENT; - } - else if (IsIn(**sourceH,"]")) - { - *temp++ = *(*sourceH)++; - *tokenType = RIGHTCOMMENT; - } - else if (IsIn(**sourceH,"?")) - { - *temp++ = *(*sourceH)++; - *tokenType = QUESTIONMARK; - } - else if (IsIn(**sourceH,"-")) - { - *temp++ = *(*sourceH)++; - *tokenType = DASH; - } - else if (IsIn(**sourceH,"$")) - { - *temp++ = *(*sourceH)++; - *tokenType = DOLLAR; - } - else if (IsIn(**sourceH,"\"") && readWord == YES) - { - (*sourceH)++; - while (**sourceH != '"' && **sourceH != '\0') - { - if (temp > tempMax) - { - *tokenType = NOTHING; - token[20]='\0'; - MrBayesPrint ("%s Error while parsing a string. Token \"%s...[followed by at least %d more charectors]\" is too long.\n", spacer,token,tempMax-token-20); - MrBayesPrint ("%s Maximum allowed lenght of a token is %d\n", spacer,tempMax-token); - return (ERROR); - } - *temp++ = *((*sourceH)++); - } - *temp='\0'; - *tokenType = ALPHA; - (*sourceH)++; - readWord = NO; - } - else if (IsIn(**sourceH,"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789.")) - { - if (IsIn(**sourceH,"0123456789.")) - allNumbers = TRUE; - else - allNumbers = FALSE; - foundExp = foundExpSign = FALSE; - *temp++ = *(*sourceH)++; - while (IsIn(**sourceH,"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789.-+")) - { - if (temp > tempMax) - { - *tokenType = NOTHING; - token[20]='\0'; - MrBayesPrint ("%s Error while parsing a string. Token \"%s...[followed by at least %d more charectors]\" is too long.\n", spacer,token,tempMax-token-20); - MrBayesPrint ("%s Maximum allowed lenght of a token is %d\n", spacer,tempMax-token); - return (ERROR); - } - if (allNumbers == TRUE && !IsIn((*sourceH)[-1],"Ee") && **sourceH=='-') - break; - else if (allNumbers == TRUE && IsIn(**sourceH,"Ee") && foundExp == NO) - foundExp = TRUE; - else if (allNumbers == TRUE && IsIn(**sourceH,"+-") && IsIn((*sourceH)[-1],"Ee")) - foundExpSign = TRUE; - else if (!IsIn(**sourceH,"0123456789.")) - allNumbers = FALSE; - *temp++ = *(*sourceH)++; - } - if (allNumbers == TRUE) - *tokenType = NUMBER; - else - *tokenType = ALPHA; - } - else if (IsIn(**sourceH,"*")) - { - *temp++ = *(*sourceH)++; - *tokenType = ASTERISK; - } - else if (IsIn(**sourceH,"/")) - { - *temp++ = *(*sourceH)++; - *tokenType = FORWARDSLASH; - } - else if (IsIn(**sourceH,"'\\'")) - { - *temp++ = *(*sourceH)++; - *tokenType = BACKSLASH; - } - else if (IsIn(**sourceH,"!")) - { - *temp++ = *(*sourceH)++; - *tokenType = EXCLAMATIONMARK; - } - else if (IsIn(**sourceH,"%")) - { - *temp++ = *(*sourceH)++; - *tokenType = PERCENT; - } - else if (IsIn(**sourceH,"\"")) - { - *temp++ = *(*sourceH)++; - *tokenType = QUOTATIONMARK; - } - else if (IsIn(**sourceH,"&")) - { - *temp++ = *(*sourceH)++; - *tokenType = AMPERSAND; - } - else if (IsIn(**sourceH,"~+^@|{}`><")) - { - *temp++ = *(*sourceH)++; - *tokenType = WEIRD; - } - - *temp = '\0'; - return (NO_ERROR); -} - - -int GetUserHelp (char *helpTkn) -{ - int i, j, k, tempInt; - char tempString[100]; - Model *mp; - - if (!strcmp(helpTkn, "Begin")) - { - MrBayesPrint (" --------------------------------------------------------------------------- \n"); - MrBayesPrint (" Begin \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" This command is used to format data or commands in the program. The correct \n"); - MrBayesPrint (" usage is \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" begin ; \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" The two valid uses of the \"begin\" command, then, are \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" begin data; \n"); - MrBayesPrint (" begin mrbayes; \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" The \"data\" specifier is used to specify the beginning of a data block; your \n"); - MrBayesPrint (" character data should follow. For example, the following is an example of \n"); - MrBayesPrint (" a data block for four taxa and ten DNA sites: \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" begin data; \n"); - MrBayesPrint (" dimensions ntax=4 nchar=10; \n"); - MrBayesPrint (" format datatype=dna; \n"); - MrBayesPrint (" matrix \n"); - MrBayesPrint (" taxon_1 AACGATTCGT \n"); - MrBayesPrint (" taxon_2 AAGGATTCCA \n"); - MrBayesPrint (" taxon_3 AACGACTCCT \n"); - MrBayesPrint (" taxon_4 AAGGATTCCT \n"); - MrBayesPrint (" ; \n"); - MrBayesPrint (" end; \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" The other commands -- dimensions, format, and matrix -- are discussed \n"); - MrBayesPrint (" in the appropriate help menu. The only thing to note here is that the \n"); - MrBayesPrint (" block begins with a \"begin data\" command. The \"mrbayes\" command is \n"); - MrBayesPrint (" used to enter commands specific to the MrBayes program into the file. \n"); - MrBayesPrint (" This allows you to automatically process commands on execution of the \n"); - MrBayesPrint (" program. The following is a simple mrbayes block: \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" begin mrbayes; \n"); - MrBayesPrint (" charset first = 1-10\\3; \n"); - MrBayesPrint (" charset second = 2-10\\3; \n"); - MrBayesPrint (" charset third = 3-10\\3; \n"); - MrBayesPrint (" end; \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" This mrbayes block sets off the three \"charset\" commands, used to \n"); - MrBayesPrint (" predefine some blocks of characters. The mrbayes block can be very useful. \n"); - MrBayesPrint (" For example, in this case, it would save you the time of typing the char- \n"); - MrBayesPrint (" acter sets each time you executed the file. Also, note that every \n"); - MrBayesPrint (" \"begin \" command ends with an \"end\". Finally, you can \n"); - MrBayesPrint (" have so-called foreign blocks in the file. An example of a foreign block \n"); - MrBayesPrint (" would be \"begin paup\". The program will simply skip this block. This is \n"); - MrBayesPrint (" useful because it means that you can use the same file for MrBayes, PAUP* \n"); - MrBayesPrint (" or MacClade (although it isn't clear why you would want to use those other \n"); - MrBayesPrint (" programs). \n"); - MrBayesPrint (" --------------------------------------------------------------------------- \n"); - } - else if (!strcmp(helpTkn, "End")) - { - MrBayesPrint (" --------------------------------------------------------------------------- \n"); - MrBayesPrint (" End \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" This command is used to terminate a data or mrbayes block. The correct \n"); - MrBayesPrint (" usage is \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" end; \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" For more information on this, check the help for the \"begin\" command. \n"); - MrBayesPrint (" --------------------------------------------------------------------------- \n"); - } - else if (!strcmp(helpTkn, "Endblock")) - { - MrBayesPrint (" --------------------------------------------------------------------------- \n"); - MrBayesPrint (" Endblock \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" This is an older, deprecated version of \"End\", see that command. \n"); - MrBayesPrint (" --------------------------------------------------------------------------- \n"); - } - else if (!strcmp(helpTkn, "Plot")) - { - MrBayesPrint (" --------------------------------------------------------------------------- \n"); - MrBayesPrint (" Plot \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" This command plots specified parameters in the .p file or one of the .p files \n"); - MrBayesPrint (" created during an MCMC analysis. An x-y graph of the parameter over the course\n"); - MrBayesPrint (" of the chain is created. The command can be useful for visually diagnosing \n"); - MrBayesPrint (" convergence for many of the parameters of the phylogenetic model. The para- \n"); - MrBayesPrint (" meter to be plotted is specified by the \"parameter\" option. Several para- \n"); - MrBayesPrint (" meters can be plotted at once by using the \"match\" option, which has a \n"); - MrBayesPrint (" default value of \"perfect\". For example, if you were to set \"parameter = pi\"\n"); - MrBayesPrint (" and \"match = consistentwith\", then all of the state frequency parameters \n"); - MrBayesPrint (" would be plotted. You can also set \"match=all\", in which case all of the \n"); - MrBayesPrint (" parameters are plotted. \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" Note that the \"Sump\" command provides a different set of convergence diag- \n"); - MrBayesPrint (" nostics tools that you may also want to explore. Unlike \"Plot\", \"Sump\" can\n"); - MrBayesPrint (" compare two or more parameter samples and will calculate convergence diagnos- \n"); - MrBayesPrint (" tics as wel as parameter summaries for the pooled sample. \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" Options: \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" Relburnin -- If this option is set to 'Yes', then a proportion of the \n"); - MrBayesPrint (" samples will be discarded as burnin when creating the plot. \n"); - MrBayesPrint (" The proportion to be discarded is set with Burninfrac (see \n"); - MrBayesPrint (" Burninfrac below). When the Relburnin option is set to 'No', \n"); - MrBayesPrint (" then a specific number of samples is discarded instead. This \n"); - MrBayesPrint (" number is set by Burnin (see below). Note that the burnin \n"); - MrBayesPrint (" setting is shared across the 'comparetree', 'sump' and 'sumt'\n"); - MrBayesPrint (" commands. \n"); - MrBayesPrint (" Burnin -- Determines the number of samples (not generations) that will \n"); - MrBayesPrint (" be discarded when summary statistics are calculated. The \n"); - MrBayesPrint (" value of this option is only relevant when Relburnin is set \n"); - MrBayesPrint (" to 'No'. \n"); - MrBayesPrint (" Burninfrac -- Determines the fraction of samples that will be discarded \n"); - MrBayesPrint (" when creating a plot. The value of this parameter is only \n"); - MrBayesPrint (" relevant when Relburnin is set to 'Yes'. Example: A value of \n"); - MrBayesPrint (" this option of 0.25 means that 25%% of the samples will be \n"); - MrBayesPrint (" discarded. \n"); - MrBayesPrint (" Filename -- The name of the file to plot. \n"); - MrBayesPrint (" Parameter -- Specification of parameters to be plotted. See above for \n"); - MrBayesPrint (" details. \n"); - MrBayesPrint (" Match -- Specifies how to match parameter names to the Parameter \n"); - MrBayesPrint (" specification. See above for details. \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" Current settings: \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" Parameter Options Current Setting \n"); - MrBayesPrint (" ------------------------------------------------------------ \n"); - MrBayesPrint (" Relburnin Yes/No %s \n", chainParams.relativeBurnin == YES ? "Yes" : "No"); - MrBayesPrint (" Burnin %d \n", chainParams.chainBurnIn); - MrBayesPrint (" Burninfrac %1.2lf \n", chainParams.burninFraction); - MrBayesPrint (" Filename %s \n", plotParams.plotFileName); - MrBayesPrint (" Parameter %s \n", plotParams.parameter); - MrBayesPrint (" Match Perfect/Consistentwith/All %s \n", plotParams.match); - MrBayesPrint (" \n"); - MrBayesPrint (" --------------------------------------------------------------------------- \n"); - } - else if (!strcmp(helpTkn, "Dimensions")) - { - MrBayesPrint (" --------------------------------------------------------------------------- \n"); - MrBayesPrint (" Dimensions \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" This command is used in a data block to define the number of taxa and \n"); - MrBayesPrint (" characters. The correct usage is \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" dimensions ntax= nchar= \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" The dimensions must be the first command in a data block. The following \n"); - MrBayesPrint (" provides an example of the proper use of this command: \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" begin data; \n"); - MrBayesPrint (" dimensions ntax=4 nchar=10; \n"); - MrBayesPrint (" format datatype=dna; \n"); - MrBayesPrint (" matrix \n"); - MrBayesPrint (" taxon_1 AACGATTCGT \n"); - MrBayesPrint (" taxon_2 AAGGATTCCA \n"); - MrBayesPrint (" taxon_3 AACGACTCCT \n"); - MrBayesPrint (" taxon_4 AAGGATTCCT \n"); - MrBayesPrint (" ; \n"); - MrBayesPrint (" end; \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" Here, the dimensions command tells MrBayes to expect a matrix with four \n"); - MrBayesPrint (" taxa and 10 characters. \n"); - MrBayesPrint (" --------------------------------------------------------------------------- \n"); - } - else if (!strcmp(helpTkn, "Format")) - { - MrBayesPrint (" --------------------------------------------------------------------------- \n"); - MrBayesPrint (" Format \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" This command is used in a data block to define the format of the char- \n"); - MrBayesPrint (" acter matrix. The correct usage is \n"); - MrBayesPrint (" \n"); - MrBayesPrint (" format datatype= ... =