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

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

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