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

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

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