File:  [Local Repository] / imach / src / imach.c
Revision 1.91: download - view: text, annotated - select for diffs
Wed Jun 25 15:30:29 2003 UTC (20 years, 11 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
* imach.c (Repository): Duplicated warning errors corrected.
(Repository): Elapsed time after each iteration is now output. It
helps to forecast when convergence will be reached. Elapsed time
is stamped in powell.  We created a new html file for the graphs
concerning matrix of covariance. It has extension -cov.htm.

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

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