Annotation of imach096d/src/imach.c, revision 1.82

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

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