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

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

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