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

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

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