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

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

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