Annotation of imach/src/imach.c, revision 1.63

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

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