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

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.15      lievre     76: int popbased=0;
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;
1.16      lievre     88: FILE *ficgp, *fichtm,*ficresprob,*ficpop;
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 ********************/
1.18    ! lievre   1153: void  freqsummary(char fileres[], int agemin, int agemax, int **s, double **agev, int nlstate, int imx, int *Tvar, int **nbcode, int *ncodemax, int fprev1,int lprev1,double **mint,double **anint, int boolprev, double dateprev1,double dateprev2)
1.2       lievre   1154: {  /* Some frequencies */
                   1155:  
1.18    ! lievre   1156:   int i, m, jk, k1,i1, j1, bool, z1,z2,j;
1.2       lievre   1157:   double ***freq; /* Frequencies */
                   1158:   double *pp;
1.18    ! lievre   1159:   double pos, k2;
1.2       lievre   1160:   FILE *ficresp;
                   1161:   char fileresp[FILENAMELENGTH];
                   1162: 
                   1163:   pp=vector(1,nlstate);
1.17      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:         }
1.18    ! lievre   1194:         if (bool==1) {
        !          1195:           if (boolprev==1){
        !          1196:             for(m=fprev1; m<=lprev1; m++){
        !          1197:               if(agev[m][i]==0) agev[m][i]=agemax+1;
        !          1198:               if(agev[m][i]==1) agev[m][i]=agemax+2;
        !          1199:               freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
        !          1200:               freq[s[m][i]][s[m+1][i]][(int) agemax+3] += weight[i];
        !          1201:             }
        !          1202:           }
        !          1203:           else {
        !          1204:            for(m=firstpass; m<=lastpass; m++){
1.17      lievre   1205:             k2=anint[m][i]+(mint[m][i]/12.);
1.18    ! lievre   1206:             if ((k2>=dateprev1) && (k2<=dateprev2)) {
1.2       lievre   1207:             if(agev[m][i]==0) agev[m][i]=agemax+1;
                   1208:             if(agev[m][i]==1) agev[m][i]=agemax+2;
                   1209:             freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
                   1210:             freq[s[m][i]][s[m+1][i]][(int) agemax+3] += weight[i];
1.17      lievre   1211:             }
                   1212:            }
1.18    ! lievre   1213:           }
1.17      lievre   1214:          }
1.2       lievre   1215:        }
                   1216:         if  (cptcovn>0) {
1.7       lievre   1217:         fprintf(ficresp, "\n#********** Variable "); 
                   1218:         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   1219:        fprintf(ficresp, "**********\n#");
1.8       lievre   1220:        }
1.2       lievre   1221:        for(i=1; i<=nlstate;i++) 
                   1222:         fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   1223:        fprintf(ficresp, "\n");
                   1224:        
                   1225:   for(i=(int)agemin; i <= (int)agemax+3; i++){
                   1226:     if(i==(int)agemax+3)
                   1227:       printf("Total");
                   1228:     else
                   1229:       printf("Age %d", i);
                   1230:     for(jk=1; jk <=nlstate ; jk++){
                   1231:       for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
1.14      lievre   1232:        pp[jk] += freq[jk][m][i]; 
1.2       lievre   1233:     }
                   1234:     for(jk=1; jk <=nlstate ; jk++){
                   1235:       for(m=-1, pos=0; m <=0 ; m++)
                   1236:        pos += freq[jk][m][i];
                   1237:       if(pp[jk]>=1.e-10)
                   1238:        printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   1239:       else
                   1240:         printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   1241:     }
1.14      lievre   1242: 
                   1243:      for(jk=1; jk <=nlstate ; jk++){
                   1244:       for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
1.2       lievre   1245:        pp[jk] += freq[jk][m][i];
1.14      lievre   1246:      }
                   1247: 
1.2       lievre   1248:     for(jk=1,pos=0; jk <=nlstate ; jk++)
                   1249:       pos += pp[jk];
                   1250:     for(jk=1; jk <=nlstate ; jk++){
                   1251:       if(pos>=1.e-5)
                   1252:        printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   1253:       else
                   1254:        printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   1255:       if( i <= (int) agemax){
1.13      lievre   1256:        if(pos>=1.e-5){
1.2       lievre   1257:          fprintf(ficresp," %d %.5f %.0f %.0f",i,pp[jk]/pos, pp[jk],pos);
1.13      lievre   1258:          probs[i][jk][j1]= pp[jk]/pos;
                   1259:          /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   1260:        }
1.2       lievre   1261:       else
                   1262:          fprintf(ficresp," %d NaNq %.0f %.0f",i,pp[jk],pos);
                   1263:       }
                   1264:     }
                   1265:     for(jk=-1; jk <=nlstate+ndeath; jk++)
                   1266:       for(m=-1; m <=nlstate+ndeath; m++)
                   1267:        if(freq[jk][m][i] !=0 ) printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   1268:     if(i <= (int) agemax)
                   1269:       fprintf(ficresp,"\n");
                   1270:     printf("\n");
                   1271:     }
                   1272:     }
                   1273:  }
                   1274:  
                   1275:   fclose(ficresp);
                   1276:   free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath,(int) agemin,(int) agemax+3);
                   1277:   free_vector(pp,1,nlstate);
                   1278: 
                   1279: }  /* End of Freq */
                   1280: 
1.15      lievre   1281: /************ Prevalence ********************/
1.18    ! lievre   1282: void prevalence(int agemin, int agemax, int **s, double **agev, int nlstate, int imx, int *Tvar, int **nbcode, int *ncodemax, int fprev1,int lprev1, double **mint,double **anint,int boolprev, double dateprev1, double dateprev2)
1.15      lievre   1283: {  /* Some frequencies */
                   1284:  
                   1285:   int i, m, jk, k1, i1, j1, bool, z1,z2,j;
                   1286:   double ***freq; /* Frequencies */
                   1287:   double *pp;
1.18    ! lievre   1288:   double pos, k2;
1.15      lievre   1289: 
                   1290:   pp=vector(1,nlstate);
                   1291:   probs= ma3x(1,130 ,1,8, 1,8);
                   1292:   
                   1293:   freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,agemin,agemax+3);
                   1294:   j1=0;
                   1295:   
                   1296:   j=cptcoveff;
                   1297:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   1298:   
                   1299:  for(k1=1; k1<=j;k1++){
                   1300:     for(i1=1; i1<=ncodemax[k1];i1++){
                   1301:       j1++;
                   1302:  
                   1303:       for (i=-1; i<=nlstate+ndeath; i++)  
                   1304:        for (jk=-1; jk<=nlstate+ndeath; jk++)  
                   1305:          for(m=agemin; m <= agemax+3; m++)
                   1306:          freq[i][jk][m]=0;
                   1307:       
                   1308:       for (i=1; i<=imx; i++) {
                   1309:        bool=1;
                   1310:        if  (cptcovn>0) {
                   1311:          for (z1=1; z1<=cptcoveff; z1++) 
                   1312:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
                   1313:              bool=0;
                   1314:              }
                   1315:        if (bool==1) {
1.18    ! lievre   1316:          if (boolprev==1){
        !          1317:            for(m=fprev1; m<=lprev1; m++){
        !          1318:              if(agev[m][i]==0) agev[m][i]=agemax+1;
        !          1319:              if(agev[m][i]==1) agev[m][i]=agemax+2;
        !          1320:              freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
        !          1321:              freq[s[m][i]][s[m+1][i]][(int) agemax+3] += weight[i];
        !          1322:            }
        !          1323:          }
        !          1324:          else {
        !          1325:            for(m=firstpass; m<=lastpass; m++){
        !          1326:              k2=anint[m][i]+(mint[m][i]/12.);
        !          1327:              if ((k2>=dateprev1) && (k2<=dateprev2)) {
        !          1328:                if(agev[m][i]==0) agev[m][i]=agemax+1;
        !          1329:                if(agev[m][i]==1) agev[m][i]=agemax+2;
        !          1330:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
        !          1331:                freq[s[m][i]][s[m+1][i]][(int) agemax+3] += weight[i];
        !          1332:              }
        !          1333:            }
1.15      lievre   1334:          }
                   1335:        }
                   1336:       }
1.18    ! lievre   1337:        for(i=(int)agemin; i <= (int)agemax+3; i++){ 
        !          1338:          for(jk=1; jk <=nlstate ; jk++){
        !          1339:            for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
        !          1340:              pp[jk] += freq[jk][m][i]; 
        !          1341:          }
        !          1342:          for(jk=1; jk <=nlstate ; jk++){
        !          1343:            for(m=-1, pos=0; m <=0 ; m++)
1.15      lievre   1344:            pos += freq[jk][m][i];
                   1345:        }
                   1346:        
                   1347:         for(jk=1; jk <=nlstate ; jk++){
                   1348:           for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   1349:             pp[jk] += freq[jk][m][i];
                   1350:         }
                   1351:         
                   1352:         for(jk=1,pos=0; jk <=nlstate ; jk++) pos += pp[jk];
                   1353: 
                   1354:         for(jk=1; jk <=nlstate ; jk++){           
                   1355:           if( i <= (int) agemax){
                   1356:             if(pos>=1.e-5){
                   1357:               probs[i][jk][j1]= pp[jk]/pos;
                   1358:             }
                   1359:           }
                   1360:         }
                   1361:         
1.18    ! lievre   1362:        }
1.15      lievre   1363:     }
                   1364:   }
                   1365:   
                   1366:   
                   1367:   free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath,(int) agemin,(int) agemax+3);
                   1368:   free_vector(pp,1,nlstate);
                   1369:   
                   1370: }  /* End of Freq */
1.2       lievre   1371: /************* Waves Concatenation ***************/
                   1372: 
                   1373: void  concatwav(int wav[], int **dh, int **mw, int **s, double *agedc, double **agev, int  firstpass, int lastpass, int imx, int nlstate, int stepm)
                   1374: {
                   1375:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   1376:      Death is a valid wave (if date is known).
                   1377:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   1378:      dh[m][i] of dh[mw[mi][i][i] is the delay between two effective waves m=mw[mi][i]
                   1379:      and mw[mi+1][i]. dh depends on stepm.
                   1380:      */
                   1381: 
                   1382:   int i, mi, m;
1.8       lievre   1383:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   1384:      double sum=0., jmean=0.;*/
1.2       lievre   1385: 
1.11      lievre   1386:   int j, k=0,jk, ju, jl;
                   1387:   double sum=0.;
                   1388:   jmin=1e+5;
                   1389:   jmax=-1;
                   1390:   jmean=0.;
1.2       lievre   1391:   for(i=1; i<=imx; i++){
                   1392:     mi=0;
                   1393:     m=firstpass;
                   1394:     while(s[m][i] <= nlstate){
                   1395:       if(s[m][i]>=1)
                   1396:        mw[++mi][i]=m;
                   1397:       if(m >=lastpass)
                   1398:        break;
                   1399:       else
                   1400:        m++;
                   1401:     }/* end while */
                   1402:     if (s[m][i] > nlstate){
                   1403:       mi++;    /* Death is another wave */
                   1404:       /* if(mi==0)  never been interviewed correctly before death */
                   1405:         /* Only death is a correct wave */
                   1406:       mw[mi][i]=m;
                   1407:     }
                   1408: 
                   1409:     wav[i]=mi;
                   1410:     if(mi==0)
                   1411:       printf("Warning, no any valid information for:%d line=%d\n",num[i],i);
                   1412:   }
                   1413: 
                   1414:   for(i=1; i<=imx; i++){
                   1415:     for(mi=1; mi<wav[i];mi++){
                   1416:       if (stepm <=0)
                   1417:        dh[mi][i]=1;
                   1418:       else{
                   1419:        if (s[mw[mi+1][i]][i] > nlstate) {
1.10      lievre   1420:          if (agedc[i] < 2*AGESUP) {
1.2       lievre   1421:          j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
1.8       lievre   1422:          if(j==0) j=1;  /* Survives at least one month after exam */
                   1423:          k=k+1;
                   1424:          if (j >= jmax) jmax=j;
1.11      lievre   1425:          if (j <= jmin) jmin=j;
1.8       lievre   1426:          sum=sum+j;
1.12      lievre   1427:          /* if (j<10) printf("j=%d num=%d ",j,i); */
1.10      lievre   1428:          }
1.2       lievre   1429:        }
                   1430:        else{
                   1431:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   1432:          k=k+1;
                   1433:          if (j >= jmax) jmax=j;
                   1434:          else if (j <= jmin)jmin=j;
1.12      lievre   1435:          /*   if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
1.2       lievre   1436:          sum=sum+j;
                   1437:        }
                   1438:        jk= j/stepm;
                   1439:        jl= j -jk*stepm;
                   1440:        ju= j -(jk+1)*stepm;
                   1441:        if(jl <= -ju)
                   1442:          dh[mi][i]=jk;
                   1443:        else
                   1444:          dh[mi][i]=jk+1;
                   1445:        if(dh[mi][i]==0)
                   1446:          dh[mi][i]=1; /* At least one step */
                   1447:       }
                   1448:     }
                   1449:   }
1.8       lievre   1450:   jmean=sum/k;
                   1451:   printf("Delay (in months) between two waves Min=%d Max=%d Mean=%f\n\n ",jmin, jmax,jmean);
1.12      lievre   1452:  }
1.2       lievre   1453: /*********** Tricode ****************************/
                   1454: void tricode(int *Tvar, int **nbcode, int imx)
                   1455: {
1.7       lievre   1456:   int Ndum[20],ij=1, k, j, i;
1.2       lievre   1457:   int cptcode=0;
1.7       lievre   1458:   cptcoveff=0; 
                   1459:  
                   1460:   for (k=0; k<19; k++) Ndum[k]=0;
1.2       lievre   1461:   for (k=1; k<=7; k++) ncodemax[k]=0;
1.6       lievre   1462: 
1.7       lievre   1463:   for (j=1; j<=(cptcovn+2*cptcovprod); j++) {
1.2       lievre   1464:     for (i=1; i<=imx; i++) {
                   1465:       ij=(int)(covar[Tvar[j]][i]);
                   1466:       Ndum[ij]++; 
1.8       lievre   1467:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.2       lievre   1468:       if (ij > cptcode) cptcode=ij; 
                   1469:     }
1.7       lievre   1470: 
1.2       lievre   1471:     for (i=0; i<=cptcode; i++) {
                   1472:       if(Ndum[i]!=0) ncodemax[j]++;
                   1473:     }
                   1474:     ij=1; 
1.7       lievre   1475: 
1.8       lievre   1476: 
1.2       lievre   1477:     for (i=1; i<=ncodemax[j]; i++) {
1.7       lievre   1478:       for (k=0; k<=19; k++) {
1.2       lievre   1479:        if (Ndum[k] != 0) {
                   1480:          nbcode[Tvar[j]][ij]=k; 
                   1481:          ij++;
                   1482:        }
                   1483:        if (ij > ncodemax[j]) break; 
                   1484:       }  
                   1485:     } 
1.7       lievre   1486:   }  
1.8       lievre   1487: 
                   1488:  for (k=0; k<19; k++) Ndum[k]=0;
                   1489: 
1.12      lievre   1490:  for (i=1; i<=ncovmodel-2; i++) {
1.7       lievre   1491:       ij=Tvar[i];
                   1492:       Ndum[ij]++; 
                   1493:     }
1.8       lievre   1494: 
1.7       lievre   1495:  ij=1;
1.8       lievre   1496:  for (i=1; i<=10; i++) {
1.7       lievre   1497:    if((Ndum[i]!=0) && (i<=ncov)){
1.8       lievre   1498:      Tvaraff[ij]=i; 
                   1499:      ij++;
1.7       lievre   1500:    }
                   1501:  }
                   1502:  
1.8       lievre   1503:     cptcoveff=ij-1;
1.6       lievre   1504: }
1.2       lievre   1505: 
                   1506: /*********** Health Expectancies ****************/
                   1507: 
                   1508: void evsij(char fileres[], double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int ij)
                   1509: {
                   1510:   /* Health expectancies */
                   1511:   int i, j, nhstepm, hstepm, h;
                   1512:   double age, agelim,hf;
                   1513:   double ***p3mat;
                   1514:   
                   1515:   fprintf(ficreseij,"# Health expectancies\n");
                   1516:   fprintf(ficreseij,"# Age");
                   1517:   for(i=1; i<=nlstate;i++)
                   1518:     for(j=1; j<=nlstate;j++)
                   1519:       fprintf(ficreseij," %1d-%1d",i,j);
                   1520:   fprintf(ficreseij,"\n");
                   1521: 
                   1522:   hstepm=1*YEARM; /*  Every j years of age (in month) */
                   1523:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   1524: 
                   1525:   agelim=AGESUP;
                   1526:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   1527:     /* nhstepm age range expressed in number of stepm */
                   1528:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); 
                   1529:     /* Typically if 20 years = 20*12/6=40 stepm */ 
                   1530:     if (stepm >= YEARM) hstepm=1;
                   1531:     nhstepm = nhstepm/hstepm;/* Expressed in hstepm, typically 40/4=10 */
                   1532:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1533:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   1534:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   1535:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, ij);  
                   1536: 
                   1537: 
                   1538:     for(i=1; i<=nlstate;i++)
                   1539:       for(j=1; j<=nlstate;j++)
                   1540:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm; h++){
                   1541:          eij[i][j][(int)age] +=p3mat[i][j][h];
                   1542:        }
                   1543:     
                   1544:     hf=1;
                   1545:     if (stepm >= YEARM) hf=stepm/YEARM;
                   1546:     fprintf(ficreseij,"%.0f",age );
                   1547:     for(i=1; i<=nlstate;i++)
                   1548:       for(j=1; j<=nlstate;j++){
                   1549:        fprintf(ficreseij," %.4f", hf*eij[i][j][(int)age]);
                   1550:       }
                   1551:     fprintf(ficreseij,"\n");
                   1552:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1553:   }
                   1554: }
                   1555: 
                   1556: /************ Variance ******************/
                   1557: 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)
                   1558: {
                   1559:   /* Variance of health expectancies */
                   1560:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   1561:   double **newm;
                   1562:   double **dnewm,**doldm;
                   1563:   int i, j, nhstepm, hstepm, h;
                   1564:   int k, cptcode;
1.12      lievre   1565:   double *xp;
1.2       lievre   1566:   double **gp, **gm;
                   1567:   double ***gradg, ***trgradg;
                   1568:   double ***p3mat;
                   1569:   double age,agelim;
                   1570:   int theta;
                   1571: 
                   1572:    fprintf(ficresvij,"# Covariances of life expectancies\n");
                   1573:   fprintf(ficresvij,"# Age");
                   1574:   for(i=1; i<=nlstate;i++)
                   1575:     for(j=1; j<=nlstate;j++)
                   1576:       fprintf(ficresvij," Cov(e%1d, e%1d)",i,j);
                   1577:   fprintf(ficresvij,"\n");
                   1578: 
                   1579:   xp=vector(1,npar);
                   1580:   dnewm=matrix(1,nlstate,1,npar);
                   1581:   doldm=matrix(1,nlstate,1,nlstate);
                   1582:   
                   1583:   hstepm=1*YEARM; /* Every year of age */
                   1584:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   1585:   agelim = AGESUP;
                   1586:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   1587:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   1588:     if (stepm >= YEARM) hstepm=1;
                   1589:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   1590:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1591:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   1592:     gp=matrix(0,nhstepm,1,nlstate);
                   1593:     gm=matrix(0,nhstepm,1,nlstate);
                   1594: 
                   1595:     for(theta=1; theta <=npar; theta++){
                   1596:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   1597:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   1598:       }
                   1599:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   1600:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
1.14      lievre   1601: 
                   1602:       if (popbased==1) {
                   1603:        for(i=1; i<=nlstate;i++)
                   1604:          prlim[i][i]=probs[(int)age][i][ij];
                   1605:       }
                   1606:       
1.2       lievre   1607:       for(j=1; j<= nlstate; j++){
                   1608:        for(h=0; h<=nhstepm; h++){
                   1609:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   1610:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   1611:        }
                   1612:       }
                   1613:     
                   1614:       for(i=1; i<=npar; i++) /* Computes gradient */
                   1615:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   1616:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   1617:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
1.14      lievre   1618: 
                   1619:       if (popbased==1) {
                   1620:        for(i=1; i<=nlstate;i++)
                   1621:          prlim[i][i]=probs[(int)age][i][ij];
                   1622:       }
                   1623: 
1.2       lievre   1624:       for(j=1; j<= nlstate; j++){
                   1625:        for(h=0; h<=nhstepm; h++){
                   1626:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   1627:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   1628:        }
                   1629:       }
1.14      lievre   1630: 
1.2       lievre   1631:       for(j=1; j<= nlstate; j++)
                   1632:        for(h=0; h<=nhstepm; h++){
                   1633:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   1634:        }
                   1635:     } /* End theta */
                   1636: 
                   1637:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar);
                   1638: 
                   1639:     for(h=0; h<=nhstepm; h++)
                   1640:       for(j=1; j<=nlstate;j++)
                   1641:        for(theta=1; theta <=npar; theta++)
                   1642:          trgradg[h][j][theta]=gradg[h][theta][j];
                   1643: 
                   1644:     for(i=1;i<=nlstate;i++)
                   1645:       for(j=1;j<=nlstate;j++)
                   1646:        vareij[i][j][(int)age] =0.;
                   1647:     for(h=0;h<=nhstepm;h++){
                   1648:       for(k=0;k<=nhstepm;k++){
                   1649:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   1650:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   1651:        for(i=1;i<=nlstate;i++)
                   1652:          for(j=1;j<=nlstate;j++)
                   1653:            vareij[i][j][(int)age] += doldm[i][j];
                   1654:       }
                   1655:     }
                   1656:     h=1;
                   1657:     if (stepm >= YEARM) h=stepm/YEARM;
                   1658:     fprintf(ficresvij,"%.0f ",age );
                   1659:     for(i=1; i<=nlstate;i++)
                   1660:       for(j=1; j<=nlstate;j++){
                   1661:        fprintf(ficresvij," %.4f", h*vareij[i][j][(int)age]);
                   1662:       }
                   1663:     fprintf(ficresvij,"\n");
                   1664:     free_matrix(gp,0,nhstepm,1,nlstate);
                   1665:     free_matrix(gm,0,nhstepm,1,nlstate);
                   1666:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   1667:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   1668:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1669:   } /* End age */
                   1670:  
                   1671:   free_vector(xp,1,npar);
                   1672:   free_matrix(doldm,1,nlstate,1,npar);
                   1673:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   1674: 
                   1675: }
                   1676: 
                   1677: /************ Variance of prevlim ******************/
                   1678: 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)
                   1679: {
                   1680:   /* Variance of prevalence limit */
                   1681:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   1682:   double **newm;
                   1683:   double **dnewm,**doldm;
                   1684:   int i, j, nhstepm, hstepm;
                   1685:   int k, cptcode;
                   1686:   double *xp;
                   1687:   double *gp, *gm;
                   1688:   double **gradg, **trgradg;
                   1689:   double age,agelim;
                   1690:   int theta;
                   1691:    
                   1692:   fprintf(ficresvpl,"# Standard deviation of prevalences limit\n");
                   1693:   fprintf(ficresvpl,"# Age");
                   1694:   for(i=1; i<=nlstate;i++)
                   1695:       fprintf(ficresvpl," %1d-%1d",i,i);
                   1696:   fprintf(ficresvpl,"\n");
                   1697: 
                   1698:   xp=vector(1,npar);
                   1699:   dnewm=matrix(1,nlstate,1,npar);
                   1700:   doldm=matrix(1,nlstate,1,nlstate);
                   1701:   
                   1702:   hstepm=1*YEARM; /* Every year of age */
                   1703:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   1704:   agelim = AGESUP;
                   1705:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   1706:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   1707:     if (stepm >= YEARM) hstepm=1;
                   1708:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   1709:     gradg=matrix(1,npar,1,nlstate);
                   1710:     gp=vector(1,nlstate);
                   1711:     gm=vector(1,nlstate);
                   1712: 
                   1713:     for(theta=1; theta <=npar; theta++){
                   1714:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   1715:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   1716:       }
                   1717:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   1718:       for(i=1;i<=nlstate;i++)
                   1719:        gp[i] = prlim[i][i];
                   1720:     
                   1721:       for(i=1; i<=npar; i++) /* Computes gradient */
                   1722:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   1723:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   1724:       for(i=1;i<=nlstate;i++)
                   1725:        gm[i] = prlim[i][i];
                   1726: 
                   1727:       for(i=1;i<=nlstate;i++)
                   1728:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   1729:     } /* End theta */
                   1730: 
                   1731:     trgradg =matrix(1,nlstate,1,npar);
                   1732: 
                   1733:     for(j=1; j<=nlstate;j++)
                   1734:       for(theta=1; theta <=npar; theta++)
                   1735:        trgradg[j][theta]=gradg[theta][j];
                   1736: 
                   1737:     for(i=1;i<=nlstate;i++)
                   1738:       varpl[i][(int)age] =0.;
                   1739:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   1740:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   1741:     for(i=1;i<=nlstate;i++)
                   1742:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   1743: 
                   1744:     fprintf(ficresvpl,"%.0f ",age );
                   1745:     for(i=1; i<=nlstate;i++)
                   1746:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   1747:     fprintf(ficresvpl,"\n");
                   1748:     free_vector(gp,1,nlstate);
                   1749:     free_vector(gm,1,nlstate);
                   1750:     free_matrix(gradg,1,npar,1,nlstate);
                   1751:     free_matrix(trgradg,1,nlstate,1,npar);
                   1752:   } /* End age */
                   1753: 
                   1754:   free_vector(xp,1,npar);
                   1755:   free_matrix(doldm,1,nlstate,1,npar);
                   1756:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   1757: 
                   1758: }
                   1759: 
1.13      lievre   1760: /************ Variance of one-step probabilities  ******************/
                   1761: void varprob(char fileres[], double **matcov, double x[], double delti[], int nlstate, double bage, double fage, int ij)
                   1762: {
                   1763:   int i, j;
                   1764:   int k=0, cptcode;
                   1765:   double **dnewm,**doldm;
                   1766:   double *xp;
                   1767:   double *gp, *gm;
                   1768:   double **gradg, **trgradg;
                   1769:   double age,agelim, cov[NCOVMAX];
                   1770:   int theta;
                   1771:   char fileresprob[FILENAMELENGTH];
                   1772: 
                   1773:   strcpy(fileresprob,"prob"); 
                   1774:   strcat(fileresprob,fileres);
                   1775:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   1776:     printf("Problem with resultfile: %s\n", fileresprob);
                   1777:   }
                   1778:   printf("Computing variance of one-step probabilities: result on file '%s' \n",fileresprob);
                   1779:   
1.2       lievre   1780: 
1.13      lievre   1781:   xp=vector(1,npar);
                   1782:   dnewm=matrix(1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   1783:   doldm=matrix(1,(nlstate+ndeath)*(nlstate+ndeath),1,(nlstate+ndeath)*(nlstate+ndeath));
                   1784:   
                   1785:   cov[1]=1;
                   1786:   for (age=bage; age<=fage; age ++){ 
                   1787:     cov[2]=age;
                   1788:     gradg=matrix(1,npar,1,9);
                   1789:     trgradg=matrix(1,9,1,npar);
                   1790:     gp=vector(1,(nlstate+ndeath)*(nlstate+ndeath));
                   1791:     gm=vector(1,(nlstate+ndeath)*(nlstate+ndeath));
                   1792:     
                   1793:     for(theta=1; theta <=npar; theta++){
                   1794:       for(i=1; i<=npar; i++)
                   1795:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   1796:      
                   1797:       pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   1798:    
                   1799:       k=0;
                   1800:       for(i=1; i<= (nlstate+ndeath); i++){
                   1801:        for(j=1; j<=(nlstate+ndeath);j++){
                   1802:           k=k+1;
                   1803:          gp[k]=pmmij[i][j];
                   1804:        }
                   1805:       }
                   1806: 
                   1807:       for(i=1; i<=npar; i++)
                   1808:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   1809:     
                   1810: 
                   1811:       pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   1812:       k=0;
                   1813:       for(i=1; i<=(nlstate+ndeath); i++){
                   1814:        for(j=1; j<=(nlstate+ndeath);j++){
                   1815:          k=k+1;
                   1816:          gm[k]=pmmij[i][j];
                   1817:        }
                   1818:       }
                   1819:      
                   1820:        for(i=1; i<= (nlstate+ndeath)*(nlstate+ndeath); i++) 
                   1821:           gradg[theta][i]=(gp[i]-gm[i])/2./delti[theta];  
                   1822:     }
                   1823: 
                   1824:      for(j=1; j<=(nlstate+ndeath)*(nlstate+ndeath);j++)
                   1825:       for(theta=1; theta <=npar; theta++)
                   1826:       trgradg[j][theta]=gradg[theta][j];
                   1827:  
                   1828:      matprod2(dnewm,trgradg,1,9,1,npar,1,npar,matcov);
                   1829:      matprod2(doldm,dnewm,1,9,1,npar,1,9,gradg);
                   1830: 
                   1831:      pmij(pmmij,cov,ncovmodel,x,nlstate);
                   1832: 
                   1833:      k=0;
                   1834:      for(i=1; i<=(nlstate+ndeath); i++){
                   1835:        for(j=1; j<=(nlstate+ndeath);j++){
                   1836:         k=k+1;
                   1837:         gm[k]=pmmij[i][j];
                   1838:        }
                   1839:      }
                   1840:      
                   1841:      /*printf("\n%d ",(int)age);
                   1842:      for (i=1; i<=(nlstate+ndeath)*(nlstate+ndeath-1);i++){
                   1843:        
                   1844: 
                   1845:        printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   1846:      }*/
                   1847: 
                   1848:   fprintf(ficresprob,"\n%d ",(int)age);
                   1849: 
                   1850:   for (i=1; i<=(nlstate+ndeath)*(nlstate+ndeath-1);i++){
                   1851:     if (i== 2) fprintf(ficresprob,"%.3e %.3e ",gm[i],doldm[i][i]);
                   1852: if (i== 4) fprintf(ficresprob,"%.3e %.3e ",gm[i],doldm[i][i]);
                   1853:   }
                   1854: 
                   1855:     free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   1856:     free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   1857:     free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   1858:     free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   1859: }
                   1860:  free_vector(xp,1,npar);
                   1861: fclose(ficresprob);
                   1862:  exit(0);
                   1863: }
1.2       lievre   1864: 
                   1865: /***********************************************/
                   1866: /**************** Main Program *****************/
                   1867: /***********************************************/
                   1868: 
                   1869: /*int main(int argc, char *argv[])*/
                   1870: int main()
                   1871: {
                   1872: 
1.8       lievre   1873:   int i,j, k, n=MAXN,iter,m,size,cptcode, cptcod;
1.2       lievre   1874:   double agedeb, agefin,hf;
                   1875:   double agemin=1.e20, agemax=-1.e20;
                   1876: 
                   1877:   double fret;
                   1878:   double **xi,tmp,delta;
                   1879: 
                   1880:   double dum; /* Dummy variable */
                   1881:   double ***p3mat;
                   1882:   int *indx;
                   1883:   char line[MAXLINE], linepar[MAXLINE];
                   1884:   char title[MAXLINE];
1.9       lievre   1885:   char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH];
1.13      lievre   1886:   char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], fileresf[FILENAMELENGTH];
1.2       lievre   1887:   char filerest[FILENAMELENGTH];
                   1888:   char fileregp[FILENAMELENGTH];
1.16      lievre   1889:   char popfile[FILENAMELENGTH];
1.2       lievre   1890:   char path[80],pathc[80],pathcd[80],pathtot[80],model[20];
                   1891:   int firstobs=1, lastobs=10;
                   1892:   int sdeb, sfin; /* Status at beginning and end */
                   1893:   int c,  h , cpt,l;
                   1894:   int ju,jl, mi;
1.7       lievre   1895:   int i1,j1, k1,k2,k3,jk,aa,bb, stepsize, ij;
1.14      lievre   1896:   int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,**adl,*tab; 
1.16      lievre   1897:   int mobilav=0, fprev, lprev ,fprevfore=1, lprevfore=1,nforecast,popforecast=0;
1.2       lievre   1898:   int hstepm, nhstepm;
1.18    ! lievre   1899:   int *popage,boolprev=0;/*boolprev=0 if date and zero if wave*/
1.14      lievre   1900: 
1.2       lievre   1901:   double bage, fage, age, agelim, agebase;
                   1902:   double ftolpl=FTOL;
                   1903:   double **prlim;
                   1904:   double *severity;
                   1905:   double ***param; /* Matrix of parameters */
                   1906:   double  *p;
                   1907:   double **matcov; /* Matrix of covariance */
                   1908:   double ***delti3; /* Scale */
                   1909:   double *delti; /* Scale */
                   1910:   double ***eij, ***vareij;
                   1911:   double **varpl; /* Variances of prevalence limits by age */
                   1912:   double *epj, vepp;
1.16      lievre   1913:   double kk1, kk2;
                   1914:   double *popeffectif,*popcount;
1.18    ! lievre   1915:   double dateprev1, dateprev2;
1.13      lievre   1916: 
1.10      lievre   1917:   char version[80]="Imach version 64b, May 2001, INED-EUROREVES ";
1.2       lievre   1918:   char *alph[]={"a","a","b","c","d","e"}, str[4];
1.5       lievre   1919: 
1.13      lievre   1920: 
1.2       lievre   1921:   char z[1]="c", occ;
                   1922: #include <sys/time.h>
                   1923: #include <time.h>
                   1924:   char stra[80], strb[80], strc[80], strd[80],stre[80],modelsav[80];
1.18    ! lievre   1925:   char strfprev[10], strlprev[10];
        !          1926:   char strfprevfore[10], strlprevfore[10];
1.2       lievre   1927:   /* long total_usecs;
                   1928:   struct timeval start_time, end_time;
                   1929:   
                   1930:   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
                   1931: 
                   1932: 
1.16      lievre   1933:   printf("\nIMACH, Version 0.7");
1.2       lievre   1934:   printf("\nEnter the parameter file name: ");
                   1935: 
                   1936: #ifdef windows
                   1937:   scanf("%s",pathtot);
1.5       lievre   1938:   getcwd(pathcd, size);
                   1939:   /*cygwin_split_path(pathtot,path,optionfile);
                   1940:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   1941:   /* cutv(path,optionfile,pathtot,'\\');*/
                   1942: 
                   1943: split(pathtot, path,optionfile);
1.2       lievre   1944:   chdir(path);
                   1945:   replace(pathc,path);
                   1946: #endif
                   1947: #ifdef unix
                   1948:   scanf("%s",optionfile);
                   1949: #endif
                   1950: 
                   1951: /*-------- arguments in the command line --------*/
                   1952: 
                   1953:   strcpy(fileres,"r");
                   1954:   strcat(fileres, optionfile);
                   1955: 
                   1956:   /*---------arguments file --------*/
                   1957: 
                   1958:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
                   1959:     printf("Problem with optionfile %s\n",optionfile);
                   1960:     goto end;
                   1961:   }
                   1962: 
                   1963:   strcpy(filereso,"o");
                   1964:   strcat(filereso,fileres);
                   1965:   if((ficparo=fopen(filereso,"w"))==NULL) {
                   1966:     printf("Problem with Output resultfile: %s\n", filereso);goto end;
                   1967:   }
                   1968: 
                   1969:   /* Reads comments: lines beginning with '#' */
                   1970:   while((c=getc(ficpar))=='#' && c!= EOF){
                   1971:     ungetc(c,ficpar);
                   1972:     fgets(line, MAXLINE, ficpar);
                   1973:     puts(line);
                   1974:     fputs(line,ficparo);
                   1975:   }
                   1976:   ungetc(c,ficpar);
                   1977: 
                   1978:   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);
                   1979:   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);
                   1980:   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   1981: while((c=getc(ficpar))=='#' && c!= EOF){
                   1982:     ungetc(c,ficpar);
                   1983:     fgets(line, MAXLINE, ficpar);
                   1984:     puts(line);
                   1985:     fputs(line,ficparo);
                   1986:   }
                   1987:   ungetc(c,ficpar);
                   1988:   
1.18    ! lievre   1989:   fscanf(ficpar,"fprevalence=%s lprevalence=%s pop_based=%d\n",strfprev,strlprev,&popbased);
        !          1990:   fprintf(ficparo,"fprevalence=%s lprevalence=%s pop_based=%d\n",strfprev,strlprev,popbased);
1.16      lievre   1991:  
1.18    ! lievre   1992:   /* printf("%s %s",strfprev,strlprev);
        !          1993:      exit(0);*/
1.14      lievre   1994:  while((c=getc(ficpar))=='#' && c!= EOF){
                   1995:     ungetc(c,ficpar);
                   1996:     fgets(line, MAXLINE, ficpar);
                   1997:     puts(line);
                   1998:     fputs(line,ficparo);
                   1999:   }
                   2000:   ungetc(c,ficpar);
                   2001:   
1.18    ! lievre   2002:   fscanf(ficpar,"fprevalence=%s lprevalence=%s nforecast=%d mob_average=%d\n",strfprevfore,strlprevfore,&nforecast,&mobilav);
        !          2003:   fprintf(ficparo,"fprevalence=%s lprevalence=%s nforecast=%d mob_average=%d\n",strfprevfore,strlprevfore,nforecast,mobilav);
1.16      lievre   2004:      
                   2005:   
                   2006: while((c=getc(ficpar))=='#' && c!= EOF){
                   2007:     ungetc(c,ficpar);
                   2008:     fgets(line, MAXLINE, ficpar);
                   2009:     puts(line);
                   2010:     fputs(line,ficparo);
                   2011:   }
                   2012:   ungetc(c,ficpar);
                   2013:   
                   2014:   fscanf(ficpar,"popforecast=%d popfile=%s\n",&popforecast,popfile);
1.14      lievre   2015:  
1.8       lievre   2016:   covar=matrix(0,NCOVMAX,1,n); 
                   2017:   cptcovn=0; 
                   2018:   if (strlen(model)>1) cptcovn=nbocc(model,'+')+1;
1.2       lievre   2019: 
                   2020:   ncovmodel=2+cptcovn;
                   2021:   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
                   2022:   
                   2023:   /* Read guess parameters */
                   2024:   /* Reads comments: lines beginning with '#' */
                   2025:   while((c=getc(ficpar))=='#' && c!= EOF){
                   2026:     ungetc(c,ficpar);
                   2027:     fgets(line, MAXLINE, ficpar);
                   2028:     puts(line);
                   2029:     fputs(line,ficparo);
                   2030:   }
                   2031:   ungetc(c,ficpar);
                   2032:   
                   2033:   param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   2034:     for(i=1; i <=nlstate; i++)
                   2035:     for(j=1; j <=nlstate+ndeath-1; j++){
                   2036:       fscanf(ficpar,"%1d%1d",&i1,&j1);
                   2037:       fprintf(ficparo,"%1d%1d",i1,j1);
                   2038:       printf("%1d%1d",i,j);
                   2039:       for(k=1; k<=ncovmodel;k++){
                   2040:        fscanf(ficpar," %lf",&param[i][j][k]);
                   2041:        printf(" %lf",param[i][j][k]);
                   2042:        fprintf(ficparo," %lf",param[i][j][k]);
                   2043:       }
                   2044:       fscanf(ficpar,"\n");
                   2045:       printf("\n");
                   2046:       fprintf(ficparo,"\n");
                   2047:     }
                   2048:   
1.12      lievre   2049:     npar= (nlstate+ndeath-1)*nlstate*ncovmodel;
                   2050: 
1.2       lievre   2051:   p=param[1][1];
                   2052:   
                   2053:   /* Reads comments: lines beginning with '#' */
                   2054:   while((c=getc(ficpar))=='#' && c!= EOF){
                   2055:     ungetc(c,ficpar);
                   2056:     fgets(line, MAXLINE, ficpar);
                   2057:     puts(line);
                   2058:     fputs(line,ficparo);
                   2059:   }
                   2060:   ungetc(c,ficpar);
                   2061: 
                   2062:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   2063:   delti=vector(1,npar); /* Scale of each paramater (output from hesscov) */
                   2064:   for(i=1; i <=nlstate; i++){
                   2065:     for(j=1; j <=nlstate+ndeath-1; j++){
                   2066:       fscanf(ficpar,"%1d%1d",&i1,&j1);
                   2067:       printf("%1d%1d",i,j);
                   2068:       fprintf(ficparo,"%1d%1d",i1,j1);
                   2069:       for(k=1; k<=ncovmodel;k++){
                   2070:        fscanf(ficpar,"%le",&delti3[i][j][k]);
                   2071:        printf(" %le",delti3[i][j][k]);
                   2072:        fprintf(ficparo," %le",delti3[i][j][k]);
                   2073:       }
                   2074:       fscanf(ficpar,"\n");
                   2075:       printf("\n");
                   2076:       fprintf(ficparo,"\n");
                   2077:     }
                   2078:   }
                   2079:   delti=delti3[1][1];
                   2080:   
                   2081:   /* Reads comments: lines beginning with '#' */
                   2082:   while((c=getc(ficpar))=='#' && c!= EOF){
                   2083:     ungetc(c,ficpar);
                   2084:     fgets(line, MAXLINE, ficpar);
                   2085:     puts(line);
                   2086:     fputs(line,ficparo);
                   2087:   }
                   2088:   ungetc(c,ficpar);
                   2089:   
                   2090:   matcov=matrix(1,npar,1,npar);
                   2091:   for(i=1; i <=npar; i++){
                   2092:     fscanf(ficpar,"%s",&str);
                   2093:     printf("%s",str);
                   2094:     fprintf(ficparo,"%s",str);
                   2095:     for(j=1; j <=i; j++){
                   2096:       fscanf(ficpar," %le",&matcov[i][j]);
                   2097:       printf(" %.5le",matcov[i][j]);
                   2098:       fprintf(ficparo," %.5le",matcov[i][j]);
                   2099:     }
                   2100:     fscanf(ficpar,"\n");
                   2101:     printf("\n");
                   2102:     fprintf(ficparo,"\n");
                   2103:   }
                   2104:   for(i=1; i <=npar; i++)
                   2105:     for(j=i+1;j<=npar;j++)
                   2106:       matcov[i][j]=matcov[j][i];
                   2107:    
                   2108:   printf("\n");
                   2109: 
                   2110: 
                   2111:     /*-------- data file ----------*/
                   2112:     if((ficres =fopen(fileres,"w"))==NULL) {
                   2113:       printf("Problem with resultfile: %s\n", fileres);goto end;
                   2114:     }
                   2115:     fprintf(ficres,"#%s\n",version);
                   2116:     
                   2117:     if((fic=fopen(datafile,"r"))==NULL)    {
                   2118:       printf("Problem with datafile: %s\n", datafile);goto end;
                   2119:     }
                   2120: 
                   2121:     n= lastobs;
                   2122:     severity = vector(1,maxwav);
                   2123:     outcome=imatrix(1,maxwav+1,1,n);
                   2124:     num=ivector(1,n);
                   2125:     moisnais=vector(1,n);
                   2126:     annais=vector(1,n);
                   2127:     moisdc=vector(1,n);
                   2128:     andc=vector(1,n);
                   2129:     agedc=vector(1,n);
                   2130:     cod=ivector(1,n);
                   2131:     weight=vector(1,n);
                   2132:     for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   2133:     mint=matrix(1,maxwav,1,n);
                   2134:     anint=matrix(1,maxwav,1,n);
                   2135:     s=imatrix(1,maxwav+1,1,n);
                   2136:     adl=imatrix(1,maxwav+1,1,n);    
                   2137:     tab=ivector(1,NCOVMAX);
1.3       lievre   2138:     ncodemax=ivector(1,8);
1.2       lievre   2139: 
1.12      lievre   2140:     i=1;
1.2       lievre   2141:     while (fgets(line, MAXLINE, fic) != NULL)    {
                   2142:       if ((i >= firstobs) && (i <=lastobs)) {
                   2143:        
                   2144:        for (j=maxwav;j>=1;j--){
                   2145:          cutv(stra, strb,line,' '); s[j][i]=atoi(strb); 
                   2146:          strcpy(line,stra);
                   2147:          cutv(stra, strb,line,'/'); anint[j][i]=(double)(atoi(strb)); strcpy(line,stra);
                   2148:          cutv(stra, strb,line,' '); mint[j][i]=(double)(atoi(strb)); strcpy(line,stra);
                   2149:        }
                   2150:        
                   2151:        cutv(stra, strb,line,'/'); andc[i]=(double)(atoi(strb)); strcpy(line,stra);
                   2152:        cutv(stra, strb,line,' '); moisdc[i]=(double)(atoi(strb)); strcpy(line,stra);
                   2153: 
                   2154:        cutv(stra, strb,line,'/'); annais[i]=(double)(atoi(strb)); strcpy(line,stra);
                   2155:        cutv(stra, strb,line,' '); moisnais[i]=(double)(atoi(strb)); strcpy(line,stra);
                   2156: 
                   2157:        cutv(stra, strb,line,' '); weight[i]=(double)(atoi(strb)); strcpy(line,stra);
                   2158:        for (j=ncov;j>=1;j--){
                   2159:          cutv(stra, strb,line,' '); covar[j][i]=(double)(atoi(strb)); strcpy(line,stra);
                   2160:        } 
                   2161:        num[i]=atol(stra);
1.12      lievre   2162:        
                   2163:        /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   2164:          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   2165: 
                   2166:        i=i+1;
                   2167:       }
                   2168:     } 
1.12      lievre   2169:     /* printf("ii=%d", ij);
                   2170:        scanf("%d",i);*/
                   2171:   imx=i-1; /* Number of individuals */
1.3       lievre   2172: 
1.12      lievre   2173:   /* for (i=1; i<=imx; i++){
                   2174:     if ((s[1][i]==3) && (s[2][i]==2)) s[2][i]=3;
                   2175:     if ((s[2][i]==3) && (s[3][i]==2)) s[3][i]=3;
                   2176:     if ((s[3][i]==3) && (s[4][i]==2)) s[4][i]=3;
1.14      lievre   2177:     }
                   2178:     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   2179: 
                   2180:   /* Calculation of the number of parameter from char model*/
1.7       lievre   2181:   Tvar=ivector(1,15); 
                   2182:   Tprod=ivector(1,15); 
                   2183:   Tvaraff=ivector(1,15); 
                   2184:   Tvard=imatrix(1,15,1,2);
1.6       lievre   2185:   Tage=ivector(1,15);      
1.2       lievre   2186:    
                   2187:   if (strlen(model) >1){
1.7       lievre   2188:     j=0, j1=0, k1=1, k2=1;
1.2       lievre   2189:     j=nbocc(model,'+');
1.6       lievre   2190:     j1=nbocc(model,'*');
1.2       lievre   2191:     cptcovn=j+1;
1.7       lievre   2192:     cptcovprod=j1;
1.3       lievre   2193:     
1.8       lievre   2194:     
1.2       lievre   2195:     strcpy(modelsav,model); 
1.8       lievre   2196:     if ((strcmp(model,"age")==0) || (strcmp(model,"age*age")==0)){
                   2197:       printf("Error. Non available option model=%s ",model);
                   2198:       goto end;
                   2199:     }
                   2200:     
                   2201:     for(i=(j+1); i>=1;i--){
                   2202:       cutv(stra,strb,modelsav,'+');
                   2203:       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); 
                   2204:       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   2205:       /*scanf("%d",i);*/
                   2206:       if (strchr(strb,'*')) {
                   2207:        cutv(strd,strc,strb,'*');
                   2208:        if (strcmp(strc,"age")==0) {
1.7       lievre   2209:          cptcovprod--;
1.8       lievre   2210:          cutv(strb,stre,strd,'V');
                   2211:          Tvar[i]=atoi(stre);
                   2212:          cptcovage++;
                   2213:            Tage[cptcovage]=i;
                   2214:            /*printf("stre=%s ", stre);*/
1.7       lievre   2215:        }
1.8       lievre   2216:        else if (strcmp(strd,"age")==0) {
1.7       lievre   2217:          cptcovprod--;
1.8       lievre   2218:          cutv(strb,stre,strc,'V');
                   2219:          Tvar[i]=atoi(stre);
                   2220:          cptcovage++;
                   2221:          Tage[cptcovage]=i;
1.7       lievre   2222:        }
                   2223:        else {
1.8       lievre   2224:          cutv(strb,stre,strc,'V');
                   2225:          Tvar[i]=ncov+k1;
                   2226:          cutv(strb,strc,strd,'V'); 
                   2227:          Tprod[k1]=i;
                   2228:          Tvard[k1][1]=atoi(strc);
                   2229:          Tvard[k1][2]=atoi(stre);
                   2230:          Tvar[cptcovn+k2]=Tvard[k1][1];
                   2231:          Tvar[cptcovn+k2+1]=Tvard[k1][2]; 
1.7       lievre   2232:          for (k=1; k<=lastobs;k++) 
1.8       lievre   2233:            covar[ncov+k1][k]=covar[atoi(stre)][k]*covar[atoi(strc)][k];
                   2234:          k1++;
                   2235:          k2=k2+2;
1.7       lievre   2236:        }
1.2       lievre   2237:       }
1.8       lievre   2238:       else {
                   2239:        /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   2240:        /*  scanf("%d",i);*/
                   2241:       cutv(strd,strc,strb,'V');
                   2242:       Tvar[i]=atoi(strc);
                   2243:       }
                   2244:       strcpy(modelsav,stra);  
                   2245:       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   2246:        scanf("%d",i);*/
1.2       lievre   2247:     }
1.8       lievre   2248: }
                   2249:   
                   2250:   /*printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   2251:   printf("cptcovprod=%d ", cptcovprod);
                   2252:   scanf("%d ",i);*/
1.2       lievre   2253:     fclose(fic);
                   2254: 
1.7       lievre   2255:     /*  if(mle==1){*/
1.2       lievre   2256:     if (weightopt != 1) { /* Maximisation without weights*/
                   2257:       for(i=1;i<=n;i++) weight[i]=1.0;
                   2258:     }
                   2259:     /*-calculation of age at interview from date of interview and age at death -*/
                   2260:     agev=matrix(1,maxwav,1,imx);
1.12      lievre   2261: 
                   2262:    for (i=1; i<=imx; i++) 
                   2263:      for(m=2; (m<= maxwav); m++)
                   2264:        if ((mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   2265:         anint[m][i]=9999;
                   2266:         s[m][i]=-1;
                   2267:        }
1.2       lievre   2268:     
                   2269:     for (i=1; i<=imx; i++)  {
                   2270:       agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   2271:       for(m=1; (m<= maxwav); m++){
                   2272:        if(s[m][i] >0){
                   2273:          if (s[m][i] == nlstate+1) {
                   2274:            if(agedc[i]>0)
                   2275:              if(moisdc[i]!=99 && andc[i]!=9999)
                   2276:              agev[m][i]=agedc[i];
1.8       lievre   2277:            else {
                   2278:              if (andc[i]!=9999){
1.2       lievre   2279:              printf("Warning negative age at death: %d line:%d\n",num[i],i);
                   2280:              agev[m][i]=-1;
1.8       lievre   2281:              }
1.2       lievre   2282:            }
                   2283:          }
                   2284:          else if(s[m][i] !=9){ /* Should no more exist */
                   2285:            agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
1.3       lievre   2286:            if(mint[m][i]==99 || anint[m][i]==9999)
1.2       lievre   2287:              agev[m][i]=1;
                   2288:            else if(agev[m][i] <agemin){ 
                   2289:              agemin=agev[m][i];
                   2290:              /*printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);*/
                   2291:            }
                   2292:            else if(agev[m][i] >agemax){
                   2293:              agemax=agev[m][i];
                   2294:             /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/
                   2295:            }
                   2296:            /*agev[m][i]=anint[m][i]-annais[i];*/
                   2297:            /*   agev[m][i] = age[i]+2*m;*/
                   2298:          }
                   2299:          else { /* =9 */
                   2300:            agev[m][i]=1;
                   2301:            s[m][i]=-1;
                   2302:          }
                   2303:        }
                   2304:        else /*= 0 Unknown */
                   2305:          agev[m][i]=1;
                   2306:       }
                   2307:     
                   2308:     }
                   2309:     for (i=1; i<=imx; i++)  {
                   2310:       for(m=1; (m<= maxwav); m++){
                   2311:        if (s[m][i] > (nlstate+ndeath)) {
                   2312:          printf("Error: Wrong value in nlstate or ndeath\n");  
                   2313:          goto end;
                   2314:        }
                   2315:       }
                   2316:     }
                   2317: 
                   2318: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
                   2319: 
                   2320:     free_vector(severity,1,maxwav);
                   2321:     free_imatrix(outcome,1,maxwav+1,1,n);
                   2322:     free_vector(moisnais,1,n);
                   2323:     free_vector(annais,1,n);
1.17      lievre   2324:     /* free_matrix(mint,1,maxwav,1,n);
                   2325:        free_matrix(anint,1,maxwav,1,n);*/
1.2       lievre   2326:     free_vector(moisdc,1,n);
                   2327:     free_vector(andc,1,n);
                   2328: 
                   2329:    
                   2330:     wav=ivector(1,imx);
                   2331:     dh=imatrix(1,lastpass-firstpass+1,1,imx);
                   2332:     mw=imatrix(1,lastpass-firstpass+1,1,imx);
                   2333:    
                   2334:     /* Concatenates waves */
                   2335:       concatwav(wav, dh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
                   2336: 
                   2337: 
1.6       lievre   2338:       Tcode=ivector(1,100);
1.8       lievre   2339:       nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
1.7       lievre   2340:       ncodemax[1]=1;
                   2341:       if (cptcovn > 0) tricode(Tvar,nbcode,imx);
                   2342:       
1.2       lievre   2343:    codtab=imatrix(1,100,1,10);
                   2344:    h=0;
1.7       lievre   2345:    m=pow(2,cptcoveff);
1.2       lievre   2346:  
1.7       lievre   2347:    for(k=1;k<=cptcoveff; k++){
1.2       lievre   2348:      for(i=1; i <=(m/pow(2,k));i++){
                   2349:        for(j=1; j <= ncodemax[k]; j++){
1.7       lievre   2350:         for(cpt=1; cpt <=(m/pow(2,cptcoveff+1-k)); cpt++){
1.2       lievre   2351:           h++;
                   2352:           if (h>m) h=1;codtab[h][k]=j;
                   2353:         } 
                   2354:        }
                   2355:      }
                   2356:    } 
                   2357:     
                   2358:    /* Calculates basic frequencies. Computes observed prevalence at single age
                   2359:        and prints on file fileres'p'. */
1.18    ! lievre   2360: 
        !          2361:     if ((nbocc(strfprev,'/')==1) && (nbocc(strlprev,'/')==1)){
        !          2362:      boolprev=0;
        !          2363:      cutv(stra,strb,strfprev,'/');
        !          2364:      dateprev1=(double)(atoi(strb)+atoi(stra)/12.);
        !          2365:      cutv(stra,strb,strlprev,'/');
        !          2366:      dateprev2=(double)(atoi(strb)+atoi(stra)/12.);
        !          2367:    }
        !          2368:    
        !          2369:    else if ((nbocc(strfprev,'/')==0) &&(nbocc(strlprev,'/')==0)){
        !          2370:      boolprev=1;
        !          2371:      fprev=atoi(strfprev); lprev=atoi(strlprev);
        !          2372:    }
        !          2373:     else {
        !          2374:       printf("Error in statement lprevalence or fprevalence\n");
        !          2375:       goto end;
        !          2376:     }
        !          2377:    
        !          2378:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvar,nbcode, ncodemax, fprev, lprev,mint,anint,boolprev,dateprev1,dateprev2); 
1.17      lievre   2379:   
                   2380:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.2       lievre   2381:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   2382:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   2383:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   2384:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.12      lievre   2385:      
1.2       lievre   2386:     /* For Powell, parameters are in a vector p[] starting at p[1]
                   2387:        so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   2388:     p=param[1][1]; /* *(*(*(param +1)+1)+0) */
1.7       lievre   2389: 
                   2390:     if(mle==1){
1.2       lievre   2391:     mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
1.7       lievre   2392:     }
1.2       lievre   2393:     
                   2394:     /*--------- results files --------------*/
1.16      lievre   2395:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncov=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncov, nlstate, ndeath, maxwav, mle,weightopt,model);
1.18    ! lievre   2396:    fprintf(ficres,"fprevalence=%s lprevalence=%s pop_based=%d\n",strfprev,strlprev,popbased); 
        !          2397:    fprintf(ficres,"fprevalence=%s lprevalence=%s nforecast=%d mob_average=%d\n",strfprevfore,strlprevfore,nforecast,mobilav);
1.16      lievre   2398: 
1.2       lievre   2399:    jk=1;
                   2400:    fprintf(ficres,"# Parameters\n");
                   2401:    printf("# Parameters\n");
                   2402:    for(i=1,jk=1; i <=nlstate; i++){
                   2403:      for(k=1; k <=(nlstate+ndeath); k++){
                   2404:        if (k != i) 
                   2405:         {
                   2406:           printf("%d%d ",i,k);
                   2407:           fprintf(ficres,"%1d%1d ",i,k);
                   2408:           for(j=1; j <=ncovmodel; j++){
                   2409:             printf("%f ",p[jk]);
                   2410:             fprintf(ficres,"%f ",p[jk]);
                   2411:             jk++; 
                   2412:           }
                   2413:           printf("\n");
                   2414:           fprintf(ficres,"\n");
                   2415:         }
                   2416:      }
                   2417:    }
1.7       lievre   2418:  if(mle==1){
1.2       lievre   2419:     /* Computing hessian and covariance matrix */
                   2420:     ftolhess=ftol; /* Usually correct */
                   2421:     hesscov(matcov, p, npar, delti, ftolhess, func);
1.7       lievre   2422:  }
1.2       lievre   2423:     fprintf(ficres,"# Scales\n");
                   2424:     printf("# Scales\n");
                   2425:      for(i=1,jk=1; i <=nlstate; i++){
                   2426:       for(j=1; j <=nlstate+ndeath; j++){
                   2427:        if (j!=i) {
                   2428:          fprintf(ficres,"%1d%1d",i,j);
                   2429:          printf("%1d%1d",i,j);
                   2430:          for(k=1; k<=ncovmodel;k++){
                   2431:            printf(" %.5e",delti[jk]);
                   2432:            fprintf(ficres," %.5e",delti[jk]);
                   2433:            jk++;
                   2434:          }
                   2435:          printf("\n");
                   2436:          fprintf(ficres,"\n");
                   2437:        }
                   2438:       }
1.18    ! lievre   2439:      }
1.2       lievre   2440:     
                   2441:     k=1;
                   2442:     fprintf(ficres,"# Covariance\n");
                   2443:     printf("# Covariance\n");
                   2444:     for(i=1;i<=npar;i++){
                   2445:       /*  if (k>nlstate) k=1;
                   2446:       i1=(i-1)/(ncovmodel*nlstate)+1; 
                   2447:       fprintf(ficres,"%s%d%d",alph[k],i1,tab[i]);
                   2448:       printf("%s%d%d",alph[k],i1,tab[i]);*/
                   2449:       fprintf(ficres,"%3d",i);
                   2450:       printf("%3d",i);
                   2451:       for(j=1; j<=i;j++){
                   2452:        fprintf(ficres," %.5e",matcov[i][j]);
                   2453:        printf(" %.5e",matcov[i][j]);
                   2454:       }
                   2455:       fprintf(ficres,"\n");
                   2456:       printf("\n");
                   2457:       k++;
                   2458:     }
                   2459:     
                   2460:     while((c=getc(ficpar))=='#' && c!= EOF){
                   2461:       ungetc(c,ficpar);
                   2462:       fgets(line, MAXLINE, ficpar);
                   2463:       puts(line);
                   2464:       fputs(line,ficparo);
                   2465:     }
                   2466:     ungetc(c,ficpar);
                   2467:   
                   2468:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf\n",&agemin,&agemax, &bage, &fage);
                   2469:     
                   2470:     if (fage <= 2) {
                   2471:       bage = agemin;
                   2472:       fage = agemax;
                   2473:     }
                   2474: 
                   2475:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
                   2476:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f\n",agemin,agemax,bage,fage);
1.7       lievre   2477: 
                   2478:    
1.2       lievre   2479: /*------------ gnuplot -------------*/
                   2480: chdir(pathcd);
                   2481:   if((ficgp=fopen("graph.plt","w"))==NULL) {
1.5       lievre   2482:     printf("Problem with file graph.gp");goto end;
1.2       lievre   2483:   }
                   2484: #ifdef windows
                   2485:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   2486: #endif
1.7       lievre   2487: m=pow(2,cptcoveff);
1.2       lievre   2488:   
                   2489:  /* 1eme*/
                   2490:   for (cpt=1; cpt<= nlstate ; cpt ++) {
                   2491:    for (k1=1; k1<= m ; k1 ++) {
                   2492: 
                   2493: #ifdef windows
                   2494:     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);
                   2495: #endif
                   2496: #ifdef unix
                   2497: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \nplot [%.f:%.f] \"vpl%s\" u 1:2 \"\%%lf",agemin,fage,fileres);
                   2498: #endif
                   2499: 
                   2500: for (i=1; i<= nlstate ; i ++) {
                   2501:   if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
                   2502:   else fprintf(ficgp," \%%*lf (\%%*lf)");
                   2503: }
                   2504:     fprintf(ficgp,"\" t\"Stationary prevalence\" w l 0,\"vpl%s\" every :::%d::%d u 1:($2+2*$3) \"\%%lf",fileres,k1-1,k1-1);
                   2505:     for (i=1; i<= nlstate ; i ++) {
                   2506:   if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
                   2507:   else fprintf(ficgp," \%%*lf (\%%*lf)");
                   2508: } 
                   2509:   fprintf(ficgp,"\" t\"95\%% CI\" w l 1,\"vpl%s\" every :::%d::%d u 1:($2-2*$3) \"\%%lf",fileres,k1-1,k1-1); 
                   2510:      for (i=1; i<= nlstate ; i ++) {
                   2511:   if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
                   2512:   else fprintf(ficgp," \%%*lf (\%%*lf)");
                   2513: }  
                   2514:      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));
                   2515: #ifdef unix
                   2516: fprintf(ficgp,"\nset ter gif small size 400,300");
                   2517: #endif
                   2518: fprintf(ficgp,"\nset out \"v%s%d%d.gif\" \nreplot\n\n",strtok(optionfile, "."),cpt,k1);
                   2519:    }
                   2520:   }
                   2521:   /*2 eme*/
                   2522: 
                   2523:   for (k1=1; k1<= m ; k1 ++) { 
                   2524:     fprintf(ficgp,"set ylabel \"Years\" \nset ter gif small size 400,300\nplot [%.f:%.f] ",agemin,fage);
                   2525:     
                   2526:     for (i=1; i<= nlstate+1 ; i ++) {
                   2527:       k=2*i;
                   2528:       fprintf(ficgp,"\"t%s\" every :::%d::%d u 1:2 \"\%%lf",fileres,k1-1,k1-1);
                   2529:       for (j=1; j<= nlstate+1 ; j ++) {
                   2530:   if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
                   2531:   else fprintf(ficgp," \%%*lf (\%%*lf)");
                   2532: }   
                   2533:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
                   2534:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
                   2535:     fprintf(ficgp,"\"t%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",fileres,k1-1,k1-1);
                   2536:       for (j=1; j<= nlstate+1 ; j ++) {
                   2537:        if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
                   2538:        else fprintf(ficgp," \%%*lf (\%%*lf)");
                   2539: }   
                   2540:       fprintf(ficgp,"\" t\"\" w l 0,");
                   2541:      fprintf(ficgp,"\"t%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",fileres,k1-1,k1-1);
                   2542:       for (j=1; j<= nlstate+1 ; j ++) {
                   2543:   if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
                   2544:   else fprintf(ficgp," \%%*lf (\%%*lf)");
                   2545: }   
                   2546:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");
                   2547:       else fprintf(ficgp,"\" t\"\" w l 0,");
                   2548:     }
                   2549:     fprintf(ficgp,"\nset out \"e%s%d.gif\" \nreplot\n\n",strtok(optionfile, "."),k1);
                   2550:   }
                   2551:  
                   2552:   /*3eme*/
                   2553: 
1.5       lievre   2554:   for (k1=1; k1<= m ; k1 ++) { 
1.2       lievre   2555:     for (cpt=1; cpt<= nlstate ; cpt ++) {
                   2556:       k=2+nlstate*(cpt-1);
                   2557:       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);
                   2558:       for (i=1; i< nlstate ; i ++) {
                   2559:        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);
                   2560:       } 
                   2561:       fprintf(ficgp,"\nset out \"exp%s%d%d.gif\" \nreplot\n\n",strtok(optionfile, "."),cpt,k1);
                   2562:     }
1.5       lievre   2563:   }
1.2       lievre   2564:  
                   2565:   /* CV preval stat */
1.5       lievre   2566:   for (k1=1; k1<= m ; k1 ++) { 
1.2       lievre   2567:     for (cpt=1; cpt<nlstate ; cpt ++) {
                   2568:       k=3;
                   2569:       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);
                   2570:       for (i=1; i< nlstate ; i ++)
                   2571:        fprintf(ficgp,"+$%d",k+i+1);
                   2572:       fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);
                   2573:       
                   2574:       l=3+(nlstate+ndeath)*cpt;
                   2575:       fprintf(ficgp,",\"pij%s\" u ($1==%d ? ($3):1/0):($%d/($%d",fileres,k1,l+cpt+1,l+1);
                   2576:       for (i=1; i< nlstate ; i ++) {
                   2577:        l=3+(nlstate+ndeath)*cpt;
                   2578:        fprintf(ficgp,"+$%d",l+i+1);
                   2579:       }
                   2580:       fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);   
                   2581:       fprintf(ficgp,"set out \"p%s%d%d.gif\" \nreplot\n\n",strtok(optionfile, "."),cpt,k1);
                   2582:     } 
1.13      lievre   2583:   }  
1.5       lievre   2584: 
1.2       lievre   2585:   /* proba elementaires */
1.5       lievre   2586:    for(i=1,jk=1; i <=nlstate; i++){
1.2       lievre   2587:     for(k=1; k <=(nlstate+ndeath); k++){
                   2588:       if (k != i) {
                   2589:        for(j=1; j <=ncovmodel; j++){
1.5       lievre   2590:          /*fprintf(ficgp,"%s%1d%1d=%f ",alph[j],i,k,p[jk]);*/
                   2591:          /*fprintf(ficgp,"%s",alph[1]);*/
                   2592:          fprintf(ficgp,"p%d=%f ",jk,p[jk]);
1.2       lievre   2593:          jk++; 
                   2594:          fprintf(ficgp,"\n");
                   2595:        }
                   2596:       }
                   2597:     }
1.5       lievre   2598:     }
                   2599: 
1.2       lievre   2600:   for(jk=1; jk <=m; jk++) {
                   2601:   fprintf(ficgp,"\nset ter gif small size 400,300\nset log y\nplot  [%.f:%.f] ",agemin,agemax);
1.5       lievre   2602:    i=1;
                   2603:    for(k2=1; k2<=nlstate; k2++) {
                   2604:      k3=i;
                   2605:      for(k=1; k<=(nlstate+ndeath); k++) {
                   2606:        if (k != k2){
                   2607:        fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
1.7       lievre   2608: ij=1;
                   2609:        for(j=3; j <=ncovmodel; j++) {
                   2610:          if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
                   2611:            fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
                   2612:            ij++;
                   2613:          }
                   2614:          else
1.6       lievre   2615:          fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
1.7       lievre   2616:        }
                   2617:          fprintf(ficgp,")/(1");
1.6       lievre   2618:        
                   2619:        for(k1=1; k1 <=nlstate; k1++){   
                   2620:          fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
1.7       lievre   2621: ij=1;
                   2622:          for(j=3; j <=ncovmodel; j++){
                   2623:          if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
                   2624:            fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
                   2625:            ij++;
                   2626:          }
                   2627:          else
1.6       lievre   2628:            fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
1.7       lievre   2629:          }
1.6       lievre   2630:          fprintf(ficgp,")");
1.5       lievre   2631:        }
                   2632:        fprintf(ficgp,") t \"p%d%d\" ", k2,k);
                   2633:        if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
1.6       lievre   2634:        i=i+ncovmodel;
1.5       lievre   2635:        }
                   2636:      }
                   2637:    }
1.6       lievre   2638:    fprintf(ficgp,"\nset out \"pe%s%d.gif\" \nreplot\n\n",strtok(optionfile, "."),jk); 
                   2639:   }
1.5       lievre   2640:    
                   2641:   fclose(ficgp);
                   2642:    
                   2643: chdir(path);
1.15      lievre   2644:    
1.2       lievre   2645:     free_ivector(wav,1,imx);
                   2646:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
1.15      lievre   2647:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
1.2       lievre   2648:     free_ivector(num,1,n);
                   2649:     free_vector(agedc,1,n);
                   2650:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   2651:     fclose(ficparo);
                   2652:     fclose(ficres);
1.7       lievre   2653:     /*  }*/
1.2       lievre   2654:    
                   2655:    /*________fin mle=1_________*/
                   2656:    
                   2657: 
                   2658:   
                   2659:     /* No more information from the sample is required now */
                   2660:   /* Reads comments: lines beginning with '#' */
                   2661:   while((c=getc(ficpar))=='#' && c!= EOF){
                   2662:     ungetc(c,ficpar);
                   2663:     fgets(line, MAXLINE, ficpar);
                   2664:     puts(line);
                   2665:     fputs(line,ficparo);
                   2666:   }
                   2667:   ungetc(c,ficpar);
                   2668:   
                   2669:   fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf\n",&agemin,&agemax, &bage, &fage);
                   2670:   printf("agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f\n",agemin,agemax, bage, fage);
                   2671:   fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f\n",agemin,agemax,bage,fage);
                   2672: /*--------- index.htm --------*/
                   2673: 
1.9       lievre   2674:   strcpy(optionfilehtm,optionfile);
                   2675:   strcat(optionfilehtm,".htm");
                   2676:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
                   2677:     printf("Problem with %s \n",optionfilehtm);goto end;
1.2       lievre   2678:   }
                   2679: 
1.16      lievre   2680:  fprintf(fichtm,"<body><ul> <font size=\"6\">Imach, Version 0.7 </font> <hr size=\"2\" color=\"#EC5E5E\"> 
1.8       lievre   2681: Titre=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>
                   2682: Total number of observations=%d <br>
                   2683: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>
                   2684: <hr  size=\"2\" color=\"#EC5E5E\"> 
                   2685: <li>Outputs files<br><br>\n
1.2       lievre   2686:         - Observed prevalence in each state: <a href=\"p%s\">p%s</a> <br>\n
                   2687: - Estimated parameters and the covariance matrix: <a href=\"%s\">%s</a> <br>
                   2688:         - Stationary prevalence in each state: <a href=\"pl%s\">pl%s</a> <br>
                   2689:         - Transition probabilities: <a href=\"pij%s\">pij%s</a><br>
                   2690:         - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>
                   2691:         - Life expectancies by age and initial health status: <a href=\"e%s\">e%s</a> <br>
                   2692:         - Variances of life expectancies by age and initial health status: <a href=\"v%s\">v%s</a><br>
                   2693:         - Health expectancies with their variances: <a href=\"t%s\">t%s</a> <br>
1.14      lievre   2694:         - Standard deviation of stationary prevalences: <a href=\"vpl%s\">vpl%s</a> <br>
1.18    ! lievre   2695:         - Prevalences and population forecasting: <a href=\"f%s\">f%s</a> <br>
1.14      lievre   2696: <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   2697: 
1.8       lievre   2698:  fprintf(fichtm," <li>Graphs</li><p>");
1.2       lievre   2699: 
1.7       lievre   2700:  m=cptcoveff;
1.2       lievre   2701:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   2702: 
                   2703:  j1=0;
                   2704:  for(k1=1; k1<=m;k1++){
                   2705:    for(i1=1; i1<=ncodemax[k1];i1++){
                   2706:        j1++;
                   2707:        if (cptcovn > 0) {
1.8       lievre   2708:         fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.7       lievre   2709:         for (cpt=1; cpt<=cptcoveff;cpt++) 
                   2710:           fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[j1][cpt]]);
1.8       lievre   2711:         fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
1.2       lievre   2712:        }
                   2713:        fprintf(fichtm,"<br>- Probabilities: pe%s%d.gif<br>
                   2714: <img src=\"pe%s%d.gif\">",strtok(optionfile, "."),j1,strtok(optionfile, "."),j1);     
                   2715:        for(cpt=1; cpt<nlstate;cpt++){
                   2716:         fprintf(fichtm,"<br>- Prevalence of disability : p%s%d%d.gif<br>
                   2717: <img src=\"p%s%d%d.gif\">",strtok(optionfile, "."),cpt,j1,strtok(optionfile, "."),cpt,j1);
                   2718:        }
                   2719:     for(cpt=1; cpt<=nlstate;cpt++) {
                   2720:        fprintf(fichtm,"<br>- Observed and stationary prevalence (with confident
                   2721: interval) in state (%d): v%s%d%d.gif <br>
                   2722: <img src=\"v%s%d%d.gif\">",cpt,strtok(optionfile, "."),cpt,j1,strtok(optionfile, "."),cpt,j1);  
                   2723:      }
                   2724:      for(cpt=1; cpt<=nlstate;cpt++) {
                   2725:         fprintf(fichtm,"\n<br>- Health life expectancies by age and initial health state (%d): exp%s%d%d.gif <br>
1.5       lievre   2726: <img src=\"exp%s%d%d.gif\">",cpt,strtok(optionfile, "."),cpt,j1,strtok(optionfile, "."),cpt,j1);
1.2       lievre   2727:      }
                   2728:      fprintf(fichtm,"\n<br>- Total life expectancy by age and
                   2729: health expectancies in states (1) and (2): e%s%d.gif<br>
                   2730: <img src=\"e%s%d.gif\">",strtok(optionfile, "."),j1,strtok(optionfile, "."),j1);
                   2731: fprintf(fichtm,"\n</body>");
                   2732:    }
                   2733:  }
                   2734: fclose(fichtm);
                   2735: 
                   2736:   /*--------------- Prevalence limit --------------*/
                   2737:   
                   2738:   strcpy(filerespl,"pl");
                   2739:   strcat(filerespl,fileres);
                   2740:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   2741:     printf("Problem with Prev limit resultfile: %s\n", filerespl);goto end;
                   2742:   }
                   2743:   printf("Computing prevalence limit: result on file '%s' \n", filerespl);
                   2744:   fprintf(ficrespl,"#Prevalence limit\n");
                   2745:   fprintf(ficrespl,"#Age ");
                   2746:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   2747:   fprintf(ficrespl,"\n");
                   2748:   
                   2749:   prlim=matrix(1,nlstate,1,nlstate);
                   2750:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   2751:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   2752:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   2753:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   2754:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   2755:   k=0;
                   2756:   agebase=agemin;
                   2757:   agelim=agemax;
                   2758:   ftolpl=1.e-10;
1.7       lievre   2759:   i1=cptcoveff;
1.2       lievre   2760:   if (cptcovn < 1){i1=1;}
                   2761: 
                   2762:   for(cptcov=1;cptcov<=i1;cptcov++){
                   2763:     for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   2764:        k=k+1;
                   2765:        /*printf("cptcov=%d cptcod=%d codtab=%d nbcode=%d\n",cptcov, cptcod,Tcode[cptcode],codtab[cptcod][cptcov]);*/
1.6       lievre   2766:        fprintf(ficrespl,"\n#******");
1.7       lievre   2767:        for(j=1;j<=cptcoveff;j++) 
                   2768:          fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
1.2       lievre   2769:        fprintf(ficrespl,"******\n");
                   2770:        
                   2771:        for (age=agebase; age<=agelim; age++){
                   2772:          prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                   2773:          fprintf(ficrespl,"%.0f",age );
                   2774:          for(i=1; i<=nlstate;i++)
                   2775:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   2776:          fprintf(ficrespl,"\n");
                   2777:        }
                   2778:       }
                   2779:     }
                   2780:   fclose(ficrespl);
1.13      lievre   2781: 
1.2       lievre   2782:   /*------------- h Pij x at various ages ------------*/
                   2783:   
                   2784:   strcpy(filerespij,"pij");  strcat(filerespij,fileres);
                   2785:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   2786:     printf("Problem with Pij resultfile: %s\n", filerespij);goto end;
                   2787:   }
                   2788:   printf("Computing pij: result on file '%s' \n", filerespij);
                   2789:   
                   2790:   stepsize=(int) (stepm+YEARM-1)/YEARM;
1.13      lievre   2791:   /*if (stepm<=24) stepsize=2;*/
1.2       lievre   2792: 
                   2793:   agelim=AGESUP;
                   2794:   hstepm=stepsize*YEARM; /* Every year of age */
                   2795:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   2796:   
                   2797:   k=0;
                   2798:   for(cptcov=1;cptcov<=i1;cptcov++){
                   2799:     for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   2800:       k=k+1;
                   2801:        fprintf(ficrespij,"\n#****** ");
1.7       lievre   2802:        for(j=1;j<=cptcoveff;j++) 
                   2803:          fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
1.2       lievre   2804:        fprintf(ficrespij,"******\n");
                   2805:        
                   2806:        for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   2807:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   2808:          nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   2809:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   2810:          oldm=oldms;savm=savms;
                   2811:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   2812:          fprintf(ficrespij,"# Age");
                   2813:          for(i=1; i<=nlstate;i++)
                   2814:            for(j=1; j<=nlstate+ndeath;j++)
                   2815:              fprintf(ficrespij," %1d-%1d",i,j);
                   2816:          fprintf(ficrespij,"\n");
                   2817:          for (h=0; h<=nhstepm; h++){
                   2818:            fprintf(ficrespij,"%d %.0f %.0f",k,agedeb, agedeb+ h*hstepm/YEARM*stepm );
                   2819:            for(i=1; i<=nlstate;i++)
                   2820:              for(j=1; j<=nlstate+ndeath;j++)
                   2821:                fprintf(ficrespij," %.5f", p3mat[i][j][h]);
                   2822:            fprintf(ficrespij,"\n");
                   2823:          }
                   2824:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   2825:          fprintf(ficrespij,"\n");
                   2826:        }
                   2827:     }
                   2828:   }
                   2829: 
1.13      lievre   2830:   /* varprob(fileres, matcov, p, delti, nlstate, (int) bage, (int) fage,k);*/
                   2831: 
1.2       lievre   2832:   fclose(ficrespij);
                   2833: 
1.13      lievre   2834:   /*---------- Forecasting ------------------*/
                   2835: 
                   2836:   strcpy(fileresf,"f"); 
                   2837:   strcat(fileresf,fileres);
                   2838:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   2839:     printf("Problem with forecast resultfile: %s\n", fileresf);goto end;
                   2840:   }
                   2841:   printf("Computing forecasting: result on file '%s' \n", fileresf);
                   2842: 
1.18    ! lievre   2843:  if ((nbocc(strfprevfore,'/')==1) && (nbocc(strlprevfore,'/')==1)){
        !          2844:      boolprev=0;
        !          2845:      cutv(stra,strb,strfprevfore,'/');
        !          2846:      dateprev1=(double)(atoi(strb)+atoi(stra)/12.);
        !          2847:      cutv(stra,strb,strlprevfore,'/');
        !          2848:      dateprev2=(double)(atoi(strb)+atoi(stra)/12.);
        !          2849:    }
        !          2850:    
        !          2851:    else if ((nbocc(strfprevfore,'/')==0) &&(nbocc(strlprevfore,'/')==0)){
        !          2852:      boolprev=1;
        !          2853:      fprev=atoi(strfprevfore); lprev=atoi(strlprevfore);
        !          2854:    }
        !          2855:     else {
        !          2856:       printf("Error in statement lprevalence or fprevalence\n");
        !          2857:       goto end;
        !          2858:     }
1.15      lievre   2859: 
1.18    ! lievre   2860:   prevalence(agemin, agemax, s, agev, nlstate, imx,Tvar,nbcode, ncodemax, fprevfore, lprevfore,mint,anint,boolprev,dateprev1,dateprev2);
        !          2861:   
        !          2862:   free_matrix(mint,1,maxwav,1,n);
        !          2863:   free_matrix(anint,1,maxwav,1,n);
        !          2864:   free_matrix(agev,1,maxwav,1,imx);
1.13      lievre   2865:   /* Mobile average */
                   2866: 
                   2867:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   2868: 
1.14      lievre   2869:   if (mobilav==1) {
                   2870:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   2871:     for (agedeb=bage+3; agedeb<=fage-2; agedeb++)
                   2872:       for (i=1; i<=nlstate;i++)
                   2873:        for (cptcod=1;cptcod<=ncodemax[cptcov];cptcod++)
                   2874:          mobaverage[(int)agedeb][i][cptcod]=0.;
                   2875:     
                   2876:     for (agedeb=bage+4; agedeb<=fage; agedeb++){
                   2877:       for (i=1; i<=nlstate;i++){
                   2878:        for (cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   2879:          for (cpt=0;cpt<=4;cpt++){
                   2880:            mobaverage[(int)agedeb-2][i][cptcod]=mobaverage[(int)agedeb-2][i][cptcod]+probs[(int)agedeb-cpt][i][cptcod];
1.13      lievre   2881:          }
                   2882:          mobaverage[(int)agedeb-2][i][cptcod]=mobaverage[(int)agedeb-2][i][cptcod]/5;
1.14      lievre   2883:        }
1.13      lievre   2884:       }
1.14      lievre   2885:     }   
1.13      lievre   2886:   }
                   2887: 
                   2888:   stepsize=(int) (stepm+YEARM-1)/YEARM;
1.15      lievre   2889:   if (stepm<=12) stepsize=1;
1.13      lievre   2890: 
                   2891:   agelim=AGESUP;
                   2892:   hstepm=stepsize*YEARM; /* Every year of age */
1.15      lievre   2893:   hstepm=hstepm/stepm; /* Typically 2 years, = 2 years/6 months = 4 */ 
1.16      lievre   2894:   
                   2895:   if (popforecast==1) {
                   2896:     if((ficpop=fopen(popfile,"r"))==NULL)    {
                   2897:       printf("Problem with population file : %s\n",popfile);goto end;
                   2898:     } 
                   2899:     popage=ivector(0,AGESUP);
                   2900:     popeffectif=vector(0,AGESUP);
                   2901:     popcount=vector(0,AGESUP);
                   2902: 
                   2903:     i=1;   
                   2904:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF)
                   2905:       {
                   2906:        i=i+1;
                   2907:       }
                   2908:     imx=i;
                   2909:   
                   2910:   for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   2911:   }
1.15      lievre   2912: 
1.13      lievre   2913:   for(cptcov=1;cptcov<=i1;cptcov++){
                   2914:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   2915:       k=k+1;
                   2916:       fprintf(ficresf,"\n#****** ");
                   2917:       for(j=1;j<=cptcoveff;j++) {
                   2918:        fprintf(ficresf,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   2919:       }
                   2920:       fprintf(ficresf,"******\n");
                   2921:       fprintf(ficresf,"# StartingAge FinalAge Horizon(in years)");
                   2922:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficresf," P.%d",j);
1.16      lievre   2923:       if (popforecast==1)  fprintf(ficresf," [Population]");
1.13      lievre   2924: 
                   2925:       for (agedeb=fage; agedeb>=bage; agedeb--){ 
1.16      lievre   2926:        fprintf(ficresf,"\n%.f %.f 0",agedeb, agedeb);
1.14      lievre   2927:        if (mobilav==1) {
1.13      lievre   2928:        for(j=1; j<=nlstate;j++) 
1.16      lievre   2929:          fprintf(ficresf," %.3f",mobaverage[(int)agedeb][j][cptcod]);
1.14      lievre   2930:        }
                   2931:        else {
                   2932:          for(j=1; j<=nlstate;j++) 
1.16      lievre   2933:          fprintf(ficresf," %.3f",probs[(int)agedeb][j][cptcod]);
1.15      lievre   2934:        }  
1.16      lievre   2935: 
                   2936:        for(j=1; j<=ndeath;j++) fprintf(ficresf," 0.00000");
                   2937:        if (popforecast==1) fprintf(ficresf," [%.f] ",popeffectif[(int)agedeb]);
1.13      lievre   2938:       }
1.16      lievre   2939:       
                   2940:       for (cpt=1; cpt<=nforecast;cpt++) { 
                   2941:        fprintf(ficresf,"\n");
1.13      lievre   2942:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
1.15      lievre   2943:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   2944:        nhstepm = nhstepm/hstepm; 
                   2945:        /*printf("agedeb=%.lf stepm=%d hstepm=%d nhstepm=%d \n",agedeb,stepm,hstepm,nhstepm);*/
1.13      lievre   2946: 
                   2947:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   2948:        oldm=oldms;savm=savms;
                   2949:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   2950:                
                   2951:        for (h=0; h<=nhstepm; h++){
                   2952:        
1.15      lievre   2953:         if (h*hstepm/YEARM*stepm==cpt)
1.16      lievre   2954:            fprintf(ficresf,"\n%.f %.f %.f",agedeb, agedeb+ h*hstepm/YEARM*stepm, h*hstepm/YEARM*stepm);
1.15      lievre   2955:         
1.13      lievre   2956:          
1.16      lievre   2957:         for(j=1; j<=nlstate+ndeath;j++) {
                   2958:           kk1=0.;kk2=0;
                   2959:           for(i=1; i<=nlstate;i++) {         
                   2960:             if (mobilav==1) 
                   2961:                kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb][i][cptcod];
                   2962:             else kk1=kk1+p3mat[i][j][h]*probs[(int)agedeb][i][cptcod];
                   2963:             if (popforecast==1) kk2=kk1*popeffectif[(int)agedeb];
                   2964:            }
                   2965:           if (h*hstepm/YEARM*stepm==cpt) {
                   2966:             fprintf(ficresf," %.3f", kk1);
                   2967:               if (popforecast==1) fprintf(ficresf," [%.f]", kk2);
                   2968:           }
1.13      lievre   2969:          }
1.14      lievre   2970:        }
1.13      lievre   2971:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
1.16      lievre   2972:        
                   2973:       }
1.13      lievre   2974:       }
                   2975:     }
1.14      lievre   2976:   }
                   2977:   if (mobilav==1) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
1.16      lievre   2978:   if (popforecast==1) {
                   2979:     free_ivector(popage,0,AGESUP);
                   2980:     free_vector(popeffectif,0,AGESUP);
                   2981:     free_vector(popcount,0,AGESUP);
                   2982:   }
1.15      lievre   2983:   free_imatrix(s,1,maxwav+1,1,n);
                   2984:   free_vector(weight,1,n);
1.13      lievre   2985:   fclose(ficresf);
1.2       lievre   2986:   /*---------- Health expectancies and variances ------------*/
                   2987: 
                   2988:   strcpy(filerest,"t");
                   2989:   strcat(filerest,fileres);
                   2990:   if((ficrest=fopen(filerest,"w"))==NULL) {
                   2991:     printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   2992:   }
                   2993:   printf("Computing Total LEs with variances: file '%s' \n", filerest); 
                   2994: 
                   2995: 
                   2996:   strcpy(filerese,"e");
                   2997:   strcat(filerese,fileres);
                   2998:   if((ficreseij=fopen(filerese,"w"))==NULL) {
                   2999:     printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   3000:   }
                   3001:   printf("Computing Health Expectancies: result on file '%s' \n", filerese);
                   3002: 
                   3003:  strcpy(fileresv,"v");
                   3004:   strcat(fileresv,fileres);
                   3005:   if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   3006:     printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   3007:   }
                   3008:   printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   3009: 
                   3010:   k=0;
                   3011:   for(cptcov=1;cptcov<=i1;cptcov++){
                   3012:     for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   3013:       k=k+1;
                   3014:       fprintf(ficrest,"\n#****** ");
1.7       lievre   3015:       for(j=1;j<=cptcoveff;j++) 
                   3016:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
1.2       lievre   3017:       fprintf(ficrest,"******\n");
                   3018: 
                   3019:       fprintf(ficreseij,"\n#****** ");
1.7       lievre   3020:       for(j=1;j<=cptcoveff;j++) 
1.2       lievre   3021:        fprintf(ficreseij,"V%d=%d ",j,nbcode[j][codtab[k][j]]);
                   3022:       fprintf(ficreseij,"******\n");
                   3023: 
                   3024:       fprintf(ficresvij,"\n#****** ");
1.7       lievre   3025:       for(j=1;j<=cptcoveff;j++) 
1.2       lievre   3026:        fprintf(ficresvij,"V%d=%d ",j,nbcode[j][codtab[k][j]]);
                   3027:       fprintf(ficresvij,"******\n");
                   3028: 
                   3029:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   3030:       oldm=oldms;savm=savms;
                   3031:       evsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k);  
                   3032:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   3033:       oldm=oldms;savm=savms;
                   3034:       varevsij(fileres, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k);
                   3035:       
                   3036:       fprintf(ficrest,"#Total LEs with variances: e.. (std) ");
                   3037:       for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   3038:       fprintf(ficrest,"\n");
                   3039:        
                   3040:       hf=1;
                   3041:       if (stepm >= YEARM) hf=stepm/YEARM;
                   3042:       epj=vector(1,nlstate+1);
                   3043:       for(age=bage; age <=fage ;age++){
                   3044:        prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
1.14      lievre   3045:        if (popbased==1) {
                   3046:          for(i=1; i<=nlstate;i++)
                   3047:            prlim[i][i]=probs[(int)age][i][k];
                   3048:        }
                   3049:        
1.2       lievre   3050:        fprintf(ficrest," %.0f",age);
                   3051:        for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   3052:          for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   3053:            epj[j] += prlim[i][i]*hf*eij[i][j][(int)age];
                   3054:          }
                   3055:          epj[nlstate+1] +=epj[j];
                   3056:        }
                   3057:        for(i=1, vepp=0.;i <=nlstate;i++)
                   3058:          for(j=1;j <=nlstate;j++)
                   3059:            vepp += vareij[i][j][(int)age];
                   3060:        fprintf(ficrest," %.2f (%.2f)", epj[nlstate+1],hf*sqrt(vepp));
                   3061:        for(j=1;j <=nlstate;j++){
                   3062:          fprintf(ficrest," %.2f (%.2f)", epj[j],hf*sqrt(vareij[j][j][(int)age]));
                   3063:        }
                   3064:        fprintf(ficrest,"\n");
                   3065:       }
                   3066:     }
                   3067:   }
                   3068:        
1.13      lievre   3069:        
                   3070: 
                   3071: 
1.2       lievre   3072:  fclose(ficreseij);
                   3073:  fclose(ficresvij);
                   3074:   fclose(ficrest);
                   3075:   fclose(ficpar);
                   3076:   free_vector(epj,1,nlstate+1);
1.5       lievre   3077:   /*  scanf("%d ",i); */
1.2       lievre   3078: 
                   3079:   /*------- Variance limit prevalence------*/   
                   3080: 
                   3081: strcpy(fileresvpl,"vpl");
                   3082:   strcat(fileresvpl,fileres);
                   3083:   if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   3084:     printf("Problem with variance prev lim resultfile: %s\n", fileresvpl);
                   3085:     exit(0);
                   3086:   }
                   3087:   printf("Computing Variance-covariance of Prevalence limit: file '%s' \n", fileresvpl);
                   3088: 
                   3089:  k=0;
                   3090:  for(cptcov=1;cptcov<=i1;cptcov++){
                   3091:    for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   3092:      k=k+1;
                   3093:      fprintf(ficresvpl,"\n#****** ");
1.7       lievre   3094:      for(j=1;j<=cptcoveff;j++) 
                   3095:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
1.2       lievre   3096:      fprintf(ficresvpl,"******\n");
                   3097:      
                   3098:      varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   3099:      oldm=oldms;savm=savms;
                   3100:      varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k);
                   3101:    }
                   3102:  }
                   3103: 
                   3104:   fclose(ficresvpl);
                   3105: 
                   3106:   /*---------- End : free ----------------*/
                   3107:   free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   3108:   
                   3109:   free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   3110:   free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   3111:   
                   3112:   
                   3113:   free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   3114:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   3115:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   3116:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.13      lievre   3117:  
1.2       lievre   3118:   free_matrix(matcov,1,npar,1,npar);
                   3119:   free_vector(delti,1,npar);
                   3120:   
                   3121:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   3122: 
                   3123:   printf("End of Imach\n");
                   3124:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
                   3125:   
                   3126:   /* 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);*/
                   3127:   /*printf("Total time was %d uSec.\n", total_usecs);*/
                   3128:   /*------ End -----------*/
1.12      lievre   3129: 
1.2       lievre   3130: 
                   3131:  end:
                   3132: #ifdef windows
                   3133:  chdir(pathcd);
                   3134: #endif 
1.13      lievre   3135:  
1.11      lievre   3136:  system("..\\gp37mgw\\wgnuplot graph.plt");
1.2       lievre   3137: 
                   3138: #ifdef windows
                   3139:   while (z[0] != 'q') {
                   3140:     chdir(pathcd); 
                   3141:     printf("\nType e to edit output files, c to start again, and q for exiting: ");
                   3142:     scanf("%s",z);
                   3143:     if (z[0] == 'c') system("./imach");
                   3144:     else if (z[0] == 'e') {
                   3145:       chdir(path);
1.10      lievre   3146:       system(optionfilehtm);
1.2       lievre   3147:     }
                   3148:     else if (z[0] == 'q') exit(0);
                   3149:   }
                   3150: #endif 
                   3151: }
                   3152: 
                   3153: 

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