File:  [Local Repository] / imach / src / imach.c
Revision 1.86: download - view: text, annotated - select for diffs
Tue Jun 17 20:04:08 2003 UTC (20 years, 11 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
(Module): Change position of html and gnuplot routines and added
routine fileappend.

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

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