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

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

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