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

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

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