File:  [Local Repository] / imach / src / imach.c
Revision 1.113: download - view: text, annotated - select for diffs
Fri Feb 24 14:20:24 2006 UTC (18 years, 3 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
(Module): Memory leaks checks with valgrind and:
datafile was not closed, some imatrix were not freed and on matrix
allocation too.

    1: /* $Id: imach.c,v 1.113 2006/02/24 14:20:24 brouard Exp $
    2:   $State: Exp $
    3:   $Log: imach.c,v $
    4:   Revision 1.113  2006/02/24 14:20:24  brouard
    5:   (Module): Memory leaks checks with valgrind and:
    6:   datafile was not closed, some imatrix were not freed and on matrix
    7:   allocation too.
    8: 
    9:   Revision 1.112  2006/01/30 09:55:26  brouard
   10:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
   11: 
   12:   Revision 1.111  2006/01/25 20:38:18  brouard
   13:   (Module): Lots of cleaning and bugs added (Gompertz)
   14:   (Module): Comments can be added in data file. Missing date values
   15:   can be a simple dot '.'.
   16: 
   17:   Revision 1.110  2006/01/25 00:51:50  brouard
   18:   (Module): Lots of cleaning and bugs added (Gompertz)
   19: 
   20:   Revision 1.109  2006/01/24 19:37:15  brouard
   21:   (Module): Comments (lines starting with a #) are allowed in data.
   22: 
   23:   Revision 1.108  2006/01/19 18:05:42  lievre
   24:   Gnuplot problem appeared...
   25:   To be fixed
   26: 
   27:   Revision 1.107  2006/01/19 16:20:37  brouard
   28:   Test existence of gnuplot in imach path
   29: 
   30:   Revision 1.106  2006/01/19 13:24:36  brouard
   31:   Some cleaning and links added in html output
   32: 
   33:   Revision 1.105  2006/01/05 20:23:19  lievre
   34:   *** empty log message ***
   35: 
   36:   Revision 1.104  2005/09/30 16:11:43  lievre
   37:   (Module): sump fixed, loop imx fixed, and simplifications.
   38:   (Module): If the status is missing at the last wave but we know
   39:   that the person is alive, then we can code his/her status as -2
   40:   (instead of missing=-1 in earlier versions) and his/her
   41:   contributions to the likelihood is 1 - Prob of dying from last
   42:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
   43:   the healthy state at last known wave). Version is 0.98
   44: 
   45:   Revision 1.103  2005/09/30 15:54:49  lievre
   46:   (Module): sump fixed, loop imx fixed, and simplifications.
   47: 
   48:   Revision 1.102  2004/09/15 17:31:30  brouard
   49:   Add the possibility to read data file including tab characters.
   50: 
   51:   Revision 1.101  2004/09/15 10:38:38  brouard
   52:   Fix on curr_time
   53: 
   54:   Revision 1.100  2004/07/12 18:29:06  brouard
   55:   Add version for Mac OS X. Just define UNIX in Makefile
   56: 
   57:   Revision 1.99  2004/06/05 08:57:40  brouard
   58:   *** empty log message ***
   59: 
   60:   Revision 1.98  2004/05/16 15:05:56  brouard
   61:   New version 0.97 . First attempt to estimate force of mortality
   62:   directly from the data i.e. without the need of knowing the health
   63:   state at each age, but using a Gompertz model: log u =a + b*age .
   64:   This is the basic analysis of mortality and should be done before any
   65:   other analysis, in order to test if the mortality estimated from the
   66:   cross-longitudinal survey is different from the mortality estimated
   67:   from other sources like vital statistic data.
   68: 
   69:   The same imach parameter file can be used but the option for mle should be -3.
   70: 
   71:   Agnès, who wrote this part of the code, tried to keep most of the
   72:   former routines in order to include the new code within the former code.
   73: 
   74:   The output is very simple: only an estimate of the intercept and of
   75:   the slope with 95% confident intervals.
   76: 
   77:   Current limitations:
   78:   A) Even if you enter covariates, i.e. with the
   79:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
   80:   B) There is no computation of Life Expectancy nor Life Table.
   81: 
   82:   Revision 1.97  2004/02/20 13:25:42  lievre
   83:   Version 0.96d. Population forecasting command line is (temporarily)
   84:   suppressed.
   85: 
   86:   Revision 1.96  2003/07/15 15:38:55  brouard
   87:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
   88:   rewritten within the same printf. Workaround: many printfs.
   89: 
   90:   Revision 1.95  2003/07/08 07:54:34  brouard
   91:   * imach.c (Repository):
   92:   (Repository): Using imachwizard code to output a more meaningful covariance
   93:   matrix (cov(a12,c31) instead of numbers.
   94: 
   95:   Revision 1.94  2003/06/27 13:00:02  brouard
   96:   Just cleaning
   97: 
   98:   Revision 1.93  2003/06/25 16:33:55  brouard
   99:   (Module): On windows (cygwin) function asctime_r doesn't
  100:   exist so I changed back to asctime which exists.
  101:   (Module): Version 0.96b
  102: 
  103:   Revision 1.92  2003/06/25 16:30:45  brouard
  104:   (Module): On windows (cygwin) function asctime_r doesn't
  105:   exist so I changed back to asctime which exists.
  106: 
  107:   Revision 1.91  2003/06/25 15:30:29  brouard
  108:   * imach.c (Repository): Duplicated warning errors corrected.
  109:   (Repository): Elapsed time after each iteration is now output. It
  110:   helps to forecast when convergence will be reached. Elapsed time
  111:   is stamped in powell.  We created a new html file for the graphs
  112:   concerning matrix of covariance. It has extension -cov.htm.
  113: 
  114:   Revision 1.90  2003/06/24 12:34:15  brouard
  115:   (Module): Some bugs corrected for windows. Also, when
  116:   mle=-1 a template is output in file "or"mypar.txt with the design
  117:   of the covariance matrix to be input.
  118: 
  119:   Revision 1.89  2003/06/24 12:30:52  brouard
  120:   (Module): Some bugs corrected for windows. Also, when
  121:   mle=-1 a template is output in file "or"mypar.txt with the design
  122:   of the covariance matrix to be input.
  123: 
  124:   Revision 1.88  2003/06/23 17:54:56  brouard
  125:   * 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.
  126: 
  127:   Revision 1.87  2003/06/18 12:26:01  brouard
  128:   Version 0.96
  129: 
  130:   Revision 1.86  2003/06/17 20:04:08  brouard
  131:   (Module): Change position of html and gnuplot routines and added
  132:   routine fileappend.
  133: 
  134:   Revision 1.85  2003/06/17 13:12:43  brouard
  135:   * imach.c (Repository): Check when date of death was earlier that
  136:   current date of interview. It may happen when the death was just
  137:   prior to the death. In this case, dh was negative and likelihood
  138:   was wrong (infinity). We still send an "Error" but patch by
  139:   assuming that the date of death was just one stepm after the
  140:   interview.
  141:   (Repository): Because some people have very long ID (first column)
  142:   we changed int to long in num[] and we added a new lvector for
  143:   memory allocation. But we also truncated to 8 characters (left
  144:   truncation)
  145:   (Repository): No more line truncation errors.
  146: 
  147:   Revision 1.84  2003/06/13 21:44:43  brouard
  148:   * imach.c (Repository): Replace "freqsummary" at a correct
  149:   place. It differs from routine "prevalence" which may be called
  150:   many times. Probs is memory consuming and must be used with
  151:   parcimony.
  152:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
  153: 
  154:   Revision 1.83  2003/06/10 13:39:11  lievre
  155:   *** empty log message ***
  156: 
  157:   Revision 1.82  2003/06/05 15:57:20  brouard
  158:   Add log in  imach.c and  fullversion number is now printed.
  159: 
  160: */
  161: /*
  162:    Interpolated Markov Chain
  163: 
  164:   Short summary of the programme:
  165:   
  166:   This program computes Healthy Life Expectancies from
  167:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
  168:   first survey ("cross") where individuals from different ages are
  169:   interviewed on their health status or degree of disability (in the
  170:   case of a health survey which is our main interest) -2- at least a
  171:   second wave of interviews ("longitudinal") which measure each change
  172:   (if any) in individual health status.  Health expectancies are
  173:   computed from the time spent in each health state according to a
  174:   model. More health states you consider, more time is necessary to reach the
  175:   Maximum Likelihood of the parameters involved in the model.  The
  176:   simplest model is the multinomial logistic model where pij is the
  177:   probability to be observed in state j at the second wave
  178:   conditional to be observed in state i at the first wave. Therefore
  179:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
  180:   'age' is age and 'sex' is a covariate. If you want to have a more
  181:   complex model than "constant and age", you should modify the program
  182:   where the markup *Covariates have to be included here again* invites
  183:   you to do it.  More covariates you add, slower the
  184:   convergence.
  185: 
  186:   The advantage of this computer programme, compared to a simple
  187:   multinomial logistic model, is clear when the delay between waves is not
  188:   identical for each individual. Also, if a individual missed an
  189:   intermediate interview, the information is lost, but taken into
  190:   account using an interpolation or extrapolation.  
  191: 
  192:   hPijx is the probability to be observed in state i at age x+h
  193:   conditional to the observed state i at age x. The delay 'h' can be
  194:   split into an exact number (nh*stepm) of unobserved intermediate
  195:   states. This elementary transition (by month, quarter,
  196:   semester or year) is modelled as a multinomial logistic.  The hPx
  197:   matrix is simply the matrix product of nh*stepm elementary matrices
  198:   and the contribution of each individual to the likelihood is simply
  199:   hPijx.
  200: 
  201:   Also this programme outputs the covariance matrix of the parameters but also
  202:   of the life expectancies. It also computes the stable prevalence. 
  203:   
  204:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
  205:            Institut national d'études démographiques, Paris.
  206:   This software have been partly granted by Euro-REVES, a concerted action
  207:   from the European Union.
  208:   It is copyrighted identically to a GNU software product, ie programme and
  209:   software can be distributed freely for non commercial use. Latest version
  210:   can be accessed at http://euroreves.ined.fr/imach .
  211: 
  212:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
  213:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
  214:   
  215:   **********************************************************************/
  216: /*
  217:   main
  218:   read parameterfile
  219:   read datafile
  220:   concatwav
  221:   freqsummary
  222:   if (mle >= 1)
  223:     mlikeli
  224:   print results files
  225:   if mle==1 
  226:      computes hessian
  227:   read end of parameter file: agemin, agemax, bage, fage, estepm
  228:       begin-prev-date,...
  229:   open gnuplot file
  230:   open html file
  231:   stable prevalence
  232:    for age prevalim()
  233:   h Pij x
  234:   variance of p varprob
  235:   forecasting if prevfcast==1 prevforecast call prevalence()
  236:   health expectancies
  237:   Variance-covariance of DFLE
  238:   prevalence()
  239:    movingaverage()
  240:   varevsij() 
  241:   if popbased==1 varevsij(,popbased)
  242:   total life expectancies
  243:   Variance of stable prevalence
  244:  end
  245: */
  246: 
  247: 
  248: 
  249:  
  250: #include <math.h>
  251: #include <stdio.h>
  252: #include <stdlib.h>
  253: #include <string.h>
  254: #include <unistd.h>
  255: 
  256: #include <limits.h>
  257: #include <sys/types.h>
  258: #include <sys/stat.h>
  259: #include <errno.h>
  260: extern int errno;
  261: 
  262: /* #include <sys/time.h> */
  263: #include <time.h>
  264: #include "timeval.h"
  265: 
  266: /* #include <libintl.h> */
  267: /* #define _(String) gettext (String) */
  268: 
  269: #define MAXLINE 256
  270: 
  271: #define GNUPLOTPROGRAM "gnuplot"
  272: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
  273: #define FILENAMELENGTH 132
  274: 
  275: #define	GLOCK_ERROR_NOPATH		-1	/* empty path */
  276: #define	GLOCK_ERROR_GETCWD		-2	/* cannot get cwd */
  277: 
  278: #define MAXPARM 30 /* Maximum number of parameters for the optimization */
  279: #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncovmodel */
  280: 
  281: #define NINTERVMAX 8
  282: #define NLSTATEMAX 8 /* Maximum number of live states (for func) */
  283: #define NDEATHMAX 8 /* Maximum number of dead states (for func) */
  284: #define NCOVMAX 8 /* Maximum number of covariates */
  285: #define MAXN 20000
  286: #define YEARM 12. /* Number of months per year */
  287: #define AGESUP 130
  288: #define AGEBASE 40
  289: #define AGEGOMP 10. /* Minimal age for Gompertz adjustment */
  290: #ifdef UNIX
  291: #define DIRSEPARATOR '/'
  292: #define CHARSEPARATOR "/"
  293: #define ODIRSEPARATOR '\\'
  294: #else
  295: #define DIRSEPARATOR '\\'
  296: #define CHARSEPARATOR "\\"
  297: #define ODIRSEPARATOR '/'
  298: #endif
  299: 
  300: /* $Id: imach.c,v 1.113 2006/02/24 14:20:24 brouard Exp $ */
  301: /* $State: Exp $ */
  302: 
  303: char version[]="Imach version 0.98b, January 2006, INED-EUROREVES ";
  304: char fullversion[]="$Revision: 1.113 $ $Date: 2006/02/24 14:20:24 $"; 
  305: int erreur, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
  306: int nvar;
  307: int cptcovn=0, cptcovage=0, cptcoveff=0,cptcov;
  308: int npar=NPARMAX;
  309: int nlstate=2; /* Number of live states */
  310: int ndeath=1; /* Number of dead states */
  311: int ncovmodel, ncovcol;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
  312: int popbased=0;
  313: 
  314: int *wav; /* Number of waves for this individuual 0 is possible */
  315: int maxwav; /* Maxim number of waves */
  316: int jmin, jmax; /* min, max spacing between 2 waves */
  317: int ijmin, ijmax; /* Individuals having jmin and jmax */ 
  318: int gipmx, gsw; /* Global variables on the number of contributions 
  319: 		   to the likelihood and the sum of weights (done by funcone)*/
  320: int mle, weightopt;
  321: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
  322: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
  323: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
  324: 	   * wave mi and wave mi+1 is not an exact multiple of stepm. */
  325: double jmean; /* Mean space between 2 waves */
  326: double **oldm, **newm, **savm; /* Working pointers to matrices */
  327: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
  328: FILE *fic,*ficpar, *ficparo,*ficres,  *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
  329: FILE *ficlog, *ficrespow;
  330: int globpr; /* Global variable for printing or not */
  331: double fretone; /* Only one call to likelihood */
  332: long ipmx; /* Number of contributions */
  333: double sw; /* Sum of weights */
  334: char filerespow[FILENAMELENGTH];
  335: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
  336: FILE *ficresilk;
  337: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
  338: FILE *ficresprobmorprev;
  339: FILE *fichtm, *fichtmcov; /* Html File */
  340: FILE *ficreseij;
  341: char filerese[FILENAMELENGTH];
  342: FILE  *ficresvij;
  343: char fileresv[FILENAMELENGTH];
  344: FILE  *ficresvpl;
  345: char fileresvpl[FILENAMELENGTH];
  346: char title[MAXLINE];
  347: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
  348: char optionfilext[10], optionfilefiname[FILENAMELENGTH], plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
  349: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
  350: char command[FILENAMELENGTH];
  351: int  outcmd=0;
  352: 
  353: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
  354: 
  355: char filelog[FILENAMELENGTH]; /* Log file */
  356: char filerest[FILENAMELENGTH];
  357: char fileregp[FILENAMELENGTH];
  358: char popfile[FILENAMELENGTH];
  359: 
  360: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
  361: 
  362: struct timeval start_time, end_time, curr_time, last_time, forecast_time;
  363: struct timezone tzp;
  364: extern int gettimeofday();
  365: struct tm tmg, tm, tmf, *gmtime(), *localtime();
  366: long time_value;
  367: extern long time();
  368: char strcurr[80], strfor[80];
  369: 
  370: char *endptr;
  371: long lval;
  372: 
  373: #define NR_END 1
  374: #define FREE_ARG char*
  375: #define FTOL 1.0e-10
  376: 
  377: #define NRANSI 
  378: #define ITMAX 200 
  379: 
  380: #define TOL 2.0e-4 
  381: 
  382: #define CGOLD 0.3819660 
  383: #define ZEPS 1.0e-10 
  384: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
  385: 
  386: #define GOLD 1.618034 
  387: #define GLIMIT 100.0 
  388: #define TINY 1.0e-20 
  389: 
  390: static double maxarg1,maxarg2;
  391: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
  392: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
  393:   
  394: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
  395: #define rint(a) floor(a+0.5)
  396: 
  397: static double sqrarg;
  398: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
  399: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
  400: int agegomp= AGEGOMP;
  401: 
  402: int imx; 
  403: int stepm=1;
  404: /* Stepm, step in month: minimum step interpolation*/
  405: 
  406: int estepm;
  407: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
  408: 
  409: int m,nb;
  410: long *num;
  411: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
  412: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
  413: double **pmmij, ***probs;
  414: double *ageexmed,*agecens;
  415: double dateintmean=0;
  416: 
  417: double *weight;
  418: int **s; /* Status */
  419: double *agedc, **covar, idx;
  420: int **nbcode, *Tcode, *Tvar, **codtab, **Tvard, *Tprod, cptcovprod, *Tvaraff;
  421: double *lsurv, *lpop, *tpop;
  422: 
  423: double ftol=FTOL; /* Tolerance for computing Max Likelihood */
  424: double ftolhess; /* Tolerance for computing hessian */
  425: 
  426: /**************** split *************************/
  427: static	int split( char *path, char *dirc, char *name, char *ext, char *finame )
  428: {
  429:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
  430:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
  431:   */ 
  432:   char	*ss;				/* pointer */
  433:   int	l1, l2;				/* length counters */
  434: 
  435:   l1 = strlen(path );			/* length of path */
  436:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
  437:   ss= strrchr( path, DIRSEPARATOR );		/* find last / */
  438:   if ( ss == NULL ) {			/* no directory, so determine current directory */
  439:     strcpy( name, path );		/* we got the fullname name because no directory */
  440:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
  441:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
  442:     /* get current working directory */
  443:     /*    extern  char* getcwd ( char *buf , int len);*/
  444:     if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
  445:       return( GLOCK_ERROR_GETCWD );
  446:     }
  447:     /* got dirc from getcwd*/
  448:     printf(" DIRC = %s \n",dirc);
  449:   } else {				/* strip direcotry from path */
  450:     ss++;				/* after this, the filename */
  451:     l2 = strlen( ss );			/* length of filename */
  452:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
  453:     strcpy( name, ss );		/* save file name */
  454:     strncpy( dirc, path, l1 - l2 );	/* now the directory */
  455:     dirc[l1-l2] = 0;			/* add zero */
  456:     printf(" DIRC2 = %s \n",dirc);
  457:   }
  458:   /* We add a separator at the end of dirc if not exists */
  459:   l1 = strlen( dirc );			/* length of directory */
  460:   if( dirc[l1-1] != DIRSEPARATOR ){
  461:     dirc[l1] =  DIRSEPARATOR;
  462:     dirc[l1+1] = 0; 
  463:     printf(" DIRC3 = %s \n",dirc);
  464:   }
  465:   ss = strrchr( name, '.' );		/* find last / */
  466:   if (ss >0){
  467:     ss++;
  468:     strcpy(ext,ss);			/* save extension */
  469:     l1= strlen( name);
  470:     l2= strlen(ss)+1;
  471:     strncpy( finame, name, l1-l2);
  472:     finame[l1-l2]= 0;
  473:   }
  474: 
  475:   return( 0 );				/* we're done */
  476: }
  477: 
  478: 
  479: /******************************************/
  480: 
  481: void replace_back_to_slash(char *s, char*t)
  482: {
  483:   int i;
  484:   int lg=0;
  485:   i=0;
  486:   lg=strlen(t);
  487:   for(i=0; i<= lg; i++) {
  488:     (s[i] = t[i]);
  489:     if (t[i]== '\\') s[i]='/';
  490:   }
  491: }
  492: 
  493: int nbocc(char *s, char occ)
  494: {
  495:   int i,j=0;
  496:   int lg=20;
  497:   i=0;
  498:   lg=strlen(s);
  499:   for(i=0; i<= lg; i++) {
  500:   if  (s[i] == occ ) j++;
  501:   }
  502:   return j;
  503: }
  504: 
  505: void cutv(char *u,char *v, char*t, char occ)
  506: {
  507:   /* cuts string t into u and v where u ends before first occurence of char 'occ' 
  508:      and v starts after first occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2')
  509:      gives u="abcedf" and v="ghi2j" */
  510:   int i,lg,j,p=0;
  511:   i=0;
  512:   for(j=0; j<=strlen(t)-1; j++) {
  513:     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1;
  514:   }
  515: 
  516:   lg=strlen(t);
  517:   for(j=0; j<p; j++) {
  518:     (u[j] = t[j]);
  519:   }
  520:      u[p]='\0';
  521: 
  522:    for(j=0; j<= lg; j++) {
  523:     if (j>=(p+1))(v[j-p-1] = t[j]);
  524:   }
  525: }
  526: 
  527: /********************** nrerror ********************/
  528: 
  529: void nrerror(char error_text[])
  530: {
  531:   fprintf(stderr,"ERREUR ...\n");
  532:   fprintf(stderr,"%s\n",error_text);
  533:   exit(EXIT_FAILURE);
  534: }
  535: /*********************** vector *******************/
  536: double *vector(int nl, int nh)
  537: {
  538:   double *v;
  539:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
  540:   if (!v) nrerror("allocation failure in vector");
  541:   return v-nl+NR_END;
  542: }
  543: 
  544: /************************ free vector ******************/
  545: void free_vector(double*v, int nl, int nh)
  546: {
  547:   free((FREE_ARG)(v+nl-NR_END));
  548: }
  549: 
  550: /************************ivector *******************************/
  551: int *ivector(long nl,long nh)
  552: {
  553:   int *v;
  554:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
  555:   if (!v) nrerror("allocation failure in ivector");
  556:   return v-nl+NR_END;
  557: }
  558: 
  559: /******************free ivector **************************/
  560: void free_ivector(int *v, long nl, long nh)
  561: {
  562:   free((FREE_ARG)(v+nl-NR_END));
  563: }
  564: 
  565: /************************lvector *******************************/
  566: long *lvector(long nl,long nh)
  567: {
  568:   long *v;
  569:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
  570:   if (!v) nrerror("allocation failure in ivector");
  571:   return v-nl+NR_END;
  572: }
  573: 
  574: /******************free lvector **************************/
  575: void free_lvector(long *v, long nl, long nh)
  576: {
  577:   free((FREE_ARG)(v+nl-NR_END));
  578: }
  579: 
  580: /******************* imatrix *******************************/
  581: int **imatrix(long nrl, long nrh, long ncl, long nch) 
  582:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
  583: { 
  584:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
  585:   int **m; 
  586:   
  587:   /* allocate pointers to rows */ 
  588:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
  589:   if (!m) nrerror("allocation failure 1 in matrix()"); 
  590:   m += NR_END; 
  591:   m -= nrl; 
  592:   
  593:   
  594:   /* allocate rows and set pointers to them */ 
  595:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
  596:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
  597:   m[nrl] += NR_END; 
  598:   m[nrl] -= ncl; 
  599:   
  600:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
  601:   
  602:   /* return pointer to array of pointers to rows */ 
  603:   return m; 
  604: } 
  605: 
  606: /****************** free_imatrix *************************/
  607: void free_imatrix(m,nrl,nrh,ncl,nch)
  608:       int **m;
  609:       long nch,ncl,nrh,nrl; 
  610:      /* free an int matrix allocated by imatrix() */ 
  611: { 
  612:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
  613:   free((FREE_ARG) (m+nrl-NR_END)); 
  614: } 
  615: 
  616: /******************* matrix *******************************/
  617: double **matrix(long nrl, long nrh, long ncl, long nch)
  618: {
  619:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
  620:   double **m;
  621: 
  622:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
  623:   if (!m) nrerror("allocation failure 1 in matrix()");
  624:   m += NR_END;
  625:   m -= nrl;
  626: 
  627:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
  628:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
  629:   m[nrl] += NR_END;
  630:   m[nrl] -= ncl;
  631: 
  632:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
  633:   return m;
  634:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) 
  635:    */
  636: }
  637: 
  638: /*************************free matrix ************************/
  639: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
  640: {
  641:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
  642:   free((FREE_ARG)(m+nrl-NR_END));
  643: }
  644: 
  645: /******************* ma3x *******************************/
  646: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
  647: {
  648:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
  649:   double ***m;
  650: 
  651:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
  652:   if (!m) nrerror("allocation failure 1 in matrix()");
  653:   m += NR_END;
  654:   m -= nrl;
  655: 
  656:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
  657:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
  658:   m[nrl] += NR_END;
  659:   m[nrl] -= ncl;
  660: 
  661:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
  662: 
  663:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
  664:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
  665:   m[nrl][ncl] += NR_END;
  666:   m[nrl][ncl] -= nll;
  667:   for (j=ncl+1; j<=nch; j++) 
  668:     m[nrl][j]=m[nrl][j-1]+nlay;
  669:   
  670:   for (i=nrl+1; i<=nrh; i++) {
  671:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
  672:     for (j=ncl+1; j<=nch; j++) 
  673:       m[i][j]=m[i][j-1]+nlay;
  674:   }
  675:   return m; 
  676:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
  677:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
  678:   */
  679: }
  680: 
  681: /*************************free ma3x ************************/
  682: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
  683: {
  684:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
  685:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
  686:   free((FREE_ARG)(m+nrl-NR_END));
  687: }
  688: 
  689: /*************** function subdirf ***********/
  690: char *subdirf(char fileres[])
  691: {
  692:   /* Caution optionfilefiname is hidden */
  693:   strcpy(tmpout,optionfilefiname);
  694:   strcat(tmpout,"/"); /* Add to the right */
  695:   strcat(tmpout,fileres);
  696:   return tmpout;
  697: }
  698: 
  699: /*************** function subdirf2 ***********/
  700: char *subdirf2(char fileres[], char *preop)
  701: {
  702:   
  703:   /* Caution optionfilefiname is hidden */
  704:   strcpy(tmpout,optionfilefiname);
  705:   strcat(tmpout,"/");
  706:   strcat(tmpout,preop);
  707:   strcat(tmpout,fileres);
  708:   return tmpout;
  709: }
  710: 
  711: /*************** function subdirf3 ***********/
  712: char *subdirf3(char fileres[], char *preop, char *preop2)
  713: {
  714:   
  715:   /* Caution optionfilefiname is hidden */
  716:   strcpy(tmpout,optionfilefiname);
  717:   strcat(tmpout,"/");
  718:   strcat(tmpout,preop);
  719:   strcat(tmpout,preop2);
  720:   strcat(tmpout,fileres);
  721:   return tmpout;
  722: }
  723: 
  724: /***************** f1dim *************************/
  725: extern int ncom; 
  726: extern double *pcom,*xicom;
  727: extern double (*nrfunc)(double []); 
  728:  
  729: double f1dim(double x) 
  730: { 
  731:   int j; 
  732:   double f;
  733:   double *xt; 
  734:  
  735:   xt=vector(1,ncom); 
  736:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
  737:   f=(*nrfunc)(xt); 
  738:   free_vector(xt,1,ncom); 
  739:   return f; 
  740: } 
  741: 
  742: /*****************brent *************************/
  743: double brent(double ax, double bx, double cx, double (*f)(double), double tol, 	double *xmin) 
  744: { 
  745:   int iter; 
  746:   double a,b,d,etemp;
  747:   double fu,fv,fw,fx;
  748:   double ftemp;
  749:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
  750:   double e=0.0; 
  751:  
  752:   a=(ax < cx ? ax : cx); 
  753:   b=(ax > cx ? ax : cx); 
  754:   x=w=v=bx; 
  755:   fw=fv=fx=(*f)(x); 
  756:   for (iter=1;iter<=ITMAX;iter++) { 
  757:     xm=0.5*(a+b); 
  758:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
  759:     /*		if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
  760:     printf(".");fflush(stdout);
  761:     fprintf(ficlog,".");fflush(ficlog);
  762: #ifdef DEBUG
  763:     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);
  764:     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);
  765:     /*		if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
  766: #endif
  767:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
  768:       *xmin=x; 
  769:       return fx; 
  770:     } 
  771:     ftemp=fu;
  772:     if (fabs(e) > tol1) { 
  773:       r=(x-w)*(fx-fv); 
  774:       q=(x-v)*(fx-fw); 
  775:       p=(x-v)*q-(x-w)*r; 
  776:       q=2.0*(q-r); 
  777:       if (q > 0.0) p = -p; 
  778:       q=fabs(q); 
  779:       etemp=e; 
  780:       e=d; 
  781:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
  782: 	d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
  783:       else { 
  784: 	d=p/q; 
  785: 	u=x+d; 
  786: 	if (u-a < tol2 || b-u < tol2) 
  787: 	  d=SIGN(tol1,xm-x); 
  788:       } 
  789:     } else { 
  790:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
  791:     } 
  792:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
  793:     fu=(*f)(u); 
  794:     if (fu <= fx) { 
  795:       if (u >= x) a=x; else b=x; 
  796:       SHFT(v,w,x,u) 
  797: 	SHFT(fv,fw,fx,fu) 
  798: 	} else { 
  799: 	  if (u < x) a=u; else b=u; 
  800: 	  if (fu <= fw || w == x) { 
  801: 	    v=w; 
  802: 	    w=u; 
  803: 	    fv=fw; 
  804: 	    fw=fu; 
  805: 	  } else if (fu <= fv || v == x || v == w) { 
  806: 	    v=u; 
  807: 	    fv=fu; 
  808: 	  } 
  809: 	} 
  810:   } 
  811:   nrerror("Too many iterations in brent"); 
  812:   *xmin=x; 
  813:   return fx; 
  814: } 
  815: 
  816: /****************** mnbrak ***********************/
  817: 
  818: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
  819: 	    double (*func)(double)) 
  820: { 
  821:   double ulim,u,r,q, dum;
  822:   double fu; 
  823:  
  824:   *fa=(*func)(*ax); 
  825:   *fb=(*func)(*bx); 
  826:   if (*fb > *fa) { 
  827:     SHFT(dum,*ax,*bx,dum) 
  828:       SHFT(dum,*fb,*fa,dum) 
  829:       } 
  830:   *cx=(*bx)+GOLD*(*bx-*ax); 
  831:   *fc=(*func)(*cx); 
  832:   while (*fb > *fc) { 
  833:     r=(*bx-*ax)*(*fb-*fc); 
  834:     q=(*bx-*cx)*(*fb-*fa); 
  835:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
  836:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); 
  837:     ulim=(*bx)+GLIMIT*(*cx-*bx); 
  838:     if ((*bx-u)*(u-*cx) > 0.0) { 
  839:       fu=(*func)(u); 
  840:     } else if ((*cx-u)*(u-ulim) > 0.0) { 
  841:       fu=(*func)(u); 
  842:       if (fu < *fc) { 
  843: 	SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
  844: 	  SHFT(*fb,*fc,fu,(*func)(u)) 
  845: 	  } 
  846:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { 
  847:       u=ulim; 
  848:       fu=(*func)(u); 
  849:     } else { 
  850:       u=(*cx)+GOLD*(*cx-*bx); 
  851:       fu=(*func)(u); 
  852:     } 
  853:     SHFT(*ax,*bx,*cx,u) 
  854:       SHFT(*fa,*fb,*fc,fu) 
  855:       } 
  856: } 
  857: 
  858: /*************** linmin ************************/
  859: 
  860: int ncom; 
  861: double *pcom,*xicom;
  862: double (*nrfunc)(double []); 
  863:  
  864: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
  865: { 
  866:   double brent(double ax, double bx, double cx, 
  867: 	       double (*f)(double), double tol, double *xmin); 
  868:   double f1dim(double x); 
  869:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
  870: 	      double *fc, double (*func)(double)); 
  871:   int j; 
  872:   double xx,xmin,bx,ax; 
  873:   double fx,fb,fa;
  874:  
  875:   ncom=n; 
  876:   pcom=vector(1,n); 
  877:   xicom=vector(1,n); 
  878:   nrfunc=func; 
  879:   for (j=1;j<=n;j++) { 
  880:     pcom[j]=p[j]; 
  881:     xicom[j]=xi[j]; 
  882:   } 
  883:   ax=0.0; 
  884:   xx=1.0; 
  885:   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); 
  886:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); 
  887: #ifdef DEBUG
  888:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
  889:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
  890: #endif
  891:   for (j=1;j<=n;j++) { 
  892:     xi[j] *= xmin; 
  893:     p[j] += xi[j]; 
  894:   } 
  895:   free_vector(xicom,1,n); 
  896:   free_vector(pcom,1,n); 
  897: } 
  898: 
  899: char *asc_diff_time(long time_sec, char ascdiff[])
  900: {
  901:   long sec_left, days, hours, minutes;
  902:   days = (time_sec) / (60*60*24);
  903:   sec_left = (time_sec) % (60*60*24);
  904:   hours = (sec_left) / (60*60) ;
  905:   sec_left = (sec_left) %(60*60);
  906:   minutes = (sec_left) /60;
  907:   sec_left = (sec_left) % (60);
  908:   sprintf(ascdiff,"%d day(s) %d hour(s) %d minute(s) %d second(s)",days, hours, minutes, sec_left);  
  909:   return ascdiff;
  910: }
  911: 
  912: /*************** powell ************************/
  913: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
  914: 	    double (*func)(double [])) 
  915: { 
  916:   void linmin(double p[], double xi[], int n, double *fret, 
  917: 	      double (*func)(double [])); 
  918:   int i,ibig,j; 
  919:   double del,t,*pt,*ptt,*xit;
  920:   double fp,fptt;
  921:   double *xits;
  922:   int niterf, itmp;
  923: 
  924:   pt=vector(1,n); 
  925:   ptt=vector(1,n); 
  926:   xit=vector(1,n); 
  927:   xits=vector(1,n); 
  928:   *fret=(*func)(p); 
  929:   for (j=1;j<=n;j++) pt[j]=p[j]; 
  930:   for (*iter=1;;++(*iter)) { 
  931:     fp=(*fret); 
  932:     ibig=0; 
  933:     del=0.0; 
  934:     last_time=curr_time;
  935:     (void) gettimeofday(&curr_time,&tzp);
  936:     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);
  937:     /*    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);
  938:     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tv_sec-start_time.tv_sec);
  939:     */
  940:    for (i=1;i<=n;i++) {
  941:       printf(" %d %.12f",i, p[i]);
  942:       fprintf(ficlog," %d %.12lf",i, p[i]);
  943:       fprintf(ficrespow," %.12lf", p[i]);
  944:     }
  945:     printf("\n");
  946:     fprintf(ficlog,"\n");
  947:     fprintf(ficrespow,"\n");fflush(ficrespow);
  948:     if(*iter <=3){
  949:       tm = *localtime(&curr_time.tv_sec);
  950:       strcpy(strcurr,asctime(&tm));
  951: /*       asctime_r(&tm,strcurr); */
  952:       forecast_time=curr_time; 
  953:       itmp = strlen(strcurr);
  954:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
  955: 	strcurr[itmp-1]='\0';
  956:       printf("\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
  957:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
  958:       for(niterf=10;niterf<=30;niterf+=10){
  959: 	forecast_time.tv_sec=curr_time.tv_sec+(niterf-*iter)*(curr_time.tv_sec-last_time.tv_sec);
  960: 	tmf = *localtime(&forecast_time.tv_sec);
  961: /* 	asctime_r(&tmf,strfor); */
  962: 	strcpy(strfor,asctime(&tmf));
  963: 	itmp = strlen(strfor);
  964: 	if(strfor[itmp-1]=='\n')
  965: 	strfor[itmp-1]='\0';
  966: 	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);
  967: 	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);
  968:       }
  969:     }
  970:     for (i=1;i<=n;i++) { 
  971:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; 
  972:       fptt=(*fret); 
  973: #ifdef DEBUG
  974:       printf("fret=%lf \n",*fret);
  975:       fprintf(ficlog,"fret=%lf \n",*fret);
  976: #endif
  977:       printf("%d",i);fflush(stdout);
  978:       fprintf(ficlog,"%d",i);fflush(ficlog);
  979:       linmin(p,xit,n,fret,func); 
  980:       if (fabs(fptt-(*fret)) > del) { 
  981: 	del=fabs(fptt-(*fret)); 
  982: 	ibig=i; 
  983:       } 
  984: #ifdef DEBUG
  985:       printf("%d %.12e",i,(*fret));
  986:       fprintf(ficlog,"%d %.12e",i,(*fret));
  987:       for (j=1;j<=n;j++) {
  988: 	xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
  989: 	printf(" x(%d)=%.12e",j,xit[j]);
  990: 	fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
  991:       }
  992:       for(j=1;j<=n;j++) {
  993: 	printf(" p=%.12e",p[j]);
  994: 	fprintf(ficlog," p=%.12e",p[j]);
  995:       }
  996:       printf("\n");
  997:       fprintf(ficlog,"\n");
  998: #endif
  999:     } 
 1000:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
 1001: #ifdef DEBUG
 1002:       int k[2],l;
 1003:       k[0]=1;
 1004:       k[1]=-1;
 1005:       printf("Max: %.12e",(*func)(p));
 1006:       fprintf(ficlog,"Max: %.12e",(*func)(p));
 1007:       for (j=1;j<=n;j++) {
 1008: 	printf(" %.12e",p[j]);
 1009: 	fprintf(ficlog," %.12e",p[j]);
 1010:       }
 1011:       printf("\n");
 1012:       fprintf(ficlog,"\n");
 1013:       for(l=0;l<=1;l++) {
 1014: 	for (j=1;j<=n;j++) {
 1015: 	  ptt[j]=p[j]+(p[j]-pt[j])*k[l];
 1016: 	  printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1017: 	  fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1018: 	}
 1019: 	printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1020: 	fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1021:       }
 1022: #endif
 1023: 
 1024: 
 1025:       free_vector(xit,1,n); 
 1026:       free_vector(xits,1,n); 
 1027:       free_vector(ptt,1,n); 
 1028:       free_vector(pt,1,n); 
 1029:       return; 
 1030:     } 
 1031:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
 1032:     for (j=1;j<=n;j++) { 
 1033:       ptt[j]=2.0*p[j]-pt[j]; 
 1034:       xit[j]=p[j]-pt[j]; 
 1035:       pt[j]=p[j]; 
 1036:     } 
 1037:     fptt=(*func)(ptt); 
 1038:     if (fptt < fp) { 
 1039:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); 
 1040:       if (t < 0.0) { 
 1041: 	linmin(p,xit,n,fret,func); 
 1042: 	for (j=1;j<=n;j++) { 
 1043: 	  xi[j][ibig]=xi[j][n]; 
 1044: 	  xi[j][n]=xit[j]; 
 1045: 	}
 1046: #ifdef DEBUG
 1047: 	printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 1048: 	fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 1049: 	for(j=1;j<=n;j++){
 1050: 	  printf(" %.12e",xit[j]);
 1051: 	  fprintf(ficlog," %.12e",xit[j]);
 1052: 	}
 1053: 	printf("\n");
 1054: 	fprintf(ficlog,"\n");
 1055: #endif
 1056:       }
 1057:     } 
 1058:   } 
 1059: } 
 1060: 
 1061: /**** Prevalence limit (stable prevalence)  ****************/
 1062: 
 1063: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
 1064: {
 1065:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
 1066:      matrix by transitions matrix until convergence is reached */
 1067: 
 1068:   int i, ii,j,k;
 1069:   double min, max, maxmin, maxmax,sumnew=0.;
 1070:   double **matprod2();
 1071:   double **out, cov[NCOVMAX], **pmij();
 1072:   double **newm;
 1073:   double agefin, delaymax=50 ; /* Max number of years to converge */
 1074: 
 1075:   for (ii=1;ii<=nlstate+ndeath;ii++)
 1076:     for (j=1;j<=nlstate+ndeath;j++){
 1077:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1078:     }
 1079: 
 1080:    cov[1]=1.;
 1081:  
 1082:  /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 1083:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
 1084:     newm=savm;
 1085:     /* Covariates have to be included here again */
 1086:      cov[2]=agefin;
 1087:   
 1088:       for (k=1; k<=cptcovn;k++) {
 1089: 	cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
 1090: 	/*	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]]);*/
 1091:       }
 1092:       for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
 1093:       for (k=1; k<=cptcovprod;k++)
 1094: 	cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 1095: 
 1096:       /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 1097:       /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 1098:       /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 1099:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
 1100: 
 1101:     savm=oldm;
 1102:     oldm=newm;
 1103:     maxmax=0.;
 1104:     for(j=1;j<=nlstate;j++){
 1105:       min=1.;
 1106:       max=0.;
 1107:       for(i=1; i<=nlstate; i++) {
 1108: 	sumnew=0;
 1109: 	for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
 1110: 	prlim[i][j]= newm[i][j]/(1-sumnew);
 1111: 	max=FMAX(max,prlim[i][j]);
 1112: 	min=FMIN(min,prlim[i][j]);
 1113:       }
 1114:       maxmin=max-min;
 1115:       maxmax=FMAX(maxmax,maxmin);
 1116:     }
 1117:     if(maxmax < ftolpl){
 1118:       return prlim;
 1119:     }
 1120:   }
 1121: }
 1122: 
 1123: /*************** transition probabilities ***************/ 
 1124: 
 1125: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 1126: {
 1127:   double s1, s2;
 1128:   /*double t34;*/
 1129:   int i,j,j1, nc, ii, jj;
 1130: 
 1131:     for(i=1; i<= nlstate; i++){
 1132:       for(j=1; j<i;j++){
 1133: 	for (nc=1, s2=0.;nc <=ncovmodel; nc++){
 1134: 	  /*s2 += param[i][j][nc]*cov[nc];*/
 1135: 	  s2 += x[(i-1)*nlstate*ncovmodel+(j-1)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
 1136: /* 	 printf("Int j<i s1=%.17e, s2=%.17e\n",s1,s2); */
 1137: 	}
 1138: 	ps[i][j]=s2;
 1139: /* 	printf("s1=%.17e, s2=%.17e\n",s1,s2); */
 1140:       }
 1141:       for(j=i+1; j<=nlstate+ndeath;j++){
 1142: 	for (nc=1, s2=0.;nc <=ncovmodel; nc++){
 1143: 	  s2 += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
 1144: /* 	  printf("Int j>i s1=%.17e, s2=%.17e %lx %lx\n",s1,s2,s1,s2); */
 1145: 	}
 1146: 	ps[i][j]=s2;
 1147:       }
 1148:     }
 1149:     /*ps[3][2]=1;*/
 1150:     
 1151:     for(i=1; i<= nlstate; i++){
 1152:       s1=0;
 1153:       for(j=1; j<i; j++)
 1154: 	s1+=exp(ps[i][j]);
 1155:       for(j=i+1; j<=nlstate+ndeath; j++)
 1156: 	s1+=exp(ps[i][j]);
 1157:       ps[i][i]=1./(s1+1.);
 1158:       for(j=1; j<i; j++)
 1159: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 1160:       for(j=i+1; j<=nlstate+ndeath; j++)
 1161: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 1162:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 1163:     } /* end i */
 1164:     
 1165:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 1166:       for(jj=1; jj<= nlstate+ndeath; jj++){
 1167: 	ps[ii][jj]=0;
 1168: 	ps[ii][ii]=1;
 1169:       }
 1170:     }
 1171:     
 1172: 
 1173: /*        for(ii=1; ii<= nlstate+ndeath; ii++){ */
 1174: /* 	 for(jj=1; jj<= nlstate+ndeath; jj++){ */
 1175: /* 	   printf("ddd %lf ",ps[ii][jj]); */
 1176: /* 	 } */
 1177: /* 	 printf("\n "); */
 1178: /*        } */
 1179: /*        printf("\n ");printf("%lf ",cov[2]); */
 1180:        /*
 1181:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
 1182:       goto end;*/
 1183:     return ps;
 1184: }
 1185: 
 1186: /**************** Product of 2 matrices ******************/
 1187: 
 1188: double **matprod2(double **out, double **in,long nrl, long nrh, long ncl, long nch, long ncolol, long ncoloh, double **b)
 1189: {
 1190:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
 1191:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
 1192:   /* in, b, out are matrice of pointers which should have been initialized 
 1193:      before: only the contents of out is modified. The function returns
 1194:      a pointer to pointers identical to out */
 1195:   long i, j, k;
 1196:   for(i=nrl; i<= nrh; i++)
 1197:     for(k=ncolol; k<=ncoloh; k++)
 1198:       for(j=ncl,out[i][k]=0.; j<=nch; j++)
 1199: 	out[i][k] +=in[i][j]*b[j][k];
 1200: 
 1201:   return out;
 1202: }
 1203: 
 1204: 
 1205: /************* Higher Matrix Product ***************/
 1206: 
 1207: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
 1208: {
 1209:   /* Computes the transition matrix starting at age 'age' over 
 1210:      'nhstepm*hstepm*stepm' months (i.e. until
 1211:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
 1212:      nhstepm*hstepm matrices. 
 1213:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
 1214:      (typically every 2 years instead of every month which is too big 
 1215:      for the memory).
 1216:      Model is determined by parameters x and covariates have to be 
 1217:      included manually here. 
 1218: 
 1219:      */
 1220: 
 1221:   int i, j, d, h, k;
 1222:   double **out, cov[NCOVMAX];
 1223:   double **newm;
 1224: 
 1225:   /* Hstepm could be zero and should return the unit matrix */
 1226:   for (i=1;i<=nlstate+ndeath;i++)
 1227:     for (j=1;j<=nlstate+ndeath;j++){
 1228:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 1229:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 1230:     }
 1231:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 1232:   for(h=1; h <=nhstepm; h++){
 1233:     for(d=1; d <=hstepm; d++){
 1234:       newm=savm;
 1235:       /* Covariates have to be included here again */
 1236:       cov[1]=1.;
 1237:       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
 1238:       for (k=1; k<=cptcovn;k++) cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
 1239:       for (k=1; k<=cptcovage;k++)
 1240: 	cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
 1241:       for (k=1; k<=cptcovprod;k++)
 1242: 	cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 1243: 
 1244: 
 1245:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 1246:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 1247:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
 1248: 		   pmij(pmmij,cov,ncovmodel,x,nlstate));
 1249:       savm=oldm;
 1250:       oldm=newm;
 1251:     }
 1252:     for(i=1; i<=nlstate+ndeath; i++)
 1253:       for(j=1;j<=nlstate+ndeath;j++) {
 1254: 	po[i][j][h]=newm[i][j];
 1255: 	/*printf("i=%d j=%d h=%d po[i][j][h]=%f ",i,j,h,po[i][j][h]);
 1256: 	 */
 1257:       }
 1258:   } /* end h */
 1259:   return po;
 1260: }
 1261: 
 1262: 
 1263: /*************** log-likelihood *************/
 1264: double func( double *x)
 1265: {
 1266:   int i, ii, j, k, mi, d, kk;
 1267:   double l, ll[NLSTATEMAX], cov[NCOVMAX];
 1268:   double **out;
 1269:   double sw; /* Sum of weights */
 1270:   double lli; /* Individual log likelihood */
 1271:   int s1, s2;
 1272:   double bbh, survp;
 1273:   long ipmx;
 1274:   /*extern weight */
 1275:   /* We are differentiating ll according to initial status */
 1276:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 1277:   /*for(i=1;i<imx;i++) 
 1278:     printf(" %d\n",s[4][i]);
 1279:   */
 1280:   cov[1]=1.;
 1281: 
 1282:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 1283: 
 1284:   if(mle==1){
 1285:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1286:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1287:       for(mi=1; mi<= wav[i]-1; mi++){
 1288: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1289: 	  for (j=1;j<=nlstate+ndeath;j++){
 1290: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1291: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1292: 	  }
 1293: 	for(d=0; d<dh[mi][i]; d++){
 1294: 	  newm=savm;
 1295: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1296: 	  for (kk=1; kk<=cptcovage;kk++) {
 1297: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1298: 	  }
 1299: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1300: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1301: 	  savm=oldm;
 1302: 	  oldm=newm;
 1303: 	} /* end mult */
 1304:       
 1305: 	/*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
 1306: 	/* But now since version 0.9 we anticipate for bias at large stepm.
 1307: 	 * If stepm is larger than one month (smallest stepm) and if the exact delay 
 1308: 	 * (in months) between two waves is not a multiple of stepm, we rounded to 
 1309: 	 * the nearest (and in case of equal distance, to the lowest) interval but now
 1310: 	 * we keep into memory the bias bh[mi][i] and also the previous matrix product
 1311: 	 * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
 1312: 	 * probability in order to take into account the bias as a fraction of the way
 1313: 	 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
 1314: 	 * -stepm/2 to stepm/2 .
 1315: 	 * For stepm=1 the results are the same as for previous versions of Imach.
 1316: 	 * For stepm > 1 the results are less biased than in previous versions. 
 1317: 	 */
 1318: 	s1=s[mw[mi][i]][i];
 1319: 	s2=s[mw[mi+1][i]][i];
 1320: 	bbh=(double)bh[mi][i]/(double)stepm; 
 1321: 	/* bias bh is positive if real duration
 1322: 	 * is higher than the multiple of stepm and negative otherwise.
 1323: 	 */
 1324: 	/* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
 1325: 	if( s2 > nlstate){ 
 1326: 	  /* i.e. if s2 is a death state and if the date of death is known 
 1327: 	     then the contribution to the likelihood is the probability to 
 1328: 	     die between last step unit time and current  step unit time, 
 1329: 	     which is also equal to probability to die before dh 
 1330: 	     minus probability to die before dh-stepm . 
 1331: 	     In version up to 0.92 likelihood was computed
 1332: 	as if date of death was unknown. Death was treated as any other
 1333: 	health state: the date of the interview describes the actual state
 1334: 	and not the date of a change in health state. The former idea was
 1335: 	to consider that at each interview the state was recorded
 1336: 	(healthy, disable or death) and IMaCh was corrected; but when we
 1337: 	introduced the exact date of death then we should have modified
 1338: 	the contribution of an exact death to the likelihood. This new
 1339: 	contribution is smaller and very dependent of the step unit
 1340: 	stepm. It is no more the probability to die between last interview
 1341: 	and month of death but the probability to survive from last
 1342: 	interview up to one month before death multiplied by the
 1343: 	probability to die within a month. Thanks to Chris
 1344: 	Jackson for correcting this bug.  Former versions increased
 1345: 	mortality artificially. The bad side is that we add another loop
 1346: 	which slows down the processing. The difference can be up to 10%
 1347: 	lower mortality.
 1348: 	  */
 1349: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 1350: 
 1351: 
 1352: 	} else if  (s2==-2) {
 1353: 	  for (j=1,survp=0. ; j<=nlstate; j++) 
 1354: 	    survp += out[s1][j];
 1355: 	  lli= survp;
 1356: 	}
 1357: 	
 1358: 	else if  (s2==-4) {
 1359: 	  for (j=3,survp=0. ; j<=nlstate; j++) 
 1360: 	    survp += out[s1][j];
 1361: 	  lli= survp;
 1362: 	}
 1363: 	
 1364: 	else if  (s2==-5) {
 1365: 	  for (j=1,survp=0. ; j<=2; j++) 
 1366: 	    survp += out[s1][j];
 1367: 	  lli= survp;
 1368: 	}
 1369: 
 1370: 
 1371: 	else{
 1372: 	  lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 1373: 	  /*  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 */
 1374: 	} 
 1375: 	/*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
 1376: 	/*if(lli ==000.0)*/
 1377: 	/*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); */
 1378:   	ipmx +=1;
 1379: 	sw += weight[i];
 1380: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1381:       } /* end of wave */
 1382:     } /* end of individual */
 1383:   }  else if(mle==2){
 1384:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1385:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1386:       for(mi=1; mi<= wav[i]-1; mi++){
 1387: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1388: 	  for (j=1;j<=nlstate+ndeath;j++){
 1389: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1390: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1391: 	  }
 1392: 	for(d=0; d<=dh[mi][i]; d++){
 1393: 	  newm=savm;
 1394: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1395: 	  for (kk=1; kk<=cptcovage;kk++) {
 1396: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1397: 	  }
 1398: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1399: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1400: 	  savm=oldm;
 1401: 	  oldm=newm;
 1402: 	} /* end mult */
 1403:       
 1404: 	s1=s[mw[mi][i]][i];
 1405: 	s2=s[mw[mi+1][i]][i];
 1406: 	bbh=(double)bh[mi][i]/(double)stepm; 
 1407: 	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 */
 1408: 	ipmx +=1;
 1409: 	sw += weight[i];
 1410: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1411:       } /* end of wave */
 1412:     } /* end of individual */
 1413:   }  else if(mle==3){  /* exponential inter-extrapolation */
 1414:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1415:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1416:       for(mi=1; mi<= wav[i]-1; mi++){
 1417: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1418: 	  for (j=1;j<=nlstate+ndeath;j++){
 1419: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1420: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1421: 	  }
 1422: 	for(d=0; d<dh[mi][i]; d++){
 1423: 	  newm=savm;
 1424: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1425: 	  for (kk=1; kk<=cptcovage;kk++) {
 1426: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1427: 	  }
 1428: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1429: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1430: 	  savm=oldm;
 1431: 	  oldm=newm;
 1432: 	} /* end mult */
 1433:       
 1434: 	s1=s[mw[mi][i]][i];
 1435: 	s2=s[mw[mi+1][i]][i];
 1436: 	bbh=(double)bh[mi][i]/(double)stepm; 
 1437: 	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 */
 1438: 	ipmx +=1;
 1439: 	sw += weight[i];
 1440: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1441:       } /* end of wave */
 1442:     } /* end of individual */
 1443:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
 1444:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1445:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1446:       for(mi=1; mi<= wav[i]-1; mi++){
 1447: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1448: 	  for (j=1;j<=nlstate+ndeath;j++){
 1449: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1450: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1451: 	  }
 1452: 	for(d=0; d<dh[mi][i]; d++){
 1453: 	  newm=savm;
 1454: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1455: 	  for (kk=1; kk<=cptcovage;kk++) {
 1456: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1457: 	  }
 1458: 	
 1459: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1460: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1461: 	  savm=oldm;
 1462: 	  oldm=newm;
 1463: 	} /* end mult */
 1464:       
 1465: 	s1=s[mw[mi][i]][i];
 1466: 	s2=s[mw[mi+1][i]][i];
 1467: 	if( s2 > nlstate){ 
 1468: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 1469: 	}else{
 1470: 	  lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 1471: 	}
 1472: 	ipmx +=1;
 1473: 	sw += weight[i];
 1474: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1475: /* 	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]); */
 1476:       } /* end of wave */
 1477:     } /* end of individual */
 1478:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
 1479:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1480:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1481:       for(mi=1; mi<= wav[i]-1; mi++){
 1482: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1483: 	  for (j=1;j<=nlstate+ndeath;j++){
 1484: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1485: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1486: 	  }
 1487: 	for(d=0; d<dh[mi][i]; d++){
 1488: 	  newm=savm;
 1489: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1490: 	  for (kk=1; kk<=cptcovage;kk++) {
 1491: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1492: 	  }
 1493: 	
 1494: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1495: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1496: 	  savm=oldm;
 1497: 	  oldm=newm;
 1498: 	} /* end mult */
 1499:       
 1500: 	s1=s[mw[mi][i]][i];
 1501: 	s2=s[mw[mi+1][i]][i];
 1502: 	lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 1503: 	ipmx +=1;
 1504: 	sw += weight[i];
 1505: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1506: 	/*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]);*/
 1507:       } /* end of wave */
 1508:     } /* end of individual */
 1509:   } /* End of if */
 1510:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 1511:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 1512:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 1513:   return -l;
 1514: }
 1515: 
 1516: /*************** log-likelihood *************/
 1517: double funcone( double *x)
 1518: {
 1519:   /* Same as likeli but slower because of a lot of printf and if */
 1520:   int i, ii, j, k, mi, d, kk;
 1521:   double l, ll[NLSTATEMAX], cov[NCOVMAX];
 1522:   double **out;
 1523:   double lli; /* Individual log likelihood */
 1524:   double llt;
 1525:   int s1, s2;
 1526:   double bbh, survp;
 1527:   /*extern weight */
 1528:   /* We are differentiating ll according to initial status */
 1529:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 1530:   /*for(i=1;i<imx;i++) 
 1531:     printf(" %d\n",s[4][i]);
 1532:   */
 1533:   cov[1]=1.;
 1534: 
 1535:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 1536: 
 1537:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1538:     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1539:     for(mi=1; mi<= wav[i]-1; mi++){
 1540:       for (ii=1;ii<=nlstate+ndeath;ii++)
 1541: 	for (j=1;j<=nlstate+ndeath;j++){
 1542: 	  oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1543: 	  savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1544: 	}
 1545:       for(d=0; d<dh[mi][i]; d++){
 1546: 	newm=savm;
 1547: 	cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1548: 	for (kk=1; kk<=cptcovage;kk++) {
 1549: 	  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1550: 	}
 1551: 	out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1552: 		     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1553: 	savm=oldm;
 1554: 	oldm=newm;
 1555:       } /* end mult */
 1556:       
 1557:       s1=s[mw[mi][i]][i];
 1558:       s2=s[mw[mi+1][i]][i];
 1559:       bbh=(double)bh[mi][i]/(double)stepm; 
 1560:       /* bias is positive if real duration
 1561:        * is higher than the multiple of stepm and negative otherwise.
 1562:        */
 1563:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
 1564: 	lli=log(out[s1][s2] - savm[s1][s2]);
 1565:       } else if (mle==1){
 1566: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 1567:       } else if(mle==2){
 1568: 	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 */
 1569:       } else if(mle==3){  /* exponential inter-extrapolation */
 1570: 	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 */
 1571:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
 1572: 	lli=log(out[s1][s2]); /* Original formula */
 1573:       } else{  /* ml>=5 no inter-extrapolation no jackson =0.8a */
 1574: 	lli=log(out[s1][s2]); /* Original formula */
 1575:       } /* End of if */
 1576:       ipmx +=1;
 1577:       sw += weight[i];
 1578:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1579: /*       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]); */
 1580:       if(globpr){
 1581: 	fprintf(ficresilk,"%9d %6d %1d %1d %1d %1d %3d %10.6f %6.4f\
 1582:  %10.6f %10.6f %10.6f ", \
 1583: 		num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
 1584: 		2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
 1585: 	for(k=1,llt=0.,l=0.; k<=nlstate; k++){
 1586: 	  llt +=ll[k]*gipmx/gsw;
 1587: 	  fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
 1588: 	}
 1589: 	fprintf(ficresilk," %10.6f\n", -llt);
 1590:       }
 1591:     } /* end of wave */
 1592:   } /* end of individual */
 1593:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 1594:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 1595:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 1596:   if(globpr==0){ /* First time we count the contributions and weights */
 1597:     gipmx=ipmx;
 1598:     gsw=sw;
 1599:   }
 1600:   return -l;
 1601: }
 1602: 
 1603: 
 1604: /*************** function likelione ***********/
 1605: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
 1606: {
 1607:   /* This routine should help understanding what is done with 
 1608:      the selection of individuals/waves and
 1609:      to check the exact contribution to the likelihood.
 1610:      Plotting could be done.
 1611:    */
 1612:   int k;
 1613: 
 1614:   if(*globpri !=0){ /* Just counts and sums, no printings */
 1615:     strcpy(fileresilk,"ilk"); 
 1616:     strcat(fileresilk,fileres);
 1617:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
 1618:       printf("Problem with resultfile: %s\n", fileresilk);
 1619:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
 1620:     }
 1621:     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");
 1622:     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
 1623:     /* 	i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
 1624:     for(k=1; k<=nlstate; k++) 
 1625:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
 1626:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
 1627:   }
 1628: 
 1629:   *fretone=(*funcone)(p);
 1630:   if(*globpri !=0){
 1631:     fclose(ficresilk);
 1632:     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
 1633:     fflush(fichtm); 
 1634:   } 
 1635:   return;
 1636: }
 1637: 
 1638: 
 1639: /*********** Maximum Likelihood Estimation ***************/
 1640: 
 1641: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
 1642: {
 1643:   int i,j, iter;
 1644:   double **xi;
 1645:   double fret;
 1646:   double fretone; /* Only one call to likelihood */
 1647:   /*  char filerespow[FILENAMELENGTH];*/
 1648:   xi=matrix(1,npar,1,npar);
 1649:   for (i=1;i<=npar;i++)
 1650:     for (j=1;j<=npar;j++)
 1651:       xi[i][j]=(i==j ? 1.0 : 0.0);
 1652:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
 1653:   strcpy(filerespow,"pow"); 
 1654:   strcat(filerespow,fileres);
 1655:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
 1656:     printf("Problem with resultfile: %s\n", filerespow);
 1657:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 1658:   }
 1659:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
 1660:   for (i=1;i<=nlstate;i++)
 1661:     for(j=1;j<=nlstate+ndeath;j++)
 1662:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 1663:   fprintf(ficrespow,"\n");
 1664: 
 1665:   powell(p,xi,npar,ftol,&iter,&fret,func);
 1666: 
 1667:   fclose(ficrespow);
 1668:   printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));
 1669:   fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
 1670:   fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
 1671: 
 1672: }
 1673: 
 1674: /**** Computes Hessian and covariance matrix ***/
 1675: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
 1676: {
 1677:   double  **a,**y,*x,pd;
 1678:   double **hess;
 1679:   int i, j,jk;
 1680:   int *indx;
 1681: 
 1682:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
 1683:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
 1684:   void lubksb(double **a, int npar, int *indx, double b[]) ;
 1685:   void ludcmp(double **a, int npar, int *indx, double *d) ;
 1686:   double gompertz(double p[]);
 1687:   hess=matrix(1,npar,1,npar);
 1688: 
 1689:   printf("\nCalculation of the hessian matrix. Wait...\n");
 1690:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
 1691:   for (i=1;i<=npar;i++){
 1692:     printf("%d",i);fflush(stdout);
 1693:     fprintf(ficlog,"%d",i);fflush(ficlog);
 1694:    
 1695:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
 1696:     
 1697:     /*  printf(" %f ",p[i]);
 1698: 	printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
 1699:   }
 1700:   
 1701:   for (i=1;i<=npar;i++) {
 1702:     for (j=1;j<=npar;j++)  {
 1703:       if (j>i) { 
 1704: 	printf(".%d%d",i,j);fflush(stdout);
 1705: 	fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
 1706: 	hess[i][j]=hessij(p,delti,i,j,func,npar);
 1707: 	
 1708: 	hess[j][i]=hess[i][j];    
 1709: 	/*printf(" %lf ",hess[i][j]);*/
 1710:       }
 1711:     }
 1712:   }
 1713:   printf("\n");
 1714:   fprintf(ficlog,"\n");
 1715: 
 1716:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
 1717:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
 1718:   
 1719:   a=matrix(1,npar,1,npar);
 1720:   y=matrix(1,npar,1,npar);
 1721:   x=vector(1,npar);
 1722:   indx=ivector(1,npar);
 1723:   for (i=1;i<=npar;i++)
 1724:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
 1725:   ludcmp(a,npar,indx,&pd);
 1726: 
 1727:   for (j=1;j<=npar;j++) {
 1728:     for (i=1;i<=npar;i++) x[i]=0;
 1729:     x[j]=1;
 1730:     lubksb(a,npar,indx,x);
 1731:     for (i=1;i<=npar;i++){ 
 1732:       matcov[i][j]=x[i];
 1733:     }
 1734:   }
 1735: 
 1736:   printf("\n#Hessian matrix#\n");
 1737:   fprintf(ficlog,"\n#Hessian matrix#\n");
 1738:   for (i=1;i<=npar;i++) { 
 1739:     for (j=1;j<=npar;j++) { 
 1740:       printf("%.3e ",hess[i][j]);
 1741:       fprintf(ficlog,"%.3e ",hess[i][j]);
 1742:     }
 1743:     printf("\n");
 1744:     fprintf(ficlog,"\n");
 1745:   }
 1746: 
 1747:   /* Recompute Inverse */
 1748:   for (i=1;i<=npar;i++)
 1749:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
 1750:   ludcmp(a,npar,indx,&pd);
 1751: 
 1752:   /*  printf("\n#Hessian matrix recomputed#\n");
 1753: 
 1754:   for (j=1;j<=npar;j++) {
 1755:     for (i=1;i<=npar;i++) x[i]=0;
 1756:     x[j]=1;
 1757:     lubksb(a,npar,indx,x);
 1758:     for (i=1;i<=npar;i++){ 
 1759:       y[i][j]=x[i];
 1760:       printf("%.3e ",y[i][j]);
 1761:       fprintf(ficlog,"%.3e ",y[i][j]);
 1762:     }
 1763:     printf("\n");
 1764:     fprintf(ficlog,"\n");
 1765:   }
 1766:   */
 1767: 
 1768:   free_matrix(a,1,npar,1,npar);
 1769:   free_matrix(y,1,npar,1,npar);
 1770:   free_vector(x,1,npar);
 1771:   free_ivector(indx,1,npar);
 1772:   free_matrix(hess,1,npar,1,npar);
 1773: 
 1774: 
 1775: }
 1776: 
 1777: /*************** hessian matrix ****************/
 1778: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
 1779: {
 1780:   int i;
 1781:   int l=1, lmax=20;
 1782:   double k1,k2;
 1783:   double p2[NPARMAX+1];
 1784:   double res;
 1785:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
 1786:   double fx;
 1787:   int k=0,kmax=10;
 1788:   double l1;
 1789: 
 1790:   fx=func(x);
 1791:   for (i=1;i<=npar;i++) p2[i]=x[i];
 1792:   for(l=0 ; l <=lmax; l++){
 1793:     l1=pow(10,l);
 1794:     delts=delt;
 1795:     for(k=1 ; k <kmax; k=k+1){
 1796:       delt = delta*(l1*k);
 1797:       p2[theta]=x[theta] +delt;
 1798:       k1=func(p2)-fx;
 1799:       p2[theta]=x[theta]-delt;
 1800:       k2=func(p2)-fx;
 1801:       /*res= (k1-2.0*fx+k2)/delt/delt; */
 1802:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
 1803:       
 1804: #ifdef DEBUG
 1805:       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);
 1806:       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);
 1807: #endif
 1808:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
 1809:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
 1810: 	k=kmax;
 1811:       }
 1812:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
 1813: 	k=kmax; l=lmax*10.;
 1814:       }
 1815:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
 1816: 	delts=delt;
 1817:       }
 1818:     }
 1819:   }
 1820:   delti[theta]=delts;
 1821:   return res; 
 1822:   
 1823: }
 1824: 
 1825: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
 1826: {
 1827:   int i;
 1828:   int l=1, l1, lmax=20;
 1829:   double k1,k2,k3,k4,res,fx;
 1830:   double p2[NPARMAX+1];
 1831:   int k;
 1832: 
 1833:   fx=func(x);
 1834:   for (k=1; k<=2; k++) {
 1835:     for (i=1;i<=npar;i++) p2[i]=x[i];
 1836:     p2[thetai]=x[thetai]+delti[thetai]/k;
 1837:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
 1838:     k1=func(p2)-fx;
 1839:   
 1840:     p2[thetai]=x[thetai]+delti[thetai]/k;
 1841:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
 1842:     k2=func(p2)-fx;
 1843:   
 1844:     p2[thetai]=x[thetai]-delti[thetai]/k;
 1845:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
 1846:     k3=func(p2)-fx;
 1847:   
 1848:     p2[thetai]=x[thetai]-delti[thetai]/k;
 1849:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
 1850:     k4=func(p2)-fx;
 1851:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
 1852: #ifdef DEBUG
 1853:     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);
 1854:     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);
 1855: #endif
 1856:   }
 1857:   return res;
 1858: }
 1859: 
 1860: /************** Inverse of matrix **************/
 1861: void ludcmp(double **a, int n, int *indx, double *d) 
 1862: { 
 1863:   int i,imax,j,k; 
 1864:   double big,dum,sum,temp; 
 1865:   double *vv; 
 1866:  
 1867:   vv=vector(1,n); 
 1868:   *d=1.0; 
 1869:   for (i=1;i<=n;i++) { 
 1870:     big=0.0; 
 1871:     for (j=1;j<=n;j++) 
 1872:       if ((temp=fabs(a[i][j])) > big) big=temp; 
 1873:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
 1874:     vv[i]=1.0/big; 
 1875:   } 
 1876:   for (j=1;j<=n;j++) { 
 1877:     for (i=1;i<j;i++) { 
 1878:       sum=a[i][j]; 
 1879:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
 1880:       a[i][j]=sum; 
 1881:     } 
 1882:     big=0.0; 
 1883:     for (i=j;i<=n;i++) { 
 1884:       sum=a[i][j]; 
 1885:       for (k=1;k<j;k++) 
 1886: 	sum -= a[i][k]*a[k][j]; 
 1887:       a[i][j]=sum; 
 1888:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
 1889: 	big=dum; 
 1890: 	imax=i; 
 1891:       } 
 1892:     } 
 1893:     if (j != imax) { 
 1894:       for (k=1;k<=n;k++) { 
 1895: 	dum=a[imax][k]; 
 1896: 	a[imax][k]=a[j][k]; 
 1897: 	a[j][k]=dum; 
 1898:       } 
 1899:       *d = -(*d); 
 1900:       vv[imax]=vv[j]; 
 1901:     } 
 1902:     indx[j]=imax; 
 1903:     if (a[j][j] == 0.0) a[j][j]=TINY; 
 1904:     if (j != n) { 
 1905:       dum=1.0/(a[j][j]); 
 1906:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
 1907:     } 
 1908:   } 
 1909:   free_vector(vv,1,n);  /* Doesn't work */
 1910: ;
 1911: } 
 1912: 
 1913: void lubksb(double **a, int n, int *indx, double b[]) 
 1914: { 
 1915:   int i,ii=0,ip,j; 
 1916:   double sum; 
 1917:  
 1918:   for (i=1;i<=n;i++) { 
 1919:     ip=indx[i]; 
 1920:     sum=b[ip]; 
 1921:     b[ip]=b[i]; 
 1922:     if (ii) 
 1923:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
 1924:     else if (sum) ii=i; 
 1925:     b[i]=sum; 
 1926:   } 
 1927:   for (i=n;i>=1;i--) { 
 1928:     sum=b[i]; 
 1929:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
 1930:     b[i]=sum/a[i][i]; 
 1931:   } 
 1932: } 
 1933: 
 1934: /************ Frequencies ********************/
 1935: 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[])
 1936: {  /* Some frequencies */
 1937:   
 1938:   int i, m, jk, k1,i1, j1, bool, z1,z2,j;
 1939:   int first;
 1940:   double ***freq; /* Frequencies */
 1941:   double *pp, **prop;
 1942:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
 1943:   FILE *ficresp;
 1944:   char fileresp[FILENAMELENGTH];
 1945:   
 1946:   pp=vector(1,nlstate);
 1947:   prop=matrix(1,nlstate,iagemin,iagemax+3);
 1948:   strcpy(fileresp,"p");
 1949:   strcat(fileresp,fileres);
 1950:   if((ficresp=fopen(fileresp,"w"))==NULL) {
 1951:     printf("Problem with prevalence resultfile: %s\n", fileresp);
 1952:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
 1953:     exit(0);
 1954:   }
 1955:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
 1956:   j1=0;
 1957:   
 1958:   j=cptcoveff;
 1959:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 1960: 
 1961:   first=1;
 1962: 
 1963:   for(k1=1; k1<=j;k1++){
 1964:     for(i1=1; i1<=ncodemax[k1];i1++){
 1965:       j1++;
 1966:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
 1967: 	scanf("%d", i);*/
 1968:       for (i=-5; i<=nlstate+ndeath; i++)  
 1969: 	for (jk=-5; jk<=nlstate+ndeath; jk++)  
 1970: 	  for(m=iagemin; m <= iagemax+3; m++)
 1971: 	    freq[i][jk][m]=0;
 1972: 
 1973:     for (i=1; i<=nlstate; i++)  
 1974:       for(m=iagemin; m <= iagemax+3; m++)
 1975: 	prop[i][m]=0;
 1976:       
 1977:       dateintsum=0;
 1978:       k2cpt=0;
 1979:       for (i=1; i<=imx; i++) {
 1980: 	bool=1;
 1981: 	if  (cptcovn>0) {
 1982: 	  for (z1=1; z1<=cptcoveff; z1++) 
 1983: 	    if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
 1984: 	      bool=0;
 1985: 	}
 1986: 	if (bool==1){
 1987: 	  for(m=firstpass; m<=lastpass; m++){
 1988: 	    k2=anint[m][i]+(mint[m][i]/12.);
 1989: 	    /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
 1990: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 1991: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 1992: 	      if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
 1993: 	      if (m<lastpass) {
 1994: 		freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
 1995: 		freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
 1996: 	      }
 1997: 	      
 1998: 	      if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
 1999: 		dateintsum=dateintsum+k2;
 2000: 		k2cpt++;
 2001: 	      }
 2002: 	      /*}*/
 2003: 	  }
 2004: 	}
 2005:       }
 2006:        
 2007:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
 2008: fprintf(ficresp, "#Local time at start: %s", strstart);
 2009:       if  (cptcovn>0) {
 2010: 	fprintf(ficresp, "\n#********** Variable "); 
 2011: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 2012: 	fprintf(ficresp, "**********\n#");
 2013:       }
 2014:       for(i=1; i<=nlstate;i++) 
 2015: 	fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
 2016:       fprintf(ficresp, "\n");
 2017:       
 2018:       for(i=iagemin; i <= iagemax+3; i++){
 2019: 	if(i==iagemax+3){
 2020: 	  fprintf(ficlog,"Total");
 2021: 	}else{
 2022: 	  if(first==1){
 2023: 	    first=0;
 2024: 	    printf("See log file for details...\n");
 2025: 	  }
 2026: 	  fprintf(ficlog,"Age %d", i);
 2027: 	}
 2028: 	for(jk=1; jk <=nlstate ; jk++){
 2029: 	  for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
 2030: 	    pp[jk] += freq[jk][m][i]; 
 2031: 	}
 2032: 	for(jk=1; jk <=nlstate ; jk++){
 2033: 	  for(m=-1, pos=0; m <=0 ; m++)
 2034: 	    pos += freq[jk][m][i];
 2035: 	  if(pp[jk]>=1.e-10){
 2036: 	    if(first==1){
 2037: 	    printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 2038: 	    }
 2039: 	    fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 2040: 	  }else{
 2041: 	    if(first==1)
 2042: 	      printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 2043: 	    fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 2044: 	  }
 2045: 	}
 2046: 
 2047: 	for(jk=1; jk <=nlstate ; jk++){
 2048: 	  for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
 2049: 	    pp[jk] += freq[jk][m][i];
 2050: 	}	
 2051: 	for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
 2052: 	  pos += pp[jk];
 2053: 	  posprop += prop[jk][i];
 2054: 	}
 2055: 	for(jk=1; jk <=nlstate ; jk++){
 2056: 	  if(pos>=1.e-5){
 2057: 	    if(first==1)
 2058: 	      printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 2059: 	    fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 2060: 	  }else{
 2061: 	    if(first==1)
 2062: 	      printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 2063: 	    fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 2064: 	  }
 2065: 	  if( i <= iagemax){
 2066: 	    if(pos>=1.e-5){
 2067: 	      fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
 2068: 	      /*probs[i][jk][j1]= pp[jk]/pos;*/
 2069: 	      /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
 2070: 	    }
 2071: 	    else
 2072: 	      fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
 2073: 	  }
 2074: 	}
 2075: 	
 2076: 	for(jk=-1; jk <=nlstate+ndeath; jk++)
 2077: 	  for(m=-1; m <=nlstate+ndeath; m++)
 2078: 	    if(freq[jk][m][i] !=0 ) {
 2079: 	    if(first==1)
 2080: 	      printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
 2081: 	      fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
 2082: 	    }
 2083: 	if(i <= iagemax)
 2084: 	  fprintf(ficresp,"\n");
 2085: 	if(first==1)
 2086: 	  printf("Others in log...\n");
 2087: 	fprintf(ficlog,"\n");
 2088:       }
 2089:     }
 2090:   }
 2091:   dateintmean=dateintsum/k2cpt; 
 2092:  
 2093:   fclose(ficresp);
 2094:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
 2095:   free_vector(pp,1,nlstate);
 2096:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
 2097:   /* End of Freq */
 2098: }
 2099: 
 2100: /************ Prevalence ********************/
 2101: 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)
 2102: {  
 2103:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 2104:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 2105:      We still use firstpass and lastpass as another selection.
 2106:   */
 2107:  
 2108:   int i, m, jk, k1, i1, j1, bool, z1,z2,j;
 2109:   double ***freq; /* Frequencies */
 2110:   double *pp, **prop;
 2111:   double pos,posprop; 
 2112:   double  y2; /* in fractional years */
 2113:   int iagemin, iagemax;
 2114: 
 2115:   iagemin= (int) agemin;
 2116:   iagemax= (int) agemax;
 2117:   /*pp=vector(1,nlstate);*/
 2118:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
 2119:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
 2120:   j1=0;
 2121:   
 2122:   j=cptcoveff;
 2123:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 2124:   
 2125:   for(k1=1; k1<=j;k1++){
 2126:     for(i1=1; i1<=ncodemax[k1];i1++){
 2127:       j1++;
 2128:       
 2129:       for (i=1; i<=nlstate; i++)  
 2130: 	for(m=iagemin; m <= iagemax+3; m++)
 2131: 	  prop[i][m]=0.0;
 2132:      
 2133:       for (i=1; i<=imx; i++) { /* Each individual */
 2134: 	bool=1;
 2135: 	if  (cptcovn>0) {
 2136: 	  for (z1=1; z1<=cptcoveff; z1++) 
 2137: 	    if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
 2138: 	      bool=0;
 2139: 	} 
 2140: 	if (bool==1) { 
 2141: 	  for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
 2142: 	    y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
 2143: 	    if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
 2144: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 2145: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 2146: 	      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); 
 2147:  	      if (s[m][i]>0 && s[m][i]<=nlstate) { 
 2148: 		/*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]]);*/
 2149:  		prop[s[m][i]][(int)agev[m][i]] += weight[i];
 2150:  		prop[s[m][i]][iagemax+3] += weight[i]; 
 2151:  	      } 
 2152: 	    }
 2153: 	  } /* end selection of waves */
 2154: 	}
 2155:       }
 2156:       for(i=iagemin; i <= iagemax+3; i++){  
 2157: 	
 2158:  	for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
 2159:  	  posprop += prop[jk][i]; 
 2160:  	} 
 2161: 
 2162:  	for(jk=1; jk <=nlstate ; jk++){	    
 2163:  	  if( i <=  iagemax){ 
 2164:  	    if(posprop>=1.e-5){ 
 2165:  	      probs[i][jk][j1]= prop[jk][i]/posprop;
 2166:  	    } 
 2167:  	  } 
 2168:  	}/* end jk */ 
 2169:       }/* end i */ 
 2170:     } /* end i1 */
 2171:   } /* end k1 */
 2172:   
 2173:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
 2174:   /*free_vector(pp,1,nlstate);*/
 2175:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
 2176: }  /* End of prevalence */
 2177: 
 2178: /************* Waves Concatenation ***************/
 2179: 
 2180: 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)
 2181: {
 2182:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
 2183:      Death is a valid wave (if date is known).
 2184:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
 2185:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 2186:      and mw[mi+1][i]. dh depends on stepm.
 2187:      */
 2188: 
 2189:   int i, mi, m;
 2190:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
 2191:      double sum=0., jmean=0.;*/
 2192:   int first;
 2193:   int j, k=0,jk, ju, jl;
 2194:   double sum=0.;
 2195:   first=0;
 2196:   jmin=1e+5;
 2197:   jmax=-1;
 2198:   jmean=0.;
 2199:   for(i=1; i<=imx; i++){
 2200:     mi=0;
 2201:     m=firstpass;
 2202:     while(s[m][i] <= nlstate){
 2203:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
 2204: 	mw[++mi][i]=m;
 2205:       if(m >=lastpass)
 2206: 	break;
 2207:       else
 2208: 	m++;
 2209:     }/* end while */
 2210:     if (s[m][i] > nlstate){
 2211:       mi++;	/* Death is another wave */
 2212:       /* if(mi==0)  never been interviewed correctly before death */
 2213: 	 /* Only death is a correct wave */
 2214:       mw[mi][i]=m;
 2215:     }
 2216: 
 2217:     wav[i]=mi;
 2218:     if(mi==0){
 2219:       nbwarn++;
 2220:       if(first==0){
 2221: 	printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
 2222: 	first=1;
 2223:       }
 2224:       if(first==1){
 2225: 	fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
 2226:       }
 2227:     } /* end mi==0 */
 2228:   } /* End individuals */
 2229: 
 2230:   for(i=1; i<=imx; i++){
 2231:     for(mi=1; mi<wav[i];mi++){
 2232:       if (stepm <=0)
 2233: 	dh[mi][i]=1;
 2234:       else{
 2235: 	if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
 2236: 	  if (agedc[i] < 2*AGESUP) {
 2237: 	    j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
 2238: 	    if(j==0) j=1;  /* Survives at least one month after exam */
 2239: 	    else if(j<0){
 2240: 	      nberr++;
 2241: 	      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]);
 2242: 	      j=1; /* Temporary Dangerous patch */
 2243: 	      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);
 2244: 	      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]);
 2245: 	      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);
 2246: 	    }
 2247: 	    k=k+1;
 2248: 	    if (j >= jmax){
 2249: 	      jmax=j;
 2250: 	      ijmax=i;
 2251: 	    }
 2252: 	    if (j <= jmin){
 2253: 	      jmin=j;
 2254: 	      ijmin=i;
 2255: 	    }
 2256: 	    sum=sum+j;
 2257: 	    /*if (j<0) printf("j=%d num=%d \n",j,i);*/
 2258: 	    /*	  printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
 2259: 	  }
 2260: 	}
 2261: 	else{
 2262: 	  j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
 2263: /* 	  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]); */
 2264: 
 2265: 	  k=k+1;
 2266: 	  if (j >= jmax) {
 2267: 	    jmax=j;
 2268: 	    ijmax=i;
 2269: 	  }
 2270: 	  else if (j <= jmin){
 2271: 	    jmin=j;
 2272: 	    ijmin=i;
 2273: 	  }
 2274: 	  /*	    if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
 2275: 	  /*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]);*/
 2276: 	  if(j<0){
 2277: 	    nberr++;
 2278: 	    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]);
 2279: 	    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]);
 2280: 	  }
 2281: 	  sum=sum+j;
 2282: 	}
 2283: 	jk= j/stepm;
 2284: 	jl= j -jk*stepm;
 2285: 	ju= j -(jk+1)*stepm;
 2286: 	if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
 2287: 	  if(jl==0){
 2288: 	    dh[mi][i]=jk;
 2289: 	    bh[mi][i]=0;
 2290: 	  }else{ /* We want a negative bias in order to only have interpolation ie
 2291: 		  * at the price of an extra matrix product in likelihood */
 2292: 	    dh[mi][i]=jk+1;
 2293: 	    bh[mi][i]=ju;
 2294: 	  }
 2295: 	}else{
 2296: 	  if(jl <= -ju){
 2297: 	    dh[mi][i]=jk;
 2298: 	    bh[mi][i]=jl;	/* bias is positive if real duration
 2299: 				 * is higher than the multiple of stepm and negative otherwise.
 2300: 				 */
 2301: 	  }
 2302: 	  else{
 2303: 	    dh[mi][i]=jk+1;
 2304: 	    bh[mi][i]=ju;
 2305: 	  }
 2306: 	  if(dh[mi][i]==0){
 2307: 	    dh[mi][i]=1; /* At least one step */
 2308: 	    bh[mi][i]=ju; /* At least one step */
 2309: 	    /*  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);*/
 2310: 	  }
 2311: 	} /* end if mle */
 2312:       }
 2313:     } /* end wave */
 2314:   }
 2315:   jmean=sum/k;
 2316:   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);
 2317:   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);
 2318:  }
 2319: 
 2320: /*********** Tricode ****************************/
 2321: void tricode(int *Tvar, int **nbcode, int imx)
 2322: {
 2323:   
 2324:   int Ndum[20],ij=1, k, j, i, maxncov=19;
 2325:   int cptcode=0;
 2326:   cptcoveff=0; 
 2327:  
 2328:   for (k=0; k<maxncov; k++) Ndum[k]=0;
 2329:   for (k=1; k<=7; k++) ncodemax[k]=0;
 2330: 
 2331:   for (j=1; j<=(cptcovn+2*cptcovprod); j++) {
 2332:     for (i=1; i<=imx; i++) { /*reads the data file to get the maximum 
 2333: 			       modality*/ 
 2334:       ij=(int)(covar[Tvar[j]][i]); /* ij is the modality of this individual*/
 2335:       Ndum[ij]++; /*store the modality */
 2336:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
 2337:       if (ij > cptcode) cptcode=ij; /* getting the maximum of covariable 
 2338: 				       Tvar[j]. If V=sex and male is 0 and 
 2339: 				       female is 1, then  cptcode=1.*/
 2340:     }
 2341: 
 2342:     for (i=0; i<=cptcode; i++) {
 2343:       if(Ndum[i]!=0) ncodemax[j]++; /* Nomber of modalities of the j th covariates. In fact ncodemax[j]=2 (dichotom. variables) but it can be more */
 2344:     }
 2345: 
 2346:     ij=1; 
 2347:     for (i=1; i<=ncodemax[j]; i++) {
 2348:       for (k=0; k<= maxncov; k++) {
 2349: 	if (Ndum[k] != 0) {
 2350: 	  nbcode[Tvar[j]][ij]=k; 
 2351: 	  /* store the modality in an array. k is a modality. If we have model=V1+V1*sex then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
 2352: 	  
 2353: 	  ij++;
 2354: 	}
 2355: 	if (ij > ncodemax[j]) break; 
 2356:       }  
 2357:     } 
 2358:   }  
 2359: 
 2360:  for (k=0; k< maxncov; k++) Ndum[k]=0;
 2361: 
 2362:  for (i=1; i<=ncovmodel-2; i++) { 
 2363:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
 2364:    ij=Tvar[i];
 2365:    Ndum[ij]++;
 2366:  }
 2367: 
 2368:  ij=1;
 2369:  for (i=1; i<= maxncov; i++) {
 2370:    if((Ndum[i]!=0) && (i<=ncovcol)){
 2371:      Tvaraff[ij]=i; /*For printing */
 2372:      ij++;
 2373:    }
 2374:  }
 2375:  
 2376:  cptcoveff=ij-1; /*Number of simple covariates*/
 2377: }
 2378: 
 2379: /*********** Health Expectancies ****************/
 2380: 
 2381: void evsij(char fileres[], double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int ij, int estepm,double delti[],double **matcov,char strstart[] )
 2382: 
 2383: {
 2384:   /* Health expectancies */
 2385:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj;
 2386:   double age, agelim, hf;
 2387:   double ***p3mat,***varhe;
 2388:   double **dnewm,**doldm;
 2389:   double *xp;
 2390:   double **gp, **gm;
 2391:   double ***gradg, ***trgradg;
 2392:   int theta;
 2393: 
 2394:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
 2395:   xp=vector(1,npar);
 2396:   dnewm=matrix(1,nlstate*nlstate,1,npar);
 2397:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
 2398:   
 2399:   fprintf(ficreseij,"# Local time at start: %s", strstart);
 2400:   fprintf(ficreseij,"# Health expectancies\n");
 2401:   fprintf(ficreseij,"# Age");
 2402:   for(i=1; i<=nlstate;i++)
 2403:     for(j=1; j<=nlstate;j++)
 2404:       fprintf(ficreseij," %1d-%1d (SE)",i,j);
 2405:   fprintf(ficreseij,"\n");
 2406: 
 2407:   if(estepm < stepm){
 2408:     printf ("Problem %d lower than %d\n",estepm, stepm);
 2409:   }
 2410:   else  hstepm=estepm;   
 2411:   /* We compute the life expectancy from trapezoids spaced every estepm months
 2412:    * This is mainly to measure the difference between two models: for example
 2413:    * if stepm=24 months pijx are given only every 2 years and by summing them
 2414:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 2415:    * progression in between and thus overestimating or underestimating according
 2416:    * to the curvature of the survival function. If, for the same date, we 
 2417:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 2418:    * to compare the new estimate of Life expectancy with the same linear 
 2419:    * hypothesis. A more precise result, taking into account a more precise
 2420:    * curvature will be obtained if estepm is as small as stepm. */
 2421: 
 2422:   /* For example we decided to compute the life expectancy with the smallest unit */
 2423:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 2424:      nhstepm is the number of hstepm from age to agelim 
 2425:      nstepm is the number of stepm from age to agelin. 
 2426:      Look at hpijx to understand the reason of that which relies in memory size
 2427:      and note for a fixed period like estepm months */
 2428:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 2429:      survival function given by stepm (the optimization length). Unfortunately it
 2430:      means that if the survival funtion is printed only each two years of age and if
 2431:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 2432:      results. So we changed our mind and took the option of the best precision.
 2433:   */
 2434:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 2435: 
 2436:   agelim=AGESUP;
 2437:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 2438:     /* nhstepm age range expressed in number of stepm */
 2439:     nstepm=(int) rint((agelim-age)*YEARM/stepm); 
 2440:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 2441:     /* if (stepm >= YEARM) hstepm=1;*/
 2442:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 2443:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 2444:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
 2445:     gp=matrix(0,nhstepm,1,nlstate*nlstate);
 2446:     gm=matrix(0,nhstepm,1,nlstate*nlstate);
 2447: 
 2448:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
 2449:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
 2450:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, ij);  
 2451:  
 2452: 
 2453:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 2454: 
 2455:     /* Computing  Variances of health expectancies */
 2456: 
 2457:      for(theta=1; theta <=npar; theta++){
 2458:       for(i=1; i<=npar; i++){ 
 2459: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 2460:       }
 2461:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 2462:   
 2463:       cptj=0;
 2464:       for(j=1; j<= nlstate; j++){
 2465: 	for(i=1; i<=nlstate; i++){
 2466: 	  cptj=cptj+1;
 2467: 	  for(h=0, gp[h][cptj]=0.; h<=nhstepm-1; h++){
 2468: 	    gp[h][cptj] = (p3mat[i][j][h]+p3mat[i][j][h+1])/2.;
 2469: 	  }
 2470: 	}
 2471:       }
 2472:      
 2473:      
 2474:       for(i=1; i<=npar; i++) 
 2475: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 2476:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 2477:       
 2478:       cptj=0;
 2479:       for(j=1; j<= nlstate; j++){
 2480: 	for(i=1;i<=nlstate;i++){
 2481: 	  cptj=cptj+1;
 2482: 	  for(h=0, gm[h][cptj]=0.; h<=nhstepm-1; h++){
 2483: 
 2484: 	    gm[h][cptj] = (p3mat[i][j][h]+p3mat[i][j][h+1])/2.;
 2485: 	  }
 2486: 	}
 2487:       }
 2488:       for(j=1; j<= nlstate*nlstate; j++)
 2489: 	for(h=0; h<=nhstepm-1; h++){
 2490: 	  gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
 2491: 	}
 2492:      } 
 2493:    
 2494: /* End theta */
 2495: 
 2496:      trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
 2497: 
 2498:      for(h=0; h<=nhstepm-1; h++)
 2499:       for(j=1; j<=nlstate*nlstate;j++)
 2500: 	for(theta=1; theta <=npar; theta++)
 2501: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 2502:      
 2503: 
 2504:      for(i=1;i<=nlstate*nlstate;i++)
 2505:       for(j=1;j<=nlstate*nlstate;j++)
 2506: 	varhe[i][j][(int)age] =0.;
 2507: 
 2508:      printf("%d|",(int)age);fflush(stdout);
 2509:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 2510:      for(h=0;h<=nhstepm-1;h++){
 2511:       for(k=0;k<=nhstepm-1;k++){
 2512: 	matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
 2513: 	matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
 2514: 	for(i=1;i<=nlstate*nlstate;i++)
 2515: 	  for(j=1;j<=nlstate*nlstate;j++)
 2516: 	    varhe[i][j][(int)age] += doldm[i][j]*hf*hf;
 2517:       }
 2518:     }
 2519:     /* Computing expectancies */
 2520:     for(i=1; i<=nlstate;i++)
 2521:       for(j=1; j<=nlstate;j++)
 2522: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 2523: 	  eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
 2524: 	  
 2525: /* 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]);*/
 2526: 
 2527: 	}
 2528: 
 2529:     fprintf(ficreseij,"%3.0f",age );
 2530:     cptj=0;
 2531:     for(i=1; i<=nlstate;i++)
 2532:       for(j=1; j<=nlstate;j++){
 2533: 	cptj++;
 2534: 	fprintf(ficreseij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[cptj][cptj][(int)age]) );
 2535:       }
 2536:     fprintf(ficreseij,"\n");
 2537:    
 2538:     free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
 2539:     free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
 2540:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
 2541:     free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
 2542:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 2543:   }
 2544:   printf("\n");
 2545:   fprintf(ficlog,"\n");
 2546: 
 2547:   free_vector(xp,1,npar);
 2548:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
 2549:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
 2550:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
 2551: }
 2552: 
 2553: /************ Variance ******************/
 2554: 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[])
 2555: {
 2556:   /* Variance of health expectancies */
 2557:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
 2558:   /* double **newm;*/
 2559:   double **dnewm,**doldm;
 2560:   double **dnewmp,**doldmp;
 2561:   int i, j, nhstepm, hstepm, h, nstepm ;
 2562:   int k, cptcode;
 2563:   double *xp;
 2564:   double **gp, **gm;  /* for var eij */
 2565:   double ***gradg, ***trgradg; /*for var eij */
 2566:   double **gradgp, **trgradgp; /* for var p point j */
 2567:   double *gpp, *gmp; /* for var p point j */
 2568:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
 2569:   double ***p3mat;
 2570:   double age,agelim, hf;
 2571:   double ***mobaverage;
 2572:   int theta;
 2573:   char digit[4];
 2574:   char digitp[25];
 2575: 
 2576:   char fileresprobmorprev[FILENAMELENGTH];
 2577: 
 2578:   if(popbased==1){
 2579:     if(mobilav!=0)
 2580:       strcpy(digitp,"-populbased-mobilav-");
 2581:     else strcpy(digitp,"-populbased-nomobil-");
 2582:   }
 2583:   else 
 2584:     strcpy(digitp,"-stablbased-");
 2585: 
 2586:   if (mobilav!=0) {
 2587:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 2588:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 2589:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 2590:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 2591:     }
 2592:   }
 2593: 
 2594:   strcpy(fileresprobmorprev,"prmorprev"); 
 2595:   sprintf(digit,"%-d",ij);
 2596:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
 2597:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
 2598:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
 2599:   strcat(fileresprobmorprev,fileres);
 2600:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
 2601:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
 2602:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
 2603:   }
 2604:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 2605:  
 2606:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 2607:   fprintf(ficresprobmorprev, "#Local time at start: %s", strstart);
 2608:   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);
 2609:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
 2610:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 2611:     fprintf(ficresprobmorprev," p.%-d SE",j);
 2612:     for(i=1; i<=nlstate;i++)
 2613:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
 2614:   }  
 2615:   fprintf(ficresprobmorprev,"\n");
 2616:   fprintf(ficgp,"\n# Routine varevsij");
 2617:   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
 2618:   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");
 2619:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
 2620: /*   } */
 2621:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 2622:  fprintf(ficresvij, "#Local time at start: %s", strstart);
 2623:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are the stable prevalence in health states i\n");
 2624:   fprintf(ficresvij,"# Age");
 2625:   for(i=1; i<=nlstate;i++)
 2626:     for(j=1; j<=nlstate;j++)
 2627:       fprintf(ficresvij," Cov(e%1d, e%1d)",i,j);
 2628:   fprintf(ficresvij,"\n");
 2629: 
 2630:   xp=vector(1,npar);
 2631:   dnewm=matrix(1,nlstate,1,npar);
 2632:   doldm=matrix(1,nlstate,1,nlstate);
 2633:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
 2634:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 2635: 
 2636:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
 2637:   gpp=vector(nlstate+1,nlstate+ndeath);
 2638:   gmp=vector(nlstate+1,nlstate+ndeath);
 2639:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 2640:   
 2641:   if(estepm < stepm){
 2642:     printf ("Problem %d lower than %d\n",estepm, stepm);
 2643:   }
 2644:   else  hstepm=estepm;   
 2645:   /* For example we decided to compute the life expectancy with the smallest unit */
 2646:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 2647:      nhstepm is the number of hstepm from age to agelim 
 2648:      nstepm is the number of stepm from age to agelin. 
 2649:      Look at hpijx to understand the reason of that which relies in memory size
 2650:      and note for a fixed period like k years */
 2651:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 2652:      survival function given by stepm (the optimization length). Unfortunately it
 2653:      means that if the survival funtion is printed every two years of age and if
 2654:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 2655:      results. So we changed our mind and took the option of the best precision.
 2656:   */
 2657:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 2658:   agelim = AGESUP;
 2659:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 2660:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 2661:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 2662:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 2663:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
 2664:     gp=matrix(0,nhstepm,1,nlstate);
 2665:     gm=matrix(0,nhstepm,1,nlstate);
 2666: 
 2667: 
 2668:     for(theta=1; theta <=npar; theta++){
 2669:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
 2670: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 2671:       }
 2672:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 2673:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 2674: 
 2675:       if (popbased==1) {
 2676: 	if(mobilav ==0){
 2677: 	  for(i=1; i<=nlstate;i++)
 2678: 	    prlim[i][i]=probs[(int)age][i][ij];
 2679: 	}else{ /* mobilav */ 
 2680: 	  for(i=1; i<=nlstate;i++)
 2681: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 2682: 	}
 2683:       }
 2684:   
 2685:       for(j=1; j<= nlstate; j++){
 2686: 	for(h=0; h<=nhstepm; h++){
 2687: 	  for(i=1, gp[h][j]=0.;i<=nlstate;i++)
 2688: 	    gp[h][j] += prlim[i][i]*p3mat[i][j][h];
 2689: 	}
 2690:       }
 2691:       /* This for computing probability of death (h=1 means
 2692:          computed over hstepm matrices product = hstepm*stepm months) 
 2693:          as a weighted average of prlim.
 2694:       */
 2695:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 2696: 	for(i=1,gpp[j]=0.; i<= nlstate; i++)
 2697: 	  gpp[j] += prlim[i][i]*p3mat[i][j][1];
 2698:       }    
 2699:       /* end probability of death */
 2700: 
 2701:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
 2702: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 2703:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 2704:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 2705:  
 2706:       if (popbased==1) {
 2707: 	if(mobilav ==0){
 2708: 	  for(i=1; i<=nlstate;i++)
 2709: 	    prlim[i][i]=probs[(int)age][i][ij];
 2710: 	}else{ /* mobilav */ 
 2711: 	  for(i=1; i<=nlstate;i++)
 2712: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 2713: 	}
 2714:       }
 2715: 
 2716:       for(j=1; j<= nlstate; j++){
 2717: 	for(h=0; h<=nhstepm; h++){
 2718: 	  for(i=1, gm[h][j]=0.;i<=nlstate;i++)
 2719: 	    gm[h][j] += prlim[i][i]*p3mat[i][j][h];
 2720: 	}
 2721:       }
 2722:       /* This for computing probability of death (h=1 means
 2723:          computed over hstepm matrices product = hstepm*stepm months) 
 2724:          as a weighted average of prlim.
 2725:       */
 2726:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 2727: 	for(i=1,gmp[j]=0.; i<= nlstate; i++)
 2728:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
 2729:       }    
 2730:       /* end probability of death */
 2731: 
 2732:       for(j=1; j<= nlstate; j++) /* vareij */
 2733: 	for(h=0; h<=nhstepm; h++){
 2734: 	  gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
 2735: 	}
 2736: 
 2737:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
 2738: 	gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
 2739:       }
 2740: 
 2741:     } /* End theta */
 2742: 
 2743:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
 2744: 
 2745:     for(h=0; h<=nhstepm; h++) /* veij */
 2746:       for(j=1; j<=nlstate;j++)
 2747: 	for(theta=1; theta <=npar; theta++)
 2748: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 2749: 
 2750:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
 2751:       for(theta=1; theta <=npar; theta++)
 2752: 	trgradgp[j][theta]=gradgp[theta][j];
 2753:   
 2754: 
 2755:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 2756:     for(i=1;i<=nlstate;i++)
 2757:       for(j=1;j<=nlstate;j++)
 2758: 	vareij[i][j][(int)age] =0.;
 2759: 
 2760:     for(h=0;h<=nhstepm;h++){
 2761:       for(k=0;k<=nhstepm;k++){
 2762: 	matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
 2763: 	matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
 2764: 	for(i=1;i<=nlstate;i++)
 2765: 	  for(j=1;j<=nlstate;j++)
 2766: 	    vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
 2767:       }
 2768:     }
 2769:   
 2770:     /* pptj */
 2771:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
 2772:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
 2773:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
 2774:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
 2775: 	varppt[j][i]=doldmp[j][i];
 2776:     /* end ppptj */
 2777:     /*  x centered again */
 2778:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
 2779:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
 2780:  
 2781:     if (popbased==1) {
 2782:       if(mobilav ==0){
 2783: 	for(i=1; i<=nlstate;i++)
 2784: 	  prlim[i][i]=probs[(int)age][i][ij];
 2785:       }else{ /* mobilav */ 
 2786: 	for(i=1; i<=nlstate;i++)
 2787: 	  prlim[i][i]=mobaverage[(int)age][i][ij];
 2788:       }
 2789:     }
 2790:              
 2791:     /* This for computing probability of death (h=1 means
 2792:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
 2793:        as a weighted average of prlim.
 2794:     */
 2795:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
 2796:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
 2797: 	gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
 2798:     }    
 2799:     /* end probability of death */
 2800: 
 2801:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
 2802:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 2803:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
 2804:       for(i=1; i<=nlstate;i++){
 2805: 	fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
 2806:       }
 2807:     } 
 2808:     fprintf(ficresprobmorprev,"\n");
 2809: 
 2810:     fprintf(ficresvij,"%.0f ",age );
 2811:     for(i=1; i<=nlstate;i++)
 2812:       for(j=1; j<=nlstate;j++){
 2813: 	fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
 2814:       }
 2815:     fprintf(ficresvij,"\n");
 2816:     free_matrix(gp,0,nhstepm,1,nlstate);
 2817:     free_matrix(gm,0,nhstepm,1,nlstate);
 2818:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
 2819:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
 2820:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 2821:   } /* End age */
 2822:   free_vector(gpp,nlstate+1,nlstate+ndeath);
 2823:   free_vector(gmp,nlstate+1,nlstate+ndeath);
 2824:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
 2825:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 2826:   fprintf(ficgp,"\nset noparametric;set nolabel; set ter png small;set size 0.65, 0.65");
 2827:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
 2828:   fprintf(ficgp,"\n set log y; set nolog x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
 2829: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
 2830: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
 2831: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
 2832:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l 1 ",subdirf(fileresprobmorprev));
 2833:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95\%% interval\" w l 2 ",subdirf(fileresprobmorprev));
 2834:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l 2 ",subdirf(fileresprobmorprev));
 2835:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
 2836:   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);
 2837:   /*  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);
 2838: */
 2839: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
 2840:   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
 2841: 
 2842:   free_vector(xp,1,npar);
 2843:   free_matrix(doldm,1,nlstate,1,nlstate);
 2844:   free_matrix(dnewm,1,nlstate,1,npar);
 2845:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 2846:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
 2847:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 2848:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 2849:   fclose(ficresprobmorprev);
 2850:   fflush(ficgp);
 2851:   fflush(fichtm); 
 2852: }  /* end varevsij */
 2853: 
 2854: /************ Variance of prevlim ******************/
 2855: 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[])
 2856: {
 2857:   /* Variance of prevalence limit */
 2858:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
 2859:   double **newm;
 2860:   double **dnewm,**doldm;
 2861:   int i, j, nhstepm, hstepm;
 2862:   int k, cptcode;
 2863:   double *xp;
 2864:   double *gp, *gm;
 2865:   double **gradg, **trgradg;
 2866:   double age,agelim;
 2867:   int theta;
 2868:   fprintf(ficresvpl, "#Local time at start: %s", strstart); 
 2869:   fprintf(ficresvpl,"# Standard deviation of stable prevalences \n");
 2870:   fprintf(ficresvpl,"# Age");
 2871:   for(i=1; i<=nlstate;i++)
 2872:       fprintf(ficresvpl," %1d-%1d",i,i);
 2873:   fprintf(ficresvpl,"\n");
 2874: 
 2875:   xp=vector(1,npar);
 2876:   dnewm=matrix(1,nlstate,1,npar);
 2877:   doldm=matrix(1,nlstate,1,nlstate);
 2878:   
 2879:   hstepm=1*YEARM; /* Every year of age */
 2880:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
 2881:   agelim = AGESUP;
 2882:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 2883:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 2884:     if (stepm >= YEARM) hstepm=1;
 2885:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 2886:     gradg=matrix(1,npar,1,nlstate);
 2887:     gp=vector(1,nlstate);
 2888:     gm=vector(1,nlstate);
 2889: 
 2890:     for(theta=1; theta <=npar; theta++){
 2891:       for(i=1; i<=npar; i++){ /* Computes gradient */
 2892: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 2893:       }
 2894:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 2895:       for(i=1;i<=nlstate;i++)
 2896: 	gp[i] = prlim[i][i];
 2897:     
 2898:       for(i=1; i<=npar; i++) /* Computes gradient */
 2899: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 2900:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 2901:       for(i=1;i<=nlstate;i++)
 2902: 	gm[i] = prlim[i][i];
 2903: 
 2904:       for(i=1;i<=nlstate;i++)
 2905: 	gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
 2906:     } /* End theta */
 2907: 
 2908:     trgradg =matrix(1,nlstate,1,npar);
 2909: 
 2910:     for(j=1; j<=nlstate;j++)
 2911:       for(theta=1; theta <=npar; theta++)
 2912: 	trgradg[j][theta]=gradg[theta][j];
 2913: 
 2914:     for(i=1;i<=nlstate;i++)
 2915:       varpl[i][(int)age] =0.;
 2916:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 2917:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 2918:     for(i=1;i<=nlstate;i++)
 2919:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
 2920: 
 2921:     fprintf(ficresvpl,"%.0f ",age );
 2922:     for(i=1; i<=nlstate;i++)
 2923:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
 2924:     fprintf(ficresvpl,"\n");
 2925:     free_vector(gp,1,nlstate);
 2926:     free_vector(gm,1,nlstate);
 2927:     free_matrix(gradg,1,npar,1,nlstate);
 2928:     free_matrix(trgradg,1,nlstate,1,npar);
 2929:   } /* End age */
 2930: 
 2931:   free_vector(xp,1,npar);
 2932:   free_matrix(doldm,1,nlstate,1,npar);
 2933:   free_matrix(dnewm,1,nlstate,1,nlstate);
 2934: 
 2935: }
 2936: 
 2937: /************ Variance of one-step probabilities  ******************/
 2938: 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[])
 2939: {
 2940:   int i, j=0,  i1, k1, l1, t, tj;
 2941:   int k2, l2, j1,  z1;
 2942:   int k=0,l, cptcode;
 2943:   int first=1, first1;
 2944:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
 2945:   double **dnewm,**doldm;
 2946:   double *xp;
 2947:   double *gp, *gm;
 2948:   double **gradg, **trgradg;
 2949:   double **mu;
 2950:   double age,agelim, cov[NCOVMAX];
 2951:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
 2952:   int theta;
 2953:   char fileresprob[FILENAMELENGTH];
 2954:   char fileresprobcov[FILENAMELENGTH];
 2955:   char fileresprobcor[FILENAMELENGTH];
 2956: 
 2957:   double ***varpij;
 2958: 
 2959:   strcpy(fileresprob,"prob"); 
 2960:   strcat(fileresprob,fileres);
 2961:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
 2962:     printf("Problem with resultfile: %s\n", fileresprob);
 2963:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
 2964:   }
 2965:   strcpy(fileresprobcov,"probcov"); 
 2966:   strcat(fileresprobcov,fileres);
 2967:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
 2968:     printf("Problem with resultfile: %s\n", fileresprobcov);
 2969:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
 2970:   }
 2971:   strcpy(fileresprobcor,"probcor"); 
 2972:   strcat(fileresprobcor,fileres);
 2973:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
 2974:     printf("Problem with resultfile: %s\n", fileresprobcor);
 2975:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
 2976:   }
 2977:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 2978:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 2979:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 2980:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 2981:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 2982:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 2983:   fprintf(ficresprob, "#Local time at start: %s", strstart);
 2984:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
 2985:   fprintf(ficresprob,"# Age");
 2986:   fprintf(ficresprobcov, "#Local time at start: %s", strstart);
 2987:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
 2988:   fprintf(ficresprobcov,"# Age");
 2989:   fprintf(ficresprobcor, "#Local time at start: %s", strstart);
 2990:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
 2991:   fprintf(ficresprobcov,"# Age");
 2992: 
 2993: 
 2994:   for(i=1; i<=nlstate;i++)
 2995:     for(j=1; j<=(nlstate+ndeath);j++){
 2996:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
 2997:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
 2998:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
 2999:     }  
 3000:  /* fprintf(ficresprob,"\n");
 3001:   fprintf(ficresprobcov,"\n");
 3002:   fprintf(ficresprobcor,"\n");
 3003:  */
 3004:  xp=vector(1,npar);
 3005:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 3006:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 3007:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
 3008:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
 3009:   first=1;
 3010:   fprintf(ficgp,"\n# Routine varprob");
 3011:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
 3012:   fprintf(fichtm,"\n");
 3013: 
 3014:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
 3015:   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
 3016:   file %s<br>\n",optionfilehtmcov);
 3017:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
 3018: and drawn. It helps understanding how is the covariance between two incidences.\
 3019:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
 3020:   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. \
 3021: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
 3022: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
 3023: standard deviations wide on each axis. <br>\
 3024:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
 3025:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
 3026: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
 3027: 
 3028:   cov[1]=1;
 3029:   tj=cptcoveff;
 3030:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
 3031:   j1=0;
 3032:   for(t=1; t<=tj;t++){
 3033:     for(i1=1; i1<=ncodemax[t];i1++){ 
 3034:       j1++;
 3035:       if  (cptcovn>0) {
 3036: 	fprintf(ficresprob, "\n#********** Variable "); 
 3037: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3038: 	fprintf(ficresprob, "**********\n#\n");
 3039: 	fprintf(ficresprobcov, "\n#********** Variable "); 
 3040: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3041: 	fprintf(ficresprobcov, "**********\n#\n");
 3042: 	
 3043: 	fprintf(ficgp, "\n#********** Variable "); 
 3044: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3045: 	fprintf(ficgp, "**********\n#\n");
 3046: 	
 3047: 	
 3048: 	fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
 3049: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3050: 	fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
 3051: 	
 3052: 	fprintf(ficresprobcor, "\n#********** Variable ");    
 3053: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3054: 	fprintf(ficresprobcor, "**********\n#");    
 3055:       }
 3056:       
 3057:       for (age=bage; age<=fage; age ++){ 
 3058: 	cov[2]=age;
 3059: 	for (k=1; k<=cptcovn;k++) {
 3060: 	  cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];
 3061: 	}
 3062: 	for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
 3063: 	for (k=1; k<=cptcovprod;k++)
 3064: 	  cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 3065: 	
 3066: 	gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
 3067: 	trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 3068: 	gp=vector(1,(nlstate)*(nlstate+ndeath));
 3069: 	gm=vector(1,(nlstate)*(nlstate+ndeath));
 3070:     
 3071: 	for(theta=1; theta <=npar; theta++){
 3072: 	  for(i=1; i<=npar; i++)
 3073: 	    xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
 3074: 	  
 3075: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 3076: 	  
 3077: 	  k=0;
 3078: 	  for(i=1; i<= (nlstate); i++){
 3079: 	    for(j=1; j<=(nlstate+ndeath);j++){
 3080: 	      k=k+1;
 3081: 	      gp[k]=pmmij[i][j];
 3082: 	    }
 3083: 	  }
 3084: 	  
 3085: 	  for(i=1; i<=npar; i++)
 3086: 	    xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
 3087:     
 3088: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 3089: 	  k=0;
 3090: 	  for(i=1; i<=(nlstate); i++){
 3091: 	    for(j=1; j<=(nlstate+ndeath);j++){
 3092: 	      k=k+1;
 3093: 	      gm[k]=pmmij[i][j];
 3094: 	    }
 3095: 	  }
 3096:      
 3097: 	  for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
 3098: 	    gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
 3099: 	}
 3100: 
 3101: 	for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
 3102: 	  for(theta=1; theta <=npar; theta++)
 3103: 	    trgradg[j][theta]=gradg[theta][j];
 3104: 	
 3105: 	matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
 3106: 	matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
 3107: 	free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
 3108: 	free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
 3109: 	free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 3110: 	free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 3111: 
 3112: 	pmij(pmmij,cov,ncovmodel,x,nlstate);
 3113: 	
 3114: 	k=0;
 3115: 	for(i=1; i<=(nlstate); i++){
 3116: 	  for(j=1; j<=(nlstate+ndeath);j++){
 3117: 	    k=k+1;
 3118: 	    mu[k][(int) age]=pmmij[i][j];
 3119: 	  }
 3120: 	}
 3121:      	for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
 3122: 	  for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
 3123: 	    varpij[i][j][(int)age] = doldm[i][j];
 3124: 
 3125: 	/*printf("\n%d ",(int)age);
 3126: 	  for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 3127: 	  printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 3128: 	  fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 3129: 	  }*/
 3130: 
 3131: 	fprintf(ficresprob,"\n%d ",(int)age);
 3132: 	fprintf(ficresprobcov,"\n%d ",(int)age);
 3133: 	fprintf(ficresprobcor,"\n%d ",(int)age);
 3134: 
 3135: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
 3136: 	  fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
 3137: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 3138: 	  fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
 3139: 	  fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
 3140: 	}
 3141: 	i=0;
 3142: 	for (k=1; k<=(nlstate);k++){
 3143:  	  for (l=1; l<=(nlstate+ndeath);l++){ 
 3144:  	    i=i++;
 3145: 	    fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
 3146: 	    fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
 3147: 	    for (j=1; j<=i;j++){
 3148: 	      fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
 3149: 	      fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
 3150: 	    }
 3151: 	  }
 3152: 	}/* end of loop for state */
 3153:       } /* end of loop for age */
 3154: 
 3155:       /* Confidence intervalle of pij  */
 3156:       /*
 3157: 	fprintf(ficgp,"\nset noparametric;unset label");
 3158: 	fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
 3159: 	fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
 3160: 	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);
 3161: 	fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
 3162: 	fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
 3163: 	fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
 3164:       */
 3165: 
 3166:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
 3167:       first1=1;
 3168:       for (k2=1; k2<=(nlstate);k2++){
 3169: 	for (l2=1; l2<=(nlstate+ndeath);l2++){ 
 3170: 	  if(l2==k2) continue;
 3171: 	  j=(k2-1)*(nlstate+ndeath)+l2;
 3172: 	  for (k1=1; k1<=(nlstate);k1++){
 3173: 	    for (l1=1; l1<=(nlstate+ndeath);l1++){ 
 3174: 	      if(l1==k1) continue;
 3175: 	      i=(k1-1)*(nlstate+ndeath)+l1;
 3176: 	      if(i<=j) continue;
 3177: 	      for (age=bage; age<=fage; age ++){ 
 3178: 		if ((int)age %5==0){
 3179: 		  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
 3180: 		  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
 3181: 		  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
 3182: 		  mu1=mu[i][(int) age]/stepm*YEARM ;
 3183: 		  mu2=mu[j][(int) age]/stepm*YEARM;
 3184: 		  c12=cv12/sqrt(v1*v2);
 3185: 		  /* Computing eigen value of matrix of covariance */
 3186: 		  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 3187: 		  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 3188: 		  /* Eigen vectors */
 3189: 		  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
 3190: 		  /*v21=sqrt(1.-v11*v11); *//* error */
 3191: 		  v21=(lc1-v1)/cv12*v11;
 3192: 		  v12=-v21;
 3193: 		  v22=v11;
 3194: 		  tnalp=v21/v11;
 3195: 		  if(first1==1){
 3196: 		    first1=0;
 3197: 		    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);
 3198: 		  }
 3199: 		  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);
 3200: 		  /*printf(fignu*/
 3201: 		  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
 3202: 		  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
 3203: 		  if(first==1){
 3204: 		    first=0;
 3205:  		    fprintf(ficgp,"\nset parametric;unset label");
 3206: 		    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);
 3207: 		    fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
 3208: 		    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
 3209:  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
 3210: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
 3211: 			    subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
 3212: 			    subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 3213: 		    fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 3214: 		    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
 3215: 		    fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 3216: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 3217: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 3218: 		    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",\
 3219: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 3220: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 3221: 		  }else{
 3222: 		    first=0;
 3223: 		    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
 3224: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 3225: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 3226: 		    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",\
 3227: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 3228: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 3229: 		  }/* if first */
 3230: 		} /* age mod 5 */
 3231: 	      } /* end loop age */
 3232: 	      fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 3233: 	      first=1;
 3234: 	    } /*l12 */
 3235: 	  } /* k12 */
 3236: 	} /*l1 */
 3237:       }/* k1 */
 3238:     } /* loop covariates */
 3239:   }
 3240:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
 3241:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
 3242:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 3243:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
 3244:   free_vector(xp,1,npar);
 3245:   fclose(ficresprob);
 3246:   fclose(ficresprobcov);
 3247:   fclose(ficresprobcor);
 3248:   fflush(ficgp);
 3249:   fflush(fichtmcov);
 3250: }
 3251: 
 3252: 
 3253: /******************* Printing html file ***********/
 3254: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
 3255: 		  int lastpass, int stepm, int weightopt, char model[],\
 3256: 		  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
 3257: 		  int popforecast, int estepm ,\
 3258: 		  double jprev1, double mprev1,double anprev1, \
 3259: 		  double jprev2, double mprev2,double anprev2){
 3260:   int jj1, k1, i1, cpt;
 3261: 
 3262:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
 3263:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
 3264: </ul>");
 3265:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
 3266:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
 3267: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
 3268:    fprintf(fichtm,"\
 3269:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 3270: 	   stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
 3271:    fprintf(fichtm,"\
 3272:  - Stable prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 3273: 	   subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
 3274:    fprintf(fichtm,"\
 3275:  - Life expectancies by age and initial health status (estepm=%2d months): \
 3276:    <a href=\"%s\">%s</a> <br>\n</li>",
 3277: 	   estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
 3278: 
 3279: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
 3280: 
 3281:  m=cptcoveff;
 3282:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 3283: 
 3284:  jj1=0;
 3285:  for(k1=1; k1<=m;k1++){
 3286:    for(i1=1; i1<=ncodemax[k1];i1++){
 3287:      jj1++;
 3288:      if (cptcovn > 0) {
 3289:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 3290:        for (cpt=1; cpt<=cptcoveff;cpt++) 
 3291: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
 3292:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 3293:      }
 3294:      /* Pij */
 3295:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i, %d (stepm) months before: %s%d1.png<br> \
 3296: <img src=\"%s%d1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     
 3297:      /* Quasi-incidences */
 3298:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
 3299:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too: %s%d2.png<br> \
 3300: <img src=\"%s%d2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 
 3301:        /* Stable prevalence in each health state */
 3302:        for(cpt=1; cpt<nlstate;cpt++){
 3303: 	 fprintf(fichtm,"<br>- Stable prevalence in each health state : p%s%d%d.png<br> \
 3304: <img src=\"%s%d%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
 3305:        }
 3306:      for(cpt=1; cpt<=nlstate;cpt++) {
 3307:         fprintf(fichtm,"\n<br>- Health life expectancies by age and initial health state (%d): %s%d%d.png <br> \
 3308: <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
 3309:      }
 3310:    } /* end i1 */
 3311:  }/* End k1 */
 3312:  fprintf(fichtm,"</ul>");
 3313: 
 3314: 
 3315:  fprintf(fichtm,"\
 3316: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
 3317:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
 3318: 
 3319:  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 3320: 	 subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
 3321:  fprintf(fichtm,"\
 3322:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 3323: 	 subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
 3324: 
 3325:  fprintf(fichtm,"\
 3326:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 3327: 	 subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
 3328:  fprintf(fichtm,"\
 3329:  - Variances and covariances of life expectancies by age and initial health status (estepm=%d months): <a href=\"%s\">%s</a><br>\n",
 3330: 	 estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
 3331:  fprintf(fichtm,"\
 3332:  - Health expectancies with their variances (no covariance): <a href=\"%s\">%s</a> <br>\n",
 3333: 	 subdirf2(fileres,"t"),subdirf2(fileres,"t"));
 3334:  fprintf(fichtm,"\
 3335:  - Standard deviation of stable prevalences: <a href=\"%s\">%s</a> <br>\n",\
 3336: 	 subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
 3337: 
 3338: /*  if(popforecast==1) fprintf(fichtm,"\n */
 3339: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
 3340: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
 3341: /* 	<br>",fileres,fileres,fileres,fileres); */
 3342: /*  else  */
 3343: /*    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); */
 3344:  fflush(fichtm);
 3345:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
 3346: 
 3347:  m=cptcoveff;
 3348:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 3349: 
 3350:  jj1=0;
 3351:  for(k1=1; k1<=m;k1++){
 3352:    for(i1=1; i1<=ncodemax[k1];i1++){
 3353:      jj1++;
 3354:      if (cptcovn > 0) {
 3355:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 3356:        for (cpt=1; cpt<=cptcoveff;cpt++) 
 3357: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
 3358:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 3359:      }
 3360:      for(cpt=1; cpt<=nlstate;cpt++) {
 3361:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
 3362: prevalence (with 95%% confidence interval) in state (%d): %s%d%d.png <br>\
 3363: <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
 3364:      }
 3365:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
 3366: health expectancies in states (1) and (2): %s%d.png<br>\
 3367: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
 3368:    } /* end i1 */
 3369:  }/* End k1 */
 3370:  fprintf(fichtm,"</ul>");
 3371:  fflush(fichtm);
 3372: }
 3373: 
 3374: /******************* Gnuplot file **************/
 3375: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 3376: 
 3377:   char dirfileres[132],optfileres[132];
 3378:   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
 3379:   int ng;
 3380: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
 3381: /*     printf("Problem with file %s",optionfilegnuplot); */
 3382: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
 3383: /*   } */
 3384: 
 3385:   /*#ifdef windows */
 3386:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 3387:     /*#endif */
 3388:   m=pow(2,cptcoveff);
 3389: 
 3390:   strcpy(dirfileres,optionfilefiname);
 3391:   strcpy(optfileres,"vpl");
 3392:  /* 1eme*/
 3393:   for (cpt=1; cpt<= nlstate ; cpt ++) {
 3394:    for (k1=1; k1<= m ; k1 ++) {
 3395:      fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
 3396:      fprintf(ficgp,"\n#set out \"v%s%d%d.png\" \n",optionfilefiname,cpt,k1);
 3397:      fprintf(ficgp,"set xlabel \"Age\" \n\
 3398: set ylabel \"Probability\" \n\
 3399: set ter png small\n\
 3400: set size 0.65,0.65\n\
 3401: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
 3402: 
 3403:      for (i=1; i<= nlstate ; i ++) {
 3404:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
 3405:        else fprintf(ficgp," \%%*lf (\%%*lf)");
 3406:      }
 3407:      fprintf(ficgp,"\" t\"Stable prevalence\" w l 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"\%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);
 3408:      for (i=1; i<= nlstate ; i ++) {
 3409:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
 3410:        else fprintf(ficgp," \%%*lf (\%%*lf)");
 3411:      } 
 3412:      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); 
 3413:      for (i=1; i<= nlstate ; i ++) {
 3414:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
 3415:        else fprintf(ficgp," \%%*lf (\%%*lf)");
 3416:      }  
 3417:      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));
 3418:    }
 3419:   }
 3420:   /*2 eme*/
 3421:   
 3422:   for (k1=1; k1<= m ; k1 ++) { 
 3423:     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
 3424:     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] ",ageminpar,fage);
 3425:     
 3426:     for (i=1; i<= nlstate+1 ; i ++) {
 3427:       k=2*i;
 3428:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 3429:       for (j=1; j<= nlstate+1 ; j ++) {
 3430: 	if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
 3431: 	else fprintf(ficgp," \%%*lf (\%%*lf)");
 3432:       }   
 3433:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
 3434:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
 3435:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 3436:       for (j=1; j<= nlstate+1 ; j ++) {
 3437: 	if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
 3438: 	else fprintf(ficgp," \%%*lf (\%%*lf)");
 3439:       }   
 3440:       fprintf(ficgp,"\" t\"\" w l 0,");
 3441:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 3442:       for (j=1; j<= nlstate+1 ; j ++) {
 3443: 	if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
 3444: 	else fprintf(ficgp," \%%*lf (\%%*lf)");
 3445:       }   
 3446:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");
 3447:       else fprintf(ficgp,"\" t\"\" w l 0,");
 3448:     }
 3449:   }
 3450:   
 3451:   /*3eme*/
 3452:   
 3453:   for (k1=1; k1<= m ; k1 ++) { 
 3454:     for (cpt=1; cpt<= nlstate ; cpt ++) {
 3455:       k=2+nlstate*(2*cpt-2);
 3456:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
 3457:       fprintf(ficgp,"set ter png small\n\
 3458: set size 0.65,0.65\n\
 3459: 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);
 3460:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 3461: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 3462: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 3463: 	fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 3464: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 3465: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 3466: 	
 3467:       */
 3468:       for (i=1; i< nlstate ; i ++) {
 3469: 	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);
 3470: 	
 3471:       } 
 3472:     }
 3473:   }
 3474:   
 3475:   /* CV preval stable (period) */
 3476:   for (k1=1; k1<= m ; k1 ++) { 
 3477:     for (cpt=1; cpt<=nlstate ; cpt ++) {
 3478:       k=3;
 3479:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
 3480:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 3481: set ter png small\nset size 0.65,0.65\n\
 3482: unset log y\n\
 3483: plot [%.f:%.f] \"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",ageminpar,agemaxpar,subdirf2(fileres,"pij"),k1,k+cpt+1,k+1);
 3484:       
 3485:       for (i=1; i< nlstate ; i ++)
 3486: 	fprintf(ficgp,"+$%d",k+i+1);
 3487:       fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);
 3488:       
 3489:       l=3+(nlstate+ndeath)*cpt;
 3490:       fprintf(ficgp,",\"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",subdirf2(fileres,"pij"),k1,l+cpt+1,l+1);
 3491:       for (i=1; i< nlstate ; i ++) {
 3492: 	l=3+(nlstate+ndeath)*cpt;
 3493: 	fprintf(ficgp,"+$%d",l+i+1);
 3494:       }
 3495:       fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);   
 3496:     } 
 3497:   }  
 3498:   
 3499:   /* proba elementaires */
 3500:   for(i=1,jk=1; i <=nlstate; i++){
 3501:     for(k=1; k <=(nlstate+ndeath); k++){
 3502:       if (k != i) {
 3503: 	for(j=1; j <=ncovmodel; j++){
 3504: 	  fprintf(ficgp,"p%d=%f ",jk,p[jk]);
 3505: 	  jk++; 
 3506: 	  fprintf(ficgp,"\n");
 3507: 	}
 3508:       }
 3509:     }
 3510:    }
 3511: 
 3512:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
 3513:      for(jk=1; jk <=m; jk++) {
 3514:        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 
 3515:        if (ng==2)
 3516: 	 fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
 3517:        else
 3518: 	 fprintf(ficgp,"\nset title \"Probability\"\n");
 3519:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
 3520:        i=1;
 3521:        for(k2=1; k2<=nlstate; k2++) {
 3522: 	 k3=i;
 3523: 	 for(k=1; k<=(nlstate+ndeath); k++) {
 3524: 	   if (k != k2){
 3525: 	     if(ng==2)
 3526: 	       fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
 3527: 	     else
 3528: 	       fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
 3529: 	     ij=1;
 3530: 	     for(j=3; j <=ncovmodel; j++) {
 3531: 	       if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
 3532: 		 fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
 3533: 		 ij++;
 3534: 	       }
 3535: 	       else
 3536: 		 fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
 3537: 	     }
 3538: 	     fprintf(ficgp,")/(1");
 3539: 	     
 3540: 	     for(k1=1; k1 <=nlstate; k1++){   
 3541: 	       fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
 3542: 	       ij=1;
 3543: 	       for(j=3; j <=ncovmodel; j++){
 3544: 		 if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
 3545: 		   fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
 3546: 		   ij++;
 3547: 		 }
 3548: 		 else
 3549: 		   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
 3550: 	       }
 3551: 	       fprintf(ficgp,")");
 3552: 	     }
 3553: 	     fprintf(ficgp,") t \"p%d%d\" ", k2,k);
 3554: 	     if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
 3555: 	     i=i+ncovmodel;
 3556: 	   }
 3557: 	 } /* end k */
 3558:        } /* end k2 */
 3559:      } /* end jk */
 3560:    } /* end ng */
 3561:    fflush(ficgp); 
 3562: }  /* end gnuplot */
 3563: 
 3564: 
 3565: /*************** Moving average **************/
 3566: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
 3567: 
 3568:   int i, cpt, cptcod;
 3569:   int modcovmax =1;
 3570:   int mobilavrange, mob;
 3571:   double age;
 3572: 
 3573:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
 3574: 			   a covariate has 2 modalities */
 3575:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
 3576: 
 3577:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
 3578:     if(mobilav==1) mobilavrange=5; /* default */
 3579:     else mobilavrange=mobilav;
 3580:     for (age=bage; age<=fage; age++)
 3581:       for (i=1; i<=nlstate;i++)
 3582: 	for (cptcod=1;cptcod<=modcovmax;cptcod++)
 3583: 	  mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
 3584:     /* We keep the original values on the extreme ages bage, fage and for 
 3585:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
 3586:        we use a 5 terms etc. until the borders are no more concerned. 
 3587:     */ 
 3588:     for (mob=3;mob <=mobilavrange;mob=mob+2){
 3589:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
 3590: 	for (i=1; i<=nlstate;i++){
 3591: 	  for (cptcod=1;cptcod<=modcovmax;cptcod++){
 3592: 	    mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
 3593: 	      for (cpt=1;cpt<=(mob-1)/2;cpt++){
 3594: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
 3595: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
 3596: 	      }
 3597: 	    mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
 3598: 	  }
 3599: 	}
 3600:       }/* end age */
 3601:     }/* end mob */
 3602:   }else return -1;
 3603:   return 0;
 3604: }/* End movingaverage */
 3605: 
 3606: 
 3607: /************** Forecasting ******************/
 3608: 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){
 3609:   /* proj1, year, month, day of starting projection 
 3610:      agemin, agemax range of age
 3611:      dateprev1 dateprev2 range of dates during which prevalence is computed
 3612:      anproj2 year of en of projection (same day and month as proj1).
 3613:   */
 3614:   int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;
 3615:   int *popage;
 3616:   double agec; /* generic age */
 3617:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
 3618:   double *popeffectif,*popcount;
 3619:   double ***p3mat;
 3620:   double ***mobaverage;
 3621:   char fileresf[FILENAMELENGTH];
 3622: 
 3623:   agelim=AGESUP;
 3624:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 3625:  
 3626:   strcpy(fileresf,"f"); 
 3627:   strcat(fileresf,fileres);
 3628:   if((ficresf=fopen(fileresf,"w"))==NULL) {
 3629:     printf("Problem with forecast resultfile: %s\n", fileresf);
 3630:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
 3631:   }
 3632:   printf("Computing forecasting: result on file '%s' \n", fileresf);
 3633:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
 3634: 
 3635:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 3636: 
 3637:   if (mobilav!=0) {
 3638:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3639:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 3640:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 3641:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 3642:     }
 3643:   }
 3644: 
 3645:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 3646:   if (stepm<=12) stepsize=1;
 3647:   if(estepm < stepm){
 3648:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3649:   }
 3650:   else  hstepm=estepm;   
 3651: 
 3652:   hstepm=hstepm/stepm; 
 3653:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
 3654:                                fractional in yp1 */
 3655:   anprojmean=yp;
 3656:   yp2=modf((yp1*12),&yp);
 3657:   mprojmean=yp;
 3658:   yp1=modf((yp2*30.5),&yp);
 3659:   jprojmean=yp;
 3660:   if(jprojmean==0) jprojmean=1;
 3661:   if(mprojmean==0) jprojmean=1;
 3662: 
 3663:   i1=cptcoveff;
 3664:   if (cptcovn < 1){i1=1;}
 3665:   
 3666:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
 3667:   
 3668:   fprintf(ficresf,"#****** Routine prevforecast **\n");
 3669: 
 3670: /* 	      if (h==(int)(YEARM*yearp)){ */
 3671:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
 3672:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 3673:       k=k+1;
 3674:       fprintf(ficresf,"\n#******");
 3675:       for(j=1;j<=cptcoveff;j++) {
 3676: 	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]]);
 3677:       }
 3678:       fprintf(ficresf,"******\n");
 3679:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
 3680:       for(j=1; j<=nlstate+ndeath;j++){ 
 3681: 	for(i=1; i<=nlstate;i++) 	      
 3682:           fprintf(ficresf," p%d%d",i,j);
 3683: 	fprintf(ficresf," p.%d",j);
 3684:       }
 3685:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
 3686: 	fprintf(ficresf,"\n");
 3687: 	fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
 3688: 
 3689:      	for (agec=fage; agec>=(ageminpar-1); agec--){ 
 3690: 	  nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
 3691: 	  nhstepm = nhstepm/hstepm; 
 3692: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3693: 	  oldm=oldms;savm=savms;
 3694: 	  hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
 3695: 	
 3696: 	  for (h=0; h<=nhstepm; h++){
 3697: 	    if (h*hstepm/YEARM*stepm ==yearp) {
 3698:               fprintf(ficresf,"\n");
 3699:               for(j=1;j<=cptcoveff;j++) 
 3700:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 3701: 	      fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
 3702: 	    } 
 3703: 	    for(j=1; j<=nlstate+ndeath;j++) {
 3704: 	      ppij=0.;
 3705: 	      for(i=1; i<=nlstate;i++) {
 3706: 		if (mobilav==1) 
 3707: 		  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
 3708: 		else {
 3709: 		  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
 3710: 		}
 3711: 		if (h*hstepm/YEARM*stepm== yearp) {
 3712: 		  fprintf(ficresf," %.3f", p3mat[i][j][h]);
 3713: 		}
 3714: 	      } /* end i */
 3715: 	      if (h*hstepm/YEARM*stepm==yearp) {
 3716: 		fprintf(ficresf," %.3f", ppij);
 3717: 	      }
 3718: 	    }/* end j */
 3719: 	  } /* end h */
 3720: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3721: 	} /* end agec */
 3722:       } /* end yearp */
 3723:     } /* end cptcod */
 3724:   } /* end  cptcov */
 3725:        
 3726:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3727: 
 3728:   fclose(ficresf);
 3729: }
 3730: 
 3731: /************** Forecasting *****not tested NB*************/
 3732: 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){
 3733:   
 3734:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
 3735:   int *popage;
 3736:   double calagedatem, agelim, kk1, kk2;
 3737:   double *popeffectif,*popcount;
 3738:   double ***p3mat,***tabpop,***tabpopprev;
 3739:   double ***mobaverage;
 3740:   char filerespop[FILENAMELENGTH];
 3741: 
 3742:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3743:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3744:   agelim=AGESUP;
 3745:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
 3746:   
 3747:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 3748:   
 3749:   
 3750:   strcpy(filerespop,"pop"); 
 3751:   strcat(filerespop,fileres);
 3752:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
 3753:     printf("Problem with forecast resultfile: %s\n", filerespop);
 3754:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
 3755:   }
 3756:   printf("Computing forecasting: result on file '%s' \n", filerespop);
 3757:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
 3758: 
 3759:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 3760: 
 3761:   if (mobilav!=0) {
 3762:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3763:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 3764:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 3765:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 3766:     }
 3767:   }
 3768: 
 3769:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 3770:   if (stepm<=12) stepsize=1;
 3771:   
 3772:   agelim=AGESUP;
 3773:   
 3774:   hstepm=1;
 3775:   hstepm=hstepm/stepm; 
 3776:   
 3777:   if (popforecast==1) {
 3778:     if((ficpop=fopen(popfile,"r"))==NULL) {
 3779:       printf("Problem with population file : %s\n",popfile);exit(0);
 3780:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
 3781:     } 
 3782:     popage=ivector(0,AGESUP);
 3783:     popeffectif=vector(0,AGESUP);
 3784:     popcount=vector(0,AGESUP);
 3785:     
 3786:     i=1;   
 3787:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
 3788:    
 3789:     imx=i;
 3790:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
 3791:   }
 3792: 
 3793:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
 3794:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 3795:       k=k+1;
 3796:       fprintf(ficrespop,"\n#******");
 3797:       for(j=1;j<=cptcoveff;j++) {
 3798: 	fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 3799:       }
 3800:       fprintf(ficrespop,"******\n");
 3801:       fprintf(ficrespop,"# Age");
 3802:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
 3803:       if (popforecast==1)  fprintf(ficrespop," [Population]");
 3804:       
 3805:       for (cpt=0; cpt<=0;cpt++) { 
 3806: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 3807: 	
 3808:      	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 3809: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 3810: 	  nhstepm = nhstepm/hstepm; 
 3811: 	  
 3812: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3813: 	  oldm=oldms;savm=savms;
 3814: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 3815: 	
 3816: 	  for (h=0; h<=nhstepm; h++){
 3817: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 3818: 	      fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 3819: 	    } 
 3820: 	    for(j=1; j<=nlstate+ndeath;j++) {
 3821: 	      kk1=0.;kk2=0;
 3822: 	      for(i=1; i<=nlstate;i++) {	      
 3823: 		if (mobilav==1) 
 3824: 		  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
 3825: 		else {
 3826: 		  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
 3827: 		}
 3828: 	      }
 3829: 	      if (h==(int)(calagedatem+12*cpt)){
 3830: 		tabpop[(int)(agedeb)][j][cptcod]=kk1;
 3831: 		  /*fprintf(ficrespop," %.3f", kk1);
 3832: 		    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
 3833: 	      }
 3834: 	    }
 3835: 	    for(i=1; i<=nlstate;i++){
 3836: 	      kk1=0.;
 3837: 		for(j=1; j<=nlstate;j++){
 3838: 		  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
 3839: 		}
 3840: 		  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
 3841: 	    }
 3842: 
 3843: 	    if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
 3844: 	      fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
 3845: 	  }
 3846: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3847: 	}
 3848:       }
 3849:  
 3850:   /******/
 3851: 
 3852:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
 3853: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 3854: 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 3855: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 3856: 	  nhstepm = nhstepm/hstepm; 
 3857: 	  
 3858: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3859: 	  oldm=oldms;savm=savms;
 3860: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 3861: 	  for (h=0; h<=nhstepm; h++){
 3862: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 3863: 	      fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 3864: 	    } 
 3865: 	    for(j=1; j<=nlstate+ndeath;j++) {
 3866: 	      kk1=0.;kk2=0;
 3867: 	      for(i=1; i<=nlstate;i++) {	      
 3868: 		kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];	
 3869: 	      }
 3870: 	      if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);	
 3871: 	    }
 3872: 	  }
 3873: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3874: 	}
 3875:       }
 3876:    } 
 3877:   }
 3878:  
 3879:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3880: 
 3881:   if (popforecast==1) {
 3882:     free_ivector(popage,0,AGESUP);
 3883:     free_vector(popeffectif,0,AGESUP);
 3884:     free_vector(popcount,0,AGESUP);
 3885:   }
 3886:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3887:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3888:   fclose(ficrespop);
 3889: } /* End of popforecast */
 3890: 
 3891: int fileappend(FILE *fichier, char *optionfich)
 3892: {
 3893:   if((fichier=fopen(optionfich,"a"))==NULL) {
 3894:     printf("Problem with file: %s\n", optionfich);
 3895:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
 3896:     return (0);
 3897:   }
 3898:   fflush(fichier);
 3899:   return (1);
 3900: }
 3901: 
 3902: 
 3903: /**************** function prwizard **********************/
 3904: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
 3905: {
 3906: 
 3907:   /* Wizard to print covariance matrix template */
 3908: 
 3909:   char ca[32], cb[32], cc[32];
 3910:   int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;
 3911:   int numlinepar;
 3912: 
 3913:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 3914:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 3915:   for(i=1; i <=nlstate; i++){
 3916:     jj=0;
 3917:     for(j=1; j <=nlstate+ndeath; j++){
 3918:       if(j==i) continue;
 3919:       jj++;
 3920:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
 3921:       printf("%1d%1d",i,j);
 3922:       fprintf(ficparo,"%1d%1d",i,j);
 3923:       for(k=1; k<=ncovmodel;k++){
 3924: 	/* 	  printf(" %lf",param[i][j][k]); */
 3925: 	/* 	  fprintf(ficparo," %lf",param[i][j][k]); */
 3926: 	printf(" 0.");
 3927: 	fprintf(ficparo," 0.");
 3928:       }
 3929:       printf("\n");
 3930:       fprintf(ficparo,"\n");
 3931:     }
 3932:   }
 3933:   printf("# Scales (for hessian or gradient estimation)\n");
 3934:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
 3935:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
 3936:   for(i=1; i <=nlstate; i++){
 3937:     jj=0;
 3938:     for(j=1; j <=nlstate+ndeath; j++){
 3939:       if(j==i) continue;
 3940:       jj++;
 3941:       fprintf(ficparo,"%1d%1d",i,j);
 3942:       printf("%1d%1d",i,j);
 3943:       fflush(stdout);
 3944:       for(k=1; k<=ncovmodel;k++){
 3945: 	/* 	printf(" %le",delti3[i][j][k]); */
 3946: 	/* 	fprintf(ficparo," %le",delti3[i][j][k]); */
 3947: 	printf(" 0.");
 3948: 	fprintf(ficparo," 0.");
 3949:       }
 3950:       numlinepar++;
 3951:       printf("\n");
 3952:       fprintf(ficparo,"\n");
 3953:     }
 3954:   }
 3955:   printf("# Covariance matrix\n");
 3956: /* # 121 Var(a12)\n\ */
 3957: /* # 122 Cov(b12,a12) Var(b12)\n\ */
 3958: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 3959: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 3960: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 3961: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 3962: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 3963: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 3964:   fflush(stdout);
 3965:   fprintf(ficparo,"# Covariance matrix\n");
 3966:   /* # 121 Var(a12)\n\ */
 3967:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
 3968:   /* #   ...\n\ */
 3969:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
 3970:   
 3971:   for(itimes=1;itimes<=2;itimes++){
 3972:     jj=0;
 3973:     for(i=1; i <=nlstate; i++){
 3974:       for(j=1; j <=nlstate+ndeath; j++){
 3975: 	if(j==i) continue;
 3976: 	for(k=1; k<=ncovmodel;k++){
 3977: 	  jj++;
 3978: 	  ca[0]= k+'a'-1;ca[1]='\0';
 3979: 	  if(itimes==1){
 3980: 	    printf("#%1d%1d%d",i,j,k);
 3981: 	    fprintf(ficparo,"#%1d%1d%d",i,j,k);
 3982: 	  }else{
 3983: 	    printf("%1d%1d%d",i,j,k);
 3984: 	    fprintf(ficparo,"%1d%1d%d",i,j,k);
 3985: 	    /* 	printf(" %.5le",matcov[i][j]); */
 3986: 	  }
 3987: 	  ll=0;
 3988: 	  for(li=1;li <=nlstate; li++){
 3989: 	    for(lj=1;lj <=nlstate+ndeath; lj++){
 3990: 	      if(lj==li) continue;
 3991: 	      for(lk=1;lk<=ncovmodel;lk++){
 3992: 		ll++;
 3993: 		if(ll<=jj){
 3994: 		  cb[0]= lk +'a'-1;cb[1]='\0';
 3995: 		  if(ll<jj){
 3996: 		    if(itimes==1){
 3997: 		      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 3998: 		      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 3999: 		    }else{
 4000: 		      printf(" 0.");
 4001: 		      fprintf(ficparo," 0.");
 4002: 		    }
 4003: 		  }else{
 4004: 		    if(itimes==1){
 4005: 		      printf(" Var(%s%1d%1d)",ca,i,j);
 4006: 		      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
 4007: 		    }else{
 4008: 		      printf(" 0.");
 4009: 		      fprintf(ficparo," 0.");
 4010: 		    }
 4011: 		  }
 4012: 		}
 4013: 	      } /* end lk */
 4014: 	    } /* end lj */
 4015: 	  } /* end li */
 4016: 	  printf("\n");
 4017: 	  fprintf(ficparo,"\n");
 4018: 	  numlinepar++;
 4019: 	} /* end k*/
 4020:       } /*end j */
 4021:     } /* end i */
 4022:   } /* end itimes */
 4023: 
 4024: } /* end of prwizard */
 4025: /******************* Gompertz Likelihood ******************************/
 4026: double gompertz(double x[])
 4027: { 
 4028:   double A,B,L=0.0,sump=0.,num=0.;
 4029:   int i,n=0; /* n is the size of the sample */
 4030: 
 4031:   for (i=0;i<=imx-1 ; i++) {
 4032:     sump=sump+weight[i];
 4033:     /*    sump=sump+1;*/
 4034:     num=num+1;
 4035:   }
 4036:  
 4037:  
 4038:   /* for (i=0; i<=imx; i++) 
 4039:      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]);*/
 4040: 
 4041:   for (i=1;i<=imx ; i++)
 4042:     {
 4043:       if (cens[i] == 1 && wav[i]>1)
 4044: 	A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
 4045:       
 4046:       if (cens[i] == 0 && wav[i]>1)
 4047: 	A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
 4048: 	     +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
 4049:       
 4050:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 4051:       if (wav[i] > 1 ) { /* ??? */
 4052: 	L=L+A*weight[i];
 4053: 	/* 	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]);*/
 4054:       }
 4055:     }
 4056: 
 4057:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 4058:  
 4059:   return -2*L*num/sump;
 4060: }
 4061: 
 4062: /******************* Printing html file ***********/
 4063: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
 4064: 		  int lastpass, int stepm, int weightopt, char model[],\
 4065: 		  int imx,  double p[],double **matcov,double agemortsup){
 4066:   int i,k;
 4067: 
 4068:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
 4069:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
 4070:   for (i=1;i<=2;i++) 
 4071:     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]));
 4072:   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
 4073:   fprintf(fichtm,"</ul>");
 4074: 
 4075: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
 4076: 
 4077:  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>");
 4078: 
 4079:  for (k=agegomp;k<(agemortsup-2);k++) 
 4080:    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]);
 4081: 
 4082:  
 4083:   fflush(fichtm);
 4084: }
 4085: 
 4086: /******************* Gnuplot file **************/
 4087: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 4088: 
 4089:   char dirfileres[132],optfileres[132];
 4090:   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
 4091:   int ng;
 4092: 
 4093: 
 4094:   /*#ifdef windows */
 4095:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 4096:     /*#endif */
 4097: 
 4098: 
 4099:   strcpy(dirfileres,optionfilefiname);
 4100:   strcpy(optfileres,"vpl");
 4101:   fprintf(ficgp,"set out \"graphmort.png\"\n "); 
 4102:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
 4103:   fprintf(ficgp, "set ter png small\n set log y\n"); 
 4104:   fprintf(ficgp, "set size 0.65,0.65\n");
 4105:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
 4106: 
 4107: } 
 4108: 
 4109: 
 4110: 
 4111: 
 4112: /***********************************************/
 4113: /**************** Main Program *****************/
 4114: /***********************************************/
 4115: 
 4116: int main(int argc, char *argv[])
 4117: {
 4118:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
 4119:   int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;
 4120:   int linei, month, year,iout;
 4121:   int jj, ll, li, lj, lk, imk;
 4122:   int numlinepar=0; /* Current linenumber of parameter file */
 4123:   int itimes;
 4124:   int NDIM=2;
 4125: 
 4126:   char ca[32], cb[32], cc[32];
 4127:   char dummy[]="                         ";
 4128:   /*  FILE *fichtm; *//* Html File */
 4129:   /* FILE *ficgp;*/ /*Gnuplot File */
 4130:   struct stat info;
 4131:   double agedeb, agefin,hf;
 4132:   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
 4133: 
 4134:   double fret;
 4135:   double **xi,tmp,delta;
 4136: 
 4137:   double dum; /* Dummy variable */
 4138:   double ***p3mat;
 4139:   double ***mobaverage;
 4140:   int *indx;
 4141:   char line[MAXLINE], linepar[MAXLINE];
 4142:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
 4143:   char pathr[MAXLINE], pathimach[MAXLINE]; 
 4144:   int firstobs=1, lastobs=10;
 4145:   int sdeb, sfin; /* Status at beginning and end */
 4146:   int c,  h , cpt,l;
 4147:   int ju,jl, mi;
 4148:   int i1,j1, k1,k2,k3,jk,aa,bb, stepsize, ij;
 4149:   int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,*tab; 
 4150:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
 4151:   int mobilav=0,popforecast=0;
 4152:   int hstepm, nhstepm;
 4153:   int agemortsup;
 4154:   float  sumlpop=0.;
 4155:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
 4156:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
 4157: 
 4158:   double bage, fage, age, agelim, agebase;
 4159:   double ftolpl=FTOL;
 4160:   double **prlim;
 4161:   double *severity;
 4162:   double ***param; /* Matrix of parameters */
 4163:   double  *p;
 4164:   double **matcov; /* Matrix of covariance */
 4165:   double ***delti3; /* Scale */
 4166:   double *delti; /* Scale */
 4167:   double ***eij, ***vareij;
 4168:   double **varpl; /* Variances of prevalence limits by age */
 4169:   double *epj, vepp;
 4170:   double kk1, kk2;
 4171:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
 4172:   double **ximort;
 4173:   char *alph[]={"a","a","b","c","d","e"}, str[4];
 4174:   int *dcwave;
 4175: 
 4176:   char z[1]="c", occ;
 4177: 
 4178:   char stra[80], strb[80], strc[80], strd[80],stre[80],modelsav[80];
 4179:   char strstart[80], *strt, strtend[80];
 4180:   char *stratrunc;
 4181:   int lstra;
 4182: 
 4183:   long total_usecs;
 4184:  
 4185: /*   setlocale (LC_ALL, ""); */
 4186: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
 4187: /*   textdomain (PACKAGE); */
 4188: /*   setlocale (LC_CTYPE, ""); */
 4189: /*   setlocale (LC_MESSAGES, ""); */
 4190: 
 4191:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
 4192:   (void) gettimeofday(&start_time,&tzp);
 4193:   curr_time=start_time;
 4194:   tm = *localtime(&start_time.tv_sec);
 4195:   tmg = *gmtime(&start_time.tv_sec);
 4196:   strcpy(strstart,asctime(&tm));
 4197: 
 4198: /*  printf("Localtime (at start)=%s",strstart); */
 4199: /*  tp.tv_sec = tp.tv_sec +86400; */
 4200: /*  tm = *localtime(&start_time.tv_sec); */
 4201: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
 4202: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
 4203: /*   tmg.tm_hour=tmg.tm_hour + 1; */
 4204: /*   tp.tv_sec = mktime(&tmg); */
 4205: /*   strt=asctime(&tmg); */
 4206: /*   printf("Time(after) =%s",strstart);  */
 4207: /*  (void) time (&time_value);
 4208: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
 4209: *  tm = *localtime(&time_value);
 4210: *  strstart=asctime(&tm);
 4211: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
 4212: */
 4213: 
 4214:   nberr=0; /* Number of errors and warnings */
 4215:   nbwarn=0;
 4216:   getcwd(pathcd, size);
 4217: 
 4218:   printf("\n%s\n%s",version,fullversion);
 4219:   if(argc <=1){
 4220:     printf("\nEnter the parameter file name: ");
 4221:     scanf("%s",pathtot);
 4222:   }
 4223:   else{
 4224:     strcpy(pathtot,argv[1]);
 4225:   }
 4226:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
 4227:   /*cygwin_split_path(pathtot,path,optionfile);
 4228:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
 4229:   /* cutv(path,optionfile,pathtot,'\\');*/
 4230: 
 4231:   /* Split argv[0], imach program to get pathimach */
 4232:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
 4233:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 4234:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 4235:  /*   strcpy(pathimach,argv[0]); */
 4236:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
 4237:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
 4238:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
 4239:   chdir(path);
 4240:   strcpy(command,"mkdir ");
 4241:   strcat(command,optionfilefiname);
 4242:   if((outcmd=system(command)) != 0){
 4243:     printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
 4244:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
 4245:     /* fclose(ficlog); */
 4246: /*     exit(1); */
 4247:   }
 4248: /*   if((imk=mkdir(optionfilefiname))<0){ */
 4249: /*     perror("mkdir"); */
 4250: /*   } */
 4251: 
 4252:   /*-------- arguments in the command line --------*/
 4253: 
 4254:   /* Log file */
 4255:   strcat(filelog, optionfilefiname);
 4256:   strcat(filelog,".log");    /* */
 4257:   if((ficlog=fopen(filelog,"w"))==NULL)    {
 4258:     printf("Problem with logfile %s\n",filelog);
 4259:     goto end;
 4260:   }
 4261:   fprintf(ficlog,"Log filename:%s\n",filelog);
 4262:   fprintf(ficlog,"\n%s\n%s",version,fullversion);
 4263:   fprintf(ficlog,"\nEnter the parameter file name: \n");
 4264:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
 4265:  path=%s \n\
 4266:  optionfile=%s\n\
 4267:  optionfilext=%s\n\
 4268:  optionfilefiname=%s\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
 4269: 
 4270:   printf("Local time (at start):%s",strstart);
 4271:   fprintf(ficlog,"Local time (at start): %s",strstart);
 4272:   fflush(ficlog);
 4273: /*   (void) gettimeofday(&curr_time,&tzp); */
 4274: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */
 4275: 
 4276:   /* */
 4277:   strcpy(fileres,"r");
 4278:   strcat(fileres, optionfilefiname);
 4279:   strcat(fileres,".txt");    /* Other files have txt extension */
 4280: 
 4281:   /*---------arguments file --------*/
 4282: 
 4283:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
 4284:     printf("Problem with optionfile %s\n",optionfile);
 4285:     fprintf(ficlog,"Problem with optionfile %s\n",optionfile);
 4286:     fflush(ficlog);
 4287:     goto end;
 4288:   }
 4289: 
 4290: 
 4291: 
 4292:   strcpy(filereso,"o");
 4293:   strcat(filereso,fileres);
 4294:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
 4295:     printf("Problem with Output resultfile: %s\n", filereso);
 4296:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
 4297:     fflush(ficlog);
 4298:     goto end;
 4299:   }
 4300: 
 4301:   /* Reads comments: lines beginning with '#' */
 4302:   numlinepar=0;
 4303:   while((c=getc(ficpar))=='#' && c!= EOF){
 4304:     ungetc(c,ficpar);
 4305:     fgets(line, MAXLINE, ficpar);
 4306:     numlinepar++;
 4307:     puts(line);
 4308:     fputs(line,ficparo);
 4309:     fputs(line,ficlog);
 4310:   }
 4311:   ungetc(c,ficpar);
 4312: 
 4313:   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);
 4314:   numlinepar++;
 4315:   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);
 4316:   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);
 4317:   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);
 4318:   fflush(ficlog);
 4319:   while((c=getc(ficpar))=='#' && c!= EOF){
 4320:     ungetc(c,ficpar);
 4321:     fgets(line, MAXLINE, ficpar);
 4322:     numlinepar++;
 4323:     puts(line);
 4324:     fputs(line,ficparo);
 4325:     fputs(line,ficlog);
 4326:   }
 4327:   ungetc(c,ficpar);
 4328: 
 4329:    
 4330:   covar=matrix(0,NCOVMAX,1,n); 
 4331:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement*/
 4332:   if (strlen(model)>1) cptcovn=nbocc(model,'+')+1;
 4333: 
 4334:   ncovmodel=2+cptcovn; /*Number of variables = cptcovn + intercept + age */
 4335:   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
 4336:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
 4337: 
 4338:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 4339:   delti=delti3[1][1];
 4340:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
 4341:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
 4342:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 4343:     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 4344:     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 4345:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 4346:     fclose (ficparo);
 4347:     fclose (ficlog);
 4348:     exit(0);
 4349:   }
 4350:   else if(mle==-3) {
 4351:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 4352:     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 4353:     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 4354:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 4355:     matcov=matrix(1,npar,1,npar);
 4356:   }
 4357:   else{
 4358:     /* Read guess parameters */
 4359:     /* Reads comments: lines beginning with '#' */
 4360:     while((c=getc(ficpar))=='#' && c!= EOF){
 4361:       ungetc(c,ficpar);
 4362:       fgets(line, MAXLINE, ficpar);
 4363:       numlinepar++;
 4364:       puts(line);
 4365:       fputs(line,ficparo);
 4366:       fputs(line,ficlog);
 4367:     }
 4368:     ungetc(c,ficpar);
 4369:     
 4370:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 4371:     for(i=1; i <=nlstate; i++){
 4372:       j=0;
 4373:       for(jj=1; jj <=nlstate+ndeath; jj++){
 4374: 	if(jj==i) continue;
 4375: 	j++;
 4376: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 4377: 	if ((i1 != i) && (j1 != j)){
 4378: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
 4379: 	  exit(1);
 4380: 	}
 4381: 	fprintf(ficparo,"%1d%1d",i1,j1);
 4382: 	if(mle==1)
 4383: 	  printf("%1d%1d",i,j);
 4384: 	fprintf(ficlog,"%1d%1d",i,j);
 4385: 	for(k=1; k<=ncovmodel;k++){
 4386: 	  fscanf(ficpar," %lf",&param[i][j][k]);
 4387: 	  if(mle==1){
 4388: 	    printf(" %lf",param[i][j][k]);
 4389: 	    fprintf(ficlog," %lf",param[i][j][k]);
 4390: 	  }
 4391: 	  else
 4392: 	    fprintf(ficlog," %lf",param[i][j][k]);
 4393: 	  fprintf(ficparo," %lf",param[i][j][k]);
 4394: 	}
 4395: 	fscanf(ficpar,"\n");
 4396: 	numlinepar++;
 4397: 	if(mle==1)
 4398: 	  printf("\n");
 4399: 	fprintf(ficlog,"\n");
 4400: 	fprintf(ficparo,"\n");
 4401:       }
 4402:     }  
 4403:     fflush(ficlog);
 4404: 
 4405:     p=param[1][1];
 4406:     
 4407:     /* Reads comments: lines beginning with '#' */
 4408:     while((c=getc(ficpar))=='#' && c!= EOF){
 4409:       ungetc(c,ficpar);
 4410:       fgets(line, MAXLINE, ficpar);
 4411:       numlinepar++;
 4412:       puts(line);
 4413:       fputs(line,ficparo);
 4414:       fputs(line,ficlog);
 4415:     }
 4416:     ungetc(c,ficpar);
 4417: 
 4418:     for(i=1; i <=nlstate; i++){
 4419:       for(j=1; j <=nlstate+ndeath-1; j++){
 4420: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 4421: 	if ((i1-i)*(j1-j)!=0){
 4422: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
 4423: 	  exit(1);
 4424: 	}
 4425: 	printf("%1d%1d",i,j);
 4426: 	fprintf(ficparo,"%1d%1d",i1,j1);
 4427: 	fprintf(ficlog,"%1d%1d",i1,j1);
 4428: 	for(k=1; k<=ncovmodel;k++){
 4429: 	  fscanf(ficpar,"%le",&delti3[i][j][k]);
 4430: 	  printf(" %le",delti3[i][j][k]);
 4431: 	  fprintf(ficparo," %le",delti3[i][j][k]);
 4432: 	  fprintf(ficlog," %le",delti3[i][j][k]);
 4433: 	}
 4434: 	fscanf(ficpar,"\n");
 4435: 	numlinepar++;
 4436: 	printf("\n");
 4437: 	fprintf(ficparo,"\n");
 4438: 	fprintf(ficlog,"\n");
 4439:       }
 4440:     }
 4441:     fflush(ficlog);
 4442: 
 4443:     delti=delti3[1][1];
 4444: 
 4445: 
 4446:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
 4447:   
 4448:     /* Reads comments: lines beginning with '#' */
 4449:     while((c=getc(ficpar))=='#' && c!= EOF){
 4450:       ungetc(c,ficpar);
 4451:       fgets(line, MAXLINE, ficpar);
 4452:       numlinepar++;
 4453:       puts(line);
 4454:       fputs(line,ficparo);
 4455:       fputs(line,ficlog);
 4456:     }
 4457:     ungetc(c,ficpar);
 4458:   
 4459:     matcov=matrix(1,npar,1,npar);
 4460:     for(i=1; i <=npar; i++){
 4461:       fscanf(ficpar,"%s",&str);
 4462:       if(mle==1)
 4463: 	printf("%s",str);
 4464:       fprintf(ficlog,"%s",str);
 4465:       fprintf(ficparo,"%s",str);
 4466:       for(j=1; j <=i; j++){
 4467: 	fscanf(ficpar," %le",&matcov[i][j]);
 4468: 	if(mle==1){
 4469: 	  printf(" %.5le",matcov[i][j]);
 4470: 	}
 4471: 	fprintf(ficlog," %.5le",matcov[i][j]);
 4472: 	fprintf(ficparo," %.5le",matcov[i][j]);
 4473:       }
 4474:       fscanf(ficpar,"\n");
 4475:       numlinepar++;
 4476:       if(mle==1)
 4477: 	printf("\n");
 4478:       fprintf(ficlog,"\n");
 4479:       fprintf(ficparo,"\n");
 4480:     }
 4481:     for(i=1; i <=npar; i++)
 4482:       for(j=i+1;j<=npar;j++)
 4483: 	matcov[i][j]=matcov[j][i];
 4484:     
 4485:     if(mle==1)
 4486:       printf("\n");
 4487:     fprintf(ficlog,"\n");
 4488:     
 4489:     fflush(ficlog);
 4490:     
 4491:     /*-------- Rewriting parameter file ----------*/
 4492:     strcpy(rfileres,"r");    /* "Rparameterfile */
 4493:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
 4494:     strcat(rfileres,".");    /* */
 4495:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
 4496:     if((ficres =fopen(rfileres,"w"))==NULL) {
 4497:       printf("Problem writing new parameter file: %s\n", fileres);goto end;
 4498:       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
 4499:     }
 4500:     fprintf(ficres,"#%s\n",version);
 4501:   }    /* End of mle != -3 */
 4502: 
 4503:   /*-------- data file ----------*/
 4504:   if((fic=fopen(datafile,"r"))==NULL)    {
 4505:     printf("Problem with datafile: %s\n", datafile);goto end;
 4506:     fprintf(ficlog,"Problem with datafile: %s\n", datafile);goto end;
 4507:   }
 4508: 
 4509:   n= lastobs;
 4510:   severity = vector(1,maxwav);
 4511:   outcome=imatrix(1,maxwav+1,1,n);
 4512:   num=lvector(1,n);
 4513:   moisnais=vector(1,n);
 4514:   annais=vector(1,n);
 4515:   moisdc=vector(1,n);
 4516:   andc=vector(1,n);
 4517:   agedc=vector(1,n);
 4518:   cod=ivector(1,n);
 4519:   weight=vector(1,n);
 4520:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
 4521:   mint=matrix(1,maxwav,1,n);
 4522:   anint=matrix(1,maxwav,1,n);
 4523:   s=imatrix(1,maxwav+1,1,n);
 4524:   tab=ivector(1,NCOVMAX);
 4525:   ncodemax=ivector(1,8);
 4526: 
 4527:   i=1;
 4528:   linei=0;
 4529:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
 4530:     linei=linei+1;
 4531:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
 4532:       if(line[j] == '\t')
 4533: 	line[j] = ' ';
 4534:     }
 4535:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
 4536:       ;
 4537:     };
 4538:     line[j+1]=0;  /* Trims blanks at end of line */
 4539:     if(line[0]=='#'){
 4540:       fprintf(ficlog,"Comment line\n%s\n",line);
 4541:       printf("Comment line\n%s\n",line);
 4542:       continue;
 4543:     }
 4544: 
 4545:     for (j=maxwav;j>=1;j--){
 4546:       cutv(stra, strb,line,' '); 
 4547:       errno=0;
 4548:       lval=strtol(strb,&endptr,10); 
 4549:       /*	if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
 4550:       if( strb[0]=='\0' || (*endptr != '\0')){
 4551: 	printf("Error reading data around '%d' at line number %d %s 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);
 4552: 	exit(1);
 4553:       }
 4554:       s[j][i]=lval;
 4555:       
 4556:       strcpy(line,stra);
 4557:       cutv(stra, strb,line,' ');
 4558:       if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
 4559:       }
 4560:       else  if(iout=sscanf(strb,"%s.") != 0){
 4561: 	month=99;
 4562: 	year=9999;
 4563:       }else{
 4564: 	printf("Error reading data around '%s' at line number %ld %s for individual %d, '%s'\nShould be a date of interview (mm/yyyy or .) at wave %d.  Exiting.\n",strb, linei,i, line,j);
 4565: 	exit(1);
 4566:       }
 4567:       anint[j][i]= (double) year; 
 4568:       mint[j][i]= (double)month; 
 4569:       strcpy(line,stra);
 4570:     } /* ENd Waves */
 4571:     
 4572:     cutv(stra, strb,line,' '); 
 4573:     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
 4574:     }
 4575:     else  if(iout=sscanf(strb,"%s.",dummy) != 0){
 4576:       month=99;
 4577:       year=9999;
 4578:     }else{
 4579:       printf("Error reading data around '%s' at line number %ld %s for individual %d, '%s'\nShould be a date of death (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);
 4580:       exit(1);
 4581:     }
 4582:     andc[i]=(double) year; 
 4583:     moisdc[i]=(double) month; 
 4584:     strcpy(line,stra);
 4585:     
 4586:     cutv(stra, strb,line,' '); 
 4587:     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
 4588:     }
 4589:     else  if(iout=sscanf(strb,"%s.") != 0){
 4590:       month=99;
 4591:       year=9999;
 4592:     }else{
 4593:       printf("Error reading data around '%s' at line number %ld %s for individual %d, '%s'\nShould be a date of birth (mm/yyyy or .).  Exiting.\n",strb, linei,i,line,j);
 4594:       exit(1);
 4595:     }
 4596:     annais[i]=(double)(year);
 4597:     moisnais[i]=(double)(month); 
 4598:     strcpy(line,stra);
 4599:     
 4600:     cutv(stra, strb,line,' '); 
 4601:     errno=0;
 4602:     lval=strtol(strb,&endptr,10); 
 4603:     if( strb[0]=='\0' || (*endptr != '\0')){
 4604:       printf("Error reading data around '%d' at line number %ld %s for individual %d\nShould be a weight.  Exiting.\n",lval, i,line,linei);
 4605:       exit(1);
 4606:     }
 4607:     weight[i]=(double)(lval); 
 4608:     strcpy(line,stra);
 4609:     
 4610:     for (j=ncovcol;j>=1;j--){
 4611:       cutv(stra, strb,line,' '); 
 4612:       errno=0;
 4613:       lval=strtol(strb,&endptr,10); 
 4614:       if( strb[0]=='\0' || (*endptr != '\0')){
 4615: 	printf("Error reading data around '%d' at line number %ld %s for individual %d, '%s'\nShould be a covar (meaning 0 for the reference or 1).  Exiting.\n",lval, linei,i, line);
 4616: 	exit(1);
 4617:       }
 4618:       if(lval <-1 || lval >1){
 4619: 	printf("Error reading data around '%d' at line number %ld %s for individual %d, '%s'\nShould be a value of the %d covar (meaning 0 for the reference or 1. IMaCh does not build design variables, do it your self).  Exiting.\n",lval,linei, i,line,j);
 4620: 	exit(1);
 4621:       }
 4622:       covar[j][i]=(double)(lval);
 4623:       strcpy(line,stra);
 4624:     } 
 4625:     lstra=strlen(stra);
 4626:     
 4627:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
 4628:       stratrunc = &(stra[lstra-9]);
 4629:       num[i]=atol(stratrunc);
 4630:     }
 4631:     else
 4632:       num[i]=atol(stra);
 4633:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
 4634:       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;}*/
 4635:     
 4636:     i=i+1;
 4637:   } /* End loop reading  data */
 4638:   fclose(fic);
 4639:   /* printf("ii=%d", ij);
 4640:      scanf("%d",i);*/
 4641:   imx=i-1; /* Number of individuals */
 4642: 
 4643:   /* for (i=1; i<=imx; i++){
 4644:     if ((s[1][i]==3) && (s[2][i]==2)) s[2][i]=3;
 4645:     if ((s[2][i]==3) && (s[3][i]==2)) s[3][i]=3;
 4646:     if ((s[3][i]==3) && (s[4][i]==2)) s[4][i]=3;
 4647:     }*/
 4648:    /*  for (i=1; i<=imx; i++){
 4649:      if (s[4][i]==9)  s[4][i]=-1; 
 4650:      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]));}*/
 4651:   
 4652:   /* for (i=1; i<=imx; i++) */
 4653:  
 4654:    /*if ((s[3][i]==3) ||  (s[4][i]==3)) weight[i]=0.08;
 4655:      else weight[i]=1;*/
 4656: 
 4657:   /* Calculation of the number of parameters from char model */
 4658:   Tvar=ivector(1,15); /* stores the number n of the covariates in Vm+Vn at 1 and m at 2 */
 4659:   Tprod=ivector(1,15); 
 4660:   Tvaraff=ivector(1,15); 
 4661:   Tvard=imatrix(1,15,1,2);
 4662:   Tage=ivector(1,15);      
 4663:    
 4664:   if (strlen(model) >1){ /* If there is at least 1 covariate */
 4665:     j=0, j1=0, k1=1, k2=1;
 4666:     j=nbocc(model,'+'); /* j=Number of '+' */
 4667:     j1=nbocc(model,'*'); /* j1=Number of '*' */
 4668:     cptcovn=j+1; 
 4669:     cptcovprod=j1; /*Number of products */
 4670:     
 4671:     strcpy(modelsav,model); 
 4672:     if ((strcmp(model,"age")==0) || (strcmp(model,"age*age")==0)){
 4673:       printf("Error. Non available option model=%s ",model);
 4674:       fprintf(ficlog,"Error. Non available option model=%s ",model);
 4675:       goto end;
 4676:     }
 4677:     
 4678:     /* This loop fills the array Tvar from the string 'model'.*/
 4679: 
 4680:     for(i=(j+1); i>=1;i--){
 4681:       cutv(stra,strb,modelsav,'+'); /* keeps in strb after the last + */ 
 4682:       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
 4683:       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
 4684:       /*scanf("%d",i);*/
 4685:       if (strchr(strb,'*')) {  /* Model includes a product */
 4686: 	cutv(strd,strc,strb,'*'); /* strd*strc  Vm*Vn (if not *age)*/
 4687: 	if (strcmp(strc,"age")==0) { /* Vn*age */
 4688: 	  cptcovprod--;
 4689: 	  cutv(strb,stre,strd,'V');
 4690: 	  Tvar[i]=atoi(stre); /* computes n in Vn and stores in Tvar*/
 4691: 	  cptcovage++;
 4692: 	    Tage[cptcovage]=i;
 4693: 	    /*printf("stre=%s ", stre);*/
 4694: 	}
 4695: 	else if (strcmp(strd,"age")==0) { /* or age*Vn */
 4696: 	  cptcovprod--;
 4697: 	  cutv(strb,stre,strc,'V');
 4698: 	  Tvar[i]=atoi(stre);
 4699: 	  cptcovage++;
 4700: 	  Tage[cptcovage]=i;
 4701: 	}
 4702: 	else {  /* Age is not in the model */
 4703: 	  cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n*/
 4704: 	  Tvar[i]=ncovcol+k1;
 4705: 	  cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */
 4706: 	  Tprod[k1]=i;
 4707: 	  Tvard[k1][1]=atoi(strc); /* m*/
 4708: 	  Tvard[k1][2]=atoi(stre); /* n */
 4709: 	  Tvar[cptcovn+k2]=Tvard[k1][1];
 4710: 	  Tvar[cptcovn+k2+1]=Tvard[k1][2]; 
 4711: 	  for (k=1; k<=lastobs;k++) 
 4712: 	    covar[ncovcol+k1][k]=covar[atoi(stre)][k]*covar[atoi(strc)][k];
 4713: 	  k1++;
 4714: 	  k2=k2+2;
 4715: 	}
 4716:       }
 4717:       else { /* no more sum */
 4718: 	/*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
 4719:        /*  scanf("%d",i);*/
 4720:       cutv(strd,strc,strb,'V');
 4721:       Tvar[i]=atoi(strc);
 4722:       }
 4723:       strcpy(modelsav,stra);  
 4724:       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
 4725: 	scanf("%d",i);*/
 4726:     } /* end of loop + */
 4727:   } /* end model */
 4728:   
 4729:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
 4730:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
 4731: 
 4732:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
 4733:   printf("cptcovprod=%d ", cptcovprod);
 4734:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
 4735: 
 4736:   scanf("%d ",i);*/
 4737: 
 4738:     /*  if(mle==1){*/
 4739:   if (weightopt != 1) { /* Maximisation without weights*/
 4740:     for(i=1;i<=n;i++) weight[i]=1.0;
 4741:   }
 4742:     /*-calculation of age at interview from date of interview and age at death -*/
 4743:   agev=matrix(1,maxwav,1,imx);
 4744: 
 4745:   for (i=1; i<=imx; i++) {
 4746:     for(m=2; (m<= maxwav); m++) {
 4747:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
 4748: 	anint[m][i]=9999;
 4749: 	s[m][i]=-1;
 4750:       }
 4751:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
 4752: 	nberr++;
 4753: 	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);
 4754: 	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);
 4755: 	s[m][i]=-1;
 4756:       }
 4757:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
 4758: 	nberr++;
 4759: 	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]); 
 4760: 	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]); 
 4761: 	s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
 4762:       }
 4763:     }
 4764:   }
 4765: 
 4766:   for (i=1; i<=imx; i++)  {
 4767:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
 4768:     for(m=firstpass; (m<= lastpass); m++){
 4769:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
 4770: 	if (s[m][i] >= nlstate+1) {
 4771: 	  if(agedc[i]>0)
 4772: 	    if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
 4773: 	      agev[m][i]=agedc[i];
 4774: 	  /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
 4775: 	    else {
 4776: 	      if ((int)andc[i]!=9999){
 4777: 		nbwarn++;
 4778: 		printf("Warning negative age at death: %ld line:%d\n",num[i],i);
 4779: 		fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
 4780: 		agev[m][i]=-1;
 4781: 	      }
 4782: 	    }
 4783: 	}
 4784: 	else if(s[m][i] !=9){ /* Standard case, age in fractional
 4785: 				 years but with the precision of a month */
 4786: 	  agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
 4787: 	  if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
 4788: 	    agev[m][i]=1;
 4789: 	  else if(agev[m][i] <agemin){ 
 4790: 	    agemin=agev[m][i];
 4791: 	    /*printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);*/
 4792: 	  }
 4793: 	  else if(agev[m][i] >agemax){
 4794: 	    agemax=agev[m][i];
 4795: 	    /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/
 4796: 	  }
 4797: 	  /*agev[m][i]=anint[m][i]-annais[i];*/
 4798: 	  /*	 agev[m][i] = age[i]+2*m;*/
 4799: 	}
 4800: 	else { /* =9 */
 4801: 	  agev[m][i]=1;
 4802: 	  s[m][i]=-1;
 4803: 	}
 4804:       }
 4805:       else /*= 0 Unknown */
 4806: 	agev[m][i]=1;
 4807:     }
 4808:     
 4809:   }
 4810:   for (i=1; i<=imx; i++)  {
 4811:     for(m=firstpass; (m<=lastpass); m++){
 4812:       if (s[m][i] > (nlstate+ndeath)) {
 4813: 	nberr++;
 4814: 	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);	
 4815: 	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);	
 4816: 	goto end;
 4817:       }
 4818:     }
 4819:   }
 4820: 
 4821:   /*for (i=1; i<=imx; i++){
 4822:   for (m=firstpass; (m<lastpass); m++){
 4823:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
 4824: }
 4825: 
 4826: }*/
 4827: 
 4828: 
 4829:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
 4830:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax); 
 4831: 
 4832:   agegomp=(int)agemin;
 4833:   free_vector(severity,1,maxwav);
 4834:   free_imatrix(outcome,1,maxwav+1,1,n);
 4835:   free_vector(moisnais,1,n);
 4836:   free_vector(annais,1,n);
 4837:   /* free_matrix(mint,1,maxwav,1,n);
 4838:      free_matrix(anint,1,maxwav,1,n);*/
 4839:   free_vector(moisdc,1,n);
 4840:   free_vector(andc,1,n);
 4841: 
 4842:    
 4843:   wav=ivector(1,imx);
 4844:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
 4845:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
 4846:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
 4847:    
 4848:   /* Concatenates waves */
 4849:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
 4850: 
 4851:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
 4852: 
 4853:   Tcode=ivector(1,100);
 4854:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
 4855:   ncodemax[1]=1;
 4856:   if (cptcovn > 0) tricode(Tvar,nbcode,imx);
 4857:       
 4858:   codtab=imatrix(1,100,1,10); /* Cross tabulation to get the order of 
 4859: 				 the estimations*/
 4860:   h=0;
 4861:   m=pow(2,cptcoveff);
 4862:  
 4863:   for(k=1;k<=cptcoveff; k++){
 4864:     for(i=1; i <=(m/pow(2,k));i++){
 4865:       for(j=1; j <= ncodemax[k]; j++){
 4866: 	for(cpt=1; cpt <=(m/pow(2,cptcoveff+1-k)); cpt++){
 4867: 	  h++;
 4868: 	  if (h>m) h=1;codtab[h][k]=j;codtab[h][Tvar[k]]=j;
 4869: 	  /*  printf("h=%d k=%d j=%d codtab[h][k]=%d tvar[k]=%d \n",h, k,j,codtab[h][k],Tvar[k]);*/
 4870: 	} 
 4871:       }
 4872:     }
 4873:   } 
 4874:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
 4875:      codtab[1][2]=1;codtab[2][2]=2; */
 4876:   /* for(i=1; i <=m ;i++){ 
 4877:      for(k=1; k <=cptcovn; k++){
 4878:      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
 4879:      }
 4880:      printf("\n");
 4881:      }
 4882:      scanf("%d",i);*/
 4883:     
 4884:   /*------------ gnuplot -------------*/
 4885:   strcpy(optionfilegnuplot,optionfilefiname);
 4886:   if(mle==-3)
 4887:     strcat(optionfilegnuplot,"-mort");
 4888:   strcat(optionfilegnuplot,".gp");
 4889: 
 4890:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
 4891:     printf("Problem with file %s",optionfilegnuplot);
 4892:   }
 4893:   else{
 4894:     fprintf(ficgp,"\n# %s\n", version); 
 4895:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
 4896:     fprintf(ficgp,"set missing 'NaNq'\n");
 4897:   }
 4898:   /*  fclose(ficgp);*/
 4899:   /*--------- index.htm --------*/
 4900: 
 4901:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
 4902:   if(mle==-3)
 4903:     strcat(optionfilehtm,"-mort");
 4904:   strcat(optionfilehtm,".htm");
 4905:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
 4906:     printf("Problem with %s \n",optionfilehtm), exit(0);
 4907:   }
 4908: 
 4909:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
 4910:   strcat(optionfilehtmcov,"-cov.htm");
 4911:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
 4912:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
 4913:   }
 4914:   else{
 4915:   fprintf(fichtmcov,"<body>\n<title>IMaCh Cov %s</title>\n <font size=\"2\">%s <br> %s</font> \
 4916: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 4917: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
 4918: 	  fileres,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 4919:   }
 4920: 
 4921:   fprintf(fichtm,"<body>\n<title>IMaCh %s</title>\n <font size=\"2\">%s <br> %s</font> \
 4922: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 4923: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
 4924: \n\
 4925: <hr  size=\"2\" color=\"#EC5E5E\">\
 4926:  <ul><li><h4>Parameter files</h4>\n\
 4927:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
 4928:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
 4929:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
 4930:  - Date and time at start: %s</ul>\n",\
 4931: 	  fileres,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
 4932: 	  fileres,fileres,\
 4933: 	  filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
 4934:   fflush(fichtm);
 4935: 
 4936:   strcpy(pathr,path);
 4937:   strcat(pathr,optionfilefiname);
 4938:   chdir(optionfilefiname); /* Move to directory named optionfile */
 4939:   
 4940:   /* Calculates basic frequencies. Computes observed prevalence at single age
 4941:      and prints on file fileres'p'. */
 4942:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
 4943: 
 4944:   fprintf(fichtm,"\n");
 4945:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
 4946: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
 4947: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
 4948: 	  imx,agemin,agemax,jmin,jmax,jmean);
 4949:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 4950:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 4951:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 4952:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 4953:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
 4954:     
 4955:    
 4956:   /* For Powell, parameters are in a vector p[] starting at p[1]
 4957:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
 4958:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
 4959: 
 4960:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
 4961: 
 4962:   if (mle==-3){
 4963:     ximort=matrix(1,NDIM,1,NDIM);
 4964:     cens=ivector(1,n);
 4965:     ageexmed=vector(1,n);
 4966:     agecens=vector(1,n);
 4967:     dcwave=ivector(1,n);
 4968:  
 4969:     for (i=1; i<=imx; i++){
 4970:       dcwave[i]=-1;
 4971:       for (m=firstpass; m<=lastpass; m++)
 4972: 	if (s[m][i]>nlstate) {
 4973: 	  dcwave[i]=m;
 4974: 	  /*	printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
 4975: 	  break;
 4976: 	}
 4977:     }
 4978: 
 4979:     for (i=1; i<=imx; i++) {
 4980:       if (wav[i]>0){
 4981: 	ageexmed[i]=agev[mw[1][i]][i];
 4982: 	j=wav[i];
 4983: 	agecens[i]=1.; 
 4984: 
 4985: 	if (ageexmed[i]> 1 && wav[i] > 0){
 4986: 	  agecens[i]=agev[mw[j][i]][i];
 4987: 	  cens[i]= 1;
 4988: 	}else if (ageexmed[i]< 1) 
 4989: 	  cens[i]= -1;
 4990: 	if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
 4991: 	  cens[i]=0 ;
 4992:       }
 4993:       else cens[i]=-1;
 4994:     }
 4995:     
 4996:     for (i=1;i<=NDIM;i++) {
 4997:       for (j=1;j<=NDIM;j++)
 4998: 	ximort[i][j]=(i == j ? 1.0 : 0.0);
 4999:     }
 5000:     
 5001:     p[1]=0.0268; p[NDIM]=0.083;
 5002:     /*printf("%lf %lf", p[1], p[2]);*/
 5003:     
 5004:     
 5005:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
 5006:     strcpy(filerespow,"pow-mort"); 
 5007:     strcat(filerespow,fileres);
 5008:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
 5009:       printf("Problem with resultfile: %s\n", filerespow);
 5010:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 5011:     }
 5012:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
 5013:     /*  for (i=1;i<=nlstate;i++)
 5014: 	for(j=1;j<=nlstate+ndeath;j++)
 5015: 	if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 5016:     */
 5017:     fprintf(ficrespow,"\n");
 5018:     
 5019:     powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
 5020:     fclose(ficrespow);
 5021:     
 5022:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
 5023: 
 5024:     for(i=1; i <=NDIM; i++)
 5025:       for(j=i+1;j<=NDIM;j++)
 5026: 	matcov[i][j]=matcov[j][i];
 5027:     
 5028:     printf("\nCovariance matrix\n ");
 5029:     for(i=1; i <=NDIM; i++) {
 5030:       for(j=1;j<=NDIM;j++){ 
 5031: 	printf("%f ",matcov[i][j]);
 5032:       }
 5033:       printf("\n ");
 5034:     }
 5035:     
 5036:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
 5037:     for (i=1;i<=NDIM;i++) 
 5038:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
 5039: 
 5040:     lsurv=vector(1,AGESUP);
 5041:     lpop=vector(1,AGESUP);
 5042:     tpop=vector(1,AGESUP);
 5043:     lsurv[agegomp]=100000;
 5044:     
 5045:     for (k=agegomp;k<=AGESUP;k++) {
 5046:       agemortsup=k;
 5047:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
 5048:     }
 5049:     
 5050:     for (k=agegomp;k<agemortsup;k++)
 5051:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
 5052:     
 5053:     for (k=agegomp;k<agemortsup;k++){
 5054:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
 5055:       sumlpop=sumlpop+lpop[k];
 5056:     }
 5057:     
 5058:     tpop[agegomp]=sumlpop;
 5059:     for (k=agegomp;k<(agemortsup-3);k++){
 5060:       /*  tpop[k+1]=2;*/
 5061:       tpop[k+1]=tpop[k]-lpop[k];
 5062:     }
 5063:     
 5064:     
 5065:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
 5066:     for (k=agegomp;k<(agemortsup-2);k++) 
 5067:       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]);
 5068:     
 5069:     
 5070:     replace_back_to_slash(pathc,path); /* Even gnuplot wants a / */
 5071:     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
 5072:     
 5073:     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
 5074: 		     stepm, weightopt,\
 5075: 		     model,imx,p,matcov,agemortsup);
 5076:     
 5077:     free_vector(lsurv,1,AGESUP);
 5078:     free_vector(lpop,1,AGESUP);
 5079:     free_vector(tpop,1,AGESUP);
 5080:   } /* Endof if mle==-3 */
 5081:   
 5082:   else{ /* For mle >=1 */
 5083:   
 5084:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 5085:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 5086:     for (k=1; k<=npar;k++)
 5087:       printf(" %d %8.5f",k,p[k]);
 5088:     printf("\n");
 5089:     globpr=1; /* to print the contributions */
 5090:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 5091:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 5092:     for (k=1; k<=npar;k++)
 5093:       printf(" %d %8.5f",k,p[k]);
 5094:     printf("\n");
 5095:     if(mle>=1){ /* Could be 1 or 2 */
 5096:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
 5097:     }
 5098:     
 5099:     /*--------- results files --------------*/
 5100:     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);
 5101:     
 5102:     
 5103:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 5104:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 5105:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 5106:     for(i=1,jk=1; i <=nlstate; i++){
 5107:       for(k=1; k <=(nlstate+ndeath); k++){
 5108: 	if (k != i) {
 5109: 	  printf("%d%d ",i,k);
 5110: 	  fprintf(ficlog,"%d%d ",i,k);
 5111: 	  fprintf(ficres,"%1d%1d ",i,k);
 5112: 	  for(j=1; j <=ncovmodel; j++){
 5113: 	    printf("%f ",p[jk]);
 5114: 	    fprintf(ficlog,"%f ",p[jk]);
 5115: 	    fprintf(ficres,"%f ",p[jk]);
 5116: 	    jk++; 
 5117: 	  }
 5118: 	  printf("\n");
 5119: 	  fprintf(ficlog,"\n");
 5120: 	  fprintf(ficres,"\n");
 5121: 	}
 5122:       }
 5123:     }
 5124:     if(mle!=0){
 5125:       /* Computing hessian and covariance matrix */
 5126:       ftolhess=ftol; /* Usually correct */
 5127:       hesscov(matcov, p, npar, delti, ftolhess, func);
 5128:     }
 5129:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
 5130:     printf("# Scales (for hessian or gradient estimation)\n");
 5131:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
 5132:     for(i=1,jk=1; i <=nlstate; i++){
 5133:       for(j=1; j <=nlstate+ndeath; j++){
 5134: 	if (j!=i) {
 5135: 	  fprintf(ficres,"%1d%1d",i,j);
 5136: 	  printf("%1d%1d",i,j);
 5137: 	  fprintf(ficlog,"%1d%1d",i,j);
 5138: 	  for(k=1; k<=ncovmodel;k++){
 5139: 	    printf(" %.5e",delti[jk]);
 5140: 	    fprintf(ficlog," %.5e",delti[jk]);
 5141: 	    fprintf(ficres," %.5e",delti[jk]);
 5142: 	    jk++;
 5143: 	  }
 5144: 	  printf("\n");
 5145: 	  fprintf(ficlog,"\n");
 5146: 	  fprintf(ficres,"\n");
 5147: 	}
 5148:       }
 5149:     }
 5150:     
 5151:     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");
 5152:     if(mle>=1)
 5153:       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");
 5154:     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");
 5155:     /* # 121 Var(a12)\n\ */
 5156:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
 5157:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 5158:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 5159:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 5160:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 5161:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 5162:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 5163:     
 5164:     
 5165:     /* Just to have a covariance matrix which will be more understandable
 5166:        even is we still don't want to manage dictionary of variables
 5167:     */
 5168:     for(itimes=1;itimes<=2;itimes++){
 5169:       jj=0;
 5170:       for(i=1; i <=nlstate; i++){
 5171: 	for(j=1; j <=nlstate+ndeath; j++){
 5172: 	  if(j==i) continue;
 5173: 	  for(k=1; k<=ncovmodel;k++){
 5174: 	    jj++;
 5175: 	    ca[0]= k+'a'-1;ca[1]='\0';
 5176: 	    if(itimes==1){
 5177: 	      if(mle>=1)
 5178: 		printf("#%1d%1d%d",i,j,k);
 5179: 	      fprintf(ficlog,"#%1d%1d%d",i,j,k);
 5180: 	      fprintf(ficres,"#%1d%1d%d",i,j,k);
 5181: 	    }else{
 5182: 	      if(mle>=1)
 5183: 		printf("%1d%1d%d",i,j,k);
 5184: 	      fprintf(ficlog,"%1d%1d%d",i,j,k);
 5185: 	      fprintf(ficres,"%1d%1d%d",i,j,k);
 5186: 	    }
 5187: 	    ll=0;
 5188: 	    for(li=1;li <=nlstate; li++){
 5189: 	      for(lj=1;lj <=nlstate+ndeath; lj++){
 5190: 		if(lj==li) continue;
 5191: 		for(lk=1;lk<=ncovmodel;lk++){
 5192: 		  ll++;
 5193: 		  if(ll<=jj){
 5194: 		    cb[0]= lk +'a'-1;cb[1]='\0';
 5195: 		    if(ll<jj){
 5196: 		      if(itimes==1){
 5197: 			if(mle>=1)
 5198: 			  printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 5199: 			fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 5200: 			fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 5201: 		      }else{
 5202: 			if(mle>=1)
 5203: 			  printf(" %.5e",matcov[jj][ll]); 
 5204: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
 5205: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
 5206: 		      }
 5207: 		    }else{
 5208: 		      if(itimes==1){
 5209: 			if(mle>=1)
 5210: 			  printf(" Var(%s%1d%1d)",ca,i,j);
 5211: 			fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
 5212: 			fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
 5213: 		      }else{
 5214: 			if(mle>=1)
 5215: 			  printf(" %.5e",matcov[jj][ll]); 
 5216: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
 5217: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
 5218: 		      }
 5219: 		    }
 5220: 		  }
 5221: 		} /* end lk */
 5222: 	      } /* end lj */
 5223: 	    } /* end li */
 5224: 	    if(mle>=1)
 5225: 	      printf("\n");
 5226: 	    fprintf(ficlog,"\n");
 5227: 	    fprintf(ficres,"\n");
 5228: 	    numlinepar++;
 5229: 	  } /* end k*/
 5230: 	} /*end j */
 5231:       } /* end i */
 5232:     } /* end itimes */
 5233:     
 5234:     fflush(ficlog);
 5235:     fflush(ficres);
 5236:     
 5237:     while((c=getc(ficpar))=='#' && c!= EOF){
 5238:       ungetc(c,ficpar);
 5239:       fgets(line, MAXLINE, ficpar);
 5240:       puts(line);
 5241:       fputs(line,ficparo);
 5242:     }
 5243:     ungetc(c,ficpar);
 5244:     
 5245:     estepm=0;
 5246:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
 5247:     if (estepm==0 || estepm < stepm) estepm=stepm;
 5248:     if (fage <= 2) {
 5249:       bage = ageminpar;
 5250:       fage = agemaxpar;
 5251:     }
 5252:     
 5253:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
 5254:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
 5255:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
 5256:     
 5257:     while((c=getc(ficpar))=='#' && c!= EOF){
 5258:       ungetc(c,ficpar);
 5259:       fgets(line, MAXLINE, ficpar);
 5260:       puts(line);
 5261:       fputs(line,ficparo);
 5262:     }
 5263:     ungetc(c,ficpar);
 5264:     
 5265:     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);
 5266:     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);
 5267:     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);
 5268:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
 5269:     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);
 5270:     
 5271:     while((c=getc(ficpar))=='#' && c!= EOF){
 5272:       ungetc(c,ficpar);
 5273:       fgets(line, MAXLINE, ficpar);
 5274:       puts(line);
 5275:       fputs(line,ficparo);
 5276:     }
 5277:     ungetc(c,ficpar);
 5278:     
 5279:     
 5280:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
 5281:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
 5282:     
 5283:     fscanf(ficpar,"pop_based=%d\n",&popbased);
 5284:     fprintf(ficparo,"pop_based=%d\n",popbased);   
 5285:     fprintf(ficres,"pop_based=%d\n",popbased);   
 5286:     
 5287:     while((c=getc(ficpar))=='#' && c!= EOF){
 5288:       ungetc(c,ficpar);
 5289:       fgets(line, MAXLINE, ficpar);
 5290:       puts(line);
 5291:       fputs(line,ficparo);
 5292:     }
 5293:     ungetc(c,ficpar);
 5294:     
 5295:     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);
 5296:     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);
 5297:     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);
 5298:     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);
 5299:     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);
 5300:     /* day and month of proj2 are not used but only year anproj2.*/
 5301:     
 5302:     
 5303:     
 5304:     /*  freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint);*/
 5305:     /*,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
 5306:     
 5307:     replace_back_to_slash(pathc,path); /* Even gnuplot wants a / */
 5308:     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
 5309:     
 5310:     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
 5311: 		 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
 5312: 		 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
 5313:       
 5314:    /*------------ free_vector  -------------*/
 5315:    /*  chdir(path); */
 5316:  
 5317:     free_ivector(wav,1,imx);
 5318:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
 5319:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
 5320:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
 5321:     free_lvector(num,1,n);
 5322:     free_vector(agedc,1,n);
 5323:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
 5324:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
 5325:     fclose(ficparo);
 5326:     fclose(ficres);
 5327: 
 5328: 
 5329:     /*--------------- Prevalence limit  (stable prevalence) --------------*/
 5330:   
 5331:     strcpy(filerespl,"pl");
 5332:     strcat(filerespl,fileres);
 5333:     if((ficrespl=fopen(filerespl,"w"))==NULL) {
 5334:       printf("Problem with stable prevalence resultfile: %s\n", filerespl);goto end;
 5335:       fprintf(ficlog,"Problem with stable prevalence resultfile: %s\n", filerespl);goto end;
 5336:     }
 5337:     printf("Computing stable prevalence: result on file '%s' \n", filerespl);
 5338:     fprintf(ficlog,"Computing stable prevalence: result on file '%s' \n", filerespl);
 5339:     fprintf(ficrespl, "#Local time at start: %s", strstart);
 5340:     fprintf(ficrespl,"#Stable prevalence \n");
 5341:     fprintf(ficrespl,"#Age ");
 5342:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
 5343:     fprintf(ficrespl,"\n");
 5344:   
 5345:     prlim=matrix(1,nlstate,1,nlstate);
 5346: 
 5347:     agebase=ageminpar;
 5348:     agelim=agemaxpar;
 5349:     ftolpl=1.e-10;
 5350:     i1=cptcoveff;
 5351:     if (cptcovn < 1){i1=1;}
 5352: 
 5353:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 5354:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 5355: 	k=k+1;
 5356: 	/*printf("cptcov=%d cptcod=%d codtab=%d nbcode=%d\n",cptcov, cptcod,Tcode[cptcode],codtab[cptcod][cptcov]);*/
 5357: 	fprintf(ficrespl,"\n#******");
 5358: 	printf("\n#******");
 5359: 	fprintf(ficlog,"\n#******");
 5360: 	for(j=1;j<=cptcoveff;j++) {
 5361: 	  fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 5362: 	  printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 5363: 	  fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 5364: 	}
 5365: 	fprintf(ficrespl,"******\n");
 5366: 	printf("******\n");
 5367: 	fprintf(ficlog,"******\n");
 5368: 	
 5369: 	for (age=agebase; age<=agelim; age++){
 5370: 	  prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
 5371: 	  fprintf(ficrespl,"%.0f ",age );
 5372: 	  for(j=1;j<=cptcoveff;j++)
 5373: 	    fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 5374: 	  for(i=1; i<=nlstate;i++)
 5375: 	    fprintf(ficrespl," %.5f", prlim[i][i]);
 5376: 	  fprintf(ficrespl,"\n");
 5377: 	}
 5378:       }
 5379:     }
 5380:     fclose(ficrespl);
 5381: 
 5382:     /*------------- h Pij x at various ages ------------*/
 5383:   
 5384:     strcpy(filerespij,"pij");  strcat(filerespij,fileres);
 5385:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
 5386:       printf("Problem with Pij resultfile: %s\n", filerespij);goto end;
 5387:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij);goto end;
 5388:     }
 5389:     printf("Computing pij: result on file '%s' \n", filerespij);
 5390:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
 5391:   
 5392:     stepsize=(int) (stepm+YEARM-1)/YEARM;
 5393:     /*if (stepm<=24) stepsize=2;*/
 5394: 
 5395:     agelim=AGESUP;
 5396:     hstepm=stepsize*YEARM; /* Every year of age */
 5397:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
 5398: 
 5399:     /* hstepm=1;   aff par mois*/
 5400:     fprintf(ficrespij, "#Local time at start: %s", strstart);
 5401:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
 5402:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 5403:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 5404: 	k=k+1;
 5405: 	fprintf(ficrespij,"\n#****** ");
 5406: 	for(j=1;j<=cptcoveff;j++) 
 5407: 	  fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 5408: 	fprintf(ficrespij,"******\n");
 5409: 	
 5410: 	for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
 5411: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 5412: 	  nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 5413: 
 5414: 	  /*	  nhstepm=nhstepm*YEARM; aff par mois*/
 5415: 
 5416: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5417: 	  oldm=oldms;savm=savms;
 5418: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 5419: 	  fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
 5420: 	  for(i=1; i<=nlstate;i++)
 5421: 	    for(j=1; j<=nlstate+ndeath;j++)
 5422: 	      fprintf(ficrespij," %1d-%1d",i,j);
 5423: 	  fprintf(ficrespij,"\n");
 5424: 	  for (h=0; h<=nhstepm; h++){
 5425: 	    fprintf(ficrespij,"%d %3.f %3.f",k,agedeb, agedeb+ h*hstepm/YEARM*stepm );
 5426: 	    for(i=1; i<=nlstate;i++)
 5427: 	      for(j=1; j<=nlstate+ndeath;j++)
 5428: 		fprintf(ficrespij," %.5f", p3mat[i][j][h]);
 5429: 	    fprintf(ficrespij,"\n");
 5430: 	  }
 5431: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5432: 	  fprintf(ficrespij,"\n");
 5433: 	}
 5434:       }
 5435:     }
 5436: 
 5437:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
 5438: 
 5439:     fclose(ficrespij);
 5440: 
 5441:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 5442:     for(i=1;i<=AGESUP;i++)
 5443:       for(j=1;j<=NCOVMAX;j++)
 5444: 	for(k=1;k<=NCOVMAX;k++)
 5445: 	  probs[i][j][k]=0.;
 5446: 
 5447:     /*---------- Forecasting ------------------*/
 5448:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
 5449:     if(prevfcast==1){
 5450:       /*    if(stepm ==1){*/
 5451:       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
 5452:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
 5453:       /*      }  */
 5454:       /*      else{ */
 5455:       /*        erreur=108; */
 5456:       /*        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); */
 5457:       /*        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); */
 5458:       /*      } */
 5459:     }
 5460:   
 5461: 
 5462:     /*---------- Health expectancies and variances ------------*/
 5463: 
 5464:     strcpy(filerest,"t");
 5465:     strcat(filerest,fileres);
 5466:     if((ficrest=fopen(filerest,"w"))==NULL) {
 5467:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
 5468:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
 5469:     }
 5470:     printf("Computing Total LEs with variances: file '%s' \n", filerest); 
 5471:     fprintf(ficlog,"Computing Total LEs with variances: file '%s' \n", filerest); 
 5472: 
 5473: 
 5474:     strcpy(filerese,"e");
 5475:     strcat(filerese,fileres);
 5476:     if((ficreseij=fopen(filerese,"w"))==NULL) {
 5477:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 5478:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 5479:     }
 5480:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
 5481:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
 5482: 
 5483:     strcpy(fileresv,"v");
 5484:     strcat(fileresv,fileres);
 5485:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
 5486:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
 5487:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
 5488:     }
 5489:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
 5490:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
 5491: 
 5492:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
 5493:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 5494:     /*  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",\
 5495: 	ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
 5496:     */
 5497: 
 5498:     if (mobilav!=0) {
 5499:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 5500:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 5501: 	fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 5502: 	printf(" Error in movingaverage mobilav=%d\n",mobilav);
 5503:       }
 5504:     }
 5505: 
 5506:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 5507:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 5508: 	k=k+1; 
 5509: 	fprintf(ficrest,"\n#****** ");
 5510: 	for(j=1;j<=cptcoveff;j++) 
 5511: 	  fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 5512: 	fprintf(ficrest,"******\n");
 5513: 
 5514: 	fprintf(ficreseij,"\n#****** ");
 5515: 	for(j=1;j<=cptcoveff;j++) 
 5516: 	  fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 5517: 	fprintf(ficreseij,"******\n");
 5518: 
 5519: 	fprintf(ficresvij,"\n#****** ");
 5520: 	for(j=1;j<=cptcoveff;j++) 
 5521: 	  fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 5522: 	fprintf(ficresvij,"******\n");
 5523: 
 5524: 	eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 5525: 	oldm=oldms;savm=savms;
 5526: 	evsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
 5527:  
 5528: 	vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 5529: 	oldm=oldms;savm=savms;
 5530: 	varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,0, mobilav, strstart);
 5531: 	if(popbased==1){
 5532: 	  varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,popbased,mobilav, strstart);
 5533: 	}
 5534: 
 5535: 	fprintf(ficrest, "#Local time at start: %s", strstart);
 5536: 	fprintf(ficrest,"#Total LEs with variances: e.. (std) ");
 5537: 	for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
 5538: 	fprintf(ficrest,"\n");
 5539: 
 5540: 	epj=vector(1,nlstate+1);
 5541: 	for(age=bage; age <=fage ;age++){
 5542: 	  prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
 5543: 	  if (popbased==1) {
 5544: 	    if(mobilav ==0){
 5545: 	      for(i=1; i<=nlstate;i++)
 5546: 		prlim[i][i]=probs[(int)age][i][k];
 5547: 	    }else{ /* mobilav */ 
 5548: 	      for(i=1; i<=nlstate;i++)
 5549: 		prlim[i][i]=mobaverage[(int)age][i][k];
 5550: 	    }
 5551: 	  }
 5552: 	
 5553: 	  fprintf(ficrest," %4.0f",age);
 5554: 	  for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
 5555: 	    for(i=1, epj[j]=0.;i <=nlstate;i++) {
 5556: 	      epj[j] += prlim[i][i]*eij[i][j][(int)age];
 5557: 	      /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
 5558: 	    }
 5559: 	    epj[nlstate+1] +=epj[j];
 5560: 	  }
 5561: 
 5562: 	  for(i=1, vepp=0.;i <=nlstate;i++)
 5563: 	    for(j=1;j <=nlstate;j++)
 5564: 	      vepp += vareij[i][j][(int)age];
 5565: 	  fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
 5566: 	  for(j=1;j <=nlstate;j++){
 5567: 	    fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
 5568: 	  }
 5569: 	  fprintf(ficrest,"\n");
 5570: 	}
 5571: 	free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 5572: 	free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 5573: 	free_vector(epj,1,nlstate+1);
 5574:       }
 5575:     }
 5576:     free_vector(weight,1,n);
 5577:     free_imatrix(Tvard,1,15,1,2);
 5578:     free_imatrix(s,1,maxwav+1,1,n);
 5579:     free_matrix(anint,1,maxwav,1,n); 
 5580:     free_matrix(mint,1,maxwav,1,n);
 5581:     free_ivector(cod,1,n);
 5582:     free_ivector(tab,1,NCOVMAX);
 5583:     fclose(ficreseij);
 5584:     fclose(ficresvij);
 5585:     fclose(ficrest);
 5586:     fclose(ficpar);
 5587:   
 5588:     /*------- Variance of stable prevalence------*/   
 5589: 
 5590:     strcpy(fileresvpl,"vpl");
 5591:     strcat(fileresvpl,fileres);
 5592:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
 5593:       printf("Problem with variance of stable prevalence  resultfile: %s\n", fileresvpl);
 5594:       exit(0);
 5595:     }
 5596:     printf("Computing Variance-covariance of stable prevalence: file '%s' \n", fileresvpl);
 5597: 
 5598:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 5599:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 5600: 	k=k+1;
 5601: 	fprintf(ficresvpl,"\n#****** ");
 5602: 	for(j=1;j<=cptcoveff;j++) 
 5603: 	  fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 5604: 	fprintf(ficresvpl,"******\n");
 5605:       
 5606: 	varpl=matrix(1,nlstate,(int) bage, (int) fage);
 5607: 	oldm=oldms;savm=savms;
 5608: 	varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
 5609: 	free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
 5610:       }
 5611:     }
 5612: 
 5613:     fclose(ficresvpl);
 5614: 
 5615:     /*---------- End : free ----------------*/
 5616:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 5617:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 5618: 
 5619:   }  /* mle==-3 arrives here for freeing */
 5620:   free_matrix(prlim,1,nlstate,1,nlstate);
 5621:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
 5622:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
 5623:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
 5624:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
 5625:     free_matrix(covar,0,NCOVMAX,1,n);
 5626:     free_matrix(matcov,1,npar,1,npar);
 5627:     /*free_vector(delti,1,npar);*/
 5628:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 5629:     free_matrix(agev,1,maxwav,1,imx);
 5630:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
 5631: 
 5632:     free_ivector(ncodemax,1,8);
 5633:     free_ivector(Tvar,1,15);
 5634:     free_ivector(Tprod,1,15);
 5635:     free_ivector(Tvaraff,1,15);
 5636:     free_ivector(Tage,1,15);
 5637:     free_ivector(Tcode,1,100);
 5638: 
 5639:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
 5640:     free_imatrix(codtab,1,100,1,10);
 5641:   fflush(fichtm);
 5642:   fflush(ficgp);
 5643:   
 5644: 
 5645:   if((nberr >0) || (nbwarn>0)){
 5646:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
 5647:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
 5648:   }else{
 5649:     printf("End of Imach\n");
 5650:     fprintf(ficlog,"End of Imach\n");
 5651:   }
 5652:   printf("See log file on %s\n",filelog);
 5653:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
 5654:   (void) gettimeofday(&end_time,&tzp);
 5655:   tm = *localtime(&end_time.tv_sec);
 5656:   tmg = *gmtime(&end_time.tv_sec);
 5657:   strcpy(strtend,asctime(&tm));
 5658:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
 5659:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
 5660:   printf("Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));
 5661: 
 5662:   printf("Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);
 5663:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));
 5664:   fprintf(ficlog,"Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);
 5665:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
 5666: /*   if(fileappend(fichtm,optionfilehtm)){ */
 5667:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>",strstart, strtend);
 5668:   fclose(fichtm);
 5669:   fclose(fichtmcov);
 5670:   fclose(ficgp);
 5671:   fclose(ficlog);
 5672:   /*------ End -----------*/
 5673: 
 5674:   chdir(path);
 5675:   /*strcat(plotcmd,CHARSEPARATOR);*/
 5676:   sprintf(plotcmd,"gnuplot");
 5677: #ifndef UNIX
 5678:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
 5679: #endif
 5680:   if(!stat(plotcmd,&info)){
 5681:     printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);
 5682:     if(!stat(getenv("GNUPLOTBIN"),&info)){
 5683:       printf("Error gnuplot program not found: %s Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
 5684:     }else
 5685:       strcpy(pplotcmd,plotcmd);
 5686: #ifdef UNIX
 5687:     strcpy(plotcmd,GNUPLOTPROGRAM);
 5688:     if(!stat(plotcmd,&info)){
 5689:       printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);
 5690:     }else
 5691:       strcpy(pplotcmd,plotcmd);
 5692: #endif
 5693:   }else
 5694:     strcpy(pplotcmd,plotcmd);
 5695:   
 5696:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
 5697:   printf("Starting graphs with: %s\n",plotcmd);fflush(stdout);
 5698: 
 5699:   if((outcmd=system(plotcmd)) != 0){
 5700:     printf("\n Problem with gnuplot\n");
 5701:   }
 5702:   printf(" Wait...");
 5703:   while (z[0] != 'q') {
 5704:     /* chdir(path); */
 5705:     printf("\nType e to edit output files, g to graph again and q for exiting: ");
 5706:     scanf("%s",z);
 5707: /*     if (z[0] == 'c') system("./imach"); */
 5708:     if (z[0] == 'e') {
 5709:       printf("Starting browser with: %s",optionfilehtm);fflush(stdout);
 5710:       system(optionfilehtm);
 5711:     }
 5712:     else if (z[0] == 'g') system(plotcmd);
 5713:     else if (z[0] == 'q') exit(0);
 5714:   }
 5715:   end:
 5716:   while (z[0] != 'q') {
 5717:     printf("\nType  q for exiting: ");
 5718:     scanf("%s",z);
 5719:   }
 5720: }
 5721: 
 5722: 
 5723: 

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