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

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

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