File:  [Local Repository] / imach / src / imach.c
Revision 1.112: download - view: text, annotated - select for diffs
Mon Jan 30 09:55:26 2006 UTC (18 years, 4 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
(Module): Back to gnuplot.exe instead of wgnuplot.exe

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

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