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

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

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