File:  [Local Repository] / imach / src / imach.c
Revision 1.138: download - view: text, annotated - select for diffs
Fri Apr 30 18:19:40 2010 UTC (14 years, 1 month ago) by brouard
Branches: MAIN
CVS tags: HEAD
*** empty log message ***

    1: /* $Id: imach.c,v 1.138 2010/04/30 18:19:40 brouard Exp $
    2:   $State: Exp $
    3:   $Log: imach.c,v $
    4:   Revision 1.138  2010/04/30 18:19:40  brouard
    5:   *** empty log message ***
    6: 
    7:   Revision 1.137  2010/04/29 18:11:38  brouard
    8:   (Module): Checking covariates for more complex models
    9:   than V1+V2. A lot of change to be done. Unstable.
   10: 
   11:   Revision 1.136  2010/04/26 20:30:53  brouard
   12:   (Module): merging some libgsl code. Fixing computation
   13:   of likelione (using inter/intrapolation if mle = 0) in order to
   14:   get same likelihood as if mle=1.
   15:   Some cleaning of code and comments added.
   16: 
   17:   Revision 1.135  2009/10/29 15:33:14  brouard
   18:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
   19: 
   20:   Revision 1.134  2009/10/29 13:18:53  brouard
   21:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
   22: 
   23:   Revision 1.133  2009/07/06 10:21:25  brouard
   24:   just nforces
   25: 
   26:   Revision 1.132  2009/07/06 08:22:05  brouard
   27:   Many tings
   28: 
   29:   Revision 1.131  2009/06/20 16:22:47  brouard
   30:   Some dimensions resccaled
   31: 
   32:   Revision 1.130  2009/05/26 06:44:34  brouard
   33:   (Module): Max Covariate is now set to 20 instead of 8. A
   34:   lot of cleaning with variables initialized to 0. Trying to make
   35:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
   36: 
   37:   Revision 1.129  2007/08/31 13:49:27  lievre
   38:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
   39: 
   40:   Revision 1.128  2006/06/30 13:02:05  brouard
   41:   (Module): Clarifications on computing e.j
   42: 
   43:   Revision 1.127  2006/04/28 18:11:50  brouard
   44:   (Module): Yes the sum of survivors was wrong since
   45:   imach-114 because nhstepm was no more computed in the age
   46:   loop. Now we define nhstepma in the age loop.
   47:   (Module): In order to speed up (in case of numerous covariates) we
   48:   compute health expectancies (without variances) in a first step
   49:   and then all the health expectancies with variances or standard
   50:   deviation (needs data from the Hessian matrices) which slows the
   51:   computation.
   52:   In the future we should be able to stop the program is only health
   53:   expectancies and graph are needed without standard deviations.
   54: 
   55:   Revision 1.126  2006/04/28 17:23:28  brouard
   56:   (Module): Yes the sum of survivors was wrong since
   57:   imach-114 because nhstepm was no more computed in the age
   58:   loop. Now we define nhstepma in the age loop.
   59:   Version 0.98h
   60: 
   61:   Revision 1.125  2006/04/04 15:20:31  lievre
   62:   Errors in calculation of health expectancies. Age was not initialized.
   63:   Forecasting file added.
   64: 
   65:   Revision 1.124  2006/03/22 17:13:53  lievre
   66:   Parameters are printed with %lf instead of %f (more numbers after the comma).
   67:   The log-likelihood is printed in the log file
   68: 
   69:   Revision 1.123  2006/03/20 10:52:43  brouard
   70:   * imach.c (Module): <title> changed, corresponds to .htm file
   71:   name. <head> headers where missing.
   72: 
   73:   * imach.c (Module): Weights can have a decimal point as for
   74:   English (a comma might work with a correct LC_NUMERIC environment,
   75:   otherwise the weight is truncated).
   76:   Modification of warning when the covariates values are not 0 or
   77:   1.
   78:   Version 0.98g
   79: 
   80:   Revision 1.122  2006/03/20 09:45:41  brouard
   81:   (Module): Weights can have a decimal point as for
   82:   English (a comma might work with a correct LC_NUMERIC environment,
   83:   otherwise the weight is truncated).
   84:   Modification of warning when the covariates values are not 0 or
   85:   1.
   86:   Version 0.98g
   87: 
   88:   Revision 1.121  2006/03/16 17:45:01  lievre
   89:   * imach.c (Module): Comments concerning covariates added
   90: 
   91:   * imach.c (Module): refinements in the computation of lli if
   92:   status=-2 in order to have more reliable computation if stepm is
   93:   not 1 month. Version 0.98f
   94: 
   95:   Revision 1.120  2006/03/16 15:10:38  lievre
   96:   (Module): refinements in the computation of lli if
   97:   status=-2 in order to have more reliable computation if stepm is
   98:   not 1 month. Version 0.98f
   99: 
  100:   Revision 1.119  2006/03/15 17:42:26  brouard
  101:   (Module): Bug if status = -2, the loglikelihood was
  102:   computed as likelihood omitting the logarithm. Version O.98e
  103: 
  104:   Revision 1.118  2006/03/14 18:20:07  brouard
  105:   (Module): varevsij Comments added explaining the second
  106:   table of variances if popbased=1 .
  107:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  108:   (Module): Function pstamp added
  109:   (Module): Version 0.98d
  110: 
  111:   Revision 1.117  2006/03/14 17:16:22  brouard
  112:   (Module): varevsij Comments added explaining the second
  113:   table of variances if popbased=1 .
  114:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  115:   (Module): Function pstamp added
  116:   (Module): Version 0.98d
  117: 
  118:   Revision 1.116  2006/03/06 10:29:27  brouard
  119:   (Module): Variance-covariance wrong links and
  120:   varian-covariance of ej. is needed (Saito).
  121: 
  122:   Revision 1.115  2006/02/27 12:17:45  brouard
  123:   (Module): One freematrix added in mlikeli! 0.98c
  124: 
  125:   Revision 1.114  2006/02/26 12:57:58  brouard
  126:   (Module): Some improvements in processing parameter
  127:   filename with strsep.
  128: 
  129:   Revision 1.113  2006/02/24 14:20:24  brouard
  130:   (Module): Memory leaks checks with valgrind and:
  131:   datafile was not closed, some imatrix were not freed and on matrix
  132:   allocation too.
  133: 
  134:   Revision 1.112  2006/01/30 09:55:26  brouard
  135:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
  136: 
  137:   Revision 1.111  2006/01/25 20:38:18  brouard
  138:   (Module): Lots of cleaning and bugs added (Gompertz)
  139:   (Module): Comments can be added in data file. Missing date values
  140:   can be a simple dot '.'.
  141: 
  142:   Revision 1.110  2006/01/25 00:51:50  brouard
  143:   (Module): Lots of cleaning and bugs added (Gompertz)
  144: 
  145:   Revision 1.109  2006/01/24 19:37:15  brouard
  146:   (Module): Comments (lines starting with a #) are allowed in data.
  147: 
  148:   Revision 1.108  2006/01/19 18:05:42  lievre
  149:   Gnuplot problem appeared...
  150:   To be fixed
  151: 
  152:   Revision 1.107  2006/01/19 16:20:37  brouard
  153:   Test existence of gnuplot in imach path
  154: 
  155:   Revision 1.106  2006/01/19 13:24:36  brouard
  156:   Some cleaning and links added in html output
  157: 
  158:   Revision 1.105  2006/01/05 20:23:19  lievre
  159:   *** empty log message ***
  160: 
  161:   Revision 1.104  2005/09/30 16:11:43  lievre
  162:   (Module): sump fixed, loop imx fixed, and simplifications.
  163:   (Module): If the status is missing at the last wave but we know
  164:   that the person is alive, then we can code his/her status as -2
  165:   (instead of missing=-1 in earlier versions) and his/her
  166:   contributions to the likelihood is 1 - Prob of dying from last
  167:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
  168:   the healthy state at last known wave). Version is 0.98
  169: 
  170:   Revision 1.103  2005/09/30 15:54:49  lievre
  171:   (Module): sump fixed, loop imx fixed, and simplifications.
  172: 
  173:   Revision 1.102  2004/09/15 17:31:30  brouard
  174:   Add the possibility to read data file including tab characters.
  175: 
  176:   Revision 1.101  2004/09/15 10:38:38  brouard
  177:   Fix on curr_time
  178: 
  179:   Revision 1.100  2004/07/12 18:29:06  brouard
  180:   Add version for Mac OS X. Just define UNIX in Makefile
  181: 
  182:   Revision 1.99  2004/06/05 08:57:40  brouard
  183:   *** empty log message ***
  184: 
  185:   Revision 1.98  2004/05/16 15:05:56  brouard
  186:   New version 0.97 . First attempt to estimate force of mortality
  187:   directly from the data i.e. without the need of knowing the health
  188:   state at each age, but using a Gompertz model: log u =a + b*age .
  189:   This is the basic analysis of mortality and should be done before any
  190:   other analysis, in order to test if the mortality estimated from the
  191:   cross-longitudinal survey is different from the mortality estimated
  192:   from other sources like vital statistic data.
  193: 
  194:   The same imach parameter file can be used but the option for mle should be -3.
  195: 
  196:   Agnès, who wrote this part of the code, tried to keep most of the
  197:   former routines in order to include the new code within the former code.
  198: 
  199:   The output is very simple: only an estimate of the intercept and of
  200:   the slope with 95% confident intervals.
  201: 
  202:   Current limitations:
  203:   A) Even if you enter covariates, i.e. with the
  204:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
  205:   B) There is no computation of Life Expectancy nor Life Table.
  206: 
  207:   Revision 1.97  2004/02/20 13:25:42  lievre
  208:   Version 0.96d. Population forecasting command line is (temporarily)
  209:   suppressed.
  210: 
  211:   Revision 1.96  2003/07/15 15:38:55  brouard
  212:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
  213:   rewritten within the same printf. Workaround: many printfs.
  214: 
  215:   Revision 1.95  2003/07/08 07:54:34  brouard
  216:   * imach.c (Repository):
  217:   (Repository): Using imachwizard code to output a more meaningful covariance
  218:   matrix (cov(a12,c31) instead of numbers.
  219: 
  220:   Revision 1.94  2003/06/27 13:00:02  brouard
  221:   Just cleaning
  222: 
  223:   Revision 1.93  2003/06/25 16:33:55  brouard
  224:   (Module): On windows (cygwin) function asctime_r doesn't
  225:   exist so I changed back to asctime which exists.
  226:   (Module): Version 0.96b
  227: 
  228:   Revision 1.92  2003/06/25 16:30:45  brouard
  229:   (Module): On windows (cygwin) function asctime_r doesn't
  230:   exist so I changed back to asctime which exists.
  231: 
  232:   Revision 1.91  2003/06/25 15:30:29  brouard
  233:   * imach.c (Repository): Duplicated warning errors corrected.
  234:   (Repository): Elapsed time after each iteration is now output. It
  235:   helps to forecast when convergence will be reached. Elapsed time
  236:   is stamped in powell.  We created a new html file for the graphs
  237:   concerning matrix of covariance. It has extension -cov.htm.
  238: 
  239:   Revision 1.90  2003/06/24 12:34:15  brouard
  240:   (Module): Some bugs corrected for windows. Also, when
  241:   mle=-1 a template is output in file "or"mypar.txt with the design
  242:   of the covariance matrix to be input.
  243: 
  244:   Revision 1.89  2003/06/24 12:30:52  brouard
  245:   (Module): Some bugs corrected for windows. Also, when
  246:   mle=-1 a template is output in file "or"mypar.txt with the design
  247:   of the covariance matrix to be input.
  248: 
  249:   Revision 1.88  2003/06/23 17:54:56  brouard
  250:   * imach.c (Repository): Create a sub-directory where all the secondary files are. Only imach, htm, gp and r(imach) are on the main directory. Correct time and other things.
  251: 
  252:   Revision 1.87  2003/06/18 12:26:01  brouard
  253:   Version 0.96
  254: 
  255:   Revision 1.86  2003/06/17 20:04:08  brouard
  256:   (Module): Change position of html and gnuplot routines and added
  257:   routine fileappend.
  258: 
  259:   Revision 1.85  2003/06/17 13:12:43  brouard
  260:   * imach.c (Repository): Check when date of death was earlier that
  261:   current date of interview. It may happen when the death was just
  262:   prior to the death. In this case, dh was negative and likelihood
  263:   was wrong (infinity). We still send an "Error" but patch by
  264:   assuming that the date of death was just one stepm after the
  265:   interview.
  266:   (Repository): Because some people have very long ID (first column)
  267:   we changed int to long in num[] and we added a new lvector for
  268:   memory allocation. But we also truncated to 8 characters (left
  269:   truncation)
  270:   (Repository): No more line truncation errors.
  271: 
  272:   Revision 1.84  2003/06/13 21:44:43  brouard
  273:   * imach.c (Repository): Replace "freqsummary" at a correct
  274:   place. It differs from routine "prevalence" which may be called
  275:   many times. Probs is memory consuming and must be used with
  276:   parcimony.
  277:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
  278: 
  279:   Revision 1.83  2003/06/10 13:39:11  lievre
  280:   *** empty log message ***
  281: 
  282:   Revision 1.82  2003/06/05 15:57:20  brouard
  283:   Add log in  imach.c and  fullversion number is now printed.
  284: 
  285: */
  286: /*
  287:    Interpolated Markov Chain
  288: 
  289:   Short summary of the programme:
  290:   
  291:   This program computes Healthy Life Expectancies from
  292:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
  293:   first survey ("cross") where individuals from different ages are
  294:   interviewed on their health status or degree of disability (in the
  295:   case of a health survey which is our main interest) -2- at least a
  296:   second wave of interviews ("longitudinal") which measure each change
  297:   (if any) in individual health status.  Health expectancies are
  298:   computed from the time spent in each health state according to a
  299:   model. More health states you consider, more time is necessary to reach the
  300:   Maximum Likelihood of the parameters involved in the model.  The
  301:   simplest model is the multinomial logistic model where pij is the
  302:   probability to be observed in state j at the second wave
  303:   conditional to be observed in state i at the first wave. Therefore
  304:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
  305:   'age' is age and 'sex' is a covariate. If you want to have a more
  306:   complex model than "constant and age", you should modify the program
  307:   where the markup *Covariates have to be included here again* invites
  308:   you to do it.  More covariates you add, slower the
  309:   convergence.
  310: 
  311:   The advantage of this computer programme, compared to a simple
  312:   multinomial logistic model, is clear when the delay between waves is not
  313:   identical for each individual. Also, if a individual missed an
  314:   intermediate interview, the information is lost, but taken into
  315:   account using an interpolation or extrapolation.  
  316: 
  317:   hPijx is the probability to be observed in state i at age x+h
  318:   conditional to the observed state i at age x. The delay 'h' can be
  319:   split into an exact number (nh*stepm) of unobserved intermediate
  320:   states. This elementary transition (by month, quarter,
  321:   semester or year) is modelled as a multinomial logistic.  The hPx
  322:   matrix is simply the matrix product of nh*stepm elementary matrices
  323:   and the contribution of each individual to the likelihood is simply
  324:   hPijx.
  325: 
  326:   Also this programme outputs the covariance matrix of the parameters but also
  327:   of the life expectancies. It also computes the period (stable) prevalence. 
  328:   
  329:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
  330:            Institut national d'études démographiques, Paris.
  331:   This software have been partly granted by Euro-REVES, a concerted action
  332:   from the European Union.
  333:   It is copyrighted identically to a GNU software product, ie programme and
  334:   software can be distributed freely for non commercial use. Latest version
  335:   can be accessed at http://euroreves.ined.fr/imach .
  336: 
  337:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
  338:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
  339:   
  340:   **********************************************************************/
  341: /*
  342:   main
  343:   read parameterfile
  344:   read datafile
  345:   concatwav
  346:   freqsummary
  347:   if (mle >= 1)
  348:     mlikeli
  349:   print results files
  350:   if mle==1 
  351:      computes hessian
  352:   read end of parameter file: agemin, agemax, bage, fage, estepm
  353:       begin-prev-date,...
  354:   open gnuplot file
  355:   open html file
  356:   period (stable) prevalence
  357:    for age prevalim()
  358:   h Pij x
  359:   variance of p varprob
  360:   forecasting if prevfcast==1 prevforecast call prevalence()
  361:   health expectancies
  362:   Variance-covariance of DFLE
  363:   prevalence()
  364:    movingaverage()
  365:   varevsij() 
  366:   if popbased==1 varevsij(,popbased)
  367:   total life expectancies
  368:   Variance of period (stable) prevalence
  369:  end
  370: */
  371: 
  372: 
  373: 
  374:  
  375: #include <math.h>
  376: #include <stdio.h>
  377: #include <stdlib.h>
  378: #include <string.h>
  379: #include <unistd.h>
  380: 
  381: #include <limits.h>
  382: #include <sys/types.h>
  383: #include <sys/stat.h>
  384: #include <errno.h>
  385: extern int errno;
  386: 
  387: /* #include <sys/time.h> */
  388: #include <time.h>
  389: #include "timeval.h"
  390: 
  391: #ifdef GSL
  392: #include <gsl/gsl_errno.h>
  393: #include <gsl/gsl_multimin.h>
  394: #endif
  395: 
  396: /* #include <libintl.h> */
  397: /* #define _(String) gettext (String) */
  398: 
  399: #define MAXLINE 256
  400: 
  401: #define GNUPLOTPROGRAM "gnuplot"
  402: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
  403: #define FILENAMELENGTH 132
  404: 
  405: #define	GLOCK_ERROR_NOPATH		-1	/* empty path */
  406: #define	GLOCK_ERROR_GETCWD		-2	/* cannot get cwd */
  407: 
  408: #define MAXPARM 128 /* Maximum number of parameters for the optimization */
  409: #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncovmodel */
  410: 
  411: #define NINTERVMAX 8
  412: #define NLSTATEMAX 8 /* Maximum number of live states (for func) */
  413: #define NDEATHMAX 8 /* Maximum number of dead states (for func) */
  414: #define NCOVMAX 20 /* Maximum number of covariates */
  415: #define MAXN 20000
  416: #define YEARM 12. /* Number of months per year */
  417: #define AGESUP 130
  418: #define AGEBASE 40
  419: #define AGEGOMP 10. /* Minimal age for Gompertz adjustment */
  420: #ifdef UNIX
  421: #define DIRSEPARATOR '/'
  422: #define CHARSEPARATOR "/"
  423: #define ODIRSEPARATOR '\\'
  424: #else
  425: #define DIRSEPARATOR '\\'
  426: #define CHARSEPARATOR "\\"
  427: #define ODIRSEPARATOR '/'
  428: #endif
  429: 
  430: /* $Id: imach.c,v 1.138 2010/04/30 18:19:40 brouard Exp $ */
  431: /* $State: Exp $ */
  432: 
  433: char version[]="Imach version 0.98m, April 2010, INED-EUROREVES-Institut de longevite ";
  434: char fullversion[]="$Revision: 1.138 $ $Date: 2010/04/30 18:19:40 $"; 
  435: char strstart[80];
  436: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
  437: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
  438: int nvar=0, nforce=0; /* Number of variables, number of forces */
  439: int cptcovn=0, cptcovage=0, cptcoveff=0,cptcov=0; /* Number of covariates, of covariates with '*age' */
  440: int npar=NPARMAX;
  441: int nlstate=2; /* Number of live states */
  442: int ndeath=1; /* Number of dead states */
  443: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
  444: int popbased=0;
  445: 
  446: int *wav; /* Number of waves for this individuual 0 is possible */
  447: int maxwav=0; /* Maxim number of waves */
  448: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
  449: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
  450: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
  451: 		   to the likelihood and the sum of weights (done by funcone)*/
  452: int mle=1, weightopt=0;
  453: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
  454: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
  455: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
  456: 	   * wave mi and wave mi+1 is not an exact multiple of stepm. */
  457: double jmean=1; /* Mean space between 2 waves */
  458: double **oldm, **newm, **savm; /* Working pointers to matrices */
  459: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
  460: /*FILE *fic ; */ /* Used in readdata only */
  461: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
  462: FILE *ficlog, *ficrespow;
  463: int globpr=0; /* Global variable for printing or not */
  464: double fretone; /* Only one call to likelihood */
  465: long ipmx=0; /* Number of contributions */
  466: double sw; /* Sum of weights */
  467: char filerespow[FILENAMELENGTH];
  468: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
  469: FILE *ficresilk;
  470: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
  471: FILE *ficresprobmorprev;
  472: FILE *fichtm, *fichtmcov; /* Html File */
  473: FILE *ficreseij;
  474: char filerese[FILENAMELENGTH];
  475: FILE *ficresstdeij;
  476: char fileresstde[FILENAMELENGTH];
  477: FILE *ficrescveij;
  478: char filerescve[FILENAMELENGTH];
  479: FILE  *ficresvij;
  480: char fileresv[FILENAMELENGTH];
  481: FILE  *ficresvpl;
  482: char fileresvpl[FILENAMELENGTH];
  483: char title[MAXLINE];
  484: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
  485: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
  486: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
  487: char command[FILENAMELENGTH];
  488: int  outcmd=0;
  489: 
  490: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
  491: 
  492: char filelog[FILENAMELENGTH]; /* Log file */
  493: char filerest[FILENAMELENGTH];
  494: char fileregp[FILENAMELENGTH];
  495: char popfile[FILENAMELENGTH];
  496: 
  497: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
  498: 
  499: struct timeval start_time, end_time, curr_time, last_time, forecast_time;
  500: struct timezone tzp;
  501: extern int gettimeofday();
  502: struct tm tmg, tm, tmf, *gmtime(), *localtime();
  503: long time_value;
  504: extern long time();
  505: char strcurr[80], strfor[80];
  506: 
  507: char *endptr;
  508: long lval;
  509: double dval;
  510: 
  511: #define NR_END 1
  512: #define FREE_ARG char*
  513: #define FTOL 1.0e-10
  514: 
  515: #define NRANSI 
  516: #define ITMAX 200 
  517: 
  518: #define TOL 2.0e-4 
  519: 
  520: #define CGOLD 0.3819660 
  521: #define ZEPS 1.0e-10 
  522: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
  523: 
  524: #define GOLD 1.618034 
  525: #define GLIMIT 100.0 
  526: #define TINY 1.0e-20 
  527: 
  528: static double maxarg1,maxarg2;
  529: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
  530: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
  531:   
  532: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
  533: #define rint(a) floor(a+0.5)
  534: 
  535: static double sqrarg;
  536: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
  537: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
  538: int agegomp= AGEGOMP;
  539: 
  540: int imx; 
  541: int stepm=1;
  542: /* Stepm, step in month: minimum step interpolation*/
  543: 
  544: int estepm;
  545: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
  546: 
  547: int m,nb;
  548: long *num;
  549: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
  550: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
  551: double **pmmij, ***probs;
  552: double *ageexmed,*agecens;
  553: double dateintmean=0;
  554: 
  555: double *weight;
  556: int **s; /* Status */
  557: double *agedc, **covar, idx;
  558: int **nbcode, *Tvar, **codtab, **Tvard, *Tprod, cptcovprod, *Tvaraff;
  559: double *lsurv, *lpop, *tpop;
  560: 
  561: double ftol=FTOL; /* Tolerance for computing Max Likelihood */
  562: double ftolhess; /* Tolerance for computing hessian */
  563: 
  564: /**************** split *************************/
  565: static	int split( char *path, char *dirc, char *name, char *ext, char *finame )
  566: {
  567:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
  568:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
  569:   */ 
  570:   char	*ss;				/* pointer */
  571:   int	l1, l2;				/* length counters */
  572: 
  573:   l1 = strlen(path );			/* length of path */
  574:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
  575:   ss= strrchr( path, DIRSEPARATOR );		/* find last / */
  576:   if ( ss == NULL ) {			/* no directory, so determine current directory */
  577:     strcpy( name, path );		/* we got the fullname name because no directory */
  578:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
  579:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
  580:     /* get current working directory */
  581:     /*    extern  char* getcwd ( char *buf , int len);*/
  582:     if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
  583:       return( GLOCK_ERROR_GETCWD );
  584:     }
  585:     /* got dirc from getcwd*/
  586:     printf(" DIRC = %s \n",dirc);
  587:   } else {				/* strip direcotry from path */
  588:     ss++;				/* after this, the filename */
  589:     l2 = strlen( ss );			/* length of filename */
  590:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
  591:     strcpy( name, ss );		/* save file name */
  592:     strncpy( dirc, path, l1 - l2 );	/* now the directory */
  593:     dirc[l1-l2] = 0;			/* add zero */
  594:     printf(" DIRC2 = %s \n",dirc);
  595:   }
  596:   /* We add a separator at the end of dirc if not exists */
  597:   l1 = strlen( dirc );			/* length of directory */
  598:   if( dirc[l1-1] != DIRSEPARATOR ){
  599:     dirc[l1] =  DIRSEPARATOR;
  600:     dirc[l1+1] = 0; 
  601:     printf(" DIRC3 = %s \n",dirc);
  602:   }
  603:   ss = strrchr( name, '.' );		/* find last / */
  604:   if (ss >0){
  605:     ss++;
  606:     strcpy(ext,ss);			/* save extension */
  607:     l1= strlen( name);
  608:     l2= strlen(ss)+1;
  609:     strncpy( finame, name, l1-l2);
  610:     finame[l1-l2]= 0;
  611:   }
  612: 
  613:   return( 0 );				/* we're done */
  614: }
  615: 
  616: 
  617: /******************************************/
  618: 
  619: void replace_back_to_slash(char *s, char*t)
  620: {
  621:   int i;
  622:   int lg=0;
  623:   i=0;
  624:   lg=strlen(t);
  625:   for(i=0; i<= lg; i++) {
  626:     (s[i] = t[i]);
  627:     if (t[i]== '\\') s[i]='/';
  628:   }
  629: }
  630: 
  631: char *trimbb(char *out, char *in)
  632: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
  633:   char *s;
  634:   s=out;
  635:   while (*in != '\0'){
  636:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
  637:       in++;
  638:     }
  639:     *out++ = *in++;
  640:   }
  641:   *out='\0';
  642:   return s;
  643: }
  644: 
  645: char *cutv(char *blocc, char *alocc, char *in, char occ)
  646: {
  647:   /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ' 
  648:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
  649:      gives blocc="abcdef2ghi" and alocc="j".
  650:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
  651:   */
  652:   char *s, *t;
  653:   t=in;s=in;
  654:   while (*in != '\0'){
  655:     while( *in == occ){
  656:       *blocc++ = *in++;
  657:       s=in;
  658:     }
  659:     *blocc++ = *in++;
  660:   }
  661:   if (s == t) /* occ not found */
  662:     *(blocc-(in-s))='\0';
  663:   else
  664:     *(blocc-(in-s)-1)='\0';
  665:   in=s;
  666:   while ( *in != '\0'){
  667:     *alocc++ = *in++;
  668:   }
  669: 
  670:   *alocc='\0';
  671:   return s;
  672: }
  673: 
  674: int nbocc(char *s, char occ)
  675: {
  676:   int i,j=0;
  677:   int lg=20;
  678:   i=0;
  679:   lg=strlen(s);
  680:   for(i=0; i<= lg; i++) {
  681:   if  (s[i] == occ ) j++;
  682:   }
  683:   return j;
  684: }
  685: 
  686: /* void cutv(char *u,char *v, char*t, char occ) */
  687: /* { */
  688: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
  689: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
  690: /*      gives u="abcdef2ghi" and v="j" *\/ */
  691: /*   int i,lg,j,p=0; */
  692: /*   i=0; */
  693: /*   lg=strlen(t); */
  694: /*   for(j=0; j<=lg-1; j++) { */
  695: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
  696: /*   } */
  697: 
  698: /*   for(j=0; j<p; j++) { */
  699: /*     (u[j] = t[j]); */
  700: /*   } */
  701: /*      u[p]='\0'; */
  702: 
  703: /*    for(j=0; j<= lg; j++) { */
  704: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
  705: /*   } */
  706: /* } */
  707: 
  708: /********************** nrerror ********************/
  709: 
  710: void nrerror(char error_text[])
  711: {
  712:   fprintf(stderr,"ERREUR ...\n");
  713:   fprintf(stderr,"%s\n",error_text);
  714:   exit(EXIT_FAILURE);
  715: }
  716: /*********************** vector *******************/
  717: double *vector(int nl, int nh)
  718: {
  719:   double *v;
  720:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
  721:   if (!v) nrerror("allocation failure in vector");
  722:   return v-nl+NR_END;
  723: }
  724: 
  725: /************************ free vector ******************/
  726: void free_vector(double*v, int nl, int nh)
  727: {
  728:   free((FREE_ARG)(v+nl-NR_END));
  729: }
  730: 
  731: /************************ivector *******************************/
  732: int *ivector(long nl,long nh)
  733: {
  734:   int *v;
  735:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
  736:   if (!v) nrerror("allocation failure in ivector");
  737:   return v-nl+NR_END;
  738: }
  739: 
  740: /******************free ivector **************************/
  741: void free_ivector(int *v, long nl, long nh)
  742: {
  743:   free((FREE_ARG)(v+nl-NR_END));
  744: }
  745: 
  746: /************************lvector *******************************/
  747: long *lvector(long nl,long nh)
  748: {
  749:   long *v;
  750:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
  751:   if (!v) nrerror("allocation failure in ivector");
  752:   return v-nl+NR_END;
  753: }
  754: 
  755: /******************free lvector **************************/
  756: void free_lvector(long *v, long nl, long nh)
  757: {
  758:   free((FREE_ARG)(v+nl-NR_END));
  759: }
  760: 
  761: /******************* imatrix *******************************/
  762: int **imatrix(long nrl, long nrh, long ncl, long nch) 
  763:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
  764: { 
  765:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
  766:   int **m; 
  767:   
  768:   /* allocate pointers to rows */ 
  769:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
  770:   if (!m) nrerror("allocation failure 1 in matrix()"); 
  771:   m += NR_END; 
  772:   m -= nrl; 
  773:   
  774:   
  775:   /* allocate rows and set pointers to them */ 
  776:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
  777:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
  778:   m[nrl] += NR_END; 
  779:   m[nrl] -= ncl; 
  780:   
  781:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
  782:   
  783:   /* return pointer to array of pointers to rows */ 
  784:   return m; 
  785: } 
  786: 
  787: /****************** free_imatrix *************************/
  788: void free_imatrix(m,nrl,nrh,ncl,nch)
  789:       int **m;
  790:       long nch,ncl,nrh,nrl; 
  791:      /* free an int matrix allocated by imatrix() */ 
  792: { 
  793:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
  794:   free((FREE_ARG) (m+nrl-NR_END)); 
  795: } 
  796: 
  797: /******************* matrix *******************************/
  798: double **matrix(long nrl, long nrh, long ncl, long nch)
  799: {
  800:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
  801:   double **m;
  802: 
  803:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
  804:   if (!m) nrerror("allocation failure 1 in matrix()");
  805:   m += NR_END;
  806:   m -= nrl;
  807: 
  808:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
  809:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
  810:   m[nrl] += NR_END;
  811:   m[nrl] -= ncl;
  812: 
  813:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
  814:   return m;
  815:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) 
  816:    */
  817: }
  818: 
  819: /*************************free matrix ************************/
  820: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
  821: {
  822:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
  823:   free((FREE_ARG)(m+nrl-NR_END));
  824: }
  825: 
  826: /******************* ma3x *******************************/
  827: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
  828: {
  829:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
  830:   double ***m;
  831: 
  832:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
  833:   if (!m) nrerror("allocation failure 1 in matrix()");
  834:   m += NR_END;
  835:   m -= nrl;
  836: 
  837:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
  838:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
  839:   m[nrl] += NR_END;
  840:   m[nrl] -= ncl;
  841: 
  842:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
  843: 
  844:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
  845:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
  846:   m[nrl][ncl] += NR_END;
  847:   m[nrl][ncl] -= nll;
  848:   for (j=ncl+1; j<=nch; j++) 
  849:     m[nrl][j]=m[nrl][j-1]+nlay;
  850:   
  851:   for (i=nrl+1; i<=nrh; i++) {
  852:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
  853:     for (j=ncl+1; j<=nch; j++) 
  854:       m[i][j]=m[i][j-1]+nlay;
  855:   }
  856:   return m; 
  857:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
  858:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
  859:   */
  860: }
  861: 
  862: /*************************free ma3x ************************/
  863: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
  864: {
  865:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
  866:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
  867:   free((FREE_ARG)(m+nrl-NR_END));
  868: }
  869: 
  870: /*************** function subdirf ***********/
  871: char *subdirf(char fileres[])
  872: {
  873:   /* Caution optionfilefiname is hidden */
  874:   strcpy(tmpout,optionfilefiname);
  875:   strcat(tmpout,"/"); /* Add to the right */
  876:   strcat(tmpout,fileres);
  877:   return tmpout;
  878: }
  879: 
  880: /*************** function subdirf2 ***********/
  881: char *subdirf2(char fileres[], char *preop)
  882: {
  883:   
  884:   /* Caution optionfilefiname is hidden */
  885:   strcpy(tmpout,optionfilefiname);
  886:   strcat(tmpout,"/");
  887:   strcat(tmpout,preop);
  888:   strcat(tmpout,fileres);
  889:   return tmpout;
  890: }
  891: 
  892: /*************** function subdirf3 ***********/
  893: char *subdirf3(char fileres[], char *preop, char *preop2)
  894: {
  895:   
  896:   /* Caution optionfilefiname is hidden */
  897:   strcpy(tmpout,optionfilefiname);
  898:   strcat(tmpout,"/");
  899:   strcat(tmpout,preop);
  900:   strcat(tmpout,preop2);
  901:   strcat(tmpout,fileres);
  902:   return tmpout;
  903: }
  904: 
  905: /***************** f1dim *************************/
  906: extern int ncom; 
  907: extern double *pcom,*xicom;
  908: extern double (*nrfunc)(double []); 
  909:  
  910: double f1dim(double x) 
  911: { 
  912:   int j; 
  913:   double f;
  914:   double *xt; 
  915:  
  916:   xt=vector(1,ncom); 
  917:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
  918:   f=(*nrfunc)(xt); 
  919:   free_vector(xt,1,ncom); 
  920:   return f; 
  921: } 
  922: 
  923: /*****************brent *************************/
  924: double brent(double ax, double bx, double cx, double (*f)(double), double tol, 	double *xmin) 
  925: { 
  926:   int iter; 
  927:   double a,b,d,etemp;
  928:   double fu,fv,fw,fx;
  929:   double ftemp;
  930:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
  931:   double e=0.0; 
  932:  
  933:   a=(ax < cx ? ax : cx); 
  934:   b=(ax > cx ? ax : cx); 
  935:   x=w=v=bx; 
  936:   fw=fv=fx=(*f)(x); 
  937:   for (iter=1;iter<=ITMAX;iter++) { 
  938:     xm=0.5*(a+b); 
  939:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
  940:     /*		if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
  941:     printf(".");fflush(stdout);
  942:     fprintf(ficlog,".");fflush(ficlog);
  943: #ifdef DEBUG
  944:     printf("br %d,x=%.10e xm=%.10e b=%.10e a=%.10e tol=%.10e tol1=%.10e tol2=%.10e x-xm=%.10e fx=%.12e fu=%.12e,fw=%.12e,ftemp=%.12e,ftol=%.12e\n",iter,x,xm,b,a,tol,tol1,tol2,(x-xm),fx,fu,fw,ftemp,ftol);
  945:     fprintf(ficlog,"br %d,x=%.10e xm=%.10e b=%.10e a=%.10e tol=%.10e tol1=%.10e tol2=%.10e x-xm=%.10e fx=%.12e fu=%.12e,fw=%.12e,ftemp=%.12e,ftol=%.12e\n",iter,x,xm,b,a,tol,tol1,tol2,(x-xm),fx,fu,fw,ftemp,ftol);
  946:     /*		if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
  947: #endif
  948:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
  949:       *xmin=x; 
  950:       return fx; 
  951:     } 
  952:     ftemp=fu;
  953:     if (fabs(e) > tol1) { 
  954:       r=(x-w)*(fx-fv); 
  955:       q=(x-v)*(fx-fw); 
  956:       p=(x-v)*q-(x-w)*r; 
  957:       q=2.0*(q-r); 
  958:       if (q > 0.0) p = -p; 
  959:       q=fabs(q); 
  960:       etemp=e; 
  961:       e=d; 
  962:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
  963: 	d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
  964:       else { 
  965: 	d=p/q; 
  966: 	u=x+d; 
  967: 	if (u-a < tol2 || b-u < tol2) 
  968: 	  d=SIGN(tol1,xm-x); 
  969:       } 
  970:     } else { 
  971:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
  972:     } 
  973:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
  974:     fu=(*f)(u); 
  975:     if (fu <= fx) { 
  976:       if (u >= x) a=x; else b=x; 
  977:       SHFT(v,w,x,u) 
  978: 	SHFT(fv,fw,fx,fu) 
  979: 	} else { 
  980: 	  if (u < x) a=u; else b=u; 
  981: 	  if (fu <= fw || w == x) { 
  982: 	    v=w; 
  983: 	    w=u; 
  984: 	    fv=fw; 
  985: 	    fw=fu; 
  986: 	  } else if (fu <= fv || v == x || v == w) { 
  987: 	    v=u; 
  988: 	    fv=fu; 
  989: 	  } 
  990: 	} 
  991:   } 
  992:   nrerror("Too many iterations in brent"); 
  993:   *xmin=x; 
  994:   return fx; 
  995: } 
  996: 
  997: /****************** mnbrak ***********************/
  998: 
  999: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
 1000: 	    double (*func)(double)) 
 1001: { 
 1002:   double ulim,u,r,q, dum;
 1003:   double fu; 
 1004:  
 1005:   *fa=(*func)(*ax); 
 1006:   *fb=(*func)(*bx); 
 1007:   if (*fb > *fa) { 
 1008:     SHFT(dum,*ax,*bx,dum) 
 1009:       SHFT(dum,*fb,*fa,dum) 
 1010:       } 
 1011:   *cx=(*bx)+GOLD*(*bx-*ax); 
 1012:   *fc=(*func)(*cx); 
 1013:   while (*fb > *fc) { 
 1014:     r=(*bx-*ax)*(*fb-*fc); 
 1015:     q=(*bx-*cx)*(*fb-*fa); 
 1016:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
 1017:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); 
 1018:     ulim=(*bx)+GLIMIT*(*cx-*bx); 
 1019:     if ((*bx-u)*(u-*cx) > 0.0) { 
 1020:       fu=(*func)(u); 
 1021:     } else if ((*cx-u)*(u-ulim) > 0.0) { 
 1022:       fu=(*func)(u); 
 1023:       if (fu < *fc) { 
 1024: 	SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
 1025: 	  SHFT(*fb,*fc,fu,(*func)(u)) 
 1026: 	  } 
 1027:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { 
 1028:       u=ulim; 
 1029:       fu=(*func)(u); 
 1030:     } else { 
 1031:       u=(*cx)+GOLD*(*cx-*bx); 
 1032:       fu=(*func)(u); 
 1033:     } 
 1034:     SHFT(*ax,*bx,*cx,u) 
 1035:       SHFT(*fa,*fb,*fc,fu) 
 1036:       } 
 1037: } 
 1038: 
 1039: /*************** linmin ************************/
 1040: 
 1041: int ncom; 
 1042: double *pcom,*xicom;
 1043: double (*nrfunc)(double []); 
 1044:  
 1045: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
 1046: { 
 1047:   double brent(double ax, double bx, double cx, 
 1048: 	       double (*f)(double), double tol, double *xmin); 
 1049:   double f1dim(double x); 
 1050:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
 1051: 	      double *fc, double (*func)(double)); 
 1052:   int j; 
 1053:   double xx,xmin,bx,ax; 
 1054:   double fx,fb,fa;
 1055:  
 1056:   ncom=n; 
 1057:   pcom=vector(1,n); 
 1058:   xicom=vector(1,n); 
 1059:   nrfunc=func; 
 1060:   for (j=1;j<=n;j++) { 
 1061:     pcom[j]=p[j]; 
 1062:     xicom[j]=xi[j]; 
 1063:   } 
 1064:   ax=0.0; 
 1065:   xx=1.0; 
 1066:   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); 
 1067:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); 
 1068: #ifdef DEBUG
 1069:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1070:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1071: #endif
 1072:   for (j=1;j<=n;j++) { 
 1073:     xi[j] *= xmin; 
 1074:     p[j] += xi[j]; 
 1075:   } 
 1076:   free_vector(xicom,1,n); 
 1077:   free_vector(pcom,1,n); 
 1078: } 
 1079: 
 1080: char *asc_diff_time(long time_sec, char ascdiff[])
 1081: {
 1082:   long sec_left, days, hours, minutes;
 1083:   days = (time_sec) / (60*60*24);
 1084:   sec_left = (time_sec) % (60*60*24);
 1085:   hours = (sec_left) / (60*60) ;
 1086:   sec_left = (sec_left) %(60*60);
 1087:   minutes = (sec_left) /60;
 1088:   sec_left = (sec_left) % (60);
 1089:   sprintf(ascdiff,"%d day(s) %d hour(s) %d minute(s) %d second(s)",days, hours, minutes, sec_left);  
 1090:   return ascdiff;
 1091: }
 1092: 
 1093: /*************** powell ************************/
 1094: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
 1095: 	    double (*func)(double [])) 
 1096: { 
 1097:   void linmin(double p[], double xi[], int n, double *fret, 
 1098: 	      double (*func)(double [])); 
 1099:   int i,ibig,j; 
 1100:   double del,t,*pt,*ptt,*xit;
 1101:   double fp,fptt;
 1102:   double *xits;
 1103:   int niterf, itmp;
 1104: 
 1105:   pt=vector(1,n); 
 1106:   ptt=vector(1,n); 
 1107:   xit=vector(1,n); 
 1108:   xits=vector(1,n); 
 1109:   *fret=(*func)(p); 
 1110:   for (j=1;j<=n;j++) pt[j]=p[j]; 
 1111:   for (*iter=1;;++(*iter)) { 
 1112:     fp=(*fret); 
 1113:     ibig=0; 
 1114:     del=0.0; 
 1115:     last_time=curr_time;
 1116:     (void) gettimeofday(&curr_time,&tzp);
 1117:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, curr_time.tv_sec-last_time.tv_sec, curr_time.tv_sec-start_time.tv_sec);fflush(stdout);
 1118:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, curr_time.tv_sec-last_time.tv_sec, curr_time.tv_sec-start_time.tv_sec); fflush(ficlog);
 1119: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tv_sec-start_time.tv_sec); */
 1120:    for (i=1;i<=n;i++) {
 1121:       printf(" %d %.12f",i, p[i]);
 1122:       fprintf(ficlog," %d %.12lf",i, p[i]);
 1123:       fprintf(ficrespow," %.12lf", p[i]);
 1124:     }
 1125:     printf("\n");
 1126:     fprintf(ficlog,"\n");
 1127:     fprintf(ficrespow,"\n");fflush(ficrespow);
 1128:     if(*iter <=3){
 1129:       tm = *localtime(&curr_time.tv_sec);
 1130:       strcpy(strcurr,asctime(&tm));
 1131: /*       asctime_r(&tm,strcurr); */
 1132:       forecast_time=curr_time; 
 1133:       itmp = strlen(strcurr);
 1134:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
 1135: 	strcurr[itmp-1]='\0';
 1136:       printf("\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
 1137:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
 1138:       for(niterf=10;niterf<=30;niterf+=10){
 1139: 	forecast_time.tv_sec=curr_time.tv_sec+(niterf-*iter)*(curr_time.tv_sec-last_time.tv_sec);
 1140: 	tmf = *localtime(&forecast_time.tv_sec);
 1141: /* 	asctime_r(&tmf,strfor); */
 1142: 	strcpy(strfor,asctime(&tmf));
 1143: 	itmp = strlen(strfor);
 1144: 	if(strfor[itmp-1]=='\n')
 1145: 	strfor[itmp-1]='\0';
 1146: 	printf("   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(forecast_time.tv_sec-curr_time.tv_sec,tmpout),strfor,strcurr);
 1147: 	fprintf(ficlog,"   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(forecast_time.tv_sec-curr_time.tv_sec,tmpout),strfor,strcurr);
 1148:       }
 1149:     }
 1150:     for (i=1;i<=n;i++) { 
 1151:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; 
 1152:       fptt=(*fret); 
 1153: #ifdef DEBUG
 1154:       printf("fret=%lf \n",*fret);
 1155:       fprintf(ficlog,"fret=%lf \n",*fret);
 1156: #endif
 1157:       printf("%d",i);fflush(stdout);
 1158:       fprintf(ficlog,"%d",i);fflush(ficlog);
 1159:       linmin(p,xit,n,fret,func); 
 1160:       if (fabs(fptt-(*fret)) > del) { 
 1161: 	del=fabs(fptt-(*fret)); 
 1162: 	ibig=i; 
 1163:       } 
 1164: #ifdef DEBUG
 1165:       printf("%d %.12e",i,(*fret));
 1166:       fprintf(ficlog,"%d %.12e",i,(*fret));
 1167:       for (j=1;j<=n;j++) {
 1168: 	xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
 1169: 	printf(" x(%d)=%.12e",j,xit[j]);
 1170: 	fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
 1171:       }
 1172:       for(j=1;j<=n;j++) {
 1173: 	printf(" p=%.12e",p[j]);
 1174: 	fprintf(ficlog," p=%.12e",p[j]);
 1175:       }
 1176:       printf("\n");
 1177:       fprintf(ficlog,"\n");
 1178: #endif
 1179:     } 
 1180:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
 1181: #ifdef DEBUG
 1182:       int k[2],l;
 1183:       k[0]=1;
 1184:       k[1]=-1;
 1185:       printf("Max: %.12e",(*func)(p));
 1186:       fprintf(ficlog,"Max: %.12e",(*func)(p));
 1187:       for (j=1;j<=n;j++) {
 1188: 	printf(" %.12e",p[j]);
 1189: 	fprintf(ficlog," %.12e",p[j]);
 1190:       }
 1191:       printf("\n");
 1192:       fprintf(ficlog,"\n");
 1193:       for(l=0;l<=1;l++) {
 1194: 	for (j=1;j<=n;j++) {
 1195: 	  ptt[j]=p[j]+(p[j]-pt[j])*k[l];
 1196: 	  printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1197: 	  fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1198: 	}
 1199: 	printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1200: 	fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1201:       }
 1202: #endif
 1203: 
 1204: 
 1205:       free_vector(xit,1,n); 
 1206:       free_vector(xits,1,n); 
 1207:       free_vector(ptt,1,n); 
 1208:       free_vector(pt,1,n); 
 1209:       return; 
 1210:     } 
 1211:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
 1212:     for (j=1;j<=n;j++) { 
 1213:       ptt[j]=2.0*p[j]-pt[j]; 
 1214:       xit[j]=p[j]-pt[j]; 
 1215:       pt[j]=p[j]; 
 1216:     } 
 1217:     fptt=(*func)(ptt); 
 1218:     if (fptt < fp) { 
 1219:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); 
 1220:       if (t < 0.0) { 
 1221: 	linmin(p,xit,n,fret,func); 
 1222: 	for (j=1;j<=n;j++) { 
 1223: 	  xi[j][ibig]=xi[j][n]; 
 1224: 	  xi[j][n]=xit[j]; 
 1225: 	}
 1226: #ifdef DEBUG
 1227: 	printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 1228: 	fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 1229: 	for(j=1;j<=n;j++){
 1230: 	  printf(" %.12e",xit[j]);
 1231: 	  fprintf(ficlog," %.12e",xit[j]);
 1232: 	}
 1233: 	printf("\n");
 1234: 	fprintf(ficlog,"\n");
 1235: #endif
 1236:       }
 1237:     } 
 1238:   } 
 1239: } 
 1240: 
 1241: /**** Prevalence limit (stable or period prevalence)  ****************/
 1242: 
 1243: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
 1244: {
 1245:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
 1246:      matrix by transitions matrix until convergence is reached */
 1247: 
 1248:   int i, ii,j,k;
 1249:   double min, max, maxmin, maxmax,sumnew=0.;
 1250:   double **matprod2();
 1251:   double **out, cov[NCOVMAX+1], **pmij();
 1252:   double **newm;
 1253:   double agefin, delaymax=50 ; /* Max number of years to converge */
 1254: 
 1255:   for (ii=1;ii<=nlstate+ndeath;ii++)
 1256:     for (j=1;j<=nlstate+ndeath;j++){
 1257:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1258:     }
 1259: 
 1260:    cov[1]=1.;
 1261:  
 1262:  /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 1263:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
 1264:     newm=savm;
 1265:     /* Covariates have to be included here again */
 1266:     cov[2]=agefin;
 1267:     
 1268:     for (k=1; k<=cptcovn;k++) {
 1269:       cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
 1270:       /*	printf("ij=%d k=%d Tvar[k]=%d nbcode=%d cov=%lf codtab[ij][Tvar[k]]=%d \n",ij,k, Tvar[k],nbcode[Tvar[k]][codtab[ij][Tvar[k]]],cov[2+k], codtab[ij][Tvar[k]]);*/
 1271:     }
 1272:     for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
 1273:     for (k=1; k<=cptcovprod;k++)
 1274:       cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 1275:     
 1276:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 1277:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 1278:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 1279:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
 1280:     
 1281:     savm=oldm;
 1282:     oldm=newm;
 1283:     maxmax=0.;
 1284:     for(j=1;j<=nlstate;j++){
 1285:       min=1.;
 1286:       max=0.;
 1287:       for(i=1; i<=nlstate; i++) {
 1288: 	sumnew=0;
 1289: 	for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
 1290: 	prlim[i][j]= newm[i][j]/(1-sumnew);
 1291: 	max=FMAX(max,prlim[i][j]);
 1292: 	min=FMIN(min,prlim[i][j]);
 1293:       }
 1294:       maxmin=max-min;
 1295:       maxmax=FMAX(maxmax,maxmin);
 1296:     }
 1297:     if(maxmax < ftolpl){
 1298:       return prlim;
 1299:     }
 1300:   }
 1301: }
 1302: 
 1303: /*************** transition probabilities ***************/ 
 1304: 
 1305: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 1306: {
 1307:   /* According to parameters values stored in x and the covariate's values stored in cov,
 1308:      computes the probability to be observed in state j being in state i by appying the
 1309:      model to the ncovmodel covariates (including constant and age).
 1310:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 1311:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 1312:      ncth covariate in the global vector x is given by the formula:
 1313:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 1314:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 1315:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 1316:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 1317:      Outputs ps[i][j] the probability to be observed in j being in j according to
 1318:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 1319:   */
 1320:   double s1, lnpijopii;
 1321:   /*double t34;*/
 1322:   int i,j,j1, nc, ii, jj;
 1323: 
 1324:     for(i=1; i<= nlstate; i++){
 1325:       for(j=1; j<i;j++){
 1326: 	for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 1327: 	  /*lnpijopii += param[i][j][nc]*cov[nc];*/
 1328: 	  lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 1329: /* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 1330: 	}
 1331: 	ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 1332: /* 	printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 1333:       }
 1334:       for(j=i+1; j<=nlstate+ndeath;j++){
 1335: 	for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 1336: 	  /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 1337: 	  lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 1338: /* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 1339: 	}
 1340: 	ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 1341:       }
 1342:     }
 1343:     
 1344:     for(i=1; i<= nlstate; i++){
 1345:       s1=0;
 1346:       for(j=1; j<i; j++){
 1347: 	s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 1348: 	/*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 1349:       }
 1350:       for(j=i+1; j<=nlstate+ndeath; j++){
 1351: 	s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 1352: 	/*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 1353:       }
 1354:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 1355:       ps[i][i]=1./(s1+1.);
 1356:       /* Computing other pijs */
 1357:       for(j=1; j<i; j++)
 1358: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 1359:       for(j=i+1; j<=nlstate+ndeath; j++)
 1360: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 1361:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 1362:     } /* end i */
 1363:     
 1364:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 1365:       for(jj=1; jj<= nlstate+ndeath; jj++){
 1366: 	ps[ii][jj]=0;
 1367: 	ps[ii][ii]=1;
 1368:       }
 1369:     }
 1370:     
 1371: 
 1372: /*        for(ii=1; ii<= nlstate+ndeath; ii++){ */
 1373: /* 	 for(jj=1; jj<= nlstate+ndeath; jj++){ */
 1374: /* 	   printf("ddd %lf ",ps[ii][jj]); */
 1375: /* 	 } */
 1376: /* 	 printf("\n "); */
 1377: /*        } */
 1378: /*        printf("\n ");printf("%lf ",cov[2]); */
 1379:        /*
 1380:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
 1381:       goto end;*/
 1382:     return ps;
 1383: }
 1384: 
 1385: /**************** Product of 2 matrices ******************/
 1386: 
 1387: double **matprod2(double **out, double **in,long nrl, long nrh, long ncl, long nch, long ncolol, long ncoloh, double **b)
 1388: {
 1389:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
 1390:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
 1391:   /* in, b, out are matrice of pointers which should have been initialized 
 1392:      before: only the contents of out is modified. The function returns
 1393:      a pointer to pointers identical to out */
 1394:   long i, j, k;
 1395:   for(i=nrl; i<= nrh; i++)
 1396:     for(k=ncolol; k<=ncoloh; k++)
 1397:       for(j=ncl,out[i][k]=0.; j<=nch; j++)
 1398: 	out[i][k] +=in[i][j]*b[j][k];
 1399: 
 1400:   return out;
 1401: }
 1402: 
 1403: 
 1404: /************* Higher Matrix Product ***************/
 1405: 
 1406: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
 1407: {
 1408:   /* Computes the transition matrix starting at age 'age' over 
 1409:      'nhstepm*hstepm*stepm' months (i.e. until
 1410:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
 1411:      nhstepm*hstepm matrices. 
 1412:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
 1413:      (typically every 2 years instead of every month which is too big 
 1414:      for the memory).
 1415:      Model is determined by parameters x and covariates have to be 
 1416:      included manually here. 
 1417: 
 1418:      */
 1419: 
 1420:   int i, j, d, h, k;
 1421:   double **out, cov[NCOVMAX+1];
 1422:   double **newm;
 1423: 
 1424:   /* Hstepm could be zero and should return the unit matrix */
 1425:   for (i=1;i<=nlstate+ndeath;i++)
 1426:     for (j=1;j<=nlstate+ndeath;j++){
 1427:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 1428:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 1429:     }
 1430:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 1431:   for(h=1; h <=nhstepm; h++){
 1432:     for(d=1; d <=hstepm; d++){
 1433:       newm=savm;
 1434:       /* Covariates have to be included here again */
 1435:       cov[1]=1.;
 1436:       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
 1437:       for (k=1; k<=cptcovn;k++) 
 1438: 	cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
 1439:       for (k=1; k<=cptcovage;k++)
 1440: 	cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
 1441:       for (k=1; k<=cptcovprod;k++)
 1442: 	cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 1443: 
 1444: 
 1445:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 1446:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 1447:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
 1448: 		   pmij(pmmij,cov,ncovmodel,x,nlstate));
 1449:       savm=oldm;
 1450:       oldm=newm;
 1451:     }
 1452:     for(i=1; i<=nlstate+ndeath; i++)
 1453:       for(j=1;j<=nlstate+ndeath;j++) {
 1454: 	po[i][j][h]=newm[i][j];
 1455: 	/*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
 1456:       }
 1457:     /*printf("h=%d ",h);*/
 1458:   } /* end h */
 1459: /*     printf("\n H=%d \n",h); */
 1460:   return po;
 1461: }
 1462: 
 1463: 
 1464: /*************** log-likelihood *************/
 1465: double func( double *x)
 1466: {
 1467:   int i, ii, j, k, mi, d, kk;
 1468:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 1469:   double **out;
 1470:   double sw; /* Sum of weights */
 1471:   double lli; /* Individual log likelihood */
 1472:   int s1, s2;
 1473:   double bbh, survp;
 1474:   long ipmx;
 1475:   /*extern weight */
 1476:   /* We are differentiating ll according to initial status */
 1477:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 1478:   /*for(i=1;i<imx;i++) 
 1479:     printf(" %d\n",s[4][i]);
 1480:   */
 1481:   cov[1]=1.;
 1482: 
 1483:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 1484: 
 1485:   if(mle==1){
 1486:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1487:       /* Computes the values of the ncovmodel covariates of the model
 1488: 	 depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
 1489: 	 Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
 1490: 	 to be observed in j being in i according to the model.
 1491:        */
 1492:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1493:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
 1494: 	 is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
 1495: 	 has been calculated etc */
 1496:       for(mi=1; mi<= wav[i]-1; mi++){
 1497: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1498: 	  for (j=1;j<=nlstate+ndeath;j++){
 1499: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1500: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1501: 	  }
 1502: 	for(d=0; d<dh[mi][i]; d++){
 1503: 	  newm=savm;
 1504: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1505: 	  for (kk=1; kk<=cptcovage;kk++) {
 1506: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
 1507: 	  }
 1508: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1509: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1510: 	  savm=oldm;
 1511: 	  oldm=newm;
 1512: 	} /* end mult */
 1513:       
 1514: 	/*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
 1515: 	/* But now since version 0.9 we anticipate for bias at large stepm.
 1516: 	 * If stepm is larger than one month (smallest stepm) and if the exact delay 
 1517: 	 * (in months) between two waves is not a multiple of stepm, we rounded to 
 1518: 	 * the nearest (and in case of equal distance, to the lowest) interval but now
 1519: 	 * we keep into memory the bias bh[mi][i] and also the previous matrix product
 1520: 	 * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
 1521: 	 * probability in order to take into account the bias as a fraction of the way
 1522: 	 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
 1523: 	 * -stepm/2 to stepm/2 .
 1524: 	 * For stepm=1 the results are the same as for previous versions of Imach.
 1525: 	 * For stepm > 1 the results are less biased than in previous versions. 
 1526: 	 */
 1527: 	s1=s[mw[mi][i]][i];
 1528: 	s2=s[mw[mi+1][i]][i];
 1529: 	bbh=(double)bh[mi][i]/(double)stepm; 
 1530: 	/* bias bh is positive if real duration
 1531: 	 * is higher than the multiple of stepm and negative otherwise.
 1532: 	 */
 1533: 	/* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
 1534: 	if( s2 > nlstate){ 
 1535: 	  /* i.e. if s2 is a death state and if the date of death is known 
 1536: 	     then the contribution to the likelihood is the probability to 
 1537: 	     die between last step unit time and current  step unit time, 
 1538: 	     which is also equal to probability to die before dh 
 1539: 	     minus probability to die before dh-stepm . 
 1540: 	     In version up to 0.92 likelihood was computed
 1541: 	as if date of death was unknown. Death was treated as any other
 1542: 	health state: the date of the interview describes the actual state
 1543: 	and not the date of a change in health state. The former idea was
 1544: 	to consider that at each interview the state was recorded
 1545: 	(healthy, disable or death) and IMaCh was corrected; but when we
 1546: 	introduced the exact date of death then we should have modified
 1547: 	the contribution of an exact death to the likelihood. This new
 1548: 	contribution is smaller and very dependent of the step unit
 1549: 	stepm. It is no more the probability to die between last interview
 1550: 	and month of death but the probability to survive from last
 1551: 	interview up to one month before death multiplied by the
 1552: 	probability to die within a month. Thanks to Chris
 1553: 	Jackson for correcting this bug.  Former versions increased
 1554: 	mortality artificially. The bad side is that we add another loop
 1555: 	which slows down the processing. The difference can be up to 10%
 1556: 	lower mortality.
 1557: 	  */
 1558: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 1559: 
 1560: 
 1561: 	} else if  (s2==-2) {
 1562: 	  for (j=1,survp=0. ; j<=nlstate; j++) 
 1563: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 1564: 	  /*survp += out[s1][j]; */
 1565: 	  lli= log(survp);
 1566: 	}
 1567: 	
 1568:  	else if  (s2==-4) { 
 1569: 	  for (j=3,survp=0. ; j<=nlstate; j++)  
 1570: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 1571:  	  lli= log(survp); 
 1572:  	} 
 1573: 
 1574:  	else if  (s2==-5) { 
 1575:  	  for (j=1,survp=0. ; j<=2; j++)  
 1576: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 1577:  	  lli= log(survp); 
 1578:  	} 
 1579: 	
 1580: 	else{
 1581: 	  lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 1582: 	  /*  lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*(savm[s1][s2])):log((1.+bbh)*out[s1][s2]));*/ /* linear interpolation */
 1583: 	} 
 1584: 	/*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
 1585: 	/*if(lli ==000.0)*/
 1586: 	/*printf("bbh= %f lli=%f savm=%f out=%f %d\n",bbh,lli,savm[s1][s2], out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]],i); */
 1587:   	ipmx +=1;
 1588: 	sw += weight[i];
 1589: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1590:       } /* end of wave */
 1591:     } /* end of individual */
 1592:   }  else if(mle==2){
 1593:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1594:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1595:       for(mi=1; mi<= wav[i]-1; mi++){
 1596: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1597: 	  for (j=1;j<=nlstate+ndeath;j++){
 1598: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1599: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1600: 	  }
 1601: 	for(d=0; d<=dh[mi][i]; d++){
 1602: 	  newm=savm;
 1603: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1604: 	  for (kk=1; kk<=cptcovage;kk++) {
 1605: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1606: 	  }
 1607: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1608: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1609: 	  savm=oldm;
 1610: 	  oldm=newm;
 1611: 	} /* end mult */
 1612:       
 1613: 	s1=s[mw[mi][i]][i];
 1614: 	s2=s[mw[mi+1][i]][i];
 1615: 	bbh=(double)bh[mi][i]/(double)stepm; 
 1616: 	lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*(savm[s1][s2])):log((1.+bbh)*out[s1][s2])); /* linear interpolation */
 1617: 	ipmx +=1;
 1618: 	sw += weight[i];
 1619: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1620:       } /* end of wave */
 1621:     } /* end of individual */
 1622:   }  else if(mle==3){  /* exponential inter-extrapolation */
 1623:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1624:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1625:       for(mi=1; mi<= wav[i]-1; mi++){
 1626: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1627: 	  for (j=1;j<=nlstate+ndeath;j++){
 1628: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1629: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1630: 	  }
 1631: 	for(d=0; d<dh[mi][i]; d++){
 1632: 	  newm=savm;
 1633: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1634: 	  for (kk=1; kk<=cptcovage;kk++) {
 1635: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1636: 	  }
 1637: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1638: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1639: 	  savm=oldm;
 1640: 	  oldm=newm;
 1641: 	} /* end mult */
 1642:       
 1643: 	s1=s[mw[mi][i]][i];
 1644: 	s2=s[mw[mi+1][i]][i];
 1645: 	bbh=(double)bh[mi][i]/(double)stepm; 
 1646: 	lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2])); /* exponential inter-extrapolation */
 1647: 	ipmx +=1;
 1648: 	sw += weight[i];
 1649: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1650:       } /* end of wave */
 1651:     } /* end of individual */
 1652:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
 1653:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1654:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1655:       for(mi=1; mi<= wav[i]-1; mi++){
 1656: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1657: 	  for (j=1;j<=nlstate+ndeath;j++){
 1658: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1659: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1660: 	  }
 1661: 	for(d=0; d<dh[mi][i]; d++){
 1662: 	  newm=savm;
 1663: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1664: 	  for (kk=1; kk<=cptcovage;kk++) {
 1665: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1666: 	  }
 1667: 	
 1668: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1669: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1670: 	  savm=oldm;
 1671: 	  oldm=newm;
 1672: 	} /* end mult */
 1673:       
 1674: 	s1=s[mw[mi][i]][i];
 1675: 	s2=s[mw[mi+1][i]][i];
 1676: 	if( s2 > nlstate){ 
 1677: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 1678: 	}else{
 1679: 	  lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 1680: 	}
 1681: 	ipmx +=1;
 1682: 	sw += weight[i];
 1683: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1684: /* 	printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]); */
 1685:       } /* end of wave */
 1686:     } /* end of individual */
 1687:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
 1688:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1689:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1690:       for(mi=1; mi<= wav[i]-1; mi++){
 1691: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1692: 	  for (j=1;j<=nlstate+ndeath;j++){
 1693: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1694: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1695: 	  }
 1696: 	for(d=0; d<dh[mi][i]; d++){
 1697: 	  newm=savm;
 1698: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1699: 	  for (kk=1; kk<=cptcovage;kk++) {
 1700: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1701: 	  }
 1702: 	
 1703: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1704: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1705: 	  savm=oldm;
 1706: 	  oldm=newm;
 1707: 	} /* end mult */
 1708:       
 1709: 	s1=s[mw[mi][i]][i];
 1710: 	s2=s[mw[mi+1][i]][i];
 1711: 	lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 1712: 	ipmx +=1;
 1713: 	sw += weight[i];
 1714: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1715: 	/*printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]);*/
 1716:       } /* end of wave */
 1717:     } /* end of individual */
 1718:   } /* End of if */
 1719:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 1720:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 1721:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 1722:   return -l;
 1723: }
 1724: 
 1725: /*************** log-likelihood *************/
 1726: double funcone( double *x)
 1727: {
 1728:   /* Same as likeli but slower because of a lot of printf and if */
 1729:   int i, ii, j, k, mi, d, kk;
 1730:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 1731:   double **out;
 1732:   double lli; /* Individual log likelihood */
 1733:   double llt;
 1734:   int s1, s2;
 1735:   double bbh, survp;
 1736:   /*extern weight */
 1737:   /* We are differentiating ll according to initial status */
 1738:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 1739:   /*for(i=1;i<imx;i++) 
 1740:     printf(" %d\n",s[4][i]);
 1741:   */
 1742:   cov[1]=1.;
 1743: 
 1744:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 1745: 
 1746:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1747:     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1748:     for(mi=1; mi<= wav[i]-1; mi++){
 1749:       for (ii=1;ii<=nlstate+ndeath;ii++)
 1750: 	for (j=1;j<=nlstate+ndeath;j++){
 1751: 	  oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1752: 	  savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1753: 	}
 1754:       for(d=0; d<dh[mi][i]; d++){
 1755: 	newm=savm;
 1756: 	cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1757: 	for (kk=1; kk<=cptcovage;kk++) {
 1758: 	  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1759: 	}
 1760: 	out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1761: 		     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1762: 	savm=oldm;
 1763: 	oldm=newm;
 1764:       } /* end mult */
 1765:       
 1766:       s1=s[mw[mi][i]][i];
 1767:       s2=s[mw[mi+1][i]][i];
 1768:       bbh=(double)bh[mi][i]/(double)stepm; 
 1769:       /* bias is positive if real duration
 1770:        * is higher than the multiple of stepm and negative otherwise.
 1771:        */
 1772:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
 1773: 	lli=log(out[s1][s2] - savm[s1][s2]);
 1774:       } else if  (s2==-2) {
 1775: 	for (j=1,survp=0. ; j<=nlstate; j++) 
 1776: 	  survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 1777: 	lli= log(survp);
 1778:       }else if (mle==1){
 1779: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 1780:       } else if(mle==2){
 1781: 	lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]):log((1.+bbh)*out[s1][s2])); /* linear interpolation */
 1782:       } else if(mle==3){  /* exponential inter-extrapolation */
 1783: 	lli= (savm[s1][s2]>(double)1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2])); /* exponential inter-extrapolation */
 1784:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
 1785: 	lli=log(out[s1][s2]); /* Original formula */
 1786:       } else{  /* mle=0 back to 1 */
 1787: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 1788: 	/*lli=log(out[s1][s2]); */ /* Original formula */
 1789:       } /* End of if */
 1790:       ipmx +=1;
 1791:       sw += weight[i];
 1792:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1793:       /*printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]); */
 1794:       if(globpr){
 1795: 	fprintf(ficresilk,"%9d %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
 1796:  %11.6f %11.6f %11.6f ", \
 1797: 		num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
 1798: 		2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
 1799: 	for(k=1,llt=0.,l=0.; k<=nlstate; k++){
 1800: 	  llt +=ll[k]*gipmx/gsw;
 1801: 	  fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
 1802: 	}
 1803: 	fprintf(ficresilk," %10.6f\n", -llt);
 1804:       }
 1805:     } /* end of wave */
 1806:   } /* end of individual */
 1807:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 1808:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 1809:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 1810:   if(globpr==0){ /* First time we count the contributions and weights */
 1811:     gipmx=ipmx;
 1812:     gsw=sw;
 1813:   }
 1814:   return -l;
 1815: }
 1816: 
 1817: 
 1818: /*************** function likelione ***********/
 1819: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
 1820: {
 1821:   /* This routine should help understanding what is done with 
 1822:      the selection of individuals/waves and
 1823:      to check the exact contribution to the likelihood.
 1824:      Plotting could be done.
 1825:    */
 1826:   int k;
 1827: 
 1828:   if(*globpri !=0){ /* Just counts and sums, no printings */
 1829:     strcpy(fileresilk,"ilk"); 
 1830:     strcat(fileresilk,fileres);
 1831:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
 1832:       printf("Problem with resultfile: %s\n", fileresilk);
 1833:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
 1834:     }
 1835:     fprintf(ficresilk, "#individual(line's_record) s1 s2 wave# effective_wave# number_of_matrices_product pij weight -2ln(pij)*weight 0pij_x 0pij_(x-stepm) cumulating_loglikeli_by_health_state(reweighted=-2ll*weightXnumber_of_contribs/sum_of_weights) and_total\n");
 1836:     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
 1837:     /* 	i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
 1838:     for(k=1; k<=nlstate; k++) 
 1839:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
 1840:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
 1841:   }
 1842: 
 1843:   *fretone=(*funcone)(p);
 1844:   if(*globpri !=0){
 1845:     fclose(ficresilk);
 1846:     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
 1847:     fflush(fichtm); 
 1848:   } 
 1849:   return;
 1850: }
 1851: 
 1852: 
 1853: /*********** Maximum Likelihood Estimation ***************/
 1854: 
 1855: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
 1856: {
 1857:   int i,j, iter;
 1858:   double **xi;
 1859:   double fret;
 1860:   double fretone; /* Only one call to likelihood */
 1861:   /*  char filerespow[FILENAMELENGTH];*/
 1862:   xi=matrix(1,npar,1,npar);
 1863:   for (i=1;i<=npar;i++)
 1864:     for (j=1;j<=npar;j++)
 1865:       xi[i][j]=(i==j ? 1.0 : 0.0);
 1866:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
 1867:   strcpy(filerespow,"pow"); 
 1868:   strcat(filerespow,fileres);
 1869:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
 1870:     printf("Problem with resultfile: %s\n", filerespow);
 1871:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 1872:   }
 1873:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
 1874:   for (i=1;i<=nlstate;i++)
 1875:     for(j=1;j<=nlstate+ndeath;j++)
 1876:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 1877:   fprintf(ficrespow,"\n");
 1878: 
 1879:   powell(p,xi,npar,ftol,&iter,&fret,func);
 1880: 
 1881:   free_matrix(xi,1,npar,1,npar);
 1882:   fclose(ficrespow);
 1883:   printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));
 1884:   fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
 1885:   fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
 1886: 
 1887: }
 1888: 
 1889: /**** Computes Hessian and covariance matrix ***/
 1890: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
 1891: {
 1892:   double  **a,**y,*x,pd;
 1893:   double **hess;
 1894:   int i, j,jk;
 1895:   int *indx;
 1896: 
 1897:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
 1898:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
 1899:   void lubksb(double **a, int npar, int *indx, double b[]) ;
 1900:   void ludcmp(double **a, int npar, int *indx, double *d) ;
 1901:   double gompertz(double p[]);
 1902:   hess=matrix(1,npar,1,npar);
 1903: 
 1904:   printf("\nCalculation of the hessian matrix. Wait...\n");
 1905:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
 1906:   for (i=1;i<=npar;i++){
 1907:     printf("%d",i);fflush(stdout);
 1908:     fprintf(ficlog,"%d",i);fflush(ficlog);
 1909:    
 1910:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
 1911:     
 1912:     /*  printf(" %f ",p[i]);
 1913: 	printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
 1914:   }
 1915:   
 1916:   for (i=1;i<=npar;i++) {
 1917:     for (j=1;j<=npar;j++)  {
 1918:       if (j>i) { 
 1919: 	printf(".%d%d",i,j);fflush(stdout);
 1920: 	fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
 1921: 	hess[i][j]=hessij(p,delti,i,j,func,npar);
 1922: 	
 1923: 	hess[j][i]=hess[i][j];    
 1924: 	/*printf(" %lf ",hess[i][j]);*/
 1925:       }
 1926:     }
 1927:   }
 1928:   printf("\n");
 1929:   fprintf(ficlog,"\n");
 1930: 
 1931:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
 1932:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
 1933:   
 1934:   a=matrix(1,npar,1,npar);
 1935:   y=matrix(1,npar,1,npar);
 1936:   x=vector(1,npar);
 1937:   indx=ivector(1,npar);
 1938:   for (i=1;i<=npar;i++)
 1939:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
 1940:   ludcmp(a,npar,indx,&pd);
 1941: 
 1942:   for (j=1;j<=npar;j++) {
 1943:     for (i=1;i<=npar;i++) x[i]=0;
 1944:     x[j]=1;
 1945:     lubksb(a,npar,indx,x);
 1946:     for (i=1;i<=npar;i++){ 
 1947:       matcov[i][j]=x[i];
 1948:     }
 1949:   }
 1950: 
 1951:   printf("\n#Hessian matrix#\n");
 1952:   fprintf(ficlog,"\n#Hessian matrix#\n");
 1953:   for (i=1;i<=npar;i++) { 
 1954:     for (j=1;j<=npar;j++) { 
 1955:       printf("%.3e ",hess[i][j]);
 1956:       fprintf(ficlog,"%.3e ",hess[i][j]);
 1957:     }
 1958:     printf("\n");
 1959:     fprintf(ficlog,"\n");
 1960:   }
 1961: 
 1962:   /* Recompute Inverse */
 1963:   for (i=1;i<=npar;i++)
 1964:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
 1965:   ludcmp(a,npar,indx,&pd);
 1966: 
 1967:   /*  printf("\n#Hessian matrix recomputed#\n");
 1968: 
 1969:   for (j=1;j<=npar;j++) {
 1970:     for (i=1;i<=npar;i++) x[i]=0;
 1971:     x[j]=1;
 1972:     lubksb(a,npar,indx,x);
 1973:     for (i=1;i<=npar;i++){ 
 1974:       y[i][j]=x[i];
 1975:       printf("%.3e ",y[i][j]);
 1976:       fprintf(ficlog,"%.3e ",y[i][j]);
 1977:     }
 1978:     printf("\n");
 1979:     fprintf(ficlog,"\n");
 1980:   }
 1981:   */
 1982: 
 1983:   free_matrix(a,1,npar,1,npar);
 1984:   free_matrix(y,1,npar,1,npar);
 1985:   free_vector(x,1,npar);
 1986:   free_ivector(indx,1,npar);
 1987:   free_matrix(hess,1,npar,1,npar);
 1988: 
 1989: 
 1990: }
 1991: 
 1992: /*************** hessian matrix ****************/
 1993: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
 1994: {
 1995:   int i;
 1996:   int l=1, lmax=20;
 1997:   double k1,k2;
 1998:   double p2[MAXPARM+1]; /* identical to x */
 1999:   double res;
 2000:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
 2001:   double fx;
 2002:   int k=0,kmax=10;
 2003:   double l1;
 2004: 
 2005:   fx=func(x);
 2006:   for (i=1;i<=npar;i++) p2[i]=x[i];
 2007:   for(l=0 ; l <=lmax; l++){
 2008:     l1=pow(10,l);
 2009:     delts=delt;
 2010:     for(k=1 ; k <kmax; k=k+1){
 2011:       delt = delta*(l1*k);
 2012:       p2[theta]=x[theta] +delt;
 2013:       k1=func(p2)-fx;
 2014:       p2[theta]=x[theta]-delt;
 2015:       k2=func(p2)-fx;
 2016:       /*res= (k1-2.0*fx+k2)/delt/delt; */
 2017:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
 2018:       
 2019: #ifdef DEBUGHESS
 2020:       printf("%d %d k1=%.12e k2=%.12e xk1=%.12e xk2=%.12e delt=%.12e res=%.12e l=%d k=%d,fx=%.12e\n",theta,theta,k1,k2,x[theta]+delt,x[theta]-delt,delt,res, l, k,fx);
 2021:       fprintf(ficlog,"%d %d k1=%.12e k2=%.12e xk1=%.12e xk2=%.12e delt=%.12e res=%.12e l=%d k=%d,fx=%.12e\n",theta,theta,k1,k2,x[theta]+delt,x[theta]-delt,delt,res, l, k,fx);
 2022: #endif
 2023:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
 2024:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
 2025: 	k=kmax;
 2026:       }
 2027:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
 2028: 	k=kmax; l=lmax*10.;
 2029:       }
 2030:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
 2031: 	delts=delt;
 2032:       }
 2033:     }
 2034:   }
 2035:   delti[theta]=delts;
 2036:   return res; 
 2037:   
 2038: }
 2039: 
 2040: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
 2041: {
 2042:   int i;
 2043:   int l=1, l1, lmax=20;
 2044:   double k1,k2,k3,k4,res,fx;
 2045:   double p2[MAXPARM+1];
 2046:   int k;
 2047: 
 2048:   fx=func(x);
 2049:   for (k=1; k<=2; k++) {
 2050:     for (i=1;i<=npar;i++) p2[i]=x[i];
 2051:     p2[thetai]=x[thetai]+delti[thetai]/k;
 2052:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
 2053:     k1=func(p2)-fx;
 2054:   
 2055:     p2[thetai]=x[thetai]+delti[thetai]/k;
 2056:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
 2057:     k2=func(p2)-fx;
 2058:   
 2059:     p2[thetai]=x[thetai]-delti[thetai]/k;
 2060:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
 2061:     k3=func(p2)-fx;
 2062:   
 2063:     p2[thetai]=x[thetai]-delti[thetai]/k;
 2064:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
 2065:     k4=func(p2)-fx;
 2066:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
 2067: #ifdef DEBUG
 2068:     printf("%d %d k=%d, k1=%.12e k2=%.12e k3=%.12e k4=%.12e delti/k=%.12e deltj/k=%.12e, xi-de/k=%.12e xj-de/k=%.12e  res=%.12e k1234=%.12e,k1-2=%.12e,k3-4=%.12e\n",thetai,thetaj,k,k1,k2,k3,k4,delti[thetai]/k,delti[thetaj]/k,x[thetai]-delti[thetai]/k,x[thetaj]-delti[thetaj]/k, res,k1-k2-k3+k4,k1-k2,k3-k4);
 2069:     fprintf(ficlog,"%d %d k=%d, k1=%.12e k2=%.12e k3=%.12e k4=%.12e delti/k=%.12e deltj/k=%.12e, xi-de/k=%.12e xj-de/k=%.12e  res=%.12e k1234=%.12e,k1-2=%.12e,k3-4=%.12e\n",thetai,thetaj,k,k1,k2,k3,k4,delti[thetai]/k,delti[thetaj]/k,x[thetai]-delti[thetai]/k,x[thetaj]-delti[thetaj]/k, res,k1-k2-k3+k4,k1-k2,k3-k4);
 2070: #endif
 2071:   }
 2072:   return res;
 2073: }
 2074: 
 2075: /************** Inverse of matrix **************/
 2076: void ludcmp(double **a, int n, int *indx, double *d) 
 2077: { 
 2078:   int i,imax,j,k; 
 2079:   double big,dum,sum,temp; 
 2080:   double *vv; 
 2081:  
 2082:   vv=vector(1,n); 
 2083:   *d=1.0; 
 2084:   for (i=1;i<=n;i++) { 
 2085:     big=0.0; 
 2086:     for (j=1;j<=n;j++) 
 2087:       if ((temp=fabs(a[i][j])) > big) big=temp; 
 2088:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
 2089:     vv[i]=1.0/big; 
 2090:   } 
 2091:   for (j=1;j<=n;j++) { 
 2092:     for (i=1;i<j;i++) { 
 2093:       sum=a[i][j]; 
 2094:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
 2095:       a[i][j]=sum; 
 2096:     } 
 2097:     big=0.0; 
 2098:     for (i=j;i<=n;i++) { 
 2099:       sum=a[i][j]; 
 2100:       for (k=1;k<j;k++) 
 2101: 	sum -= a[i][k]*a[k][j]; 
 2102:       a[i][j]=sum; 
 2103:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
 2104: 	big=dum; 
 2105: 	imax=i; 
 2106:       } 
 2107:     } 
 2108:     if (j != imax) { 
 2109:       for (k=1;k<=n;k++) { 
 2110: 	dum=a[imax][k]; 
 2111: 	a[imax][k]=a[j][k]; 
 2112: 	a[j][k]=dum; 
 2113:       } 
 2114:       *d = -(*d); 
 2115:       vv[imax]=vv[j]; 
 2116:     } 
 2117:     indx[j]=imax; 
 2118:     if (a[j][j] == 0.0) a[j][j]=TINY; 
 2119:     if (j != n) { 
 2120:       dum=1.0/(a[j][j]); 
 2121:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
 2122:     } 
 2123:   } 
 2124:   free_vector(vv,1,n);  /* Doesn't work */
 2125: ;
 2126: } 
 2127: 
 2128: void lubksb(double **a, int n, int *indx, double b[]) 
 2129: { 
 2130:   int i,ii=0,ip,j; 
 2131:   double sum; 
 2132:  
 2133:   for (i=1;i<=n;i++) { 
 2134:     ip=indx[i]; 
 2135:     sum=b[ip]; 
 2136:     b[ip]=b[i]; 
 2137:     if (ii) 
 2138:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
 2139:     else if (sum) ii=i; 
 2140:     b[i]=sum; 
 2141:   } 
 2142:   for (i=n;i>=1;i--) { 
 2143:     sum=b[i]; 
 2144:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
 2145:     b[i]=sum/a[i][i]; 
 2146:   } 
 2147: } 
 2148: 
 2149: void pstamp(FILE *fichier)
 2150: {
 2151:   fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
 2152: }
 2153: 
 2154: /************ Frequencies ********************/
 2155: void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, int *Tvaraff, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[])
 2156: {  /* Some frequencies */
 2157:   
 2158:   int i, m, jk, k1,i1, j1, bool, z1,j;
 2159:   int first;
 2160:   double ***freq; /* Frequencies */
 2161:   double *pp, **prop;
 2162:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
 2163:   char fileresp[FILENAMELENGTH];
 2164:   
 2165:   pp=vector(1,nlstate);
 2166:   prop=matrix(1,nlstate,iagemin,iagemax+3);
 2167:   strcpy(fileresp,"p");
 2168:   strcat(fileresp,fileres);
 2169:   if((ficresp=fopen(fileresp,"w"))==NULL) {
 2170:     printf("Problem with prevalence resultfile: %s\n", fileresp);
 2171:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
 2172:     exit(0);
 2173:   }
 2174:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
 2175:   j1=0;
 2176:   
 2177:   j=cptcoveff;
 2178:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 2179: 
 2180:   first=1;
 2181: 
 2182:   for(k1=1; k1<=j;k1++){
 2183:     for(i1=1; i1<=ncodemax[k1];i1++){
 2184:       j1++;
 2185:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
 2186: 	scanf("%d", i);*/
 2187:       for (i=-5; i<=nlstate+ndeath; i++)  
 2188: 	for (jk=-5; jk<=nlstate+ndeath; jk++)  
 2189: 	  for(m=iagemin; m <= iagemax+3; m++)
 2190: 	    freq[i][jk][m]=0;
 2191: 
 2192:     for (i=1; i<=nlstate; i++)  
 2193:       for(m=iagemin; m <= iagemax+3; m++)
 2194: 	prop[i][m]=0;
 2195:       
 2196:       dateintsum=0;
 2197:       k2cpt=0;
 2198:       for (i=1; i<=imx; i++) {
 2199: 	bool=1;
 2200: 	if  (cptcovn>0) {
 2201: 	  for (z1=1; z1<=cptcoveff; z1++) 
 2202: 	    if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
 2203: 	      bool=0;
 2204: 	}
 2205: 	if (bool==1){
 2206: 	  for(m=firstpass; m<=lastpass; m++){
 2207: 	    k2=anint[m][i]+(mint[m][i]/12.);
 2208: 	    /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
 2209: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 2210: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 2211: 	      if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
 2212: 	      if (m<lastpass) {
 2213: 		freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
 2214: 		freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
 2215: 	      }
 2216: 	      
 2217: 	      if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
 2218: 		dateintsum=dateintsum+k2;
 2219: 		k2cpt++;
 2220: 	      }
 2221: 	      /*}*/
 2222: 	  }
 2223: 	}
 2224:       }
 2225:        
 2226:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
 2227:       pstamp(ficresp);
 2228:       if  (cptcovn>0) {
 2229: 	fprintf(ficresp, "\n#********** Variable "); 
 2230: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 2231: 	fprintf(ficresp, "**********\n#");
 2232:       }
 2233:       for(i=1; i<=nlstate;i++) 
 2234: 	fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
 2235:       fprintf(ficresp, "\n");
 2236:       
 2237:       for(i=iagemin; i <= iagemax+3; i++){
 2238: 	if(i==iagemax+3){
 2239: 	  fprintf(ficlog,"Total");
 2240: 	}else{
 2241: 	  if(first==1){
 2242: 	    first=0;
 2243: 	    printf("See log file for details...\n");
 2244: 	  }
 2245: 	  fprintf(ficlog,"Age %d", i);
 2246: 	}
 2247: 	for(jk=1; jk <=nlstate ; jk++){
 2248: 	  for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
 2249: 	    pp[jk] += freq[jk][m][i]; 
 2250: 	}
 2251: 	for(jk=1; jk <=nlstate ; jk++){
 2252: 	  for(m=-1, pos=0; m <=0 ; m++)
 2253: 	    pos += freq[jk][m][i];
 2254: 	  if(pp[jk]>=1.e-10){
 2255: 	    if(first==1){
 2256: 	      printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 2257: 	    }
 2258: 	    fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 2259: 	  }else{
 2260: 	    if(first==1)
 2261: 	      printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 2262: 	    fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 2263: 	  }
 2264: 	}
 2265: 
 2266: 	for(jk=1; jk <=nlstate ; jk++){
 2267: 	  for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
 2268: 	    pp[jk] += freq[jk][m][i];
 2269: 	}	
 2270: 	for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
 2271: 	  pos += pp[jk];
 2272: 	  posprop += prop[jk][i];
 2273: 	}
 2274: 	for(jk=1; jk <=nlstate ; jk++){
 2275: 	  if(pos>=1.e-5){
 2276: 	    if(first==1)
 2277: 	      printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 2278: 	    fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 2279: 	  }else{
 2280: 	    if(first==1)
 2281: 	      printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 2282: 	    fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 2283: 	  }
 2284: 	  if( i <= iagemax){
 2285: 	    if(pos>=1.e-5){
 2286: 	      fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
 2287: 	      /*probs[i][jk][j1]= pp[jk]/pos;*/
 2288: 	      /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
 2289: 	    }
 2290: 	    else
 2291: 	      fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
 2292: 	  }
 2293: 	}
 2294: 	
 2295: 	for(jk=-1; jk <=nlstate+ndeath; jk++)
 2296: 	  for(m=-1; m <=nlstate+ndeath; m++)
 2297: 	    if(freq[jk][m][i] !=0 ) {
 2298: 	    if(first==1)
 2299: 	      printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
 2300: 	      fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
 2301: 	    }
 2302: 	if(i <= iagemax)
 2303: 	  fprintf(ficresp,"\n");
 2304: 	if(first==1)
 2305: 	  printf("Others in log...\n");
 2306: 	fprintf(ficlog,"\n");
 2307:       }
 2308:     }
 2309:   }
 2310:   dateintmean=dateintsum/k2cpt; 
 2311:  
 2312:   fclose(ficresp);
 2313:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
 2314:   free_vector(pp,1,nlstate);
 2315:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
 2316:   /* End of Freq */
 2317: }
 2318: 
 2319: /************ Prevalence ********************/
 2320: void prevalence(double ***probs, double agemin, double agemax, int **s, double **agev, int nlstate, int imx, int *Tvar, int **nbcode, int *ncodemax,double **mint,double **anint, double dateprev1,double dateprev2, int firstpass, int lastpass)
 2321: {  
 2322:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 2323:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 2324:      We still use firstpass and lastpass as another selection.
 2325:   */
 2326:  
 2327:   int i, m, jk, k1, i1, j1, bool, z1,j;
 2328:   double ***freq; /* Frequencies */
 2329:   double *pp, **prop;
 2330:   double pos,posprop; 
 2331:   double  y2; /* in fractional years */
 2332:   int iagemin, iagemax;
 2333: 
 2334:   iagemin= (int) agemin;
 2335:   iagemax= (int) agemax;
 2336:   /*pp=vector(1,nlstate);*/
 2337:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
 2338:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
 2339:   j1=0;
 2340:   
 2341:   j=cptcoveff;
 2342:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 2343:   
 2344:   for(k1=1; k1<=j;k1++){
 2345:     for(i1=1; i1<=ncodemax[k1];i1++){
 2346:       j1++;
 2347:       
 2348:       for (i=1; i<=nlstate; i++)  
 2349: 	for(m=iagemin; m <= iagemax+3; m++)
 2350: 	  prop[i][m]=0.0;
 2351:      
 2352:       for (i=1; i<=imx; i++) { /* Each individual */
 2353: 	bool=1;
 2354: 	if  (cptcovn>0) {
 2355: 	  for (z1=1; z1<=cptcoveff; z1++) 
 2356: 	    if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
 2357: 	      bool=0;
 2358: 	} 
 2359: 	if (bool==1) { 
 2360: 	  for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
 2361: 	    y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
 2362: 	    if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
 2363: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 2364: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 2365: 	      if((int)agev[m][i] <iagemin || (int)agev[m][i] >iagemax+3) printf("Error on individual =%d agev[m][i]=%f m=%d\n",i, agev[m][i],m); 
 2366:  	      if (s[m][i]>0 && s[m][i]<=nlstate) { 
 2367: 		/*if(i>4620) printf(" i=%d m=%d s[m][i]=%d (int)agev[m][i]=%d weight[i]=%f prop=%f\n",i,m,s[m][i],(int)agev[m][m],weight[i],prop[s[m][i]][(int)agev[m][i]]);*/
 2368:  		prop[s[m][i]][(int)agev[m][i]] += weight[i];
 2369:  		prop[s[m][i]][iagemax+3] += weight[i]; 
 2370:  	      } 
 2371: 	    }
 2372: 	  } /* end selection of waves */
 2373: 	}
 2374:       }
 2375:       for(i=iagemin; i <= iagemax+3; i++){  
 2376: 	
 2377:  	for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
 2378:  	  posprop += prop[jk][i]; 
 2379:  	} 
 2380: 
 2381:  	for(jk=1; jk <=nlstate ; jk++){	    
 2382:  	  if( i <=  iagemax){ 
 2383:  	    if(posprop>=1.e-5){ 
 2384:  	      probs[i][jk][j1]= prop[jk][i]/posprop;
 2385:  	    } else
 2386: 	      printf("Warning Observed prevalence probs[%d][%d][%d]=%lf because of lack of cases\n",jk,i,j1,probs[i][jk][j1]);
 2387:  	  } 
 2388:  	}/* end jk */ 
 2389:       }/* end i */ 
 2390:     } /* end i1 */
 2391:   } /* end k1 */
 2392:   
 2393:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
 2394:   /*free_vector(pp,1,nlstate);*/
 2395:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
 2396: }  /* End of prevalence */
 2397: 
 2398: /************* Waves Concatenation ***************/
 2399: 
 2400: void  concatwav(int wav[], int **dh, int **bh,  int **mw, int **s, double *agedc, double **agev, int  firstpass, int lastpass, int imx, int nlstate, int stepm)
 2401: {
 2402:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
 2403:      Death is a valid wave (if date is known).
 2404:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
 2405:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 2406:      and mw[mi+1][i]. dh depends on stepm.
 2407:      */
 2408: 
 2409:   int i, mi, m;
 2410:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
 2411:      double sum=0., jmean=0.;*/
 2412:   int first;
 2413:   int j, k=0,jk, ju, jl;
 2414:   double sum=0.;
 2415:   first=0;
 2416:   jmin=1e+5;
 2417:   jmax=-1;
 2418:   jmean=0.;
 2419:   for(i=1; i<=imx; i++){
 2420:     mi=0;
 2421:     m=firstpass;
 2422:     while(s[m][i] <= nlstate){
 2423:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
 2424: 	mw[++mi][i]=m;
 2425:       if(m >=lastpass)
 2426: 	break;
 2427:       else
 2428: 	m++;
 2429:     }/* end while */
 2430:     if (s[m][i] > nlstate){
 2431:       mi++;	/* Death is another wave */
 2432:       /* if(mi==0)  never been interviewed correctly before death */
 2433: 	 /* Only death is a correct wave */
 2434:       mw[mi][i]=m;
 2435:     }
 2436: 
 2437:     wav[i]=mi;
 2438:     if(mi==0){
 2439:       nbwarn++;
 2440:       if(first==0){
 2441: 	printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
 2442: 	first=1;
 2443:       }
 2444:       if(first==1){
 2445: 	fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
 2446:       }
 2447:     } /* end mi==0 */
 2448:   } /* End individuals */
 2449: 
 2450:   for(i=1; i<=imx; i++){
 2451:     for(mi=1; mi<wav[i];mi++){
 2452:       if (stepm <=0)
 2453: 	dh[mi][i]=1;
 2454:       else{
 2455: 	if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
 2456: 	  if (agedc[i] < 2*AGESUP) {
 2457: 	    j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
 2458: 	    if(j==0) j=1;  /* Survives at least one month after exam */
 2459: 	    else if(j<0){
 2460: 	      nberr++;
 2461: 	      printf("Error! Negative delay (%d to death) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
 2462: 	      j=1; /* Temporary Dangerous patch */
 2463: 	      printf("   We assumed that the date of interview was correct (and not the date of death) and postponed the death %d month(s) (one stepm) after the interview. You MUST fix the contradiction between dates.\n",stepm);
 2464: 	      fprintf(ficlog,"Error! Negative delay (%d to death) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
 2465: 	      fprintf(ficlog,"   We assumed that the date of interview was correct (and not the date of death) and postponed the death %d month(s) (one stepm) after the interview. You MUST fix the contradiction between dates.\n",stepm);
 2466: 	    }
 2467: 	    k=k+1;
 2468: 	    if (j >= jmax){
 2469: 	      jmax=j;
 2470: 	      ijmax=i;
 2471: 	    }
 2472: 	    if (j <= jmin){
 2473: 	      jmin=j;
 2474: 	      ijmin=i;
 2475: 	    }
 2476: 	    sum=sum+j;
 2477: 	    /*if (j<0) printf("j=%d num=%d \n",j,i);*/
 2478: 	    /*	  printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
 2479: 	  }
 2480: 	}
 2481: 	else{
 2482: 	  j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
 2483: /* 	  if (j<0) printf("%d %lf %lf %d %d %d\n", i,agev[mw[mi+1][i]][i], agev[mw[mi][i]][i],j,s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]); */
 2484: 
 2485: 	  k=k+1;
 2486: 	  if (j >= jmax) {
 2487: 	    jmax=j;
 2488: 	    ijmax=i;
 2489: 	  }
 2490: 	  else if (j <= jmin){
 2491: 	    jmin=j;
 2492: 	    ijmin=i;
 2493: 	  }
 2494: 	  /*	    if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
 2495: 	  /*printf("%d %lf %d %d %d\n", i,agev[mw[mi][i]][i],j,s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);*/
 2496: 	  if(j<0){
 2497: 	    nberr++;
 2498: 	    printf("Error! Negative delay (%d) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
 2499: 	    fprintf(ficlog,"Error! Negative delay (%d) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
 2500: 	  }
 2501: 	  sum=sum+j;
 2502: 	}
 2503: 	jk= j/stepm;
 2504: 	jl= j -jk*stepm;
 2505: 	ju= j -(jk+1)*stepm;
 2506: 	if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
 2507: 	  if(jl==0){
 2508: 	    dh[mi][i]=jk;
 2509: 	    bh[mi][i]=0;
 2510: 	  }else{ /* We want a negative bias in order to only have interpolation ie
 2511: 		  * to avoid the price of an extra matrix product in likelihood */
 2512: 	    dh[mi][i]=jk+1;
 2513: 	    bh[mi][i]=ju;
 2514: 	  }
 2515: 	}else{
 2516: 	  if(jl <= -ju){
 2517: 	    dh[mi][i]=jk;
 2518: 	    bh[mi][i]=jl;	/* bias is positive if real duration
 2519: 				 * is higher than the multiple of stepm and negative otherwise.
 2520: 				 */
 2521: 	  }
 2522: 	  else{
 2523: 	    dh[mi][i]=jk+1;
 2524: 	    bh[mi][i]=ju;
 2525: 	  }
 2526: 	  if(dh[mi][i]==0){
 2527: 	    dh[mi][i]=1; /* At least one step */
 2528: 	    bh[mi][i]=ju; /* At least one step */
 2529: 	    /*  printf(" bh=%d ju=%d jl=%d dh=%d jk=%d stepm=%d %d\n",bh[mi][i],ju,jl,dh[mi][i],jk,stepm,i);*/
 2530: 	  }
 2531: 	} /* end if mle */
 2532:       }
 2533:     } /* end wave */
 2534:   }
 2535:   jmean=sum/k;
 2536:   printf("Delay (in months) between two waves Min=%d (for indiviudal %ld) Max=%d (%ld) Mean=%f\n\n ",jmin, num[ijmin], jmax, num[ijmax], jmean);
 2537:   fprintf(ficlog,"Delay (in months) between two waves Min=%d (for indiviudal %ld) Max=%d (%ld) Mean=%f\n\n ",jmin, ijmin, jmax, ijmax, jmean);
 2538:  }
 2539: 
 2540: /*********** Tricode ****************************/
 2541: void tricode(int *Tvar, int **nbcode, int imx)
 2542: {
 2543:   /* Uses cptcovn+2*cptcovprod as the number of covariates */
 2544:   /*	  Tvar[i]=atoi(stre); /* find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 */
 2545: 
 2546:   int Ndum[20],ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
 2547:   int modmaxcovj=0; /* Modality max of covariates j */
 2548:   cptcoveff=0; 
 2549:  
 2550:   for (k=0; k<maxncov; k++) Ndum[k]=0;
 2551:   for (k=1; k<=7; k++) ncodemax[k]=0; /* Horrible constant again */
 2552: 
 2553:   for (j=1; j<=(cptcovn+2*cptcovprod); j++) { /* For each covariate j */
 2554:     for (i=1; i<=imx; i++) { /*reads the data file to get the maximum value of the 
 2555: 			       modality of this covariate Vj*/ 
 2556:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Finds for covariate j, n=Tvar[j] of Vn . ij is the
 2557: 				      modality of the nth covariate of individual i. */
 2558:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
 2559:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
 2560:       if (ij > modmaxcovj) modmaxcovj=ij; 
 2561:       /* getting the maximum value of the modality of the covariate
 2562: 	 (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
 2563: 	 female is 1, then modmaxcovj=1.*/
 2564:     }
 2565:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
 2566:     for (i=0; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each modality of model-cov j */
 2567:       if( Ndum[i] != 0 )
 2568: 	ncodemax[j]++; 
 2569:       /* Number of modalities of the j th covariate. In fact
 2570: 	 ncodemax[j]=2 (dichotom. variables only) but it could be more for
 2571: 	 historical reasons */
 2572:     } /* Ndum[-1] number of undefined modalities */
 2573: 
 2574:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
 2575:     ij=1; 
 2576:     for (i=1; i<=ncodemax[j]; i++) { /* i= 1 to 2 for dichotomous */
 2577:       for (k=0; k<= modmaxcovj; k++) { /* k=-1 ? NCOVMAX*//* maxncov or modmaxcovj */
 2578: 	if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
 2579: 	  nbcode[Tvar[j]][ij]=k;  /* stores the modality in an array nbcode. 
 2580: 				     k is a modality. If we have model=V1+V1*sex 
 2581: 				     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
 2582: 	  ij++;
 2583: 	}
 2584: 	if (ij > ncodemax[j]) break; 
 2585:       }  /* end of loop on */
 2586:     } /* end of loop on modality */ 
 2587:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
 2588:   
 2589:   for (k=0; k< maxncov; k++) Ndum[k]=0;
 2590:   
 2591:   for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */
 2592:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
 2593:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
 2594:    Ndum[ij]++;
 2595:  }
 2596: 
 2597:  ij=1;
 2598:  for (i=1; i<= maxncov; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
 2599:    if((Ndum[i]!=0) && (i<=ncovcol)){
 2600:      Tvaraff[ij]=i; /*For printing */
 2601:      ij++;
 2602:    }
 2603:  }
 2604:  ij--;
 2605:  cptcoveff=ij; /*Number of simple covariates*/
 2606: }
 2607: 
 2608: /*********** Health Expectancies ****************/
 2609: 
 2610: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
 2611: 
 2612: {
 2613:   /* Health expectancies, no variances */
 2614:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;
 2615:   int nhstepma, nstepma; /* Decreasing with age */
 2616:   double age, agelim, hf;
 2617:   double ***p3mat;
 2618:   double eip;
 2619: 
 2620:   pstamp(ficreseij);
 2621:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
 2622:   fprintf(ficreseij,"# Age");
 2623:   for(i=1; i<=nlstate;i++){
 2624:     for(j=1; j<=nlstate;j++){
 2625:       fprintf(ficreseij," e%1d%1d ",i,j);
 2626:     }
 2627:     fprintf(ficreseij," e%1d. ",i);
 2628:   }
 2629:   fprintf(ficreseij,"\n");
 2630: 
 2631:   
 2632:   if(estepm < stepm){
 2633:     printf ("Problem %d lower than %d\n",estepm, stepm);
 2634:   }
 2635:   else  hstepm=estepm;   
 2636:   /* We compute the life expectancy from trapezoids spaced every estepm months
 2637:    * This is mainly to measure the difference between two models: for example
 2638:    * if stepm=24 months pijx are given only every 2 years and by summing them
 2639:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 2640:    * progression in between and thus overestimating or underestimating according
 2641:    * to the curvature of the survival function. If, for the same date, we 
 2642:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 2643:    * to compare the new estimate of Life expectancy with the same linear 
 2644:    * hypothesis. A more precise result, taking into account a more precise
 2645:    * curvature will be obtained if estepm is as small as stepm. */
 2646: 
 2647:   /* For example we decided to compute the life expectancy with the smallest unit */
 2648:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 2649:      nhstepm is the number of hstepm from age to agelim 
 2650:      nstepm is the number of stepm from age to agelin. 
 2651:      Look at hpijx to understand the reason of that which relies in memory size
 2652:      and note for a fixed period like estepm months */
 2653:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 2654:      survival function given by stepm (the optimization length). Unfortunately it
 2655:      means that if the survival funtion is printed only each two years of age and if
 2656:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 2657:      results. So we changed our mind and took the option of the best precision.
 2658:   */
 2659:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 2660: 
 2661:   agelim=AGESUP;
 2662:   /* If stepm=6 months */
 2663:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
 2664:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
 2665:     
 2666: /* nhstepm age range expressed in number of stepm */
 2667:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 2668:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 2669:   /* if (stepm >= YEARM) hstepm=1;*/
 2670:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 2671:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 2672: 
 2673:   for (age=bage; age<=fage; age ++){ 
 2674:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 2675:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 2676:     /* if (stepm >= YEARM) hstepm=1;*/
 2677:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 2678: 
 2679:     /* If stepm=6 months */
 2680:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 2681:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 2682:     
 2683:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 2684:     
 2685:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 2686:     
 2687:     printf("%d|",(int)age);fflush(stdout);
 2688:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 2689:     
 2690:     /* Computing expectancies */
 2691:     for(i=1; i<=nlstate;i++)
 2692:       for(j=1; j<=nlstate;j++)
 2693: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 2694: 	  eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
 2695: 	  
 2696: 	  /* if((int)age==70)printf("i=%2d,j=%2d,h=%2d,age=%3d,%9.4f,%9.4f,%9.4f\n",i,j,h,(int)age,p3mat[i][j][h],hf,eij[i][j][(int)age]);*/
 2697: 
 2698: 	}
 2699: 
 2700:     fprintf(ficreseij,"%3.0f",age );
 2701:     for(i=1; i<=nlstate;i++){
 2702:       eip=0;
 2703:       for(j=1; j<=nlstate;j++){
 2704: 	eip +=eij[i][j][(int)age];
 2705: 	fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
 2706:       }
 2707:       fprintf(ficreseij,"%9.4f", eip );
 2708:     }
 2709:     fprintf(ficreseij,"\n");
 2710:     
 2711:   }
 2712:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 2713:   printf("\n");
 2714:   fprintf(ficlog,"\n");
 2715:   
 2716: }
 2717: 
 2718: void cvevsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,double delti[],double **matcov,char strstart[] )
 2719: 
 2720: {
 2721:   /* Covariances of health expectancies eij and of total life expectancies according
 2722:    to initial status i, ei. .
 2723:   */
 2724:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
 2725:   int nhstepma, nstepma; /* Decreasing with age */
 2726:   double age, agelim, hf;
 2727:   double ***p3matp, ***p3matm, ***varhe;
 2728:   double **dnewm,**doldm;
 2729:   double *xp, *xm;
 2730:   double **gp, **gm;
 2731:   double ***gradg, ***trgradg;
 2732:   int theta;
 2733: 
 2734:   double eip, vip;
 2735: 
 2736:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
 2737:   xp=vector(1,npar);
 2738:   xm=vector(1,npar);
 2739:   dnewm=matrix(1,nlstate*nlstate,1,npar);
 2740:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
 2741:   
 2742:   pstamp(ficresstdeij);
 2743:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
 2744:   fprintf(ficresstdeij,"# Age");
 2745:   for(i=1; i<=nlstate;i++){
 2746:     for(j=1; j<=nlstate;j++)
 2747:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
 2748:     fprintf(ficresstdeij," e%1d. ",i);
 2749:   }
 2750:   fprintf(ficresstdeij,"\n");
 2751: 
 2752:   pstamp(ficrescveij);
 2753:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
 2754:   fprintf(ficrescveij,"# Age");
 2755:   for(i=1; i<=nlstate;i++)
 2756:     for(j=1; j<=nlstate;j++){
 2757:       cptj= (j-1)*nlstate+i;
 2758:       for(i2=1; i2<=nlstate;i2++)
 2759: 	for(j2=1; j2<=nlstate;j2++){
 2760: 	  cptj2= (j2-1)*nlstate+i2;
 2761: 	  if(cptj2 <= cptj)
 2762: 	    fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
 2763: 	}
 2764:     }
 2765:   fprintf(ficrescveij,"\n");
 2766:   
 2767:   if(estepm < stepm){
 2768:     printf ("Problem %d lower than %d\n",estepm, stepm);
 2769:   }
 2770:   else  hstepm=estepm;   
 2771:   /* We compute the life expectancy from trapezoids spaced every estepm months
 2772:    * This is mainly to measure the difference between two models: for example
 2773:    * if stepm=24 months pijx are given only every 2 years and by summing them
 2774:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 2775:    * progression in between and thus overestimating or underestimating according
 2776:    * to the curvature of the survival function. If, for the same date, we 
 2777:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 2778:    * to compare the new estimate of Life expectancy with the same linear 
 2779:    * hypothesis. A more precise result, taking into account a more precise
 2780:    * curvature will be obtained if estepm is as small as stepm. */
 2781: 
 2782:   /* For example we decided to compute the life expectancy with the smallest unit */
 2783:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 2784:      nhstepm is the number of hstepm from age to agelim 
 2785:      nstepm is the number of stepm from age to agelin. 
 2786:      Look at hpijx to understand the reason of that which relies in memory size
 2787:      and note for a fixed period like estepm months */
 2788:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 2789:      survival function given by stepm (the optimization length). Unfortunately it
 2790:      means that if the survival funtion is printed only each two years of age and if
 2791:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 2792:      results. So we changed our mind and took the option of the best precision.
 2793:   */
 2794:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 2795: 
 2796:   /* If stepm=6 months */
 2797:   /* nhstepm age range expressed in number of stepm */
 2798:   agelim=AGESUP;
 2799:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
 2800:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 2801:   /* if (stepm >= YEARM) hstepm=1;*/
 2802:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 2803:   
 2804:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 2805:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 2806:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
 2807:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
 2808:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
 2809:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
 2810: 
 2811:   for (age=bage; age<=fage; age ++){ 
 2812:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 2813:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 2814:     /* if (stepm >= YEARM) hstepm=1;*/
 2815:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 2816: 
 2817:     /* If stepm=6 months */
 2818:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 2819:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 2820:     
 2821:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 2822: 
 2823:     /* Computing  Variances of health expectancies */
 2824:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
 2825:        decrease memory allocation */
 2826:     for(theta=1; theta <=npar; theta++){
 2827:       for(i=1; i<=npar; i++){ 
 2828: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 2829: 	xm[i] = x[i] - (i==theta ?delti[theta]:0);
 2830:       }
 2831:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
 2832:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
 2833:   
 2834:       for(j=1; j<= nlstate; j++){
 2835: 	for(i=1; i<=nlstate; i++){
 2836: 	  for(h=0; h<=nhstepm-1; h++){
 2837: 	    gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
 2838: 	    gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
 2839: 	  }
 2840: 	}
 2841:       }
 2842:      
 2843:       for(ij=1; ij<= nlstate*nlstate; ij++)
 2844: 	for(h=0; h<=nhstepm-1; h++){
 2845: 	  gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
 2846: 	}
 2847:     }/* End theta */
 2848:     
 2849:     
 2850:     for(h=0; h<=nhstepm-1; h++)
 2851:       for(j=1; j<=nlstate*nlstate;j++)
 2852: 	for(theta=1; theta <=npar; theta++)
 2853: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 2854:     
 2855: 
 2856:      for(ij=1;ij<=nlstate*nlstate;ij++)
 2857:       for(ji=1;ji<=nlstate*nlstate;ji++)
 2858: 	varhe[ij][ji][(int)age] =0.;
 2859: 
 2860:      printf("%d|",(int)age);fflush(stdout);
 2861:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 2862:      for(h=0;h<=nhstepm-1;h++){
 2863:       for(k=0;k<=nhstepm-1;k++){
 2864: 	matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
 2865: 	matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
 2866: 	for(ij=1;ij<=nlstate*nlstate;ij++)
 2867: 	  for(ji=1;ji<=nlstate*nlstate;ji++)
 2868: 	    varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
 2869:       }
 2870:     }
 2871: 
 2872:     /* Computing expectancies */
 2873:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 2874:     for(i=1; i<=nlstate;i++)
 2875:       for(j=1; j<=nlstate;j++)
 2876: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 2877: 	  eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
 2878: 	  
 2879: 	  /* if((int)age==70)printf("i=%2d,j=%2d,h=%2d,age=%3d,%9.4f,%9.4f,%9.4f\n",i,j,h,(int)age,p3mat[i][j][h],hf,eij[i][j][(int)age]);*/
 2880: 
 2881: 	}
 2882: 
 2883:     fprintf(ficresstdeij,"%3.0f",age );
 2884:     for(i=1; i<=nlstate;i++){
 2885:       eip=0.;
 2886:       vip=0.;
 2887:       for(j=1; j<=nlstate;j++){
 2888: 	eip += eij[i][j][(int)age];
 2889: 	for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
 2890: 	  vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
 2891: 	fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
 2892:       }
 2893:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
 2894:     }
 2895:     fprintf(ficresstdeij,"\n");
 2896: 
 2897:     fprintf(ficrescveij,"%3.0f",age );
 2898:     for(i=1; i<=nlstate;i++)
 2899:       for(j=1; j<=nlstate;j++){
 2900: 	cptj= (j-1)*nlstate+i;
 2901: 	for(i2=1; i2<=nlstate;i2++)
 2902: 	  for(j2=1; j2<=nlstate;j2++){
 2903: 	    cptj2= (j2-1)*nlstate+i2;
 2904: 	    if(cptj2 <= cptj)
 2905: 	      fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
 2906: 	  }
 2907:       }
 2908:     fprintf(ficrescveij,"\n");
 2909:    
 2910:   }
 2911:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
 2912:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
 2913:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
 2914:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
 2915:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 2916:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 2917:   printf("\n");
 2918:   fprintf(ficlog,"\n");
 2919: 
 2920:   free_vector(xm,1,npar);
 2921:   free_vector(xp,1,npar);
 2922:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
 2923:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
 2924:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
 2925: }
 2926: 
 2927: /************ Variance ******************/
 2928: void varevsij(char optionfilefiname[], double ***vareij, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int ij, int estepm, int cptcov, int cptcod, int popbased, int mobilav, char strstart[])
 2929: {
 2930:   /* Variance of health expectancies */
 2931:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
 2932:   /* double **newm;*/
 2933:   double **dnewm,**doldm;
 2934:   double **dnewmp,**doldmp;
 2935:   int i, j, nhstepm, hstepm, h, nstepm ;
 2936:   int k, cptcode;
 2937:   double *xp;
 2938:   double **gp, **gm;  /* for var eij */
 2939:   double ***gradg, ***trgradg; /*for var eij */
 2940:   double **gradgp, **trgradgp; /* for var p point j */
 2941:   double *gpp, *gmp; /* for var p point j */
 2942:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
 2943:   double ***p3mat;
 2944:   double age,agelim, hf;
 2945:   double ***mobaverage;
 2946:   int theta;
 2947:   char digit[4];
 2948:   char digitp[25];
 2949: 
 2950:   char fileresprobmorprev[FILENAMELENGTH];
 2951: 
 2952:   if(popbased==1){
 2953:     if(mobilav!=0)
 2954:       strcpy(digitp,"-populbased-mobilav-");
 2955:     else strcpy(digitp,"-populbased-nomobil-");
 2956:   }
 2957:   else 
 2958:     strcpy(digitp,"-stablbased-");
 2959: 
 2960:   if (mobilav!=0) {
 2961:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 2962:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 2963:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 2964:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 2965:     }
 2966:   }
 2967: 
 2968:   strcpy(fileresprobmorprev,"prmorprev"); 
 2969:   sprintf(digit,"%-d",ij);
 2970:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
 2971:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
 2972:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
 2973:   strcat(fileresprobmorprev,fileres);
 2974:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
 2975:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
 2976:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
 2977:   }
 2978:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 2979:  
 2980:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 2981:   pstamp(ficresprobmorprev);
 2982:   fprintf(ficresprobmorprev,"# probabilities of dying before estepm=%d months for people of exact age and weighted probabilities w1*p1j+w2*p2j+... stand dev in()\n",estepm);
 2983:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
 2984:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 2985:     fprintf(ficresprobmorprev," p.%-d SE",j);
 2986:     for(i=1; i<=nlstate;i++)
 2987:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
 2988:   }  
 2989:   fprintf(ficresprobmorprev,"\n");
 2990:   fprintf(ficgp,"\n# Routine varevsij");
 2991:   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
 2992:   fprintf(fichtm,"\n<li><h4> Computing probabilities of dying over estepm months as a weighted average (i.e global mortality independent of initial healh state)</h4></li>\n");
 2993:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
 2994: /*   } */
 2995:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 2996:   pstamp(ficresvij);
 2997:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
 2998:   if(popbased==1)
 2999:     fprintf(ficresvij,"the age specific prevalence observed (cross-sectionally) in the population i.e cross-sectionally\n in each health state (popbased=1) (mobilav=%d\n",mobilav);
 3000:   else
 3001:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
 3002:   fprintf(ficresvij,"# Age");
 3003:   for(i=1; i<=nlstate;i++)
 3004:     for(j=1; j<=nlstate;j++)
 3005:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
 3006:   fprintf(ficresvij,"\n");
 3007: 
 3008:   xp=vector(1,npar);
 3009:   dnewm=matrix(1,nlstate,1,npar);
 3010:   doldm=matrix(1,nlstate,1,nlstate);
 3011:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
 3012:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3013: 
 3014:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
 3015:   gpp=vector(nlstate+1,nlstate+ndeath);
 3016:   gmp=vector(nlstate+1,nlstate+ndeath);
 3017:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 3018:   
 3019:   if(estepm < stepm){
 3020:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3021:   }
 3022:   else  hstepm=estepm;   
 3023:   /* For example we decided to compute the life expectancy with the smallest unit */
 3024:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3025:      nhstepm is the number of hstepm from age to agelim 
 3026:      nstepm is the number of stepm from age to agelin. 
 3027:      Look at function hpijx to understand why (it is linked to memory size questions) */
 3028:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3029:      survival function given by stepm (the optimization length). Unfortunately it
 3030:      means that if the survival funtion is printed every two years of age and if
 3031:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3032:      results. So we changed our mind and took the option of the best precision.
 3033:   */
 3034:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3035:   agelim = AGESUP;
 3036:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 3037:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 3038:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3039:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3040:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
 3041:     gp=matrix(0,nhstepm,1,nlstate);
 3042:     gm=matrix(0,nhstepm,1,nlstate);
 3043: 
 3044: 
 3045:     for(theta=1; theta <=npar; theta++){
 3046:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
 3047: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 3048:       }
 3049:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 3050:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3051: 
 3052:       if (popbased==1) {
 3053: 	if(mobilav ==0){
 3054: 	  for(i=1; i<=nlstate;i++)
 3055: 	    prlim[i][i]=probs[(int)age][i][ij];
 3056: 	}else{ /* mobilav */ 
 3057: 	  for(i=1; i<=nlstate;i++)
 3058: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 3059: 	}
 3060:       }
 3061:   
 3062:       for(j=1; j<= nlstate; j++){
 3063: 	for(h=0; h<=nhstepm; h++){
 3064: 	  for(i=1, gp[h][j]=0.;i<=nlstate;i++)
 3065: 	    gp[h][j] += prlim[i][i]*p3mat[i][j][h];
 3066: 	}
 3067:       }
 3068:       /* This for computing probability of death (h=1 means
 3069:          computed over hstepm matrices product = hstepm*stepm months) 
 3070:          as a weighted average of prlim.
 3071:       */
 3072:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3073: 	for(i=1,gpp[j]=0.; i<= nlstate; i++)
 3074: 	  gpp[j] += prlim[i][i]*p3mat[i][j][1];
 3075:       }    
 3076:       /* end probability of death */
 3077: 
 3078:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
 3079: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 3080:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 3081:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3082:  
 3083:       if (popbased==1) {
 3084: 	if(mobilav ==0){
 3085: 	  for(i=1; i<=nlstate;i++)
 3086: 	    prlim[i][i]=probs[(int)age][i][ij];
 3087: 	}else{ /* mobilav */ 
 3088: 	  for(i=1; i<=nlstate;i++)
 3089: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 3090: 	}
 3091:       }
 3092: 
 3093:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
 3094: 	for(h=0; h<=nhstepm; h++){
 3095: 	  for(i=1, gm[h][j]=0.;i<=nlstate;i++)
 3096: 	    gm[h][j] += prlim[i][i]*p3mat[i][j][h];
 3097: 	}
 3098:       }
 3099:       /* This for computing probability of death (h=1 means
 3100:          computed over hstepm matrices product = hstepm*stepm months) 
 3101:          as a weighted average of prlim.
 3102:       */
 3103:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3104: 	for(i=1,gmp[j]=0.; i<= nlstate; i++)
 3105:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
 3106:       }    
 3107:       /* end probability of death */
 3108: 
 3109:       for(j=1; j<= nlstate; j++) /* vareij */
 3110: 	for(h=0; h<=nhstepm; h++){
 3111: 	  gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
 3112: 	}
 3113: 
 3114:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
 3115: 	gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
 3116:       }
 3117: 
 3118:     } /* End theta */
 3119: 
 3120:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
 3121: 
 3122:     for(h=0; h<=nhstepm; h++) /* veij */
 3123:       for(j=1; j<=nlstate;j++)
 3124: 	for(theta=1; theta <=npar; theta++)
 3125: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 3126: 
 3127:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
 3128:       for(theta=1; theta <=npar; theta++)
 3129: 	trgradgp[j][theta]=gradgp[theta][j];
 3130:   
 3131: 
 3132:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3133:     for(i=1;i<=nlstate;i++)
 3134:       for(j=1;j<=nlstate;j++)
 3135: 	vareij[i][j][(int)age] =0.;
 3136: 
 3137:     for(h=0;h<=nhstepm;h++){
 3138:       for(k=0;k<=nhstepm;k++){
 3139: 	matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
 3140: 	matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
 3141: 	for(i=1;i<=nlstate;i++)
 3142: 	  for(j=1;j<=nlstate;j++)
 3143: 	    vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
 3144:       }
 3145:     }
 3146:   
 3147:     /* pptj */
 3148:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
 3149:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
 3150:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
 3151:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
 3152: 	varppt[j][i]=doldmp[j][i];
 3153:     /* end ppptj */
 3154:     /*  x centered again */
 3155:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
 3156:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
 3157:  
 3158:     if (popbased==1) {
 3159:       if(mobilav ==0){
 3160: 	for(i=1; i<=nlstate;i++)
 3161: 	  prlim[i][i]=probs[(int)age][i][ij];
 3162:       }else{ /* mobilav */ 
 3163: 	for(i=1; i<=nlstate;i++)
 3164: 	  prlim[i][i]=mobaverage[(int)age][i][ij];
 3165:       }
 3166:     }
 3167:              
 3168:     /* This for computing probability of death (h=1 means
 3169:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
 3170:        as a weighted average of prlim.
 3171:     */
 3172:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3173:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
 3174: 	gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
 3175:     }    
 3176:     /* end probability of death */
 3177: 
 3178:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
 3179:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 3180:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
 3181:       for(i=1; i<=nlstate;i++){
 3182: 	fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
 3183:       }
 3184:     } 
 3185:     fprintf(ficresprobmorprev,"\n");
 3186: 
 3187:     fprintf(ficresvij,"%.0f ",age );
 3188:     for(i=1; i<=nlstate;i++)
 3189:       for(j=1; j<=nlstate;j++){
 3190: 	fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
 3191:       }
 3192:     fprintf(ficresvij,"\n");
 3193:     free_matrix(gp,0,nhstepm,1,nlstate);
 3194:     free_matrix(gm,0,nhstepm,1,nlstate);
 3195:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
 3196:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
 3197:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3198:   } /* End age */
 3199:   free_vector(gpp,nlstate+1,nlstate+ndeath);
 3200:   free_vector(gmp,nlstate+1,nlstate+ndeath);
 3201:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
 3202:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 3203:   fprintf(ficgp,"\nunset parametric;unset label; set ter png small;set size 0.65, 0.65");
 3204:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
 3205:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
 3206: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
 3207: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
 3208: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
 3209:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l 1 ",subdirf(fileresprobmorprev));
 3210:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95\%% interval\" w l 2 ",subdirf(fileresprobmorprev));
 3211:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l 2 ",subdirf(fileresprobmorprev));
 3212:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
 3213:   fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months. <br> <img src=\"%s%s.png\"> <br>\n", estepm,subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
 3214:   /*  fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months and then divided by estepm and multiplied by %.0f in order to have the probability to die over a year <br> <img src=\"varmuptjgr%s%s.png\"> <br>\n", stepm,YEARM,digitp,digit);
 3215: */
 3216: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
 3217:   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
 3218: 
 3219:   free_vector(xp,1,npar);
 3220:   free_matrix(doldm,1,nlstate,1,nlstate);
 3221:   free_matrix(dnewm,1,nlstate,1,npar);
 3222:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3223:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
 3224:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3225:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3226:   fclose(ficresprobmorprev);
 3227:   fflush(ficgp);
 3228:   fflush(fichtm); 
 3229: }  /* end varevsij */
 3230: 
 3231: /************ Variance of prevlim ******************/
 3232: void varprevlim(char fileres[], double **varpl, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int ij, char strstart[])
 3233: {
 3234:   /* Variance of prevalence limit */
 3235:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
 3236:   double **newm;
 3237:   double **dnewm,**doldm;
 3238:   int i, j, nhstepm, hstepm;
 3239:   int k, cptcode;
 3240:   double *xp;
 3241:   double *gp, *gm;
 3242:   double **gradg, **trgradg;
 3243:   double age,agelim;
 3244:   int theta;
 3245:   
 3246:   pstamp(ficresvpl);
 3247:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
 3248:   fprintf(ficresvpl,"# Age");
 3249:   for(i=1; i<=nlstate;i++)
 3250:       fprintf(ficresvpl," %1d-%1d",i,i);
 3251:   fprintf(ficresvpl,"\n");
 3252: 
 3253:   xp=vector(1,npar);
 3254:   dnewm=matrix(1,nlstate,1,npar);
 3255:   doldm=matrix(1,nlstate,1,nlstate);
 3256:   
 3257:   hstepm=1*YEARM; /* Every year of age */
 3258:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
 3259:   agelim = AGESUP;
 3260:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 3261:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 3262:     if (stepm >= YEARM) hstepm=1;
 3263:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 3264:     gradg=matrix(1,npar,1,nlstate);
 3265:     gp=vector(1,nlstate);
 3266:     gm=vector(1,nlstate);
 3267: 
 3268:     for(theta=1; theta <=npar; theta++){
 3269:       for(i=1; i<=npar; i++){ /* Computes gradient */
 3270: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 3271:       }
 3272:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3273:       for(i=1;i<=nlstate;i++)
 3274: 	gp[i] = prlim[i][i];
 3275:     
 3276:       for(i=1; i<=npar; i++) /* Computes gradient */
 3277: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 3278:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3279:       for(i=1;i<=nlstate;i++)
 3280: 	gm[i] = prlim[i][i];
 3281: 
 3282:       for(i=1;i<=nlstate;i++)
 3283: 	gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
 3284:     } /* End theta */
 3285: 
 3286:     trgradg =matrix(1,nlstate,1,npar);
 3287: 
 3288:     for(j=1; j<=nlstate;j++)
 3289:       for(theta=1; theta <=npar; theta++)
 3290: 	trgradg[j][theta]=gradg[theta][j];
 3291: 
 3292:     for(i=1;i<=nlstate;i++)
 3293:       varpl[i][(int)age] =0.;
 3294:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 3295:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 3296:     for(i=1;i<=nlstate;i++)
 3297:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
 3298: 
 3299:     fprintf(ficresvpl,"%.0f ",age );
 3300:     for(i=1; i<=nlstate;i++)
 3301:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
 3302:     fprintf(ficresvpl,"\n");
 3303:     free_vector(gp,1,nlstate);
 3304:     free_vector(gm,1,nlstate);
 3305:     free_matrix(gradg,1,npar,1,nlstate);
 3306:     free_matrix(trgradg,1,nlstate,1,npar);
 3307:   } /* End age */
 3308: 
 3309:   free_vector(xp,1,npar);
 3310:   free_matrix(doldm,1,nlstate,1,npar);
 3311:   free_matrix(dnewm,1,nlstate,1,nlstate);
 3312: 
 3313: }
 3314: 
 3315: /************ Variance of one-step probabilities  ******************/
 3316: void varprob(char optionfilefiname[], double **matcov, double x[], double delti[], int nlstate, double bage, double fage, int ij, int *Tvar, int **nbcode, int *ncodemax, char strstart[])
 3317: {
 3318:   int i, j=0,  i1, k1, l1, t, tj;
 3319:   int k2, l2, j1,  z1;
 3320:   int k=0,l, cptcode;
 3321:   int first=1, first1;
 3322:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
 3323:   double **dnewm,**doldm;
 3324:   double *xp;
 3325:   double *gp, *gm;
 3326:   double **gradg, **trgradg;
 3327:   double **mu;
 3328:   double age,agelim, cov[NCOVMAX];
 3329:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
 3330:   int theta;
 3331:   char fileresprob[FILENAMELENGTH];
 3332:   char fileresprobcov[FILENAMELENGTH];
 3333:   char fileresprobcor[FILENAMELENGTH];
 3334: 
 3335:   double ***varpij;
 3336: 
 3337:   strcpy(fileresprob,"prob"); 
 3338:   strcat(fileresprob,fileres);
 3339:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
 3340:     printf("Problem with resultfile: %s\n", fileresprob);
 3341:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
 3342:   }
 3343:   strcpy(fileresprobcov,"probcov"); 
 3344:   strcat(fileresprobcov,fileres);
 3345:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
 3346:     printf("Problem with resultfile: %s\n", fileresprobcov);
 3347:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
 3348:   }
 3349:   strcpy(fileresprobcor,"probcor"); 
 3350:   strcat(fileresprobcor,fileres);
 3351:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
 3352:     printf("Problem with resultfile: %s\n", fileresprobcor);
 3353:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
 3354:   }
 3355:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 3356:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 3357:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 3358:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 3359:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 3360:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 3361:   pstamp(ficresprob);
 3362:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
 3363:   fprintf(ficresprob,"# Age");
 3364:   pstamp(ficresprobcov);
 3365:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
 3366:   fprintf(ficresprobcov,"# Age");
 3367:   pstamp(ficresprobcor);
 3368:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
 3369:   fprintf(ficresprobcor,"# Age");
 3370: 
 3371: 
 3372:   for(i=1; i<=nlstate;i++)
 3373:     for(j=1; j<=(nlstate+ndeath);j++){
 3374:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
 3375:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
 3376:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
 3377:     }  
 3378:  /* fprintf(ficresprob,"\n");
 3379:   fprintf(ficresprobcov,"\n");
 3380:   fprintf(ficresprobcor,"\n");
 3381:  */
 3382:   xp=vector(1,npar);
 3383:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 3384:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 3385:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
 3386:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
 3387:   first=1;
 3388:   fprintf(ficgp,"\n# Routine varprob");
 3389:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
 3390:   fprintf(fichtm,"\n");
 3391: 
 3392:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
 3393:   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
 3394:   file %s<br>\n",optionfilehtmcov);
 3395:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
 3396: and drawn. It helps understanding how is the covariance between two incidences.\
 3397:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
 3398:   fprintf(fichtmcov,"\n<br> Contour plot corresponding to x'cov<sup>-1</sup>x = 4 (where x is the column vector (pij,pkl)) are drawn. \
 3399: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
 3400: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
 3401: standard deviations wide on each axis. <br>\
 3402:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
 3403:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
 3404: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
 3405: 
 3406:   cov[1]=1;
 3407:   tj=cptcoveff;
 3408:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
 3409:   j1=0;
 3410:   for(t=1; t<=tj;t++){
 3411:     for(i1=1; i1<=ncodemax[t];i1++){ 
 3412:       j1++;
 3413:       if  (cptcovn>0) {
 3414: 	fprintf(ficresprob, "\n#********** Variable "); 
 3415: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3416: 	fprintf(ficresprob, "**********\n#\n");
 3417: 	fprintf(ficresprobcov, "\n#********** Variable "); 
 3418: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3419: 	fprintf(ficresprobcov, "**********\n#\n");
 3420: 	
 3421: 	fprintf(ficgp, "\n#********** Variable "); 
 3422: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3423: 	fprintf(ficgp, "**********\n#\n");
 3424: 	
 3425: 	
 3426: 	fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
 3427: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3428: 	fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
 3429: 	
 3430: 	fprintf(ficresprobcor, "\n#********** Variable ");    
 3431: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3432: 	fprintf(ficresprobcor, "**********\n#");    
 3433:       }
 3434:       
 3435:       for (age=bage; age<=fage; age ++){ 
 3436: 	cov[2]=age;
 3437: 	for (k=1; k<=cptcovn;k++) {
 3438: 	  cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];
 3439: 	}
 3440: 	for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
 3441: 	for (k=1; k<=cptcovprod;k++)
 3442: 	  cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 3443: 	
 3444: 	gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
 3445: 	trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 3446: 	gp=vector(1,(nlstate)*(nlstate+ndeath));
 3447: 	gm=vector(1,(nlstate)*(nlstate+ndeath));
 3448:     
 3449: 	for(theta=1; theta <=npar; theta++){
 3450: 	  for(i=1; i<=npar; i++)
 3451: 	    xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
 3452: 	  
 3453: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 3454: 	  
 3455: 	  k=0;
 3456: 	  for(i=1; i<= (nlstate); i++){
 3457: 	    for(j=1; j<=(nlstate+ndeath);j++){
 3458: 	      k=k+1;
 3459: 	      gp[k]=pmmij[i][j];
 3460: 	    }
 3461: 	  }
 3462: 	  
 3463: 	  for(i=1; i<=npar; i++)
 3464: 	    xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
 3465:     
 3466: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 3467: 	  k=0;
 3468: 	  for(i=1; i<=(nlstate); i++){
 3469: 	    for(j=1; j<=(nlstate+ndeath);j++){
 3470: 	      k=k+1;
 3471: 	      gm[k]=pmmij[i][j];
 3472: 	    }
 3473: 	  }
 3474:      
 3475: 	  for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
 3476: 	    gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
 3477: 	}
 3478: 
 3479: 	for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
 3480: 	  for(theta=1; theta <=npar; theta++)
 3481: 	    trgradg[j][theta]=gradg[theta][j];
 3482: 	
 3483: 	matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
 3484: 	matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
 3485: 	free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
 3486: 	free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
 3487: 	free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 3488: 	free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 3489: 
 3490: 	pmij(pmmij,cov,ncovmodel,x,nlstate);
 3491: 	
 3492: 	k=0;
 3493: 	for(i=1; i<=(nlstate); i++){
 3494: 	  for(j=1; j<=(nlstate+ndeath);j++){
 3495: 	    k=k+1;
 3496: 	    mu[k][(int) age]=pmmij[i][j];
 3497: 	  }
 3498: 	}
 3499:      	for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
 3500: 	  for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
 3501: 	    varpij[i][j][(int)age] = doldm[i][j];
 3502: 
 3503: 	/*printf("\n%d ",(int)age);
 3504: 	  for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 3505: 	  printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 3506: 	  fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 3507: 	  }*/
 3508: 
 3509: 	fprintf(ficresprob,"\n%d ",(int)age);
 3510: 	fprintf(ficresprobcov,"\n%d ",(int)age);
 3511: 	fprintf(ficresprobcor,"\n%d ",(int)age);
 3512: 
 3513: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
 3514: 	  fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
 3515: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 3516: 	  fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
 3517: 	  fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
 3518: 	}
 3519: 	i=0;
 3520: 	for (k=1; k<=(nlstate);k++){
 3521:  	  for (l=1; l<=(nlstate+ndeath);l++){ 
 3522:  	    i=i++;
 3523: 	    fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
 3524: 	    fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
 3525: 	    for (j=1; j<=i;j++){
 3526: 	      fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
 3527: 	      fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
 3528: 	    }
 3529: 	  }
 3530: 	}/* end of loop for state */
 3531:       } /* end of loop for age */
 3532: 
 3533:       /* Confidence intervalle of pij  */
 3534:       /*
 3535: 	fprintf(ficgp,"\nunset parametric;unset label");
 3536: 	fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
 3537: 	fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
 3538: 	fprintf(fichtm,"\n<br>Probability with  confidence intervals expressed in year<sup>-1</sup> :<a href=\"pijgr%s.png\">pijgr%s.png</A>, ",optionfilefiname,optionfilefiname);
 3539: 	fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
 3540: 	fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
 3541: 	fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
 3542:       */
 3543: 
 3544:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
 3545:       first1=1;
 3546:       for (k2=1; k2<=(nlstate);k2++){
 3547: 	for (l2=1; l2<=(nlstate+ndeath);l2++){ 
 3548: 	  if(l2==k2) continue;
 3549: 	  j=(k2-1)*(nlstate+ndeath)+l2;
 3550: 	  for (k1=1; k1<=(nlstate);k1++){
 3551: 	    for (l1=1; l1<=(nlstate+ndeath);l1++){ 
 3552: 	      if(l1==k1) continue;
 3553: 	      i=(k1-1)*(nlstate+ndeath)+l1;
 3554: 	      if(i<=j) continue;
 3555: 	      for (age=bage; age<=fage; age ++){ 
 3556: 		if ((int)age %5==0){
 3557: 		  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
 3558: 		  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
 3559: 		  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
 3560: 		  mu1=mu[i][(int) age]/stepm*YEARM ;
 3561: 		  mu2=mu[j][(int) age]/stepm*YEARM;
 3562: 		  c12=cv12/sqrt(v1*v2);
 3563: 		  /* Computing eigen value of matrix of covariance */
 3564: 		  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 3565: 		  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 3566: 		  if ((lc2 <0) || (lc1 <0) ){
 3567: 		    printf("Error: One eigen value of 2x2 matrix of covariance is negative, lc1=%11.3e, lc2=%11.3e, v1=%11.3e, v2=%11.3e, cv12=%11.3e.\n It means that the matrix was not well estimated (varpij), for i=%2d, j=%2d, age=%4d .\n See files %s and %s. Continuing by making them positive: WRONG RESULTS.\n", lc1, lc2, v1, v2, cv12, i, j, (int)age,fileresprobcov, fileresprobcor);
 3568: 		    fprintf(ficlog,"Error: One eigen value of 2x2 matrix of covariance is negative, lc1=%11.3e, lc2=%11.3e, v1=%11.3e, v2=%11.3e, cv12=%11.3e\n", lc1, lc2, v1, v2, cv12);fflush(ficlog);
 3569: 		    lc1=fabs(lc1);
 3570: 		    lc2=fabs(lc2);
 3571: 		  }
 3572: 
 3573: 		  /* Eigen vectors */
 3574: 		  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
 3575: 		  /*v21=sqrt(1.-v11*v11); *//* error */
 3576: 		  v21=(lc1-v1)/cv12*v11;
 3577: 		  v12=-v21;
 3578: 		  v22=v11;
 3579: 		  tnalp=v21/v11;
 3580: 		  if(first1==1){
 3581: 		    first1=0;
 3582: 		    printf("%d %d%d-%d%d mu %.4e %.4e Var %.4e %.4e cor %.3f cov %.4e Eig %.3e %.3e 1stv %.3f %.3f tang %.3f\nOthers in log...\n",(int) age,k1,l1,k2,l2,mu1,mu2,v1,v2,c12,cv12,lc1,lc2,v11,v21,tnalp);
 3583: 		  }
 3584: 		  fprintf(ficlog,"%d %d%d-%d%d mu %.4e %.4e Var %.4e %.4e cor %.3f cov %.4e Eig %.3e %.3e 1stv %.3f %.3f tan %.3f\n",(int) age,k1,l1,k2,l2,mu1,mu2,v1,v2,c12,cv12,lc1,lc2,v11,v21,tnalp);
 3585: 		  /*printf(fignu*/
 3586: 		  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
 3587: 		  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
 3588: 		  if(first==1){
 3589: 		    first=0;
 3590:  		    fprintf(ficgp,"\nset parametric;unset label");
 3591: 		    fprintf(ficgp,"\nset log y;set log x; set xlabel \"p%1d%1d (year-1)\";set ylabel \"p%1d%1d (year-1)\"",k1,l1,k2,l2);
 3592: 		    fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
 3593: 		    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
 3594:  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
 3595: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
 3596: 			    subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
 3597: 			    subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 3598: 		    fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 3599: 		    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
 3600: 		    fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 3601: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 3602: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 3603: 		    fprintf(ficgp,"\nplot [-pi:pi] %11.3e+ %.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)), %11.3e +%.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)) not",\
 3604: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 3605: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 3606: 		  }else{
 3607: 		    first=0;
 3608: 		    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
 3609: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 3610: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 3611: 		    fprintf(ficgp,"\nreplot %11.3e+ %.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)), %11.3e +%.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)) not",\
 3612: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 3613: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 3614: 		  }/* if first */
 3615: 		} /* age mod 5 */
 3616: 	      } /* end loop age */
 3617: 	      fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 3618: 	      first=1;
 3619: 	    } /*l12 */
 3620: 	  } /* k12 */
 3621: 	} /*l1 */
 3622:       }/* k1 */
 3623:     } /* loop covariates */
 3624:   }
 3625:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
 3626:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
 3627:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 3628:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
 3629:   free_vector(xp,1,npar);
 3630:   fclose(ficresprob);
 3631:   fclose(ficresprobcov);
 3632:   fclose(ficresprobcor);
 3633:   fflush(ficgp);
 3634:   fflush(fichtmcov);
 3635: }
 3636: 
 3637: 
 3638: /******************* Printing html file ***********/
 3639: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
 3640: 		  int lastpass, int stepm, int weightopt, char model[],\
 3641: 		  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
 3642: 		  int popforecast, int estepm ,\
 3643: 		  double jprev1, double mprev1,double anprev1, \
 3644: 		  double jprev2, double mprev2,double anprev2){
 3645:   int jj1, k1, i1, cpt;
 3646: 
 3647:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
 3648:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
 3649: </ul>");
 3650:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
 3651:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
 3652: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
 3653:    fprintf(fichtm,"\
 3654:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 3655: 	   stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
 3656:    fprintf(fichtm,"\
 3657:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 3658: 	   subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
 3659:    fprintf(fichtm,"\
 3660:  - (a) Life expectancies by health status at initial age, ei. (b) health expectancies by health status at initial age, eij . If one or more covariates are included, specific tables for each value of the covariate are output in sequences within the same file (estepm=%2d months): \
 3661:    <a href=\"%s\">%s</a> <br>\n",
 3662: 	   estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
 3663:    fprintf(fichtm,"\
 3664:  - Population projections by age and states: \
 3665:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
 3666: 
 3667: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
 3668: 
 3669:  m=cptcoveff;
 3670:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 3671: 
 3672:  jj1=0;
 3673:  for(k1=1; k1<=m;k1++){
 3674:    for(i1=1; i1<=ncodemax[k1];i1++){
 3675:      jj1++;
 3676:      if (cptcovn > 0) {
 3677:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 3678:        for (cpt=1; cpt<=cptcoveff;cpt++) 
 3679: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
 3680:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 3681:      }
 3682:      /* Pij */
 3683:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s%d1.png\">%s%d1.png</a><br> \
 3684: <img src=\"%s%d1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     
 3685:      /* Quasi-incidences */
 3686:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
 3687:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too: <a href=\"%s%d2.png\">%s%d2.png</a><br> \
 3688: <img src=\"%s%d2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 
 3689:        /* Period (stable) prevalence in each health state */
 3690:        for(cpt=1; cpt<nlstate;cpt++){
 3691: 	 fprintf(fichtm,"<br>- Period (stable) prevalence in each health state : <a href=\"%s%d%d.png\">%s%d%d.png</a><br> \
 3692: <img src=\"%s%d%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
 3693:        }
 3694:      for(cpt=1; cpt<=nlstate;cpt++) {
 3695:         fprintf(fichtm,"\n<br>- Life expectancy by health state (%d) at initial age and its decomposition into health expectancies : <a href=\"%s%d%d.png\">%s%d%d.png</a> <br> \
 3696: <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
 3697:      }
 3698:    } /* end i1 */
 3699:  }/* End k1 */
 3700:  fprintf(fichtm,"</ul>");
 3701: 
 3702: 
 3703:  fprintf(fichtm,"\
 3704: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
 3705:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
 3706: 
 3707:  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 3708: 	 subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
 3709:  fprintf(fichtm,"\
 3710:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 3711: 	 subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
 3712: 
 3713:  fprintf(fichtm,"\
 3714:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 3715: 	 subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
 3716:  fprintf(fichtm,"\
 3717:  - Variances and covariances of health expectancies by age and <b>initial health status</b> (cov(e<sup>ij</sup>,e<sup>kl</sup>)(estepm=%2d months): \
 3718:    <a href=\"%s\">%s</a> <br>\n</li>",
 3719: 	   estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
 3720:  fprintf(fichtm,"\
 3721:  - (a) Health expectancies by health status at initial age (e<sup>ij</sup>) and standard errors (in parentheses) (b) life expectancies and standard errors (e<sup>i.</sup>=e<sup>i1</sup>+e<sup>i2</sup>+...)(estepm=%2d months): \
 3722:    <a href=\"%s\">%s</a> <br>\n</li>",
 3723: 	   estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
 3724:  fprintf(fichtm,"\
 3725:  - Variances and covariances of health expectancies by age. Status (i) based health expectancies (in state j), e<sup>ij</sup> are weighted by the period prevalences in each state i (if popbased=1, an additional computation is done using the cross-sectional prevalences, i.e population based) (estepm=%d months): <a href=\"%s\">%s</a><br>\n",
 3726: 	 estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
 3727:  fprintf(fichtm,"\
 3728:  - Total life expectancy and total health expectancies to be spent in each health state e<sup>.j</sup> with their standard errors (if popbased=1, an additional computation is done using the cross-sectional prevalences, i.e population based) (estepm=%d months): <a href=\"%s\">%s</a> <br>\n",
 3729: 	 estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
 3730:  fprintf(fichtm,"\
 3731:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
 3732: 	 subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
 3733: 
 3734: /*  if(popforecast==1) fprintf(fichtm,"\n */
 3735: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
 3736: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
 3737: /* 	<br>",fileres,fileres,fileres,fileres); */
 3738: /*  else  */
 3739: /*    fprintf(fichtm,"\n No population forecast: popforecast = %d (instead of 1) or stepm = %d (instead of 1) or model=%s (instead of .)<br><br></li>\n",popforecast, stepm, model); */
 3740:  fflush(fichtm);
 3741:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
 3742: 
 3743:  m=cptcoveff;
 3744:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 3745: 
 3746:  jj1=0;
 3747:  for(k1=1; k1<=m;k1++){
 3748:    for(i1=1; i1<=ncodemax[k1];i1++){
 3749:      jj1++;
 3750:      if (cptcovn > 0) {
 3751:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 3752:        for (cpt=1; cpt<=cptcoveff;cpt++) 
 3753: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
 3754:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 3755:      }
 3756:      for(cpt=1; cpt<=nlstate;cpt++) {
 3757:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
 3758: prevalence (with 95%% confidence interval) in state (%d): %s%d%d.png <br>\
 3759: <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
 3760:      }
 3761:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
 3762: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
 3763: true period expectancies (those weighted with period prevalences are also\
 3764:  drawn in addition to the population based expectancies computed using\
 3765:  observed and cahotic prevalences: %s%d.png<br>\
 3766: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
 3767:    } /* end i1 */
 3768:  }/* End k1 */
 3769:  fprintf(fichtm,"</ul>");
 3770:  fflush(fichtm);
 3771: }
 3772: 
 3773: /******************* Gnuplot file **************/
 3774: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 3775: 
 3776:   char dirfileres[132],optfileres[132];
 3777:   int m0,cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
 3778:   int ng=0;
 3779: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
 3780: /*     printf("Problem with file %s",optionfilegnuplot); */
 3781: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
 3782: /*   } */
 3783: 
 3784:   /*#ifdef windows */
 3785:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 3786:     /*#endif */
 3787:   m=pow(2,cptcoveff);
 3788: 
 3789:   strcpy(dirfileres,optionfilefiname);
 3790:   strcpy(optfileres,"vpl");
 3791:  /* 1eme*/
 3792:   for (cpt=1; cpt<= nlstate ; cpt ++) {
 3793:    for (k1=1; k1<= m ; k1 ++) {
 3794:      fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
 3795:      fprintf(ficgp,"\n#set out \"v%s%d%d.png\" \n",optionfilefiname,cpt,k1);
 3796:      fprintf(ficgp,"set xlabel \"Age\" \n\
 3797: set ylabel \"Probability\" \n\
 3798: set ter png small\n\
 3799: set size 0.65,0.65\n\
 3800: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
 3801: 
 3802:      for (i=1; i<= nlstate ; i ++) {
 3803:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
 3804:        else        fprintf(ficgp," \%%*lf (\%%*lf)");
 3805:      }
 3806:      fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"\%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);
 3807:      for (i=1; i<= nlstate ; i ++) {
 3808:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
 3809:        else fprintf(ficgp," \%%*lf (\%%*lf)");
 3810:      } 
 3811:      fprintf(ficgp,"\" t\"95\%% CI\" w l 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"\%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1); 
 3812:      for (i=1; i<= nlstate ; i ++) {
 3813:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
 3814:        else fprintf(ficgp," \%%*lf (\%%*lf)");
 3815:      }  
 3816:      fprintf(ficgp,"\" t\"\" w l 1,\"%s\" every :::%d::%d u 1:($%d) t\"Observed prevalence \" w l 2",subdirf2(fileres,"p"),k1-1,k1-1,2+4*(cpt-1));
 3817:    }
 3818:   }
 3819:   /*2 eme*/
 3820:   
 3821:   for (k1=1; k1<= m ; k1 ++) { 
 3822:     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
 3823:     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] ",ageminpar,fage);
 3824:     
 3825:     for (i=1; i<= nlstate+1 ; i ++) {
 3826:       k=2*i;
 3827:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 3828:       for (j=1; j<= nlstate+1 ; j ++) {
 3829: 	if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
 3830: 	else fprintf(ficgp," \%%*lf (\%%*lf)");
 3831:       }   
 3832:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
 3833:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
 3834:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 3835:       for (j=1; j<= nlstate+1 ; j ++) {
 3836: 	if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
 3837: 	else fprintf(ficgp," \%%*lf (\%%*lf)");
 3838:       }   
 3839:       fprintf(ficgp,"\" t\"\" w l 0,");
 3840:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 3841:       for (j=1; j<= nlstate+1 ; j ++) {
 3842: 	if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
 3843: 	else fprintf(ficgp," \%%*lf (\%%*lf)");
 3844:       }   
 3845:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");
 3846:       else fprintf(ficgp,"\" t\"\" w l 0,");
 3847:     }
 3848:   }
 3849:   
 3850:   /*3eme*/
 3851:   
 3852:   for (k1=1; k1<= m ; k1 ++) { 
 3853:     for (cpt=1; cpt<= nlstate ; cpt ++) {
 3854:       /*       k=2+nlstate*(2*cpt-2); */
 3855:       k=2+(nlstate+1)*(cpt-1);
 3856:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
 3857:       fprintf(ficgp,"set ter png small\n\
 3858: set size 0.65,0.65\n\
 3859: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",ageminpar,fage,subdirf2(fileres,"e"),k1-1,k1-1,k,cpt);
 3860:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 3861: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 3862: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 3863: 	fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 3864: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 3865: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 3866: 	
 3867:       */
 3868:       for (i=1; i< nlstate ; i ++) {
 3869: 	fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+i,cpt,i+1);
 3870: 	/*	fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+2*i,cpt,i+1);*/
 3871: 	
 3872:       } 
 3873:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
 3874:     }
 3875:   }
 3876:   
 3877:   /* CV preval stable (period) */
 3878:   for (k1=1; k1<= m ; k1 ++) { 
 3879:     for (cpt=1; cpt<=nlstate ; cpt ++) {
 3880:       k=3;
 3881:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
 3882:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 3883: set ter png small\nset size 0.65,0.65\n\
 3884: unset log y\n\
 3885: plot [%.f:%.f] \"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",ageminpar,agemaxpar,subdirf2(fileres,"pij"),k1,k+cpt+1,k+1);
 3886:       
 3887:       for (i=1; i< nlstate ; i ++)
 3888: 	fprintf(ficgp,"+$%d",k+i+1);
 3889:       fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);
 3890:       
 3891:       l=3+(nlstate+ndeath)*cpt;
 3892:       fprintf(ficgp,",\"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",subdirf2(fileres,"pij"),k1,l+cpt+1,l+1);
 3893:       for (i=1; i< nlstate ; i ++) {
 3894: 	l=3+(nlstate+ndeath)*cpt;
 3895: 	fprintf(ficgp,"+$%d",l+i+1);
 3896:       }
 3897:       fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);   
 3898:     } 
 3899:   }  
 3900:   
 3901:   /* proba elementaires */
 3902:   for(i=1,jk=1; i <=nlstate; i++){
 3903:     for(k=1; k <=(nlstate+ndeath); k++){
 3904:       if (k != i) {
 3905: 	for(j=1; j <=ncovmodel; j++){
 3906: 	  fprintf(ficgp,"p%d=%f ",jk,p[jk]);
 3907: 	  jk++; 
 3908: 	  fprintf(ficgp,"\n");
 3909: 	}
 3910:       }
 3911:     }
 3912:    }
 3913: 
 3914:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
 3915:      for(jk=1; jk <=m; jk++) {
 3916:        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 
 3917:        if (ng==2)
 3918: 	 fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
 3919:        else
 3920: 	 fprintf(ficgp,"\nset title \"Probability\"\n");
 3921:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
 3922:        i=1;
 3923:        for(k2=1; k2<=nlstate; k2++) {
 3924: 	 k3=i;
 3925: 	 for(k=1; k<=(nlstate+ndeath); k++) {
 3926: 	   if (k != k2){
 3927: 	     if(ng==2)
 3928: 	       fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
 3929: 	     else
 3930: 	       fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
 3931: 	     ij=1;
 3932: 	     for(j=3; j <=ncovmodel; j++) {
 3933: 	       if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
 3934: 		 fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
 3935: 		 ij++;
 3936: 	       }
 3937: 	       else
 3938: 		 fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
 3939: 	     }
 3940: 	     fprintf(ficgp,")/(1");
 3941: 	     
 3942: 	     for(k1=1; k1 <=nlstate; k1++){   
 3943: 	       fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
 3944: 	       ij=1;
 3945: 	       for(j=3; j <=ncovmodel; j++){
 3946: 		 if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
 3947: 		   fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
 3948: 		   ij++;
 3949: 		 }
 3950: 		 else
 3951: 		   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
 3952: 	       }
 3953: 	       fprintf(ficgp,")");
 3954: 	     }
 3955: 	     fprintf(ficgp,") t \"p%d%d\" ", k2,k);
 3956: 	     if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
 3957: 	     i=i+ncovmodel;
 3958: 	   }
 3959: 	 } /* end k */
 3960:        } /* end k2 */
 3961:      } /* end jk */
 3962:    } /* end ng */
 3963:    fflush(ficgp); 
 3964: }  /* end gnuplot */
 3965: 
 3966: 
 3967: /*************** Moving average **************/
 3968: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
 3969: 
 3970:   int i, cpt, cptcod;
 3971:   int modcovmax =1;
 3972:   int mobilavrange, mob;
 3973:   double age;
 3974: 
 3975:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
 3976: 			   a covariate has 2 modalities */
 3977:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
 3978: 
 3979:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
 3980:     if(mobilav==1) mobilavrange=5; /* default */
 3981:     else mobilavrange=mobilav;
 3982:     for (age=bage; age<=fage; age++)
 3983:       for (i=1; i<=nlstate;i++)
 3984: 	for (cptcod=1;cptcod<=modcovmax;cptcod++)
 3985: 	  mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
 3986:     /* We keep the original values on the extreme ages bage, fage and for 
 3987:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
 3988:        we use a 5 terms etc. until the borders are no more concerned. 
 3989:     */ 
 3990:     for (mob=3;mob <=mobilavrange;mob=mob+2){
 3991:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
 3992: 	for (i=1; i<=nlstate;i++){
 3993: 	  for (cptcod=1;cptcod<=modcovmax;cptcod++){
 3994: 	    mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
 3995: 	      for (cpt=1;cpt<=(mob-1)/2;cpt++){
 3996: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
 3997: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
 3998: 	      }
 3999: 	    mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
 4000: 	  }
 4001: 	}
 4002:       }/* end age */
 4003:     }/* end mob */
 4004:   }else return -1;
 4005:   return 0;
 4006: }/* End movingaverage */
 4007: 
 4008: 
 4009: /************** Forecasting ******************/
 4010: prevforecast(char fileres[], double anproj1, double mproj1, double jproj1, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double anproj2, double p[], int cptcoveff){
 4011:   /* proj1, year, month, day of starting projection 
 4012:      agemin, agemax range of age
 4013:      dateprev1 dateprev2 range of dates during which prevalence is computed
 4014:      anproj2 year of en of projection (same day and month as proj1).
 4015:   */
 4016:   int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;
 4017:   int *popage;
 4018:   double agec; /* generic age */
 4019:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
 4020:   double *popeffectif,*popcount;
 4021:   double ***p3mat;
 4022:   double ***mobaverage;
 4023:   char fileresf[FILENAMELENGTH];
 4024: 
 4025:   agelim=AGESUP;
 4026:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 4027:  
 4028:   strcpy(fileresf,"f"); 
 4029:   strcat(fileresf,fileres);
 4030:   if((ficresf=fopen(fileresf,"w"))==NULL) {
 4031:     printf("Problem with forecast resultfile: %s\n", fileresf);
 4032:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
 4033:   }
 4034:   printf("Computing forecasting: result on file '%s' \n", fileresf);
 4035:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
 4036: 
 4037:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 4038: 
 4039:   if (mobilav!=0) {
 4040:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4041:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 4042:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 4043:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 4044:     }
 4045:   }
 4046: 
 4047:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 4048:   if (stepm<=12) stepsize=1;
 4049:   if(estepm < stepm){
 4050:     printf ("Problem %d lower than %d\n",estepm, stepm);
 4051:   }
 4052:   else  hstepm=estepm;   
 4053: 
 4054:   hstepm=hstepm/stepm; 
 4055:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
 4056:                                fractional in yp1 */
 4057:   anprojmean=yp;
 4058:   yp2=modf((yp1*12),&yp);
 4059:   mprojmean=yp;
 4060:   yp1=modf((yp2*30.5),&yp);
 4061:   jprojmean=yp;
 4062:   if(jprojmean==0) jprojmean=1;
 4063:   if(mprojmean==0) jprojmean=1;
 4064: 
 4065:   i1=cptcoveff;
 4066:   if (cptcovn < 1){i1=1;}
 4067:   
 4068:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
 4069:   
 4070:   fprintf(ficresf,"#****** Routine prevforecast **\n");
 4071: 
 4072: /* 	      if (h==(int)(YEARM*yearp)){ */
 4073:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
 4074:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 4075:       k=k+1;
 4076:       fprintf(ficresf,"\n#******");
 4077:       for(j=1;j<=cptcoveff;j++) {
 4078: 	fprintf(ficresf," V%d=%d, hpijx=probability over h years, hp.jx is weighted by observed prev ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4079:       }
 4080:       fprintf(ficresf,"******\n");
 4081:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
 4082:       for(j=1; j<=nlstate+ndeath;j++){ 
 4083: 	for(i=1; i<=nlstate;i++) 	      
 4084:           fprintf(ficresf," p%d%d",i,j);
 4085: 	fprintf(ficresf," p.%d",j);
 4086:       }
 4087:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
 4088: 	fprintf(ficresf,"\n");
 4089: 	fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
 4090: 
 4091:      	for (agec=fage; agec>=(ageminpar-1); agec--){ 
 4092: 	  nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
 4093: 	  nhstepm = nhstepm/hstepm; 
 4094: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4095: 	  oldm=oldms;savm=savms;
 4096: 	  hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
 4097: 	
 4098: 	  for (h=0; h<=nhstepm; h++){
 4099: 	    if (h*hstepm/YEARM*stepm ==yearp) {
 4100:               fprintf(ficresf,"\n");
 4101:               for(j=1;j<=cptcoveff;j++) 
 4102:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4103: 	      fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
 4104: 	    } 
 4105: 	    for(j=1; j<=nlstate+ndeath;j++) {
 4106: 	      ppij=0.;
 4107: 	      for(i=1; i<=nlstate;i++) {
 4108: 		if (mobilav==1) 
 4109: 		  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
 4110: 		else {
 4111: 		  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
 4112: 		}
 4113: 		if (h*hstepm/YEARM*stepm== yearp) {
 4114: 		  fprintf(ficresf," %.3f", p3mat[i][j][h]);
 4115: 		}
 4116: 	      } /* end i */
 4117: 	      if (h*hstepm/YEARM*stepm==yearp) {
 4118: 		fprintf(ficresf," %.3f", ppij);
 4119: 	      }
 4120: 	    }/* end j */
 4121: 	  } /* end h */
 4122: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4123: 	} /* end agec */
 4124:       } /* end yearp */
 4125:     } /* end cptcod */
 4126:   } /* end  cptcov */
 4127:        
 4128:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4129: 
 4130:   fclose(ficresf);
 4131: }
 4132: 
 4133: /************** Forecasting *****not tested NB*************/
 4134: populforecast(char fileres[], double anpyram,double mpyram,double jpyram,double ageminpar, double agemax,double dateprev1, double dateprev2, int mobilav, double agedeb, double fage, int popforecast, char popfile[], double anpyram1,double p[], int i2){
 4135:   
 4136:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
 4137:   int *popage;
 4138:   double calagedatem, agelim, kk1, kk2;
 4139:   double *popeffectif,*popcount;
 4140:   double ***p3mat,***tabpop,***tabpopprev;
 4141:   double ***mobaverage;
 4142:   char filerespop[FILENAMELENGTH];
 4143: 
 4144:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4145:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4146:   agelim=AGESUP;
 4147:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
 4148:   
 4149:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 4150:   
 4151:   
 4152:   strcpy(filerespop,"pop"); 
 4153:   strcat(filerespop,fileres);
 4154:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
 4155:     printf("Problem with forecast resultfile: %s\n", filerespop);
 4156:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
 4157:   }
 4158:   printf("Computing forecasting: result on file '%s' \n", filerespop);
 4159:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
 4160: 
 4161:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 4162: 
 4163:   if (mobilav!=0) {
 4164:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4165:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 4166:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 4167:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 4168:     }
 4169:   }
 4170: 
 4171:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 4172:   if (stepm<=12) stepsize=1;
 4173:   
 4174:   agelim=AGESUP;
 4175:   
 4176:   hstepm=1;
 4177:   hstepm=hstepm/stepm; 
 4178:   
 4179:   if (popforecast==1) {
 4180:     if((ficpop=fopen(popfile,"r"))==NULL) {
 4181:       printf("Problem with population file : %s\n",popfile);exit(0);
 4182:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
 4183:     } 
 4184:     popage=ivector(0,AGESUP);
 4185:     popeffectif=vector(0,AGESUP);
 4186:     popcount=vector(0,AGESUP);
 4187:     
 4188:     i=1;   
 4189:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
 4190:    
 4191:     imx=i;
 4192:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
 4193:   }
 4194: 
 4195:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
 4196:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 4197:       k=k+1;
 4198:       fprintf(ficrespop,"\n#******");
 4199:       for(j=1;j<=cptcoveff;j++) {
 4200: 	fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4201:       }
 4202:       fprintf(ficrespop,"******\n");
 4203:       fprintf(ficrespop,"# Age");
 4204:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
 4205:       if (popforecast==1)  fprintf(ficrespop," [Population]");
 4206:       
 4207:       for (cpt=0; cpt<=0;cpt++) { 
 4208: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 4209: 	
 4210:      	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 4211: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 4212: 	  nhstepm = nhstepm/hstepm; 
 4213: 	  
 4214: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4215: 	  oldm=oldms;savm=savms;
 4216: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 4217: 	
 4218: 	  for (h=0; h<=nhstepm; h++){
 4219: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 4220: 	      fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 4221: 	    } 
 4222: 	    for(j=1; j<=nlstate+ndeath;j++) {
 4223: 	      kk1=0.;kk2=0;
 4224: 	      for(i=1; i<=nlstate;i++) {	      
 4225: 		if (mobilav==1) 
 4226: 		  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
 4227: 		else {
 4228: 		  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
 4229: 		}
 4230: 	      }
 4231: 	      if (h==(int)(calagedatem+12*cpt)){
 4232: 		tabpop[(int)(agedeb)][j][cptcod]=kk1;
 4233: 		  /*fprintf(ficrespop," %.3f", kk1);
 4234: 		    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
 4235: 	      }
 4236: 	    }
 4237: 	    for(i=1; i<=nlstate;i++){
 4238: 	      kk1=0.;
 4239: 		for(j=1; j<=nlstate;j++){
 4240: 		  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
 4241: 		}
 4242: 		  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
 4243: 	    }
 4244: 
 4245: 	    if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
 4246: 	      fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
 4247: 	  }
 4248: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4249: 	}
 4250:       }
 4251:  
 4252:   /******/
 4253: 
 4254:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
 4255: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 4256: 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 4257: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 4258: 	  nhstepm = nhstepm/hstepm; 
 4259: 	  
 4260: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4261: 	  oldm=oldms;savm=savms;
 4262: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 4263: 	  for (h=0; h<=nhstepm; h++){
 4264: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 4265: 	      fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 4266: 	    } 
 4267: 	    for(j=1; j<=nlstate+ndeath;j++) {
 4268: 	      kk1=0.;kk2=0;
 4269: 	      for(i=1; i<=nlstate;i++) {	      
 4270: 		kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];	
 4271: 	      }
 4272: 	      if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);	
 4273: 	    }
 4274: 	  }
 4275: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4276: 	}
 4277:       }
 4278:    } 
 4279:   }
 4280:  
 4281:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4282: 
 4283:   if (popforecast==1) {
 4284:     free_ivector(popage,0,AGESUP);
 4285:     free_vector(popeffectif,0,AGESUP);
 4286:     free_vector(popcount,0,AGESUP);
 4287:   }
 4288:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4289:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4290:   fclose(ficrespop);
 4291: } /* End of popforecast */
 4292: 
 4293: int fileappend(FILE *fichier, char *optionfich)
 4294: {
 4295:   if((fichier=fopen(optionfich,"a"))==NULL) {
 4296:     printf("Problem with file: %s\n", optionfich);
 4297:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
 4298:     return (0);
 4299:   }
 4300:   fflush(fichier);
 4301:   return (1);
 4302: }
 4303: 
 4304: 
 4305: /**************** function prwizard **********************/
 4306: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
 4307: {
 4308: 
 4309:   /* Wizard to print covariance matrix template */
 4310: 
 4311:   char ca[32], cb[32], cc[32];
 4312:   int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;
 4313:   int numlinepar;
 4314: 
 4315:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 4316:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 4317:   for(i=1; i <=nlstate; i++){
 4318:     jj=0;
 4319:     for(j=1; j <=nlstate+ndeath; j++){
 4320:       if(j==i) continue;
 4321:       jj++;
 4322:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
 4323:       printf("%1d%1d",i,j);
 4324:       fprintf(ficparo,"%1d%1d",i,j);
 4325:       for(k=1; k<=ncovmodel;k++){
 4326: 	/* 	  printf(" %lf",param[i][j][k]); */
 4327: 	/* 	  fprintf(ficparo," %lf",param[i][j][k]); */
 4328: 	printf(" 0.");
 4329: 	fprintf(ficparo," 0.");
 4330:       }
 4331:       printf("\n");
 4332:       fprintf(ficparo,"\n");
 4333:     }
 4334:   }
 4335:   printf("# Scales (for hessian or gradient estimation)\n");
 4336:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
 4337:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
 4338:   for(i=1; i <=nlstate; i++){
 4339:     jj=0;
 4340:     for(j=1; j <=nlstate+ndeath; j++){
 4341:       if(j==i) continue;
 4342:       jj++;
 4343:       fprintf(ficparo,"%1d%1d",i,j);
 4344:       printf("%1d%1d",i,j);
 4345:       fflush(stdout);
 4346:       for(k=1; k<=ncovmodel;k++){
 4347: 	/* 	printf(" %le",delti3[i][j][k]); */
 4348: 	/* 	fprintf(ficparo," %le",delti3[i][j][k]); */
 4349: 	printf(" 0.");
 4350: 	fprintf(ficparo," 0.");
 4351:       }
 4352:       numlinepar++;
 4353:       printf("\n");
 4354:       fprintf(ficparo,"\n");
 4355:     }
 4356:   }
 4357:   printf("# Covariance matrix\n");
 4358: /* # 121 Var(a12)\n\ */
 4359: /* # 122 Cov(b12,a12) Var(b12)\n\ */
 4360: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 4361: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 4362: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 4363: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 4364: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 4365: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 4366:   fflush(stdout);
 4367:   fprintf(ficparo,"# Covariance matrix\n");
 4368:   /* # 121 Var(a12)\n\ */
 4369:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
 4370:   /* #   ...\n\ */
 4371:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
 4372:   
 4373:   for(itimes=1;itimes<=2;itimes++){
 4374:     jj=0;
 4375:     for(i=1; i <=nlstate; i++){
 4376:       for(j=1; j <=nlstate+ndeath; j++){
 4377: 	if(j==i) continue;
 4378: 	for(k=1; k<=ncovmodel;k++){
 4379: 	  jj++;
 4380: 	  ca[0]= k+'a'-1;ca[1]='\0';
 4381: 	  if(itimes==1){
 4382: 	    printf("#%1d%1d%d",i,j,k);
 4383: 	    fprintf(ficparo,"#%1d%1d%d",i,j,k);
 4384: 	  }else{
 4385: 	    printf("%1d%1d%d",i,j,k);
 4386: 	    fprintf(ficparo,"%1d%1d%d",i,j,k);
 4387: 	    /* 	printf(" %.5le",matcov[i][j]); */
 4388: 	  }
 4389: 	  ll=0;
 4390: 	  for(li=1;li <=nlstate; li++){
 4391: 	    for(lj=1;lj <=nlstate+ndeath; lj++){
 4392: 	      if(lj==li) continue;
 4393: 	      for(lk=1;lk<=ncovmodel;lk++){
 4394: 		ll++;
 4395: 		if(ll<=jj){
 4396: 		  cb[0]= lk +'a'-1;cb[1]='\0';
 4397: 		  if(ll<jj){
 4398: 		    if(itimes==1){
 4399: 		      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 4400: 		      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 4401: 		    }else{
 4402: 		      printf(" 0.");
 4403: 		      fprintf(ficparo," 0.");
 4404: 		    }
 4405: 		  }else{
 4406: 		    if(itimes==1){
 4407: 		      printf(" Var(%s%1d%1d)",ca,i,j);
 4408: 		      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
 4409: 		    }else{
 4410: 		      printf(" 0.");
 4411: 		      fprintf(ficparo," 0.");
 4412: 		    }
 4413: 		  }
 4414: 		}
 4415: 	      } /* end lk */
 4416: 	    } /* end lj */
 4417: 	  } /* end li */
 4418: 	  printf("\n");
 4419: 	  fprintf(ficparo,"\n");
 4420: 	  numlinepar++;
 4421: 	} /* end k*/
 4422:       } /*end j */
 4423:     } /* end i */
 4424:   } /* end itimes */
 4425: 
 4426: } /* end of prwizard */
 4427: /******************* Gompertz Likelihood ******************************/
 4428: double gompertz(double x[])
 4429: { 
 4430:   double A,B,L=0.0,sump=0.,num=0.;
 4431:   int i,n=0; /* n is the size of the sample */
 4432: 
 4433:   for (i=0;i<=imx-1 ; i++) {
 4434:     sump=sump+weight[i];
 4435:     /*    sump=sump+1;*/
 4436:     num=num+1;
 4437:   }
 4438:  
 4439:  
 4440:   /* for (i=0; i<=imx; i++) 
 4441:      if (wav[i]>0) printf("i=%d ageex=%lf agecens=%lf agedc=%lf cens=%d %d\n" ,i,ageexmed[i],agecens[i],agedc[i],cens[i],wav[i]);*/
 4442: 
 4443:   for (i=1;i<=imx ; i++)
 4444:     {
 4445:       if (cens[i] == 1 && wav[i]>1)
 4446: 	A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
 4447:       
 4448:       if (cens[i] == 0 && wav[i]>1)
 4449: 	A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
 4450: 	     +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
 4451:       
 4452:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 4453:       if (wav[i] > 1 ) { /* ??? */
 4454: 	L=L+A*weight[i];
 4455: 	/* 	printf("\ni=%d A=%f L=%lf x[1]=%lf x[2]=%lf ageex=%lf agecens=%lf cens=%d agedc=%lf weight=%lf\n",i,A,L,x[1],x[2],ageexmed[i]*12,agecens[i]*12,cens[i],agedc[i]*12,weight[i]);*/
 4456:       }
 4457:     }
 4458: 
 4459:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 4460:  
 4461:   return -2*L*num/sump;
 4462: }
 4463: 
 4464: #ifdef GSL
 4465: /******************* Gompertz_f Likelihood ******************************/
 4466: double gompertz_f(const gsl_vector *v, void *params)
 4467: { 
 4468:   double A,B,LL=0.0,sump=0.,num=0.;
 4469:   double *x= (double *) v->data;
 4470:   int i,n=0; /* n is the size of the sample */
 4471: 
 4472:   for (i=0;i<=imx-1 ; i++) {
 4473:     sump=sump+weight[i];
 4474:     /*    sump=sump+1;*/
 4475:     num=num+1;
 4476:   }
 4477:  
 4478:  
 4479:   /* for (i=0; i<=imx; i++) 
 4480:      if (wav[i]>0) printf("i=%d ageex=%lf agecens=%lf agedc=%lf cens=%d %d\n" ,i,ageexmed[i],agecens[i],agedc[i],cens[i],wav[i]);*/
 4481:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
 4482:   for (i=1;i<=imx ; i++)
 4483:     {
 4484:       if (cens[i] == 1 && wav[i]>1)
 4485: 	A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
 4486:       
 4487:       if (cens[i] == 0 && wav[i]>1)
 4488: 	A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
 4489: 	     +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
 4490:       
 4491:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 4492:       if (wav[i] > 1 ) { /* ??? */
 4493: 	LL=LL+A*weight[i];
 4494: 	/* 	printf("\ni=%d A=%f L=%lf x[1]=%lf x[2]=%lf ageex=%lf agecens=%lf cens=%d agedc=%lf weight=%lf\n",i,A,L,x[1],x[2],ageexmed[i]*12,agecens[i]*12,cens[i],agedc[i]*12,weight[i]);*/
 4495:       }
 4496:     }
 4497: 
 4498:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 4499:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
 4500:  
 4501:   return -2*LL*num/sump;
 4502: }
 4503: #endif
 4504: 
 4505: /******************* Printing html file ***********/
 4506: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
 4507: 		  int lastpass, int stepm, int weightopt, char model[],\
 4508: 		  int imx,  double p[],double **matcov,double agemortsup){
 4509:   int i,k;
 4510: 
 4511:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
 4512:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
 4513:   for (i=1;i<=2;i++) 
 4514:     fprintf(fichtm," p[%d] = %lf [%f ; %f]<br>\n",i,p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
 4515:   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
 4516:   fprintf(fichtm,"</ul>");
 4517: 
 4518: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
 4519: 
 4520:  fprintf(fichtm,"\nAge   l<inf>x</inf>     q<inf>x</inf> d(x,x+1)    L<inf>x</inf>     T<inf>x</inf>     e<infx</inf><br>");
 4521: 
 4522:  for (k=agegomp;k<(agemortsup-2);k++) 
 4523:    fprintf(fichtm,"%d %.0lf %lf %.0lf %.0lf %.0lf %lf<br>\n",k,lsurv[k],p[1]*exp(p[2]*(k-agegomp)),(p[1]*exp(p[2]*(k-agegomp)))*lsurv[k],lpop[k],tpop[k],tpop[k]/lsurv[k]);
 4524: 
 4525:  
 4526:   fflush(fichtm);
 4527: }
 4528: 
 4529: /******************* Gnuplot file **************/
 4530: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 4531: 
 4532:   char dirfileres[132],optfileres[132];
 4533:   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
 4534:   int ng;
 4535: 
 4536: 
 4537:   /*#ifdef windows */
 4538:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 4539:     /*#endif */
 4540: 
 4541: 
 4542:   strcpy(dirfileres,optionfilefiname);
 4543:   strcpy(optfileres,"vpl");
 4544:   fprintf(ficgp,"set out \"graphmort.png\"\n "); 
 4545:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
 4546:   fprintf(ficgp, "set ter png small\n set log y\n"); 
 4547:   fprintf(ficgp, "set size 0.65,0.65\n");
 4548:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
 4549: 
 4550: } 
 4551: 
 4552: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
 4553: {
 4554: 
 4555:   /*-------- data file ----------*/
 4556:   FILE *fic;
 4557:   char dummy[]="                         ";
 4558:   int i, j, n;
 4559:   int linei, month, year,iout;
 4560:   char line[MAXLINE], linetmp[MAXLINE];
 4561:   char stra[80], strb[80];
 4562:   char *stratrunc;
 4563:   int lstra;
 4564: 
 4565: 
 4566:   if((fic=fopen(datafile,"r"))==NULL)    {
 4567:     printf("Problem while opening datafile: %s\n", datafile);return 1;
 4568:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
 4569:   }
 4570: 
 4571:   i=1;
 4572:   linei=0;
 4573:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
 4574:     linei=linei+1;
 4575:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
 4576:       if(line[j] == '\t')
 4577: 	line[j] = ' ';
 4578:     }
 4579:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
 4580:       ;
 4581:     };
 4582:     line[j+1]=0;  /* Trims blanks at end of line */
 4583:     if(line[0]=='#'){
 4584:       fprintf(ficlog,"Comment line\n%s\n",line);
 4585:       printf("Comment line\n%s\n",line);
 4586:       continue;
 4587:     }
 4588:     trimbb(linetmp,line); /* Trims multiple blanks in line */
 4589:     for (j=0; line[j]!='\0';j++){
 4590:       line[j]=linetmp[j];
 4591:     }
 4592:   
 4593: 
 4594:     for (j=maxwav;j>=1;j--){
 4595:       cutv(stra, strb, line, ' '); 
 4596:       if(strb[0]=='.') { /* Missing status */
 4597: 	lval=-1;
 4598:       }else{
 4599: 	errno=0;
 4600: 	lval=strtol(strb,&endptr,10); 
 4601:       /*	if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
 4602: 	if( strb[0]=='\0' || (*endptr != '\0')){
 4603: 	  printf("Error reading data around '%s' at line number %ld for individual %d, '%s'\nShould be a status of wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,j,maxwav);
 4604: 	  fprintf(ficlog,"Error reading data around '%s' at line number %ld for individual %d, '%s'\nShould be a status of wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,j,maxwav);fflush(ficlog);
 4605: 	  return 1;
 4606: 	}
 4607:       }
 4608:       s[j][i]=lval;
 4609:       
 4610:       strcpy(line,stra);
 4611:       cutv(stra, strb,line,' ');
 4612:       if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
 4613:       }
 4614:       else  if(iout=sscanf(strb,"%s.") != 0){
 4615: 	month=99;
 4616: 	year=9999;
 4617:       }else{
 4618: 	printf("Error reading data around '%s' at line number %ld for individual %d, '%s'\nShould be a date of interview (mm/yyyy or .) at wave %d.  Exiting.\n",strb, linei,i, line,j);
 4619: 	fprintf(ficlog,"Error reading data around '%s' at line number %ld for individual %d, '%s'\nShould be a date of interview (mm/yyyy or .) at wave %d.  Exiting.\n",strb, linei,i, line,j);fflush(ficlog);
 4620: 	return 1;
 4621:       }
 4622:       anint[j][i]= (double) year; 
 4623:       mint[j][i]= (double)month; 
 4624:       strcpy(line,stra);
 4625:     } /* ENd Waves */
 4626:     
 4627:     cutv(stra, strb,line,' '); 
 4628:     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
 4629:     }
 4630:     else  if(iout=sscanf(strb,"%s.",dummy) != 0){
 4631:       month=99;
 4632:       year=9999;
 4633:     }else{
 4634:       printf("Error reading data around '%s' at line number %ld for individual %d, '%s'\nShould be a date of death (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);
 4635: 	fprintf(ficlog,"Error reading data around '%s' at line number %ld for individual %d, '%s'\nShould be a date of death (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);fflush(ficlog);
 4636: 	return 1;
 4637:     }
 4638:     andc[i]=(double) year; 
 4639:     moisdc[i]=(double) month; 
 4640:     strcpy(line,stra);
 4641:     
 4642:     cutv(stra, strb,line,' '); 
 4643:     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
 4644:     }
 4645:     else  if(iout=sscanf(strb,"%s.") != 0){
 4646:       month=99;
 4647:       year=9999;
 4648:     }else{
 4649:       printf("Error reading data around '%s' at line number %ld for individual %d, '%s'\nShould be a date of birth (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);
 4650:       fprintf(ficlog,"Error reading data around '%s' at line number %ld for individual %d, '%s'\nShould be a date of birth (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);fflush(ficlog);
 4651: 	return 1;
 4652:     }
 4653:     if (year==9999) {
 4654:       printf("Error reading data around '%s' at line number %ld for individual %d, '%s'\nShould be a date of birth (mm/yyyy) but at least the year of birth should be given.  Exiting.\n",strb, linei,i,line);
 4655:       fprintf(ficlog,"Error reading data around '%s' at line number %ld for individual %d, '%s'\nShould be a date of birth (mm/yyyy) but at least the year of birth should be given. Exiting.\n",strb, linei,i,line);fflush(ficlog);
 4656: 	return 1;
 4657: 
 4658:     }
 4659:     annais[i]=(double)(year);
 4660:     moisnais[i]=(double)(month); 
 4661:     strcpy(line,stra);
 4662:     
 4663:     cutv(stra, strb,line,' '); 
 4664:     errno=0;
 4665:     dval=strtod(strb,&endptr); 
 4666:     if( strb[0]=='\0' || (*endptr != '\0')){
 4667:       printf("Error reading data around '%f' at line number %ld, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
 4668:       fprintf(ficlog,"Error reading data around '%f' at line number %ld, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
 4669:       fflush(ficlog);
 4670:       return 1;
 4671:     }
 4672:     weight[i]=dval; 
 4673:     strcpy(line,stra);
 4674:     
 4675:     for (j=ncovcol;j>=1;j--){
 4676:       cutv(stra, strb,line,' '); 
 4677:       if(strb[0]=='.') { /* Missing status */
 4678: 	lval=-1;
 4679:       }else{
 4680: 	errno=0;
 4681: 	lval=strtol(strb,&endptr,10); 
 4682: 	if( strb[0]=='\0' || (*endptr != '\0')){
 4683: 	  printf("Error reading data around '%d' at line number %ld for individual %d, '%s'\nShould be a covariate value (=0 for the reference or 1 for alternative).  Exiting.\n",lval, linei,i, line);
 4684: 	  fprintf(ficlog,"Error reading data around '%d' at line number %ld for individual %d, '%s'\nShould be a covariate value (=0 for the reference or 1 for alternative).  Exiting.\n",lval, linei,i, line);fflush(ficlog);
 4685: 	  return 1;
 4686: 	}
 4687:       }
 4688:       if(lval <-1 || lval >1){
 4689: 	printf("Error reading data around '%d' at line number %ld for individual %d, '%s'\n \
 4690:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 4691:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 4692:  For example, for multinomial values like 1, 2 and 3,\n \
 4693:  build V1=0 V2=0 for the reference value (1),\n \
 4694:         V1=1 V2=0 for (2) \n \
 4695:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 4696:  output of IMaCh is often meaningless.\n \
 4697:  Exiting.\n",lval,linei, i,line,j);
 4698: 	fprintf(ficlog,"Error reading data around '%d' at line number %ld for individual %d, '%s'\n \
 4699:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 4700:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 4701:  For example, for multinomial values like 1, 2 and 3,\n \
 4702:  build V1=0 V2=0 for the reference value (1),\n \
 4703:         V1=1 V2=0 for (2) \n \
 4704:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 4705:  output of IMaCh is often meaningless.\n \
 4706:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
 4707: 	return 1;
 4708:       }
 4709:       covar[j][i]=(double)(lval);
 4710:       strcpy(line,stra);
 4711:     }  
 4712:     lstra=strlen(stra);
 4713:      
 4714:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
 4715:       stratrunc = &(stra[lstra-9]);
 4716:       num[i]=atol(stratrunc);
 4717:     }
 4718:     else
 4719:       num[i]=atol(stra);
 4720:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
 4721:       printf("%ld %.lf %.lf %.lf %.lf/%.lf %.lf/%.lf %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d\n",num[i],(covar[1][i]), (covar[2][i]),weight[i], (moisnais[i]), (annais[i]), (moisdc[i]), (andc[i]), (mint[1][i]), (anint[1][i]), (s[1][i]),  (mint[2][i]), (anint[2][i]), (s[2][i]),  (mint[3][i]), (anint[3][i]), (s[3][i]),  (mint[4][i]), (anint[4][i]), (s[4][i])); ij=ij+1;}*/
 4722:     
 4723:     i=i+1;
 4724:   } /* End loop reading  data */
 4725: 
 4726:   *imax=i-1; /* Number of individuals */
 4727:   fclose(fic);
 4728:  
 4729:   return (0);
 4730:   endread:
 4731:     printf("Exiting readdata: ");
 4732:     fclose(fic);
 4733:     return (1);
 4734: 
 4735: 
 4736: 
 4737: }
 4738: 
 4739: int decodemodel ( char model[], int lastobs)
 4740: {
 4741:   int i, j, k;
 4742:   int i1, j1, k1, k2;
 4743:   char modelsav[80];
 4744:    char stra[80], strb[80], strc[80], strd[80],stre[80];
 4745: 
 4746:   if (strlen(model) >1){ /* If there is at least 1 covariate */
 4747:     j=0, j1=0, k1=1, k2=1;
 4748:     j=nbocc(model,'+'); /* j=Number of '+' */
 4749:     j1=nbocc(model,'*'); /* j1=Number of '*' */
 4750:     cptcovn=j+1; /* Number of covariates V1+V2*age+V3 =>(2 plus signs) + 1=3 
 4751: 		  but the covariates which are product must be computed and stored. */
 4752:     cptcovprod=j1; /*Number of products  V1*V2 +v3*age = 2 */
 4753:     
 4754:     strcpy(modelsav,model); 
 4755:     if (strstr(model,"AGE") !=0){
 4756:       printf("Error. AGE must be in lower case 'age' model=%s ",model);
 4757:       fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
 4758:       return 1;
 4759:     }
 4760:     
 4761:     /* This loop fills the array Tvar from the string 'model'.*/
 4762:     /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
 4763:     /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
 4764:     /* 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
 4765:     /* 	k=3 V4 Tvar[k=3]= 4 (from V4) */
 4766:     /* 	k=2 V1 Tvar[k=2]= 1 (from V1) */
 4767:     /* 	k=1 Tvar[1]=2 (from V2) */
 4768:     /* 	k=5 Tvar[5] */
 4769:     /* for (k=1; k<=cptcovn;k++) { */
 4770:     /* 	cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
 4771:     /* 	} */
 4772:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 4773:     for(k=cptcovn; k>=1;k--){
 4774:       cutv(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
 4775: 				     modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 
 4776: 				    */ 
 4777:       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
 4778:       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
 4779:       /*scanf("%d",i);*/
 4780:       if (strchr(strb,'*')) {  /* Model includes a product V2+V1+V4+V3*age strb=V3*age */
 4781: 	cutv(strd,strc,strb,'*'); /* strd*strc  Vm*Vn: strb=V3*age strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
 4782: 	if (strcmp(strc,"age")==0) { /* Vn*age */
 4783: 	  cptcovprod--;
 4784: 	  cutv(strb,stre,strd,'V'); /* stre="V3" */
 4785: 	  Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=2 ; V1+V2*age Tvar[2]=2 */
 4786: 	  cptcovage++; /* Sums the number of covariates which include age as a product */
 4787: 	  Tage[cptcovage]=k;  /* Tage[1] = 4 */
 4788: 	  /*printf("stre=%s ", stre);*/
 4789: 	} else if (strcmp(strd,"age")==0) { /* or age*Vn */
 4790: 	  cptcovprod--;
 4791: 	  cutv(strb,stre,strc,'V');
 4792: 	  Tvar[k]=atoi(stre);
 4793: 	  cptcovage++;
 4794: 	  Tage[cptcovage]=k;
 4795: 	} else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
 4796: 	  /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
 4797: 	  cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
 4798: 	  Tvar[k]=ncovcol+k1;  /* For model-covariate k tells which data-covariate to use but
 4799: 				  because this model-covariate is a construction we invent a new column
 4800: 				  ncovcol + k1
 4801: 				  If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
 4802: 				  Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
 4803: 	  cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */
 4804: 	  Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
 4805: 	  Tvard[k1][1]=atoi(strc); /* m 1 for V1*/
 4806: 	  Tvard[k1][2]=atoi(stre); /* n 4 for V4*/
 4807: 	  Tvar[cptcovn+k2]=Tvard[k1][1]; /* Tvar[(cptcovn=4+k2=1)=5]= 1 (V1) */
 4808: 	  Tvar[cptcovn+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovn=4+(k2=1)+1)=6]= 4 (V4) */
 4809: 	  for (i=1; i<=lastobs;i++){
 4810: 	    /* Computes the new covariate which is a product of
 4811: 	       covar[n][i]* covar[m][i] and stores it at ncovol+k1 */
 4812: 	    covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
 4813: 	  }
 4814: 	  k1++;
 4815: 	  k2=k2+2;
 4816: 	} /* End age is not in the model */
 4817:       } /* End if model includes a product */
 4818:       else { /* no more sum */
 4819: 	/*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
 4820:        /*  scanf("%d",i);*/
 4821: 	cutv(strd,strc,strb,'V');
 4822: 	Tvar[k]=atoi(strc);
 4823:       }
 4824:       strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
 4825:       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
 4826: 	scanf("%d",i);*/
 4827:     } /* end of loop + */
 4828:   } /* end model */
 4829:   
 4830:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
 4831:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
 4832: 
 4833:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
 4834:   printf("cptcovprod=%d ", cptcovprod);
 4835:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
 4836: 
 4837:   scanf("%d ",i);*/
 4838: 
 4839: 
 4840:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
 4841:   endread:
 4842:     printf("Exiting decodemodel: ");
 4843:     return (1);
 4844: }
 4845: 
 4846: calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
 4847: {
 4848:   int i, m;
 4849: 
 4850:   for (i=1; i<=imx; i++) {
 4851:     for(m=2; (m<= maxwav); m++) {
 4852:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
 4853: 	anint[m][i]=9999;
 4854: 	s[m][i]=-1;
 4855:       }
 4856:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
 4857: 	*nberr++;
 4858: 	printf("Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased\n",(int)moisdc[i],(int)andc[i],num[i],i);
 4859: 	fprintf(ficlog,"Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased\n",(int)moisdc[i],(int)andc[i],num[i],i);
 4860: 	s[m][i]=-1;
 4861:       }
 4862:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
 4863: 	*nberr++;
 4864: 	printf("Error! Month of death of individual %ld on line %d was unknown %2d, you should set it otherwise the information on the death is skipped and results are biased.\n",num[i],i,(int)moisdc[i]); 
 4865: 	fprintf(ficlog,"Error! Month of death of individual %ld on line %d was unknown %f, you should set it otherwise the information on the death is skipped and results are biased.\n",num[i],i,moisdc[i]); 
 4866: 	s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
 4867:       }
 4868:     }
 4869:   }
 4870: 
 4871:   for (i=1; i<=imx; i++)  {
 4872:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
 4873:     for(m=firstpass; (m<= lastpass); m++){
 4874:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
 4875: 	if (s[m][i] >= nlstate+1) {
 4876: 	  if(agedc[i]>0)
 4877: 	    if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
 4878: 	      agev[m][i]=agedc[i];
 4879: 	  /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
 4880: 	    else {
 4881: 	      if ((int)andc[i]!=9999){
 4882: 		nbwarn++;
 4883: 		printf("Warning negative age at death: %ld line:%d\n",num[i],i);
 4884: 		fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
 4885: 		agev[m][i]=-1;
 4886: 	      }
 4887: 	    }
 4888: 	}
 4889: 	else if(s[m][i] !=9){ /* Standard case, age in fractional
 4890: 				 years but with the precision of a month */
 4891: 	  agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
 4892: 	  if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
 4893: 	    agev[m][i]=1;
 4894: 	  else if(agev[m][i] < *agemin){ 
 4895: 	    *agemin=agev[m][i];
 4896: 	    printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
 4897: 	  }
 4898: 	  else if(agev[m][i] >*agemax){
 4899: 	    *agemax=agev[m][i];
 4900: 	    /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/
 4901: 	  }
 4902: 	  /*agev[m][i]=anint[m][i]-annais[i];*/
 4903: 	  /*	 agev[m][i] = age[i]+2*m;*/
 4904: 	}
 4905: 	else { /* =9 */
 4906: 	  agev[m][i]=1;
 4907: 	  s[m][i]=-1;
 4908: 	}
 4909:       }
 4910:       else /*= 0 Unknown */
 4911: 	agev[m][i]=1;
 4912:     }
 4913:     
 4914:   }
 4915:   for (i=1; i<=imx; i++)  {
 4916:     for(m=firstpass; (m<=lastpass); m++){
 4917:       if (s[m][i] > (nlstate+ndeath)) {
 4918: 	*nberr++;
 4919: 	printf("Error: on wave %d of individual %d status %d > (nlstate+ndeath)=(%d+%d)=%d\n",m,i,s[m][i],nlstate, ndeath, nlstate+ndeath);	
 4920: 	fprintf(ficlog,"Error: on wave %d of individual %d status %d > (nlstate+ndeath)=(%d+%d)=%d\n",m,i,s[m][i],nlstate, ndeath, nlstate+ndeath);	
 4921: 	return 1;
 4922:       }
 4923:     }
 4924:   }
 4925: 
 4926:   /*for (i=1; i<=imx; i++){
 4927:   for (m=firstpass; (m<lastpass); m++){
 4928:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
 4929: }
 4930: 
 4931: }*/
 4932: 
 4933: 
 4934:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
 4935:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax); 
 4936: 
 4937:   return (0);
 4938:   endread:
 4939:     printf("Exiting calandcheckages: ");
 4940:     return (1);
 4941: }
 4942: 
 4943: 
 4944: /***********************************************/
 4945: /**************** Main Program *****************/
 4946: /***********************************************/
 4947: 
 4948: int main(int argc, char *argv[])
 4949: {
 4950: #ifdef GSL
 4951:   const gsl_multimin_fminimizer_type *T;
 4952:   size_t iteri = 0, it;
 4953:   int rval = GSL_CONTINUE;
 4954:   int status = GSL_SUCCESS;
 4955:   double ssval;
 4956: #endif
 4957:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
 4958:   int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;
 4959:   int linei, month, year,iout;
 4960:   int jj, ll, li, lj, lk, imk;
 4961:   int numlinepar=0; /* Current linenumber of parameter file */
 4962:   int itimes;
 4963:   int NDIM=2;
 4964:   int vpopbased=0;
 4965: 
 4966:   char ca[32], cb[32], cc[32];
 4967:   /*  FILE *fichtm; *//* Html File */
 4968:   /* FILE *ficgp;*/ /*Gnuplot File */
 4969:   struct stat info;
 4970:   double agedeb, agefin,hf;
 4971:   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
 4972: 
 4973:   double fret;
 4974:   double **xi,tmp,delta;
 4975: 
 4976:   double dum; /* Dummy variable */
 4977:   double ***p3mat;
 4978:   double ***mobaverage;
 4979:   int *indx;
 4980:   char line[MAXLINE], linepar[MAXLINE];
 4981:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
 4982:   char pathr[MAXLINE], pathimach[MAXLINE]; 
 4983:   char **bp, *tok, *val; /* pathtot */
 4984:   int firstobs=1, lastobs=10;
 4985:   int sdeb, sfin; /* Status at beginning and end */
 4986:   int c,  h , cpt,l;
 4987:   int ju,jl, mi;
 4988:   int i1,j1, jk,aa,bb, stepsize, ij;
 4989:   int jnais,jdc,jint4,jint1,jint2,jint3,*tab; 
 4990:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
 4991:   int mobilav=0,popforecast=0;
 4992:   int hstepm, nhstepm;
 4993:   int agemortsup;
 4994:   float  sumlpop=0.;
 4995:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
 4996:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
 4997: 
 4998:   double bage, fage, age, agelim, agebase;
 4999:   double ftolpl=FTOL;
 5000:   double **prlim;
 5001:   double ***param; /* Matrix of parameters */
 5002:   double  *p;
 5003:   double **matcov; /* Matrix of covariance */
 5004:   double ***delti3; /* Scale */
 5005:   double *delti; /* Scale */
 5006:   double ***eij, ***vareij;
 5007:   double **varpl; /* Variances of prevalence limits by age */
 5008:   double *epj, vepp;
 5009:   double kk1, kk2;
 5010:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
 5011:   double **ximort;
 5012:   char *alph[]={"a","a","b","c","d","e"}, str[4];
 5013:   int *dcwave;
 5014: 
 5015:   char z[1]="c", occ;
 5016: 
 5017:   /*char  *strt;*/
 5018:   char strtend[80];
 5019: 
 5020:   long total_usecs;
 5021:  
 5022: /*   setlocale (LC_ALL, ""); */
 5023: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
 5024: /*   textdomain (PACKAGE); */
 5025: /*   setlocale (LC_CTYPE, ""); */
 5026: /*   setlocale (LC_MESSAGES, ""); */
 5027: 
 5028:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
 5029:   (void) gettimeofday(&start_time,&tzp);
 5030:   curr_time=start_time;
 5031:   tm = *localtime(&start_time.tv_sec);
 5032:   tmg = *gmtime(&start_time.tv_sec);
 5033:   strcpy(strstart,asctime(&tm));
 5034: 
 5035: /*  printf("Localtime (at start)=%s",strstart); */
 5036: /*  tp.tv_sec = tp.tv_sec +86400; */
 5037: /*  tm = *localtime(&start_time.tv_sec); */
 5038: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
 5039: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
 5040: /*   tmg.tm_hour=tmg.tm_hour + 1; */
 5041: /*   tp.tv_sec = mktime(&tmg); */
 5042: /*   strt=asctime(&tmg); */
 5043: /*   printf("Time(after) =%s",strstart);  */
 5044: /*  (void) time (&time_value);
 5045: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
 5046: *  tm = *localtime(&time_value);
 5047: *  strstart=asctime(&tm);
 5048: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
 5049: */
 5050: 
 5051:   nberr=0; /* Number of errors and warnings */
 5052:   nbwarn=0;
 5053:   getcwd(pathcd, size);
 5054: 
 5055:   printf("\n%s\n%s",version,fullversion);
 5056:   if(argc <=1){
 5057:     printf("\nEnter the parameter file name: ");
 5058:     fgets(pathr,FILENAMELENGTH,stdin);
 5059:     i=strlen(pathr);
 5060:     if(pathr[i-1]=='\n')
 5061:       pathr[i-1]='\0';
 5062:    for (tok = pathr; tok != NULL; ){
 5063:       printf("Pathr |%s|\n",pathr);
 5064:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
 5065:       printf("val= |%s| pathr=%s\n",val,pathr);
 5066:       strcpy (pathtot, val);
 5067:       if(pathr[0] == '\0') break; /* Dirty */
 5068:     }
 5069:   }
 5070:   else{
 5071:     strcpy(pathtot,argv[1]);
 5072:   }
 5073:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
 5074:   /*cygwin_split_path(pathtot,path,optionfile);
 5075:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
 5076:   /* cutv(path,optionfile,pathtot,'\\');*/
 5077: 
 5078:   /* Split argv[0], imach program to get pathimach */
 5079:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
 5080:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 5081:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 5082:  /*   strcpy(pathimach,argv[0]); */
 5083:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
 5084:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
 5085:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
 5086:   chdir(path); /* Can be a relative path */
 5087:   if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
 5088:     printf("Current directory %s!\n",pathcd);
 5089:   strcpy(command,"mkdir ");
 5090:   strcat(command,optionfilefiname);
 5091:   if((outcmd=system(command)) != 0){
 5092:     printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
 5093:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
 5094:     /* fclose(ficlog); */
 5095: /*     exit(1); */
 5096:   }
 5097: /*   if((imk=mkdir(optionfilefiname))<0){ */
 5098: /*     perror("mkdir"); */
 5099: /*   } */
 5100: 
 5101:   /*-------- arguments in the command line --------*/
 5102: 
 5103:   /* Log file */
 5104:   strcat(filelog, optionfilefiname);
 5105:   strcat(filelog,".log");    /* */
 5106:   if((ficlog=fopen(filelog,"w"))==NULL)    {
 5107:     printf("Problem with logfile %s\n",filelog);
 5108:     goto end;
 5109:   }
 5110:   fprintf(ficlog,"Log filename:%s\n",filelog);
 5111:   fprintf(ficlog,"\n%s\n%s",version,fullversion);
 5112:   fprintf(ficlog,"\nEnter the parameter file name: \n");
 5113:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
 5114:  path=%s \n\
 5115:  optionfile=%s\n\
 5116:  optionfilext=%s\n\
 5117:  optionfilefiname=%s\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
 5118: 
 5119:   printf("Local time (at start):%s",strstart);
 5120:   fprintf(ficlog,"Local time (at start): %s",strstart);
 5121:   fflush(ficlog);
 5122: /*   (void) gettimeofday(&curr_time,&tzp); */
 5123: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */
 5124: 
 5125:   /* */
 5126:   strcpy(fileres,"r");
 5127:   strcat(fileres, optionfilefiname);
 5128:   strcat(fileres,".txt");    /* Other files have txt extension */
 5129: 
 5130:   /*---------arguments file --------*/
 5131: 
 5132:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
 5133:     printf("Problem with optionfile %s\n",optionfile);
 5134:     fprintf(ficlog,"Problem with optionfile %s\n",optionfile);
 5135:     fflush(ficlog);
 5136:     goto end;
 5137:   }
 5138: 
 5139: 
 5140: 
 5141:   strcpy(filereso,"o");
 5142:   strcat(filereso,fileres);
 5143:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
 5144:     printf("Problem with Output resultfile: %s\n", filereso);
 5145:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
 5146:     fflush(ficlog);
 5147:     goto end;
 5148:   }
 5149: 
 5150:   /* Reads comments: lines beginning with '#' */
 5151:   numlinepar=0;
 5152:   while((c=getc(ficpar))=='#' && c!= EOF){
 5153:     ungetc(c,ficpar);
 5154:     fgets(line, MAXLINE, ficpar);
 5155:     numlinepar++;
 5156:     puts(line);
 5157:     fputs(line,ficparo);
 5158:     fputs(line,ficlog);
 5159:   }
 5160:   ungetc(c,ficpar);
 5161: 
 5162:   fscanf(ficpar,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d model=%s\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncovcol, &nlstate,&ndeath, &maxwav, &mle, &weightopt,model);
 5163:   numlinepar++;
 5164:   printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt,model);
 5165:   fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
 5166:   fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
 5167:   fflush(ficlog);
 5168:   while((c=getc(ficpar))=='#' && c!= EOF){
 5169:     ungetc(c,ficpar);
 5170:     fgets(line, MAXLINE, ficpar);
 5171:     numlinepar++;
 5172:     puts(line);
 5173:     fputs(line,ficparo);
 5174:     fputs(line,ficlog);
 5175:   }
 5176:   ungetc(c,ficpar);
 5177: 
 5178:    
 5179:   covar=matrix(0,NCOVMAX,1,n); 
 5180:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
 5181:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
 5182:      v1+v2*age+v2*v3 makes cptcovn = 3
 5183:   */
 5184:   if (strlen(model)>1) 
 5185:     cptcovn=nbocc(model,'+')+1;
 5186:   /* ncovprod */
 5187:   ncovmodel=2+cptcovn; /*Number of variables including intercept and age = cptcovn + intercept + age : v1+v2+v3+v2*v4+v5*age makes 5+2=7*/
 5188:   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
 5189:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
 5190:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
 5191:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
 5192:     printf("Too complex model for current IMaCh: npar=(nlstate+ndeath-1)*nlstate*ncovmodel=%d >= %d(MAXPARM) or nlstate=%d >= %d(NLSTATEMAX) or ndeath=%d >= %d(NDEATHMAX) or ncovmodel=(k+age+#of+signs)=%d(NCOVMAX) >= %d\n",npar, MAXPARM, nlstate, NLSTATEMAX, ndeath, NDEATHMAX, ncovmodel, NCOVMAX);
 5193:     fprintf(ficlog,"Too complex model for current IMaCh: %d >=%d(MAXPARM) or %d >=%d(NLSTATEMAX) or %d >=%d(NDEATHMAX) or %d(NCOVMAX) >=%d\n",npar, MAXPARM, nlstate, NLSTATEMAX, ndeath, NDEATHMAX, ncovmodel, NCOVMAX);
 5194:     fflush(stdout);
 5195:     fclose (ficlog);
 5196:     goto end;
 5197:   }
 5198:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 5199:   delti=delti3[1][1];
 5200:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
 5201:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
 5202:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 5203:     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 5204:     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 5205:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 5206:     fclose (ficparo);
 5207:     fclose (ficlog);
 5208:     goto end;
 5209:     exit(0);
 5210:   }
 5211:   else if(mle==-3) {
 5212:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 5213:     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 5214:     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 5215:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 5216:     matcov=matrix(1,npar,1,npar);
 5217:   }
 5218:   else{
 5219:     /* Read guess parameters */
 5220:     /* Reads comments: lines beginning with '#' */
 5221:     while((c=getc(ficpar))=='#' && c!= EOF){
 5222:       ungetc(c,ficpar);
 5223:       fgets(line, MAXLINE, ficpar);
 5224:       numlinepar++;
 5225:       puts(line);
 5226:       fputs(line,ficparo);
 5227:       fputs(line,ficlog);
 5228:     }
 5229:     ungetc(c,ficpar);
 5230:     
 5231:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 5232:     for(i=1; i <=nlstate; i++){
 5233:       j=0;
 5234:       for(jj=1; jj <=nlstate+ndeath; jj++){
 5235: 	if(jj==i) continue;
 5236: 	j++;
 5237: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 5238: 	if ((i1 != i) && (j1 != j)){
 5239: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
 5240: It might be a problem of design; if ncovcol and the model are correct\n \
 5241: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
 5242: 	  exit(1);
 5243: 	}
 5244: 	fprintf(ficparo,"%1d%1d",i1,j1);
 5245: 	if(mle==1)
 5246: 	  printf("%1d%1d",i,j);
 5247: 	fprintf(ficlog,"%1d%1d",i,j);
 5248: 	for(k=1; k<=ncovmodel;k++){
 5249: 	  fscanf(ficpar," %lf",&param[i][j][k]);
 5250: 	  if(mle==1){
 5251: 	    printf(" %lf",param[i][j][k]);
 5252: 	    fprintf(ficlog," %lf",param[i][j][k]);
 5253: 	  }
 5254: 	  else
 5255: 	    fprintf(ficlog," %lf",param[i][j][k]);
 5256: 	  fprintf(ficparo," %lf",param[i][j][k]);
 5257: 	}
 5258: 	fscanf(ficpar,"\n");
 5259: 	numlinepar++;
 5260: 	if(mle==1)
 5261: 	  printf("\n");
 5262: 	fprintf(ficlog,"\n");
 5263: 	fprintf(ficparo,"\n");
 5264:       }
 5265:     }  
 5266:     fflush(ficlog);
 5267: 
 5268:     p=param[1][1];
 5269:     
 5270:     /* Reads comments: lines beginning with '#' */
 5271:     while((c=getc(ficpar))=='#' && c!= EOF){
 5272:       ungetc(c,ficpar);
 5273:       fgets(line, MAXLINE, ficpar);
 5274:       numlinepar++;
 5275:       puts(line);
 5276:       fputs(line,ficparo);
 5277:       fputs(line,ficlog);
 5278:     }
 5279:     ungetc(c,ficpar);
 5280: 
 5281:     for(i=1; i <=nlstate; i++){
 5282:       for(j=1; j <=nlstate+ndeath-1; j++){
 5283: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 5284: 	if ((i1-i)*(j1-j)!=0){
 5285: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
 5286: 	  exit(1);
 5287: 	}
 5288: 	printf("%1d%1d",i,j);
 5289: 	fprintf(ficparo,"%1d%1d",i1,j1);
 5290: 	fprintf(ficlog,"%1d%1d",i1,j1);
 5291: 	for(k=1; k<=ncovmodel;k++){
 5292: 	  fscanf(ficpar,"%le",&delti3[i][j][k]);
 5293: 	  printf(" %le",delti3[i][j][k]);
 5294: 	  fprintf(ficparo," %le",delti3[i][j][k]);
 5295: 	  fprintf(ficlog," %le",delti3[i][j][k]);
 5296: 	}
 5297: 	fscanf(ficpar,"\n");
 5298: 	numlinepar++;
 5299: 	printf("\n");
 5300: 	fprintf(ficparo,"\n");
 5301: 	fprintf(ficlog,"\n");
 5302:       }
 5303:     }
 5304:     fflush(ficlog);
 5305: 
 5306:     delti=delti3[1][1];
 5307: 
 5308: 
 5309:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
 5310:   
 5311:     /* Reads comments: lines beginning with '#' */
 5312:     while((c=getc(ficpar))=='#' && c!= EOF){
 5313:       ungetc(c,ficpar);
 5314:       fgets(line, MAXLINE, ficpar);
 5315:       numlinepar++;
 5316:       puts(line);
 5317:       fputs(line,ficparo);
 5318:       fputs(line,ficlog);
 5319:     }
 5320:     ungetc(c,ficpar);
 5321:   
 5322:     matcov=matrix(1,npar,1,npar);
 5323:     for(i=1; i <=npar; i++)
 5324:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
 5325:       
 5326:     for(i=1; i <=npar; i++){
 5327:       fscanf(ficpar,"%s",&str);
 5328:       if(mle==1)
 5329: 	printf("%s",str);
 5330:       fprintf(ficlog,"%s",str);
 5331:       fprintf(ficparo,"%s",str);
 5332:       for(j=1; j <=i; j++){
 5333: 	fscanf(ficpar," %le",&matcov[i][j]);
 5334: 	if(mle==1){
 5335: 	  printf(" %.5le",matcov[i][j]);
 5336: 	}
 5337: 	fprintf(ficlog," %.5le",matcov[i][j]);
 5338: 	fprintf(ficparo," %.5le",matcov[i][j]);
 5339:       }
 5340:       fscanf(ficpar,"\n");
 5341:       numlinepar++;
 5342:       if(mle==1)
 5343: 	printf("\n");
 5344:       fprintf(ficlog,"\n");
 5345:       fprintf(ficparo,"\n");
 5346:     }
 5347:     for(i=1; i <=npar; i++)
 5348:       for(j=i+1;j<=npar;j++)
 5349: 	matcov[i][j]=matcov[j][i];
 5350:     
 5351:     if(mle==1)
 5352:       printf("\n");
 5353:     fprintf(ficlog,"\n");
 5354:     
 5355:     fflush(ficlog);
 5356:     
 5357:     /*-------- Rewriting parameter file ----------*/
 5358:     strcpy(rfileres,"r");    /* "Rparameterfile */
 5359:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
 5360:     strcat(rfileres,".");    /* */
 5361:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
 5362:     if((ficres =fopen(rfileres,"w"))==NULL) {
 5363:       printf("Problem writing new parameter file: %s\n", fileres);goto end;
 5364:       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
 5365:     }
 5366:     fprintf(ficres,"#%s\n",version);
 5367:   }    /* End of mle != -3 */
 5368: 
 5369: 
 5370:   n= lastobs;
 5371:   num=lvector(1,n);
 5372:   moisnais=vector(1,n);
 5373:   annais=vector(1,n);
 5374:   moisdc=vector(1,n);
 5375:   andc=vector(1,n);
 5376:   agedc=vector(1,n);
 5377:   cod=ivector(1,n);
 5378:   weight=vector(1,n);
 5379:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
 5380:   mint=matrix(1,maxwav,1,n);
 5381:   anint=matrix(1,maxwav,1,n);
 5382:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
 5383:   tab=ivector(1,NCOVMAX);
 5384:   ncodemax=ivector(1,8); /* hard coded ? */
 5385: 
 5386:   /* Reads data from file datafile */
 5387:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
 5388:     goto end;
 5389: 
 5390:   /* Calculation of the number of parameters from char model */
 5391:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
 5392: 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
 5393: 	k=3 V4 Tvar[k=3]= 4 (from V4)
 5394: 	k=2 V1 Tvar[k=2]= 1 (from V1)
 5395: 	k=1 Tvar[1]=2 (from V2)
 5396:     */
 5397:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
 5398:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
 5399:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
 5400:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
 5401:   */
 5402:   /* For model-covariate k tells which data-covariate to use but
 5403:     because this model-covariate is a construction we invent a new column
 5404:     ncovcol + k1
 5405:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
 5406:     Tvar[3=V1*V4]=4+1 etc */
 5407:   Tprod=ivector(1,15); 
 5408:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
 5409:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
 5410:   */
 5411:   Tvaraff=ivector(1,15); 
 5412:   Tvard=imatrix(1,15,1,2); /* For V3*V2 Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
 5413:   Tage=ivector(1,15); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
 5414: 			 4 covariates (3 plus signs)
 5415: 			 Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
 5416: 		      */  
 5417: 
 5418:   if(decodemodel(model, lastobs) == 1)
 5419:     goto end;
 5420: 
 5421:   if((double)(lastobs-imx)/(double)imx > 1.10){
 5422:     nbwarn++;
 5423:     printf("Warning: The value of parameter lastobs=%d is big compared to the \n  effective number of cases imx=%d, please adjust, \n  otherwise you are allocating more memory than necessary.\n",lastobs, imx); 
 5424:     fprintf(ficlog,"Warning: The value of parameter lastobs=%d is big compared to the \n  effective number of cases imx=%d, please adjust, \n  otherwise you are allocating more memory than necessary.\n",lastobs, imx); 
 5425:   }
 5426:     /*  if(mle==1){*/
 5427:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
 5428:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
 5429:   }
 5430: 
 5431:     /*-calculation of age at interview from date of interview and age at death -*/
 5432:   agev=matrix(1,maxwav,1,imx);
 5433: 
 5434:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
 5435:     goto end;
 5436: 
 5437: 
 5438:   agegomp=(int)agemin;
 5439:   free_vector(moisnais,1,n);
 5440:   free_vector(annais,1,n);
 5441:   /* free_matrix(mint,1,maxwav,1,n);
 5442:      free_matrix(anint,1,maxwav,1,n);*/
 5443:   free_vector(moisdc,1,n);
 5444:   free_vector(andc,1,n);
 5445: 
 5446:    
 5447:   wav=ivector(1,imx);
 5448:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
 5449:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
 5450:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
 5451:    
 5452:   /* Concatenates waves */
 5453:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
 5454: 
 5455:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
 5456: 
 5457:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
 5458:   ncodemax[1]=1;
 5459:   if (cptcovn > 0) tricode(Tvar,nbcode,imx);
 5460:       
 5461:   codtab=imatrix(1,100,1,10); /* Cross tabulation to get the order of 
 5462: 				 the estimations*/
 5463:   h=0;
 5464:   m=pow(2,cptcoveff);
 5465:  
 5466:   for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
 5467:     for(i=1; i <=(m/pow(2,k));i++){ /* i=1 to 8/1=8; i=1 to 8/2=4; i=1 to 8/8=1 */ 
 5468:       for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate */
 5469: 	for(cpt=1; cpt <=(m/pow(2,cptcoveff+1-k)); cpt++){  /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */ 
 5470: 	  h++;
 5471: 	  if (h>m) {
 5472: 	    h=1;
 5473: 	    codtab[h][k]=j;
 5474: 	    codtab[h][Tvar[k]]=j;
 5475: 	  }
 5476: 	  printf("h=%d k=%d j=%d codtab[h][k]=%d Tvar[k]=%d codtab[h][Tvar[k]]=%d \n",h, k,j,codtab[h][k],Tvar[k],codtab[h][Tvar[k]]);
 5477: 	} 
 5478:       }
 5479:     }
 5480:   } 
 5481:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
 5482:      codtab[1][2]=1;codtab[2][2]=2; */
 5483:   /* for(i=1; i <=m ;i++){ 
 5484:      for(k=1; k <=cptcovn; k++){
 5485:        printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
 5486:      }
 5487:      printf("\n");
 5488:      }
 5489:      scanf("%d",i);*/
 5490:     
 5491:   /*------------ gnuplot -------------*/
 5492:   strcpy(optionfilegnuplot,optionfilefiname);
 5493:   if(mle==-3)
 5494:     strcat(optionfilegnuplot,"-mort");
 5495:   strcat(optionfilegnuplot,".gp");
 5496: 
 5497:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
 5498:     printf("Problem with file %s",optionfilegnuplot);
 5499:   }
 5500:   else{
 5501:     fprintf(ficgp,"\n# %s\n", version); 
 5502:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
 5503:     fprintf(ficgp,"set missing 'NaNq'\n");
 5504:   }
 5505:   /*  fclose(ficgp);*/
 5506:   /*--------- index.htm --------*/
 5507: 
 5508:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
 5509:   if(mle==-3)
 5510:     strcat(optionfilehtm,"-mort");
 5511:   strcat(optionfilehtm,".htm");
 5512:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
 5513:     printf("Problem with %s \n",optionfilehtm);
 5514:     exit(0);
 5515:   }
 5516: 
 5517:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
 5518:   strcat(optionfilehtmcov,"-cov.htm");
 5519:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
 5520:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
 5521:   }
 5522:   else{
 5523:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 5524: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 5525: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
 5526: 	  optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 5527:   }
 5528: 
 5529:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 5530: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 5531: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
 5532: \n\
 5533: <hr  size=\"2\" color=\"#EC5E5E\">\
 5534:  <ul><li><h4>Parameter files</h4>\n\
 5535:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
 5536:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
 5537:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
 5538:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
 5539:  - Date and time at start: %s</ul>\n",\
 5540: 	  optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
 5541: 	  optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
 5542: 	  fileres,fileres,\
 5543: 	  filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
 5544:   fflush(fichtm);
 5545: 
 5546:   strcpy(pathr,path);
 5547:   strcat(pathr,optionfilefiname);
 5548:   chdir(optionfilefiname); /* Move to directory named optionfile */
 5549:   
 5550:   /* Calculates basic frequencies. Computes observed prevalence at single age
 5551:      and prints on file fileres'p'. */
 5552:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
 5553: 
 5554:   fprintf(fichtm,"\n");
 5555:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
 5556: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
 5557: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
 5558: 	  imx,agemin,agemax,jmin,jmax,jmean);
 5559:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 5560:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 5561:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 5562:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 5563:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
 5564:     
 5565:    
 5566:   /* For Powell, parameters are in a vector p[] starting at p[1]
 5567:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
 5568:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
 5569: 
 5570:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
 5571: 
 5572:   if (mle==-3){
 5573:     ximort=matrix(1,NDIM,1,NDIM); 
 5574: /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
 5575:     cens=ivector(1,n);
 5576:     ageexmed=vector(1,n);
 5577:     agecens=vector(1,n);
 5578:     dcwave=ivector(1,n);
 5579:  
 5580:     for (i=1; i<=imx; i++){
 5581:       dcwave[i]=-1;
 5582:       for (m=firstpass; m<=lastpass; m++)
 5583: 	if (s[m][i]>nlstate) {
 5584: 	  dcwave[i]=m;
 5585: 	  /*	printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
 5586: 	  break;
 5587: 	}
 5588:     }
 5589: 
 5590:     for (i=1; i<=imx; i++) {
 5591:       if (wav[i]>0){
 5592: 	ageexmed[i]=agev[mw[1][i]][i];
 5593: 	j=wav[i];
 5594: 	agecens[i]=1.; 
 5595: 
 5596: 	if (ageexmed[i]> 1 && wav[i] > 0){
 5597: 	  agecens[i]=agev[mw[j][i]][i];
 5598: 	  cens[i]= 1;
 5599: 	}else if (ageexmed[i]< 1) 
 5600: 	  cens[i]= -1;
 5601: 	if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
 5602: 	  cens[i]=0 ;
 5603:       }
 5604:       else cens[i]=-1;
 5605:     }
 5606:     
 5607:     for (i=1;i<=NDIM;i++) {
 5608:       for (j=1;j<=NDIM;j++)
 5609: 	ximort[i][j]=(i == j ? 1.0 : 0.0);
 5610:     }
 5611:     
 5612:     p[1]=0.0268; p[NDIM]=0.083;
 5613:     /*printf("%lf %lf", p[1], p[2]);*/
 5614:     
 5615:     
 5616: #ifdef GSL
 5617:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
 5618: #elsedef
 5619:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
 5620: #endif
 5621:     strcpy(filerespow,"pow-mort"); 
 5622:     strcat(filerespow,fileres);
 5623:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
 5624:       printf("Problem with resultfile: %s\n", filerespow);
 5625:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 5626:     }
 5627: #ifdef GSL
 5628:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
 5629: #elsedef
 5630:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
 5631: #endif
 5632:     /*  for (i=1;i<=nlstate;i++)
 5633: 	for(j=1;j<=nlstate+ndeath;j++)
 5634: 	if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 5635:     */
 5636:     fprintf(ficrespow,"\n");
 5637: #ifdef GSL
 5638:     /* gsl starts here */ 
 5639:     T = gsl_multimin_fminimizer_nmsimplex;
 5640:     gsl_multimin_fminimizer *sfm = NULL;
 5641:     gsl_vector *ss, *x;
 5642:     gsl_multimin_function minex_func;
 5643: 
 5644:     /* Initial vertex size vector */
 5645:     ss = gsl_vector_alloc (NDIM);
 5646:     
 5647:     if (ss == NULL){
 5648:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
 5649:     }
 5650:     /* Set all step sizes to 1 */
 5651:     gsl_vector_set_all (ss, 0.001);
 5652: 
 5653:     /* Starting point */
 5654:     
 5655:     x = gsl_vector_alloc (NDIM);
 5656:     
 5657:     if (x == NULL){
 5658:       gsl_vector_free(ss);
 5659:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
 5660:     }
 5661:   
 5662:     /* Initialize method and iterate */
 5663:     /*     p[1]=0.0268; p[NDIM]=0.083; */
 5664: /*     gsl_vector_set(x, 0, 0.0268); */
 5665: /*     gsl_vector_set(x, 1, 0.083); */
 5666:     gsl_vector_set(x, 0, p[1]);
 5667:     gsl_vector_set(x, 1, p[2]);
 5668: 
 5669:     minex_func.f = &gompertz_f;
 5670:     minex_func.n = NDIM;
 5671:     minex_func.params = (void *)&p; /* ??? */
 5672:     
 5673:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
 5674:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
 5675:     
 5676:     printf("Iterations beginning .....\n\n");
 5677:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
 5678: 
 5679:     iteri=0;
 5680:     while (rval == GSL_CONTINUE){
 5681:       iteri++;
 5682:       status = gsl_multimin_fminimizer_iterate(sfm);
 5683:       
 5684:       if (status) printf("error: %s\n", gsl_strerror (status));
 5685:       fflush(0);
 5686:       
 5687:       if (status) 
 5688:         break;
 5689:       
 5690:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
 5691:       ssval = gsl_multimin_fminimizer_size (sfm);
 5692:       
 5693:       if (rval == GSL_SUCCESS)
 5694:         printf ("converged to a local maximum at\n");
 5695:       
 5696:       printf("%5d ", iteri);
 5697:       for (it = 0; it < NDIM; it++){
 5698: 	printf ("%10.5f ", gsl_vector_get (sfm->x, it));
 5699:       }
 5700:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
 5701:     }
 5702:     
 5703:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
 5704:     
 5705:     gsl_vector_free(x); /* initial values */
 5706:     gsl_vector_free(ss); /* inital step size */
 5707:     for (it=0; it<NDIM; it++){
 5708:       p[it+1]=gsl_vector_get(sfm->x,it);
 5709:       fprintf(ficrespow," %.12lf", p[it]);
 5710:     }
 5711:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
 5712: #endif
 5713: #ifdef POWELL
 5714:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
 5715: #endif  
 5716:     fclose(ficrespow);
 5717:     
 5718:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
 5719: 
 5720:     for(i=1; i <=NDIM; i++)
 5721:       for(j=i+1;j<=NDIM;j++)
 5722: 	matcov[i][j]=matcov[j][i];
 5723:     
 5724:     printf("\nCovariance matrix\n ");
 5725:     for(i=1; i <=NDIM; i++) {
 5726:       for(j=1;j<=NDIM;j++){ 
 5727: 	printf("%f ",matcov[i][j]);
 5728:       }
 5729:       printf("\n ");
 5730:     }
 5731:     
 5732:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
 5733:     for (i=1;i<=NDIM;i++) 
 5734:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
 5735: 
 5736:     lsurv=vector(1,AGESUP);
 5737:     lpop=vector(1,AGESUP);
 5738:     tpop=vector(1,AGESUP);
 5739:     lsurv[agegomp]=100000;
 5740:     
 5741:     for (k=agegomp;k<=AGESUP;k++) {
 5742:       agemortsup=k;
 5743:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
 5744:     }
 5745:     
 5746:     for (k=agegomp;k<agemortsup;k++)
 5747:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
 5748:     
 5749:     for (k=agegomp;k<agemortsup;k++){
 5750:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
 5751:       sumlpop=sumlpop+lpop[k];
 5752:     }
 5753:     
 5754:     tpop[agegomp]=sumlpop;
 5755:     for (k=agegomp;k<(agemortsup-3);k++){
 5756:       /*  tpop[k+1]=2;*/
 5757:       tpop[k+1]=tpop[k]-lpop[k];
 5758:     }
 5759:     
 5760:     
 5761:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
 5762:     for (k=agegomp;k<(agemortsup-2);k++) 
 5763:       printf("%d %.0lf %lf %.0lf %.0lf %.0lf %lf\n",k,lsurv[k],p[1]*exp(p[2]*(k-agegomp)),(p[1]*exp(p[2]*(k-agegomp)))*lsurv[k],lpop[k],tpop[k],tpop[k]/lsurv[k]);
 5764:     
 5765:     
 5766:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 5767:     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
 5768:     
 5769:     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
 5770: 		     stepm, weightopt,\
 5771: 		     model,imx,p,matcov,agemortsup);
 5772:     
 5773:     free_vector(lsurv,1,AGESUP);
 5774:     free_vector(lpop,1,AGESUP);
 5775:     free_vector(tpop,1,AGESUP);
 5776: #ifdef GSL
 5777:     free_ivector(cens,1,n);
 5778:     free_vector(agecens,1,n);
 5779:     free_ivector(dcwave,1,n);
 5780:     free_matrix(ximort,1,NDIM,1,NDIM);
 5781: #endif
 5782:   } /* Endof if mle==-3 */
 5783:   
 5784:   else{ /* For mle >=1 */
 5785:     globpr=0;/* debug */
 5786:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 5787:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 5788:     for (k=1; k<=npar;k++)
 5789:       printf(" %d %8.5f",k,p[k]);
 5790:     printf("\n");
 5791:     globpr=1; /* to print the contributions */
 5792:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 5793:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 5794:     for (k=1; k<=npar;k++)
 5795:       printf(" %d %8.5f",k,p[k]);
 5796:     printf("\n");
 5797:     if(mle>=1){ /* Could be 1 or 2 */
 5798:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
 5799:     }
 5800:     
 5801:     /*--------- results files --------------*/
 5802:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle= 0 weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate, ndeath, maxwav, weightopt,model);
 5803:     
 5804:     
 5805:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 5806:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 5807:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 5808:     for(i=1,jk=1; i <=nlstate; i++){
 5809:       for(k=1; k <=(nlstate+ndeath); k++){
 5810: 	if (k != i) {
 5811: 	  printf("%d%d ",i,k);
 5812: 	  fprintf(ficlog,"%d%d ",i,k);
 5813: 	  fprintf(ficres,"%1d%1d ",i,k);
 5814: 	  for(j=1; j <=ncovmodel; j++){
 5815: 	    printf("%lf ",p[jk]);
 5816: 	    fprintf(ficlog,"%lf ",p[jk]);
 5817: 	    fprintf(ficres,"%lf ",p[jk]);
 5818: 	    jk++; 
 5819: 	  }
 5820: 	  printf("\n");
 5821: 	  fprintf(ficlog,"\n");
 5822: 	  fprintf(ficres,"\n");
 5823: 	}
 5824:       }
 5825:     }
 5826:     if(mle!=0){
 5827:       /* Computing hessian and covariance matrix */
 5828:       ftolhess=ftol; /* Usually correct */
 5829:       hesscov(matcov, p, npar, delti, ftolhess, func);
 5830:     }
 5831:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
 5832:     printf("# Scales (for hessian or gradient estimation)\n");
 5833:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
 5834:     for(i=1,jk=1; i <=nlstate; i++){
 5835:       for(j=1; j <=nlstate+ndeath; j++){
 5836: 	if (j!=i) {
 5837: 	  fprintf(ficres,"%1d%1d",i,j);
 5838: 	  printf("%1d%1d",i,j);
 5839: 	  fprintf(ficlog,"%1d%1d",i,j);
 5840: 	  for(k=1; k<=ncovmodel;k++){
 5841: 	    printf(" %.5e",delti[jk]);
 5842: 	    fprintf(ficlog," %.5e",delti[jk]);
 5843: 	    fprintf(ficres," %.5e",delti[jk]);
 5844: 	    jk++;
 5845: 	  }
 5846: 	  printf("\n");
 5847: 	  fprintf(ficlog,"\n");
 5848: 	  fprintf(ficres,"\n");
 5849: 	}
 5850:       }
 5851:     }
 5852:     
 5853:     fprintf(ficres,"# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");
 5854:     if(mle>=1)
 5855:       printf("# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");
 5856:     fprintf(ficlog,"# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");
 5857:     /* # 121 Var(a12)\n\ */
 5858:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
 5859:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 5860:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 5861:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 5862:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 5863:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 5864:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 5865:     
 5866:     
 5867:     /* Just to have a covariance matrix which will be more understandable
 5868:        even is we still don't want to manage dictionary of variables
 5869:     */
 5870:     for(itimes=1;itimes<=2;itimes++){
 5871:       jj=0;
 5872:       for(i=1; i <=nlstate; i++){
 5873: 	for(j=1; j <=nlstate+ndeath; j++){
 5874: 	  if(j==i) continue;
 5875: 	  for(k=1; k<=ncovmodel;k++){
 5876: 	    jj++;
 5877: 	    ca[0]= k+'a'-1;ca[1]='\0';
 5878: 	    if(itimes==1){
 5879: 	      if(mle>=1)
 5880: 		printf("#%1d%1d%d",i,j,k);
 5881: 	      fprintf(ficlog,"#%1d%1d%d",i,j,k);
 5882: 	      fprintf(ficres,"#%1d%1d%d",i,j,k);
 5883: 	    }else{
 5884: 	      if(mle>=1)
 5885: 		printf("%1d%1d%d",i,j,k);
 5886: 	      fprintf(ficlog,"%1d%1d%d",i,j,k);
 5887: 	      fprintf(ficres,"%1d%1d%d",i,j,k);
 5888: 	    }
 5889: 	    ll=0;
 5890: 	    for(li=1;li <=nlstate; li++){
 5891: 	      for(lj=1;lj <=nlstate+ndeath; lj++){
 5892: 		if(lj==li) continue;
 5893: 		for(lk=1;lk<=ncovmodel;lk++){
 5894: 		  ll++;
 5895: 		  if(ll<=jj){
 5896: 		    cb[0]= lk +'a'-1;cb[1]='\0';
 5897: 		    if(ll<jj){
 5898: 		      if(itimes==1){
 5899: 			if(mle>=1)
 5900: 			  printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 5901: 			fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 5902: 			fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 5903: 		      }else{
 5904: 			if(mle>=1)
 5905: 			  printf(" %.5e",matcov[jj][ll]); 
 5906: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
 5907: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
 5908: 		      }
 5909: 		    }else{
 5910: 		      if(itimes==1){
 5911: 			if(mle>=1)
 5912: 			  printf(" Var(%s%1d%1d)",ca,i,j);
 5913: 			fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
 5914: 			fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
 5915: 		      }else{
 5916: 			if(mle>=1)
 5917: 			  printf(" %.5e",matcov[jj][ll]); 
 5918: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
 5919: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
 5920: 		      }
 5921: 		    }
 5922: 		  }
 5923: 		} /* end lk */
 5924: 	      } /* end lj */
 5925: 	    } /* end li */
 5926: 	    if(mle>=1)
 5927: 	      printf("\n");
 5928: 	    fprintf(ficlog,"\n");
 5929: 	    fprintf(ficres,"\n");
 5930: 	    numlinepar++;
 5931: 	  } /* end k*/
 5932: 	} /*end j */
 5933:       } /* end i */
 5934:     } /* end itimes */
 5935:     
 5936:     fflush(ficlog);
 5937:     fflush(ficres);
 5938:     
 5939:     while((c=getc(ficpar))=='#' && c!= EOF){
 5940:       ungetc(c,ficpar);
 5941:       fgets(line, MAXLINE, ficpar);
 5942:       puts(line);
 5943:       fputs(line,ficparo);
 5944:     }
 5945:     ungetc(c,ficpar);
 5946:     
 5947:     estepm=0;
 5948:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
 5949:     if (estepm==0 || estepm < stepm) estepm=stepm;
 5950:     if (fage <= 2) {
 5951:       bage = ageminpar;
 5952:       fage = agemaxpar;
 5953:     }
 5954:     
 5955:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
 5956:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
 5957:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
 5958:     
 5959:     while((c=getc(ficpar))=='#' && c!= EOF){
 5960:       ungetc(c,ficpar);
 5961:       fgets(line, MAXLINE, ficpar);
 5962:       puts(line);
 5963:       fputs(line,ficparo);
 5964:     }
 5965:     ungetc(c,ficpar);
 5966:     
 5967:     fscanf(ficpar,"begin-prev-date=%lf/%lf/%lf end-prev-date=%lf/%lf/%lf mov_average=%d\n",&jprev1, &mprev1,&anprev1,&jprev2, &mprev2,&anprev2,&mobilav);
 5968:     fprintf(ficparo,"begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
 5969:     fprintf(ficres,"begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
 5970:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
 5971:     fprintf(ficlog,"begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
 5972:     
 5973:     while((c=getc(ficpar))=='#' && c!= EOF){
 5974:       ungetc(c,ficpar);
 5975:       fgets(line, MAXLINE, ficpar);
 5976:       puts(line);
 5977:       fputs(line,ficparo);
 5978:     }
 5979:     ungetc(c,ficpar);
 5980:     
 5981:     
 5982:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
 5983:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
 5984:     
 5985:     fscanf(ficpar,"pop_based=%d\n",&popbased);
 5986:     fprintf(ficparo,"pop_based=%d\n",popbased);   
 5987:     fprintf(ficres,"pop_based=%d\n",popbased);   
 5988:     
 5989:     while((c=getc(ficpar))=='#' && c!= EOF){
 5990:       ungetc(c,ficpar);
 5991:       fgets(line, MAXLINE, ficpar);
 5992:       puts(line);
 5993:       fputs(line,ficparo);
 5994:     }
 5995:     ungetc(c,ficpar);
 5996:     
 5997:     fscanf(ficpar,"prevforecast=%d starting-proj-date=%lf/%lf/%lf final-proj-date=%lf/%lf/%lf mobil_average=%d\n",&prevfcast,&jproj1,&mproj1,&anproj1,&jproj2,&mproj2,&anproj2,&mobilavproj);
 5998:     fprintf(ficparo,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);
 5999:     printf("prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);
 6000:     fprintf(ficlog,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);
 6001:     fprintf(ficres,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);
 6002:     /* day and month of proj2 are not used but only year anproj2.*/
 6003:     
 6004:     
 6005:     
 6006:     /*  freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint);*/
 6007:     /*,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
 6008:     
 6009:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 6010:     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
 6011:     
 6012:     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
 6013: 		 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
 6014: 		 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
 6015:       
 6016:    /*------------ free_vector  -------------*/
 6017:    /*  chdir(path); */
 6018:  
 6019:     free_ivector(wav,1,imx);
 6020:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
 6021:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
 6022:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
 6023:     free_lvector(num,1,n);
 6024:     free_vector(agedc,1,n);
 6025:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
 6026:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
 6027:     fclose(ficparo);
 6028:     fclose(ficres);
 6029: 
 6030: 
 6031:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
 6032:   
 6033:     strcpy(filerespl,"pl");
 6034:     strcat(filerespl,fileres);
 6035:     if((ficrespl=fopen(filerespl,"w"))==NULL) {
 6036:       printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;
 6037:       fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;
 6038:     }
 6039:     printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
 6040:     fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
 6041:     pstamp(ficrespl);
 6042:     fprintf(ficrespl,"# Period (stable) prevalence \n");
 6043:     fprintf(ficrespl,"#Age ");
 6044:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
 6045:     fprintf(ficrespl,"\n");
 6046:   
 6047:     prlim=matrix(1,nlstate,1,nlstate);
 6048: 
 6049:     agebase=ageminpar;
 6050:     agelim=agemaxpar;
 6051:     ftolpl=1.e-10;
 6052:     i1=cptcoveff;
 6053:     if (cptcovn < 1){i1=1;}
 6054: 
 6055:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 6056:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 6057: 	k=k+1;
 6058: 	/* to clean */
 6059: 	printf("cptcov=%d cptcod=%d codtab=%d nbcode=%d\n",cptcov, cptcod,codtab[cptcod][cptcov],nbcode);
 6060: 	fprintf(ficrespl,"\n#******");
 6061: 	printf("\n#******");
 6062: 	fprintf(ficlog,"\n#******");
 6063: 	for(j=1;j<=cptcoveff;j++) {
 6064: 	  fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6065: 	  printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6066: 	  fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6067: 	}
 6068: 	fprintf(ficrespl,"******\n");
 6069: 	printf("******\n");
 6070: 	fprintf(ficlog,"******\n");
 6071: 	
 6072: 	for (age=agebase; age<=agelim; age++){
 6073: 	  prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
 6074: 	  fprintf(ficrespl,"%.0f ",age );
 6075: 	  for(j=1;j<=cptcoveff;j++)
 6076: 	    fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6077: 	  for(i=1; i<=nlstate;i++)
 6078: 	    fprintf(ficrespl," %.5f", prlim[i][i]);
 6079: 	  fprintf(ficrespl,"\n");
 6080: 	}
 6081:       }
 6082:     }
 6083:     fclose(ficrespl);
 6084: 
 6085:     /*------------- h Pij x at various ages ------------*/
 6086:   
 6087:     strcpy(filerespij,"pij");  strcat(filerespij,fileres);
 6088:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
 6089:       printf("Problem with Pij resultfile: %s\n", filerespij);goto end;
 6090:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij);goto end;
 6091:     }
 6092:     printf("Computing pij: result on file '%s' \n", filerespij);
 6093:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
 6094:   
 6095:     stepsize=(int) (stepm+YEARM-1)/YEARM;
 6096:     /*if (stepm<=24) stepsize=2;*/
 6097: 
 6098:     agelim=AGESUP;
 6099:     hstepm=stepsize*YEARM; /* Every year of age */
 6100:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
 6101: 
 6102:     /* hstepm=1;   aff par mois*/
 6103:     pstamp(ficrespij);
 6104:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
 6105:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 6106:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 6107: 	k=k+1;
 6108: 	fprintf(ficrespij,"\n#****** ");
 6109: 	for(j=1;j<=cptcoveff;j++) 
 6110: 	  fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6111: 	fprintf(ficrespij,"******\n");
 6112: 	
 6113: 	for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
 6114: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 6115: 	  nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 6116: 
 6117: 	  /*	  nhstepm=nhstepm*YEARM; aff par mois*/
 6118: 
 6119: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6120: 	  oldm=oldms;savm=savms;
 6121: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 6122: 	  fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
 6123: 	  for(i=1; i<=nlstate;i++)
 6124: 	    for(j=1; j<=nlstate+ndeath;j++)
 6125: 	      fprintf(ficrespij," %1d-%1d",i,j);
 6126: 	  fprintf(ficrespij,"\n");
 6127: 	  for (h=0; h<=nhstepm; h++){
 6128: 	    fprintf(ficrespij,"%d %3.f %3.f",k,agedeb, agedeb+ h*hstepm/YEARM*stepm );
 6129: 	    for(i=1; i<=nlstate;i++)
 6130: 	      for(j=1; j<=nlstate+ndeath;j++)
 6131: 		fprintf(ficrespij," %.5f", p3mat[i][j][h]);
 6132: 	    fprintf(ficrespij,"\n");
 6133: 	  }
 6134: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6135: 	  fprintf(ficrespij,"\n");
 6136: 	}
 6137:       }
 6138:     }
 6139: 
 6140:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
 6141: 
 6142:     fclose(ficrespij);
 6143: 
 6144:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6145:     for(i=1;i<=AGESUP;i++)
 6146:       for(j=1;j<=NCOVMAX;j++)
 6147: 	for(k=1;k<=NCOVMAX;k++)
 6148: 	  probs[i][j][k]=0.;
 6149: 
 6150:     /*---------- Forecasting ------------------*/
 6151:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
 6152:     if(prevfcast==1){
 6153:       /*    if(stepm ==1){*/
 6154:       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
 6155:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
 6156:       /*      }  */
 6157:       /*      else{ */
 6158:       /*        erreur=108; */
 6159:       /*        printf("Warning %d!! You can only forecast the prevalences if the optimization\n  has been performed with stepm = 1 (month) instead of %d or model=. instead of '%s'\n", erreur, stepm, model); */
 6160:       /*        fprintf(ficlog,"Warning %d!! You can only forecast the prevalences if the optimization\n  has been performed with stepm = 1 (month) instead of %d or model=. instead of '%s'\n", erreur, stepm, model); */
 6161:       /*      } */
 6162:     }
 6163:   
 6164: 
 6165:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
 6166: 
 6167:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 6168:     /*  printf("ageminpar=%f, agemax=%f, s[lastpass][imx]=%d, agev[lastpass][imx]=%f, nlstate=%d, imx=%d,  mint[lastpass][imx]=%f, anint[lastpass][imx]=%f,dateprev1=%f, dateprev2=%f, firstpass=%d, lastpass=%d\n",\
 6169: 	ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
 6170:     */
 6171: 
 6172:     if (mobilav!=0) {
 6173:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6174:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 6175: 	fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 6176: 	printf(" Error in movingaverage mobilav=%d\n",mobilav);
 6177:       }
 6178:     }
 6179: 
 6180: 
 6181:     /*---------- Health expectancies, no variances ------------*/
 6182: 
 6183:     strcpy(filerese,"e");
 6184:     strcat(filerese,fileres);
 6185:     if((ficreseij=fopen(filerese,"w"))==NULL) {
 6186:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 6187:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 6188:     }
 6189:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
 6190:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
 6191:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 6192:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 6193: 	k=k+1; 
 6194: 	fprintf(ficreseij,"\n#****** ");
 6195: 	for(j=1;j<=cptcoveff;j++) {
 6196: 	  fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6197: 	}
 6198: 	fprintf(ficreseij,"******\n");
 6199: 
 6200: 	eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 6201: 	oldm=oldms;savm=savms;
 6202: 	evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
 6203:       
 6204: 	free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 6205:       }
 6206:     }
 6207:     fclose(ficreseij);
 6208: 
 6209: 
 6210:     /*---------- Health expectancies and variances ------------*/
 6211: 
 6212: 
 6213:     strcpy(filerest,"t");
 6214:     strcat(filerest,fileres);
 6215:     if((ficrest=fopen(filerest,"w"))==NULL) {
 6216:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
 6217:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
 6218:     }
 6219:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
 6220:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
 6221: 
 6222: 
 6223:     strcpy(fileresstde,"stde");
 6224:     strcat(fileresstde,fileres);
 6225:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
 6226:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 6227:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 6228:     }
 6229:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 6230:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 6231: 
 6232:     strcpy(filerescve,"cve");
 6233:     strcat(filerescve,fileres);
 6234:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
 6235:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 6236:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 6237:     }
 6238:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 6239:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 6240: 
 6241:     strcpy(fileresv,"v");
 6242:     strcat(fileresv,fileres);
 6243:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
 6244:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
 6245:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
 6246:     }
 6247:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
 6248:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
 6249: 
 6250:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 6251:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 6252: 	k=k+1; 
 6253: 	fprintf(ficrest,"\n#****** ");
 6254: 	for(j=1;j<=cptcoveff;j++) 
 6255: 	  fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6256: 	fprintf(ficrest,"******\n");
 6257: 
 6258: 	fprintf(ficresstdeij,"\n#****** ");
 6259: 	fprintf(ficrescveij,"\n#****** ");
 6260: 	for(j=1;j<=cptcoveff;j++) {
 6261: 	  fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6262: 	  fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6263: 	}
 6264: 	fprintf(ficresstdeij,"******\n");
 6265: 	fprintf(ficrescveij,"******\n");
 6266: 
 6267: 	fprintf(ficresvij,"\n#****** ");
 6268: 	for(j=1;j<=cptcoveff;j++) 
 6269: 	  fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6270: 	fprintf(ficresvij,"******\n");
 6271: 
 6272: 	eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 6273: 	oldm=oldms;savm=savms;
 6274: 	cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
 6275:  
 6276: 	vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 6277: 	pstamp(ficrest);
 6278: 	for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
 6279: 	  oldm=oldms;savm=savms;
 6280: 	  varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart);	  fprintf(ficrest,"# Total life expectancy with std error and decomposition into time to be expected in each health state\n#  (weighted average of eij where weights are ");
 6281: 	  if(vpopbased==1)
 6282: 	    fprintf(ficrest,"the age specific prevalence observed (cross-sectionally) in the population i.e cross-sectionally\n in each health state (popbased=1) (mobilav=%d)\n",mobilav);
 6283: 	  else
 6284: 	    fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
 6285: 	  fprintf(ficrest,"# Age e.. (std) ");
 6286: 	  for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
 6287: 	  fprintf(ficrest,"\n");
 6288: 
 6289: 	  epj=vector(1,nlstate+1);
 6290: 	  for(age=bage; age <=fage ;age++){
 6291: 	    prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
 6292: 	    if (vpopbased==1) {
 6293: 	      if(mobilav ==0){
 6294: 		for(i=1; i<=nlstate;i++)
 6295: 		  prlim[i][i]=probs[(int)age][i][k];
 6296: 	      }else{ /* mobilav */ 
 6297: 		for(i=1; i<=nlstate;i++)
 6298: 		  prlim[i][i]=mobaverage[(int)age][i][k];
 6299: 	      }
 6300: 	    }
 6301: 	
 6302: 	    fprintf(ficrest," %4.0f",age);
 6303: 	    for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
 6304: 	      for(i=1, epj[j]=0.;i <=nlstate;i++) {
 6305: 		epj[j] += prlim[i][i]*eij[i][j][(int)age];
 6306: 		/*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
 6307: 	      }
 6308: 	      epj[nlstate+1] +=epj[j];
 6309: 	    }
 6310: 
 6311: 	    for(i=1, vepp=0.;i <=nlstate;i++)
 6312: 	      for(j=1;j <=nlstate;j++)
 6313: 		vepp += vareij[i][j][(int)age];
 6314: 	    fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
 6315: 	    for(j=1;j <=nlstate;j++){
 6316: 	      fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
 6317: 	    }
 6318: 	    fprintf(ficrest,"\n");
 6319: 	  }
 6320: 	}
 6321: 	free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 6322: 	free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 6323: 	free_vector(epj,1,nlstate+1);
 6324:       }
 6325:     }
 6326:     free_vector(weight,1,n);
 6327:     free_imatrix(Tvard,1,15,1,2);
 6328:     free_imatrix(s,1,maxwav+1,1,n);
 6329:     free_matrix(anint,1,maxwav,1,n); 
 6330:     free_matrix(mint,1,maxwav,1,n);
 6331:     free_ivector(cod,1,n);
 6332:     free_ivector(tab,1,NCOVMAX);
 6333:     fclose(ficresstdeij);
 6334:     fclose(ficrescveij);
 6335:     fclose(ficresvij);
 6336:     fclose(ficrest);
 6337:     fclose(ficpar);
 6338:   
 6339:     /*------- Variance of period (stable) prevalence------*/   
 6340: 
 6341:     strcpy(fileresvpl,"vpl");
 6342:     strcat(fileresvpl,fileres);
 6343:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
 6344:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
 6345:       exit(0);
 6346:     }
 6347:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
 6348: 
 6349:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 6350:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 6351: 	k=k+1;
 6352: 	fprintf(ficresvpl,"\n#****** ");
 6353: 	for(j=1;j<=cptcoveff;j++) 
 6354: 	  fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6355: 	fprintf(ficresvpl,"******\n");
 6356:       
 6357: 	varpl=matrix(1,nlstate,(int) bage, (int) fage);
 6358: 	oldm=oldms;savm=savms;
 6359: 	varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
 6360: 	free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
 6361:       }
 6362:     }
 6363: 
 6364:     fclose(ficresvpl);
 6365: 
 6366:     /*---------- End : free ----------------*/
 6367:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6368:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6369: 
 6370:   }  /* mle==-3 arrives here for freeing */
 6371:  endfree:
 6372:   free_matrix(prlim,1,nlstate,1,nlstate);
 6373:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
 6374:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
 6375:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
 6376:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
 6377:     free_matrix(covar,0,NCOVMAX,1,n);
 6378:     free_matrix(matcov,1,npar,1,npar);
 6379:     /*free_vector(delti,1,npar);*/
 6380:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 6381:     free_matrix(agev,1,maxwav,1,imx);
 6382:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
 6383: 
 6384:     free_ivector(ncodemax,1,8);
 6385:     free_ivector(Tvar,1,15);
 6386:     free_ivector(Tprod,1,15);
 6387:     free_ivector(Tvaraff,1,15);
 6388:     free_ivector(Tage,1,15);
 6389: 
 6390:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
 6391:     free_imatrix(codtab,1,100,1,10);
 6392:   fflush(fichtm);
 6393:   fflush(ficgp);
 6394:   
 6395: 
 6396:   if((nberr >0) || (nbwarn>0)){
 6397:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
 6398:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
 6399:   }else{
 6400:     printf("End of Imach\n");
 6401:     fprintf(ficlog,"End of Imach\n");
 6402:   }
 6403:   printf("See log file on %s\n",filelog);
 6404:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
 6405:   (void) gettimeofday(&end_time,&tzp);
 6406:   tm = *localtime(&end_time.tv_sec);
 6407:   tmg = *gmtime(&end_time.tv_sec);
 6408:   strcpy(strtend,asctime(&tm));
 6409:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
 6410:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
 6411:   printf("Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));
 6412: 
 6413:   printf("Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);
 6414:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));
 6415:   fprintf(ficlog,"Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);
 6416:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
 6417: /*   if(fileappend(fichtm,optionfilehtm)){ */
 6418:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 6419:   fclose(fichtm);
 6420:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 6421:   fclose(fichtmcov);
 6422:   fclose(ficgp);
 6423:   fclose(ficlog);
 6424:   /*------ End -----------*/
 6425: 
 6426: 
 6427:    printf("Before Current directory %s!\n",pathcd);
 6428:    if(chdir(pathcd) != 0)
 6429:     printf("Can't move to directory %s!\n",path);
 6430:   if(getcwd(pathcd,MAXLINE) > 0)
 6431:     printf("Current directory %s!\n",pathcd);
 6432:   /*strcat(plotcmd,CHARSEPARATOR);*/
 6433:   sprintf(plotcmd,"gnuplot");
 6434: #ifndef UNIX
 6435:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
 6436: #endif
 6437:   if(!stat(plotcmd,&info)){
 6438:     printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);
 6439:     if(!stat(getenv("GNUPLOTBIN"),&info)){
 6440:       printf("Error gnuplot program not found: %s Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
 6441:     }else
 6442:       strcpy(pplotcmd,plotcmd);
 6443: #ifdef UNIX
 6444:     strcpy(plotcmd,GNUPLOTPROGRAM);
 6445:     if(!stat(plotcmd,&info)){
 6446:       printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);
 6447:     }else
 6448:       strcpy(pplotcmd,plotcmd);
 6449: #endif
 6450:   }else
 6451:     strcpy(pplotcmd,plotcmd);
 6452:   
 6453:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
 6454:   printf("Starting graphs with: %s\n",plotcmd);fflush(stdout);
 6455: 
 6456:   if((outcmd=system(plotcmd)) != 0){
 6457:     printf("\n Problem with gnuplot\n");
 6458:   }
 6459:   printf(" Wait...");
 6460:   while (z[0] != 'q') {
 6461:     /* chdir(path); */
 6462:     printf("\nType e to edit output files, g to graph again and q for exiting: ");
 6463:     scanf("%s",z);
 6464: /*     if (z[0] == 'c') system("./imach"); */
 6465:     if (z[0] == 'e') {
 6466:       printf("Starting browser with: %s",optionfilehtm);fflush(stdout);
 6467:       system(optionfilehtm);
 6468:     }
 6469:     else if (z[0] == 'g') system(plotcmd);
 6470:     else if (z[0] == 'q') exit(0);
 6471:   }
 6472:   end:
 6473:   while (z[0] != 'q') {
 6474:     printf("\nType  q for exiting: ");
 6475:     scanf("%s",z);
 6476:   }
 6477: }
 6478: 
 6479: 
 6480: 

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>