File:  [Local Repository] / imach / src / imach.c
Revision 1.1: download - view: text, annotated - select for diffs
Thu Dec 28 18:49:56 2000 UTC (23 years, 5 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
Initial revision

    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
   11:   reach the Maximum Likekilhood of the parameters involved in the model.
   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.
   25:   hPijx is the probability to be
   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 win*/
   54: 
   55: #define MAXPARM 30 /* Maximum number of parameters for the optimization */
   56: #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncov */
   57: 
   58: #define NINTERVMAX 8
   59: #define NLSTATEMAX 8 /* Maximum number of live states (for func) */
   60: #define NDEATHMAX 8 /* Maximum number of dead states (for func) */
   61: #define NCOVMAX 8 /* Maximum number of covariates */
   62: #define MAXN 20000
   63: #define YEARM 12. /* Number of months per year */
   64: #define AGESUP 130
   65: #define AGEBASE 40
   66: 
   67: 
   68: int nvar;
   69: 
   70: int npar=NPARMAX;
   71: int nlstate=2; /* Number of live states */
   72: int ndeath=1; /* Number of dead states */
   73: int ncov;     /* Total number of covariables including constant a12*1 +b12*x ncov=2 */
   74: 
   75: int *wav; /* Number of waves for this individuual 0 is possible */
   76: int maxwav; /* Maxim number of waves */
   77: int mle, weightopt;
   78: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
   79: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
   80: double **oldm, **newm, **savm; /* Working pointers to matrices */
   81: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
   82: FILE *fic,*ficpar, *ficparo,*ficres,  *ficrespl, *ficrespij, *ficrest;
   83: FILE *ficgp, *fichtm;
   84: 
   85: #define NR_END 1
   86: #define FREE_ARG char*
   87: #define FTOL 1.0e-10
   88: 
   89: #define NRANSI 
   90: #define ITMAX 200 
   91: 
   92: #define TOL 2.0e-4 
   93: 
   94: #define CGOLD 0.3819660 
   95: #define ZEPS 1.0e-10 
   96: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
   97: 
   98: #define GOLD 1.618034 
   99: #define GLIMIT 100.0 
  100: #define TINY 1.0e-20 
  101: 
  102: static double maxarg1,maxarg2;
  103: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
  104: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
  105:  
  106: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
  107: #define rint(a) floor(a+0.5)
  108: 
  109: static double sqrarg;
  110: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
  111: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
  112: 
  113: int imx; 
  114: int stepm;
  115: /* Stepm, step in month: minimum step interpolation*/
  116: 
  117: int m,nb;
  118: int *num, firstpass=0, lastpass=2,*cod;
  119: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
  120: double **pmmij;
  121: 
  122: double *weight;
  123: int **s; /* Status */
  124: double *agedc, **covar, idx;
  125: 
  126: 
  127: double ftol=FTOL; /* Tolerance for computing Max Likelihood */
  128: double ftolhess; /* Tolerance for computing hessian */
  129: 
  130: 
  131: /******************************************/
  132: 
  133: void replace(char *s, char*t)
  134: {
  135:   int i;
  136:   int lg=20;
  137:   i=0;
  138:   lg=strlen(t);
  139:   for(i=0; i<= lg; i++) {
  140:     (s[i] = t[i]);
  141:     if (t[i]== '\\') s[i]='/';
  142:   }
  143: }
  144: void cut(char *u,char *v, char*t)
  145: {
  146:   int i,lg,j,p;
  147:   i=0;
  148:   for(j=0; j<=strlen(t); j++) {
  149:     if(t[j]=='\\') p=j;
  150:   }
  151: 
  152:   lg=strlen(t);
  153:   for(j=0; j<p; j++) {
  154:     (u[j] = t[j]);
  155:     u[p]='\0';
  156:   }
  157: 
  158:   for(j=0; j<= lg; j++) {
  159:     if (j>=(p+1))(v[j-p-1] = t[j]);
  160:   }
  161: }
  162: 
  163: /********************** nrerror ********************/
  164: 
  165: void nrerror(char error_text[])
  166: {
  167:   fprintf(stderr,"ERREUR ...\n");
  168:   fprintf(stderr,"%s\n",error_text);
  169:   exit(1);
  170: }
  171: /*********************** vector *******************/
  172: double *vector(int nl, int nh)
  173: {
  174:   double *v;
  175:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
  176:   if (!v) nrerror("allocation failure in vector");
  177:   return v-nl+NR_END;
  178: }
  179: 
  180: /************************ free vector ******************/
  181: void free_vector(double*v, int nl, int nh)
  182: {
  183:   free((FREE_ARG)(v+nl-NR_END));
  184: }
  185: 
  186: /************************ivector *******************************/
  187: int *ivector(long nl,long nh)
  188: {
  189:   int *v;
  190:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
  191:   if (!v) nrerror("allocation failure in ivector");
  192:   return v-nl+NR_END;
  193: }
  194: 
  195: /******************free ivector **************************/
  196: void free_ivector(int *v, long nl, long nh)
  197: {
  198:   free((FREE_ARG)(v+nl-NR_END));
  199: }
  200: 
  201: /******************* imatrix *******************************/
  202: int **imatrix(long nrl, long nrh, long ncl, long nch) 
  203:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
  204: { 
  205:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
  206:   int **m; 
  207:   
  208:   /* allocate pointers to rows */ 
  209:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
  210:   if (!m) nrerror("allocation failure 1 in matrix()"); 
  211:   m += NR_END; 
  212:   m -= nrl; 
  213:   
  214:   
  215:   /* allocate rows and set pointers to them */ 
  216:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
  217:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
  218:   m[nrl] += NR_END; 
  219:   m[nrl] -= ncl; 
  220:   
  221:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
  222:   
  223:   /* return pointer to array of pointers to rows */ 
  224:   return m; 
  225: } 
  226: 
  227: /****************** free_imatrix *************************/
  228: void free_imatrix(m,nrl,nrh,ncl,nch)
  229:       int **m;
  230:       long nch,ncl,nrh,nrl; 
  231:      /* free an int matrix allocated by imatrix() */ 
  232: { 
  233:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
  234:   free((FREE_ARG) (m+nrl-NR_END)); 
  235: } 
  236: 
  237: /******************* matrix *******************************/
  238: double **matrix(long nrl, long nrh, long ncl, long nch)
  239: {
  240:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
  241:   double **m;
  242: 
  243:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
  244:   if (!m) nrerror("allocation failure 1 in matrix()");
  245:   m += NR_END;
  246:   m -= nrl;
  247: 
  248:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
  249:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
  250:   m[nrl] += NR_END;
  251:   m[nrl] -= ncl;
  252: 
  253:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
  254:   return m;
  255: }
  256: 
  257: /*************************free matrix ************************/
  258: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
  259: {
  260:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
  261:   free((FREE_ARG)(m+nrl-NR_END));
  262: }
  263: 
  264: /******************* ma3x *******************************/
  265: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
  266: {
  267:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
  268:   double ***m;
  269: 
  270:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
  271:   if (!m) nrerror("allocation failure 1 in matrix()");
  272:   m += NR_END;
  273:   m -= nrl;
  274: 
  275:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
  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:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
  283:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
  284:   m[nrl][ncl] += NR_END;
  285:   m[nrl][ncl] -= nll;
  286:   for (j=ncl+1; j<=nch; j++) 
  287:     m[nrl][j]=m[nrl][j-1]+nlay;
  288:   
  289:   for (i=nrl+1; i<=nrh; i++) {
  290:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
  291:     for (j=ncl+1; j<=nch; j++) 
  292:       m[i][j]=m[i][j-1]+nlay;
  293:   }
  294:   return m;
  295: }
  296: 
  297: /*************************free ma3x ************************/
  298: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
  299: {
  300:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
  301:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
  302:   free((FREE_ARG)(m+nrl-NR_END));
  303: }
  304: 
  305: /***************** f1dim *************************/
  306: extern int ncom; 
  307: extern double *pcom,*xicom;
  308: extern double (*nrfunc)(double []); 
  309:  
  310: double f1dim(double x) 
  311: { 
  312:   int j; 
  313:   double f;
  314:   double *xt; 
  315:  
  316:   xt=vector(1,ncom); 
  317:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
  318:   f=(*nrfunc)(xt); 
  319:   free_vector(xt,1,ncom); 
  320:   return f; 
  321: } 
  322: 
  323: /*****************brent *************************/
  324: double brent(double ax, double bx, double cx, double (*f)(double), double tol, 	double *xmin) 
  325: { 
  326:   int iter; 
  327:   double a,b,d,etemp;
  328:   double fu,fv,fw,fx;
  329:   double ftemp;
  330:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
  331:   double e=0.0; 
  332:  
  333:   a=(ax < cx ? ax : cx); 
  334:   b=(ax > cx ? ax : cx); 
  335:   x=w=v=bx; 
  336:   fw=fv=fx=(*f)(x); 
  337:   for (iter=1;iter<=ITMAX;iter++) { 
  338:     xm=0.5*(a+b); 
  339:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
  340:     /*		if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
  341:     printf(".");fflush(stdout);
  342: #ifdef DEBUG
  343:     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);
  344:     /*		if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
  345: #endif
  346:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
  347:       *xmin=x; 
  348:       return fx; 
  349:     } 
  350:     ftemp=fu;
  351:     if (fabs(e) > tol1) { 
  352:       r=(x-w)*(fx-fv); 
  353:       q=(x-v)*(fx-fw); 
  354:       p=(x-v)*q-(x-w)*r; 
  355:       q=2.0*(q-r); 
  356:       if (q > 0.0) p = -p; 
  357:       q=fabs(q); 
  358:       etemp=e; 
  359:       e=d; 
  360:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
  361: 	d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
  362:       else { 
  363: 	d=p/q; 
  364: 	u=x+d; 
  365: 	if (u-a < tol2 || b-u < tol2) 
  366: 	  d=SIGN(tol1,xm-x); 
  367:       } 
  368:     } else { 
  369:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
  370:     } 
  371:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
  372:     fu=(*f)(u); 
  373:     if (fu <= fx) { 
  374:       if (u >= x) a=x; else b=x; 
  375:       SHFT(v,w,x,u) 
  376: 	SHFT(fv,fw,fx,fu) 
  377: 	} else { 
  378: 	  if (u < x) a=u; else b=u; 
  379: 	  if (fu <= fw || w == x) { 
  380: 	    v=w; 
  381: 	    w=u; 
  382: 	    fv=fw; 
  383: 	    fw=fu; 
  384: 	  } else if (fu <= fv || v == x || v == w) { 
  385: 	    v=u; 
  386: 	    fv=fu; 
  387: 	  } 
  388: 	} 
  389:   } 
  390:   nrerror("Too many iterations in brent"); 
  391:   *xmin=x; 
  392:   return fx; 
  393: } 
  394: 
  395: /****************** mnbrak ***********************/
  396: 
  397: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
  398: 	    double (*func)(double)) 
  399: { 
  400:   double ulim,u,r,q, dum;
  401:   double fu; 
  402:  
  403:   *fa=(*func)(*ax); 
  404:   *fb=(*func)(*bx); 
  405:   if (*fb > *fa) { 
  406:     SHFT(dum,*ax,*bx,dum) 
  407:       SHFT(dum,*fb,*fa,dum) 
  408:       } 
  409:   *cx=(*bx)+GOLD*(*bx-*ax); 
  410:   *fc=(*func)(*cx); 
  411:   while (*fb > *fc) { 
  412:     r=(*bx-*ax)*(*fb-*fc); 
  413:     q=(*bx-*cx)*(*fb-*fa); 
  414:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
  415:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); 
  416:     ulim=(*bx)+GLIMIT*(*cx-*bx); 
  417:     if ((*bx-u)*(u-*cx) > 0.0) { 
  418:       fu=(*func)(u); 
  419:     } else if ((*cx-u)*(u-ulim) > 0.0) { 
  420:       fu=(*func)(u); 
  421:       if (fu < *fc) { 
  422: 	SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
  423: 	  SHFT(*fb,*fc,fu,(*func)(u)) 
  424: 	  } 
  425:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { 
  426:       u=ulim; 
  427:       fu=(*func)(u); 
  428:     } else { 
  429:       u=(*cx)+GOLD*(*cx-*bx); 
  430:       fu=(*func)(u); 
  431:     } 
  432:     SHFT(*ax,*bx,*cx,u) 
  433:       SHFT(*fa,*fb,*fc,fu) 
  434:       } 
  435: } 
  436: 
  437: /*************** linmin ************************/
  438: 
  439: int ncom; 
  440: double *pcom,*xicom;
  441: double (*nrfunc)(double []); 
  442:  
  443: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
  444: { 
  445:   double brent(double ax, double bx, double cx, 
  446: 	       double (*f)(double), double tol, double *xmin); 
  447:   double f1dim(double x); 
  448:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
  449: 	      double *fc, double (*func)(double)); 
  450:   int j; 
  451:   double xx,xmin,bx,ax; 
  452:   double fx,fb,fa;
  453:  
  454:   ncom=n; 
  455:   pcom=vector(1,n); 
  456:   xicom=vector(1,n); 
  457:   nrfunc=func; 
  458:   for (j=1;j<=n;j++) { 
  459:     pcom[j]=p[j]; 
  460:     xicom[j]=xi[j]; 
  461:   } 
  462:   ax=0.0; 
  463:   xx=1.0; 
  464:   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); 
  465:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); 
  466: #ifdef DEBUG
  467:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
  468: #endif
  469:   for (j=1;j<=n;j++) { 
  470:     xi[j] *= xmin; 
  471:     p[j] += xi[j]; 
  472:   } 
  473:   free_vector(xicom,1,n); 
  474:   free_vector(pcom,1,n); 
  475: } 
  476: 
  477: /*************** powell ************************/
  478: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
  479: 	    double (*func)(double [])) 
  480: 
  481: { 
  482: 
  483: 
  484:   void linmin(double p[], double xi[], int n, double *fret, 
  485: 	      double (*func)(double [])); 
  486:   int i,ibig,j; 
  487:   double del,t,*pt,*ptt,*xit;
  488:   double fp,fptt;
  489:   double *xits;
  490:   pt=vector(1,n); 
  491:   ptt=vector(1,n); 
  492:   xit=vector(1,n); 
  493:   xits=vector(1,n); 
  494:   *fret=(*func)(p); 
  495:   for (j=1;j<=n;j++) pt[j]=p[j]; 
  496:   for (*iter=1;;++(*iter)) { 
  497:     fp=(*fret); 
  498:     ibig=0; 
  499:     del=0.0; 
  500:     printf("\nPowell iter=%d -2*LL=%.12f",*iter,*fret);
  501:     for (i=1;i<=n;i++) 
  502:       printf(" %d %.12f",i, p[i]);
  503:     printf("\n");
  504:     for (i=1;i<=n;i++) { 
  505:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; 
  506:       fptt=(*fret); 
  507: #ifdef DEBUG
  508:       printf("fret=%lf \n",*fret);
  509: #endif
  510:       printf("%d",i);fflush(stdout);
  511:       linmin(p,xit,n,fret,func); 
  512:       if (fabs(fptt-(*fret)) > del) { 
  513: 	del=fabs(fptt-(*fret)); 
  514: 	ibig=i; 
  515:       } 
  516: #ifdef DEBUG
  517:       printf("%d %.12e",i,(*fret));
  518:       for (j=1;j<=n;j++) {
  519: 	xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
  520: 	printf(" x(%d)=%.12e",j,xit[j]);
  521:       }
  522:       for(j=1;j<=n;j++) 
  523: 	printf(" p=%.12e",p[j]);
  524:       printf("\n");
  525: #endif
  526:     } 
  527:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
  528: #ifdef DEBUG
  529:       int k[2],l;
  530:       k[0]=1;
  531:       k[1]=-1;
  532:       printf("Max: %.12e",(*func)(p));
  533:       for (j=1;j<=n;j++) 
  534: 	printf(" %.12e",p[j]);
  535:       printf("\n");
  536:       for(l=0;l<=1;l++) {
  537: 	for (j=1;j<=n;j++) {
  538: 	  ptt[j]=p[j]+(p[j]-pt[j])*k[l];
  539: 	  printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
  540: 	}
  541: 	printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
  542:       }
  543: #endif
  544: 
  545: 
  546:       free_vector(xit,1,n); 
  547:       free_vector(xits,1,n); 
  548:       free_vector(ptt,1,n); 
  549:       free_vector(pt,1,n); 
  550:       return; 
  551:     } 
  552:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
  553:     for (j=1;j<=n;j++) { 
  554:       ptt[j]=2.0*p[j]-pt[j]; 
  555:       xit[j]=p[j]-pt[j]; 
  556:       pt[j]=p[j]; 
  557:     } 
  558:     fptt=(*func)(ptt); 
  559:     if (fptt < fp) { 
  560:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); 
  561:       if (t < 0.0) { 
  562: 	linmin(p,xit,n,fret,func); 
  563: 	for (j=1;j<=n;j++) { 
  564: 	  xi[j][ibig]=xi[j][n]; 
  565: 	  xi[j][n]=xit[j]; 
  566: 	}
  567: #ifdef DEBUG
  568: 	printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
  569: 	for(j=1;j<=n;j++)
  570: 	  printf(" %.12e",xit[j]);
  571: 	printf("\n");
  572: #endif
  573:       } 
  574:     } 
  575:   } 
  576: } 
  577: 
  578: /**** Prevalence limit ****************/
  579: 
  580: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl)
  581: {
  582:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
  583:      matrix by transitions matrix until convergence is reached */
  584: 
  585:   int i, ii,j,k;
  586:   double min, max, maxmin, maxmax,sumnew=0.;
  587:   double **matprod2();
  588:   double **out, cov[NCOVMAX], **pmij();
  589:   double **newm;
  590:   double agefin, delaymax=50 ; /* Max number of years to converge */
  591: 
  592:   for (ii=1;ii<=nlstate+ndeath;ii++)
  593:     for (j=1;j<=nlstate+ndeath;j++){
  594:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
  595:     }
  596:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
  597:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
  598:     newm=savm;
  599:     /* Covariates have to be included here again */
  600:     cov[1]=1.;
  601:     cov[2]=agefin;
  602:     out=matprod2(newm, pmij(pmmij,cov,ncov,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
  603: /*    printf("age=%f agefin=%f po=%f pn=%f\n",age,agefin,oldm[1][1],newm[1][1]);*/
  604:     
  605:     savm=oldm;
  606:     oldm=newm;
  607:     maxmax=0.;
  608:     for(j=1;j<=nlstate;j++){
  609:       min=1.;
  610:       max=0.;
  611:       for(i=1; i<=nlstate; i++) {
  612: 	sumnew=0;
  613: 	for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
  614: 	prlim[i][j]= newm[i][j]/(1-sumnew);
  615: 	max=FMAX(max,prlim[i][j]);
  616: 	min=FMIN(min,prlim[i][j]);
  617:       }
  618:       maxmin=max-min;
  619:       maxmax=FMAX(maxmax,maxmin);
  620:     }
  621:     if(maxmax < ftolpl){
  622:       return prlim;
  623:     }
  624:   }
  625: }
  626: 
  627: /*************** transition probabilities **********/ 
  628: 
  629: double **pmij(double **ps, double *cov, int ncov, double *x, int nlstate )
  630: {
  631:   double s1, s2;
  632:   /*double t34;*/
  633:   int i,j,j1, nc, ii, jj;
  634: 
  635:     for(i=1; i<= nlstate; i++){
  636:     for(j=1; j<i;j++){
  637:       for (nc=1, s2=0.;nc <=ncov; nc++){
  638: 	/*s2 += param[i][j][nc]*cov[nc];*/
  639: 	s2 += x[(i-1)*nlstate*ncov+(j-1)*ncov+nc+(i-1)*(ndeath-1)*ncov]*cov[nc];
  640: 	/*printf("Int j<i s1=%.17e, s2=%.17e\n",s1,s2);*/
  641:       }
  642:       ps[i][j]=s2;
  643:       /*printf("s1=%.17e, s2=%.17e\n",s1,s2);*/
  644:     }
  645:     for(j=i+1; j<=nlstate+ndeath;j++){
  646:       for (nc=1, s2=0.;nc <=ncov; nc++){
  647: 	s2 += x[(i-1)*nlstate*ncov+(j-2)*ncov+nc+(i-1)*(ndeath-1)*ncov]*cov[nc];
  648: 	/*printf("Int j>i s1=%.17e, s2=%.17e %lx %lx\n",s1,s2,s1,s2);*/
  649:       }
  650:       ps[i][j]=s2;
  651:     }
  652:   }
  653:   for(i=1; i<= nlstate; i++){
  654:      s1=0;
  655:     for(j=1; j<i; j++)
  656:       s1+=exp(ps[i][j]);
  657:     for(j=i+1; j<=nlstate+ndeath; j++)
  658:       s1+=exp(ps[i][j]);
  659:     ps[i][i]=1./(s1+1.);
  660:     for(j=1; j<i; j++)
  661:       ps[i][j]= exp(ps[i][j])*ps[i][i];
  662:     for(j=i+1; j<=nlstate+ndeath; j++)
  663:       ps[i][j]= exp(ps[i][j])*ps[i][i];
  664:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
  665:   } /* end i */
  666: 
  667:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
  668:     for(jj=1; jj<= nlstate+ndeath; jj++){
  669:       ps[ii][jj]=0;
  670:       ps[ii][ii]=1;
  671:     }
  672:   }
  673: 
  674:   /*   for(ii=1; ii<= nlstate+ndeath; ii++){
  675:     for(jj=1; jj<= nlstate+ndeath; jj++){
  676:      printf("%lf ",ps[ii][jj]);
  677:    }
  678:     printf("\n ");
  679:     }
  680:     printf("\n ");printf("%lf ",cov[2]);*/
  681: /*
  682:   for(i=1; i<= npar; i++) printf("%f ",x[i]);
  683:   goto end;*/
  684:     return ps;
  685: }
  686: 
  687: /**************** Product of 2 matrices ******************/
  688: 
  689: double **matprod2(double **out, double **in,long nrl, long nrh, long ncl, long nch, long ncolol, long ncoloh, double **b)
  690: {
  691:   /* Computes the matric product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
  692:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
  693:   /* in, b, out are matrice of pointers which should have been initialized 
  694:      before: only the contents of out is modified. The function returns
  695:      a pointer to pointers identical to out */
  696:   long i, j, k;
  697:   for(i=nrl; i<= nrh; i++)
  698:     for(k=ncolol; k<=ncoloh; k++)
  699:       for(j=ncl,out[i][k]=0.; j<=nch; j++)
  700: 	out[i][k] +=in[i][j]*b[j][k];
  701: 
  702:   return out;
  703: }
  704: 
  705: 
  706: /************* Higher Matrix Product ***************/
  707: 
  708: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm )
  709: {
  710:   /* Computes the transition matrix starting at age 'age' over 'nhstepm*hstepm*stepm' month 
  711:      duration (i.e. until
  712:      age (in years)  age+nhstepm*stepm/12) by multiplying nhstepm*hstepm matrices. 
  713:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
  714:      (typically every 2 years instead of every month which is too big).
  715:      Model is determined by parameters x and covariates have to be 
  716:      included manually here. 
  717: 
  718:      */
  719: 
  720:   int i, j, d, h;
  721:   double **out, cov[NCOVMAX];
  722:   double **newm;
  723: 
  724:   /* Hstepm could be zero and should return the unit matrix */
  725:   for (i=1;i<=nlstate+ndeath;i++)
  726:     for (j=1;j<=nlstate+ndeath;j++){
  727:       oldm[i][j]=(i==j ? 1.0 : 0.0);
  728:       po[i][j][0]=(i==j ? 1.0 : 0.0);
  729:     }
  730:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
  731:   for(h=1; h <=nhstepm; h++){
  732:     for(d=1; d <=hstepm; d++){
  733:       newm=savm;
  734:       /* Covariates have to be included here again */
  735:       cov[1]=1.;
  736:       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
  737:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
  738:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
  739: 		   pmij(pmmij,cov,ncov,x,nlstate));
  740:       savm=oldm;
  741:       oldm=newm;
  742:     }
  743:     for(i=1; i<=nlstate+ndeath; i++)
  744:       for(j=1;j<=nlstate+ndeath;j++) {
  745: 	po[i][j][h]=newm[i][j];
  746: 	/*printf("i=%d j=%d h=%d po[i][j][h]=%f ",i,j,h,po[i][j][h]);
  747: 	 */
  748:       }
  749:   } /* end h */
  750:   return po;
  751: }
  752: 
  753: 
  754: /*************** log-likelihood *************/
  755: double func( double *x)
  756: {
  757:   int i, ii, j, k, mi, d;
  758:   double l, ll[NLSTATEMAX], cov[NCOVMAX];
  759:   double **out;
  760:   double sw; /* Sum of weights */
  761:   double lli; /* Individual log likelihood */
  762:   long ipmx;
  763:   /*extern weight */
  764:   /* We are differentiating ll according to initial status */
  765:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
  766:   /*for(i=1;i<imx;i++) 
  767: printf(" %d\n",s[4][i]);
  768:   */
  769: 
  770:   for(k=1; k<=nlstate; k++) ll[k]=0.;
  771:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
  772:        for(mi=1; mi<= wav[i]-1; mi++){
  773:       for (ii=1;ii<=nlstate+ndeath;ii++)
  774: 	for (j=1;j<=nlstate+ndeath;j++) oldm[ii][j]=(ii==j ? 1.0 : 0.0);
  775:             for(d=0; d<dh[mi][i]; d++){
  776: 	newm=savm;
  777: 	  cov[1]=1.;
  778: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
  779: 	    out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
  780: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncov,x,nlstate));
  781: 	  savm=oldm;
  782: 	  oldm=newm;
  783: 
  784: 
  785:       } /* end mult */
  786:    
  787:       lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);
  788:       /* printf(" %f ",out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/
  789:       ipmx +=1;
  790:       sw += weight[i];
  791:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
  792:     } /* end of wave */
  793:   } /* end of individual */
  794: 
  795:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
  796:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
  797:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
  798:   return -l;
  799: }
  800: 
  801: 
  802: /*********** Maximum Likelihood Estimation ***************/
  803: 
  804: void mlikeli(FILE *ficres,double p[], int npar, int ncov, int nlstate, double ftol, double (*func)(double []))
  805: {
  806:   int i,j, iter;
  807:   double **xi,*delti;
  808:   double fret;
  809:   xi=matrix(1,npar,1,npar);
  810:   for (i=1;i<=npar;i++)
  811:     for (j=1;j<=npar;j++)
  812:       xi[i][j]=(i==j ? 1.0 : 0.0);
  813:   printf("Powell\n");
  814:   powell(p,xi,npar,ftol,&iter,&fret,func);
  815: 
  816:    printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));
  817:   fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f ",iter,func(p));
  818: 
  819: }
  820: 
  821: /**** Computes Hessian and covariance matrix ***/
  822: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
  823: {
  824:   double  **a,**y,*x,pd;
  825:   double **hess;
  826:   int i, j,jk;
  827:   int *indx;
  828: 
  829:   double hessii(double p[], double delta, int theta, double delti[]);
  830:   double hessij(double p[], double delti[], int i, int j);
  831:   void lubksb(double **a, int npar, int *indx, double b[]) ;
  832:   void ludcmp(double **a, int npar, int *indx, double *d) ;
  833: 
  834: 
  835:   hess=matrix(1,npar,1,npar);
  836: 
  837:   printf("\nCalculation of the hessian matrix. Wait...\n");
  838:   for (i=1;i<=npar;i++){
  839:     printf("%d",i);fflush(stdout);
  840:     hess[i][i]=hessii(p,ftolhess,i,delti);
  841:     /*printf(" %f ",p[i]);*/
  842:   }
  843: 
  844:   for (i=1;i<=npar;i++) {
  845:     for (j=1;j<=npar;j++)  {
  846:       if (j>i) { 
  847: 	printf(".%d%d",i,j);fflush(stdout);
  848: 	hess[i][j]=hessij(p,delti,i,j);
  849: 	hess[j][i]=hess[i][j];
  850:       }
  851:     }
  852:   }
  853:   printf("\n");
  854: 
  855:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
  856:   
  857:   a=matrix(1,npar,1,npar);
  858:   y=matrix(1,npar,1,npar);
  859:   x=vector(1,npar);
  860:   indx=ivector(1,npar);
  861:   for (i=1;i<=npar;i++)
  862:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
  863:   ludcmp(a,npar,indx,&pd);
  864: 
  865:   for (j=1;j<=npar;j++) {
  866:     for (i=1;i<=npar;i++) x[i]=0;
  867:     x[j]=1;
  868:     lubksb(a,npar,indx,x);
  869:     for (i=1;i<=npar;i++){ 
  870:       matcov[i][j]=x[i];
  871:     }
  872:   }
  873: 
  874:   printf("\n#Hessian matrix#\n");
  875:   for (i=1;i<=npar;i++) { 
  876:     for (j=1;j<=npar;j++) { 
  877:       printf("%.3e ",hess[i][j]);
  878:     }
  879:     printf("\n");
  880:   }
  881: 
  882:   /* Recompute Inverse */
  883:   for (i=1;i<=npar;i++)
  884:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
  885:   ludcmp(a,npar,indx,&pd);
  886: 
  887:   /*  printf("\n#Hessian matrix recomputed#\n");
  888: 
  889:   for (j=1;j<=npar;j++) {
  890:     for (i=1;i<=npar;i++) x[i]=0;
  891:     x[j]=1;
  892:     lubksb(a,npar,indx,x);
  893:     for (i=1;i<=npar;i++){ 
  894:       y[i][j]=x[i];
  895:       printf("%.3e ",y[i][j]);
  896:     }
  897:     printf("\n");
  898:   }
  899:   */
  900: 
  901:   free_matrix(a,1,npar,1,npar);
  902:   free_matrix(y,1,npar,1,npar);
  903:   free_vector(x,1,npar);
  904:   free_ivector(indx,1,npar);
  905:   free_matrix(hess,1,npar,1,npar);
  906: 
  907: 
  908: }
  909: 
  910: /*************** hessian matrix ****************/
  911: double hessii( double x[], double delta, int theta, double delti[])
  912: {
  913:   int i;
  914:   int l=1, lmax=20;
  915:   double k1,k2;
  916:   double p2[NPARMAX+1];
  917:   double res;
  918:   double delt, delts, nkhi=10.,nkhif=1., khi=1.e-4;
  919:   double fx;
  920:   int k=0,kmax=10;
  921:   double l1;
  922: 
  923:   fx=func(x);
  924:   for (i=1;i<=npar;i++) p2[i]=x[i];
  925:   for(l=0 ; l <=lmax; l++){
  926:     l1=pow(10,l);
  927:     delts=delt;
  928:     for(k=1 ; k <kmax; k=k+1){
  929:       delt = delta*(l1*k);
  930:       p2[theta]=x[theta] +delt;
  931:       k1=func(p2)-fx;
  932:       p2[theta]=x[theta]-delt;
  933:       k2=func(p2)-fx;
  934:       /*res= (k1-2.0*fx+k2)/delt/delt; */
  935:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
  936:       
  937: #ifdef DEBUG
  938:       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);
  939: #endif
  940:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
  941:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
  942: 	k=kmax;
  943:       }
  944:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
  945: 	k=kmax; l=lmax*10.;
  946:       }
  947:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
  948: 	delts=delt;
  949:       }
  950:     }
  951:   }
  952:   delti[theta]=delts;
  953:   return res;
  954:   
  955: }
  956: 
  957: double hessij( double x[], double delti[], int thetai,int thetaj)
  958: {
  959:   int i;
  960:   int l=1, l1, lmax=20;
  961:   double k1,k2,k3,k4,res,fx;
  962:   double p2[NPARMAX+1];
  963:   int k;
  964: 
  965:   fx=func(x);
  966:   for (k=1; k<=2; k++) {
  967:     for (i=1;i<=npar;i++) p2[i]=x[i];
  968:     p2[thetai]=x[thetai]+delti[thetai]/k;
  969:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
  970:     k1=func(p2)-fx;
  971:   
  972:     p2[thetai]=x[thetai]+delti[thetai]/k;
  973:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
  974:     k2=func(p2)-fx;
  975:   
  976:     p2[thetai]=x[thetai]-delti[thetai]/k;
  977:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
  978:     k3=func(p2)-fx;
  979:   
  980:     p2[thetai]=x[thetai]-delti[thetai]/k;
  981:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
  982:     k4=func(p2)-fx;
  983:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
  984: #ifdef DEBUG
  985:     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);
  986: #endif
  987:   }
  988:   return res;
  989: }
  990: 
  991: /************** Inverse of matrix **************/
  992: void ludcmp(double **a, int n, int *indx, double *d) 
  993: { 
  994:   int i,imax,j,k; 
  995:   double big,dum,sum,temp; 
  996:   double *vv; 
  997:  
  998:   vv=vector(1,n); 
  999:   *d=1.0; 
 1000:   for (i=1;i<=n;i++) { 
 1001:     big=0.0; 
 1002:     for (j=1;j<=n;j++) 
 1003:       if ((temp=fabs(a[i][j])) > big) big=temp; 
 1004:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
 1005:     vv[i]=1.0/big; 
 1006:   } 
 1007:   for (j=1;j<=n;j++) { 
 1008:     for (i=1;i<j;i++) { 
 1009:       sum=a[i][j]; 
 1010:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
 1011:       a[i][j]=sum; 
 1012:     } 
 1013:     big=0.0; 
 1014:     for (i=j;i<=n;i++) { 
 1015:       sum=a[i][j]; 
 1016:       for (k=1;k<j;k++) 
 1017: 	sum -= a[i][k]*a[k][j]; 
 1018:       a[i][j]=sum; 
 1019:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
 1020: 	big=dum; 
 1021: 	imax=i; 
 1022:       } 
 1023:     } 
 1024:     if (j != imax) { 
 1025:       for (k=1;k<=n;k++) { 
 1026: 	dum=a[imax][k]; 
 1027: 	a[imax][k]=a[j][k]; 
 1028: 	a[j][k]=dum; 
 1029:       } 
 1030:       *d = -(*d); 
 1031:       vv[imax]=vv[j]; 
 1032:     } 
 1033:     indx[j]=imax; 
 1034:     if (a[j][j] == 0.0) a[j][j]=TINY; 
 1035:     if (j != n) { 
 1036:       dum=1.0/(a[j][j]); 
 1037:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
 1038:     } 
 1039:   } 
 1040:   free_vector(vv,1,n);  /* Doesn't work */
 1041: ;
 1042: } 
 1043: 
 1044: void lubksb(double **a, int n, int *indx, double b[]) 
 1045: { 
 1046:   int i,ii=0,ip,j; 
 1047:   double sum; 
 1048:  
 1049:   for (i=1;i<=n;i++) { 
 1050:     ip=indx[i]; 
 1051:     sum=b[ip]; 
 1052:     b[ip]=b[i]; 
 1053:     if (ii) 
 1054:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
 1055:     else if (sum) ii=i; 
 1056:     b[i]=sum; 
 1057:   } 
 1058:   for (i=n;i>=1;i--) { 
 1059:     sum=b[i]; 
 1060:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
 1061:     b[i]=sum/a[i][i]; 
 1062:   } 
 1063: } 
 1064: 
 1065: /************ Frequencies ********************/
 1066: void  freqsummary(char fileres[], int agemin, int agemax, int **s, double **agev, int nlstate, int imx)
 1067: {  /* Some frequencies */
 1068:  
 1069:   int i, m, jk;
 1070:   double ***freq; /* Frequencies */
 1071:   double *pp;
 1072:   double pos;
 1073:   FILE *ficresp;
 1074:   char fileresp[FILENAMELENGTH];
 1075: 
 1076:   pp=vector(1,nlstate);
 1077: 
 1078:   strcpy(fileresp,"p");
 1079:   strcat(fileresp,fileres);
 1080:   if((ficresp=fopen(fileresp,"w"))==NULL) {
 1081:     printf("Problem with prevalence resultfile: %s\n", fileresp);
 1082:     exit(0);
 1083:   }
 1084: 
 1085:   freq= ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,agemin,agemax+3);
 1086:   for (i=-1; i<=nlstate+ndeath; i++)  
 1087:     for (jk=-1; jk<=nlstate+ndeath; jk++)  
 1088:       for(m=agemin; m <= agemax+3; m++)
 1089: 	freq[i][jk][m]=0;
 1090: 
 1091:   for (i=1; i<=imx; i++)  {
 1092:     for(m=firstpass; m<= lastpass-1; m++){
 1093:       if(agev[m][i]==0) agev[m][i]=agemax+1;
 1094:       if(agev[m][i]==1) agev[m][i]=agemax+2;
 1095:        freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
 1096:        freq[s[m][i]][s[m+1][i]][(int) agemax+3] += weight[i];
 1097:     }
 1098:   }
 1099: 
 1100:   fprintf(ficresp, "#");
 1101:   for(i=1; i<=nlstate;i++) 
 1102:     fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
 1103: fprintf(ficresp, "\n");
 1104: 
 1105:   for(i=(int)agemin; i <= (int)agemax+3; i++){
 1106:     if(i==(int)agemax+3)
 1107:       printf("Total");
 1108:     else
 1109:       printf("Age %d", i);
 1110:     for(jk=1; jk <=nlstate ; jk++){
 1111:       for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
 1112: 	pp[jk] += freq[jk][m][i];
 1113:     }
 1114:     for(jk=1; jk <=nlstate ; jk++){
 1115:       for(m=-1, pos=0; m <=0 ; m++)
 1116: 	pos += freq[jk][m][i];
 1117:       if(pp[jk]>=1.e-10)
 1118: 	printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 1119:       else
 1120:         printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 1121:     }
 1122:     for(jk=1; jk <=nlstate ; jk++){
 1123:       for(m=1, pp[jk]=0; m <=nlstate+ndeath; m++)
 1124: 	pp[jk] += freq[jk][m][i];
 1125:     }
 1126:     for(jk=1,pos=0; jk <=nlstate ; jk++)
 1127:       pos += pp[jk];
 1128:     for(jk=1; jk <=nlstate ; jk++){
 1129:       if(pos>=1.e-5)
 1130: 	printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 1131:       else
 1132: 	printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 1133:       if( i <= (int) agemax){
 1134: 	if(pos>=1.e-5)
 1135: 	  fprintf(ficresp," %d %.5f %.0f %.0f",i,pp[jk]/pos, pp[jk],pos);
 1136:       else
 1137: 	  fprintf(ficresp," %d NaNq %.0f %.0f",i,pp[jk],pos);
 1138:       }
 1139:     }
 1140:     for(jk=-1; jk <=nlstate+ndeath; jk++)
 1141:       for(m=-1; m <=nlstate+ndeath; m++)
 1142: 	if(freq[jk][m][i] !=0 ) printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
 1143:     if(i <= (int) agemax)
 1144:       fprintf(ficresp,"\n");
 1145:     printf("\n");
 1146:   }
 1147: 
 1148:   fclose(ficresp);
 1149:   free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath,(int) agemin,(int) agemax+3);
 1150:   free_vector(pp,1,nlstate);
 1151: 
 1152: }  /* End of Freq */
 1153: 
 1154: /************* Waves Concatenation ***************/
 1155: 
 1156: void  concatwav(int wav[], int **dh, int **mw, int **s, double *agedc, double **agev, int  firstpass, int lastpass, int imx, int nlstate, int stepm)
 1157: {
 1158:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
 1159:      Death is a valid wave (if date is known).
 1160:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
 1161:      dh[m][i] of dh[mw[mi][i][i] is the delay between two effective waves m=mw[mi][i]
 1162:      and mw[mi+1][i]. dh depends on stepm.
 1163:      */
 1164: 
 1165:   int i, mi, m;
 1166:   int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
 1167: float sum=0.;
 1168: 
 1169:   for(i=1; i<=imx; i++){
 1170:     mi=0;
 1171:     m=firstpass;
 1172:     while(s[m][i] <= nlstate){
 1173:       if(s[m][i]>=1)
 1174: 	mw[++mi][i]=m;
 1175:       if(m >=lastpass)
 1176: 	break;
 1177:       else
 1178: 	m++;
 1179:     }/* end while */
 1180:     if (s[m][i] > nlstate){
 1181:       mi++;	/* Death is another wave */
 1182:       /* if(mi==0)  never been interviewed correctly before death */
 1183: 	 /* Only death is a correct wave */
 1184:       mw[mi][i]=m;
 1185:     }
 1186: 
 1187:     wav[i]=mi;
 1188:     if(mi==0)
 1189:       printf("Warning, no any valid information for:%d line=%d\n",num[i],i);
 1190:   }
 1191: 
 1192:   for(i=1; i<=imx; i++){
 1193:     for(mi=1; mi<wav[i];mi++){
 1194:       if (stepm <=0)
 1195: 	dh[mi][i]=1;
 1196:       else{
 1197: 	if (s[mw[mi+1][i]][i] > nlstate) {
 1198: 	  j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
 1199: 	  if(j=0) j=1;  /* Survives at least one month after exam */
 1200: 	}
 1201: 	else{
 1202: 	  j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
 1203: 	  k=k+1;
 1204: 	  if (j >= jmax) jmax=j;
 1205: 	  else if (j <= jmin)jmin=j;
 1206: 	  sum=sum+j;
 1207: 	}
 1208: 	jk= j/stepm;
 1209: 	jl= j -jk*stepm;
 1210: 	ju= j -(jk+1)*stepm;
 1211: 	if(jl <= -ju)
 1212: 	  dh[mi][i]=jk;
 1213: 	else
 1214: 	  dh[mi][i]=jk+1;
 1215: 	if(dh[mi][i]==0)
 1216: 	  dh[mi][i]=1; /* At least one step */
 1217:       }
 1218:     }
 1219:   }
 1220:   printf("Delay (in months) between two waves Min=%d Max=%d Mean=%f\n\n ",jmin, jmax,sum/k);
 1221: }
 1222: 
 1223: /*********** Health Expectancies ****************/
 1224: 
 1225: void evsij(char fileres[], double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm)
 1226: {
 1227:   /* Health expectancies */
 1228:   int i, j, nhstepm, hstepm, h;
 1229:   double age, agelim,hf;
 1230:   double ***p3mat;
 1231: 
 1232:   FILE  *ficreseij;
 1233:   char filerese[FILENAMELENGTH];
 1234: 
 1235:   strcpy(filerese,"e");
 1236:   strcat(filerese,fileres);
 1237:   if((ficreseij=fopen(filerese,"w"))==NULL) {
 1238:     printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 1239:   }
 1240:   printf("Computing Health Expectancies: result on file '%s' \n", filerese);
 1241: 
 1242:   fprintf(ficreseij,"# Health expectancies\n");
 1243:   fprintf(ficreseij,"# Age");
 1244:   for(i=1; i<=nlstate;i++)
 1245:     for(j=1; j<=nlstate;j++)
 1246:       fprintf(ficreseij," %1d-%1d",i,j);
 1247:   fprintf(ficreseij,"\n");
 1248: 
 1249:   hstepm=1*YEARM; /*  Every j years of age (in month) */
 1250:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
 1251: 
 1252:   agelim=AGESUP;
 1253:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 1254:     /* nhstepm age range expressed in number of stepm */
 1255:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); 
 1256:     /* Typically if 20 years = 20*12/6=40 stepm */ 
 1257:     if (stepm >= YEARM) hstepm=1;
 1258:     nhstepm = nhstepm/hstepm;/* Expressed in hstepm, typically 40/4=10 */
 1259:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 1260:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
 1261:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
 1262:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm);  
 1263: 
 1264: 
 1265:     for(i=1; i<=nlstate;i++)
 1266:       for(j=1; j<=nlstate;j++)
 1267: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm; h++){
 1268: 	  eij[i][j][(int)age] +=p3mat[i][j][h];
 1269: 	}
 1270:     
 1271:     hf=1;
 1272:     if (stepm >= YEARM) hf=stepm/YEARM;
 1273:     fprintf(ficreseij,"%.0f",age );
 1274:     for(i=1; i<=nlstate;i++)
 1275:       for(j=1; j<=nlstate;j++){
 1276: 	fprintf(ficreseij," %.4f", hf*eij[i][j][(int)age]);
 1277:       }
 1278:     fprintf(ficreseij,"\n");
 1279:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 1280:   }
 1281:   fclose(ficreseij);
 1282: }
 1283: 
 1284: /************ Variance ******************/
 1285: 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)
 1286: {
 1287:   /* Variance of health expectancies */
 1288:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
 1289:   double **newm;
 1290:   double **dnewm,**doldm;
 1291:   int i, j, nhstepm, hstepm, h;
 1292:   int k;
 1293:   FILE  *ficresvij;
 1294:   char fileresv[FILENAMELENGTH];
 1295:   double *xp;
 1296:   double **gp, **gm;
 1297:   double ***gradg, ***trgradg;
 1298:   double ***p3mat;
 1299:   double age,agelim;
 1300:   int theta;
 1301: 
 1302:   strcpy(fileresv,"v");
 1303:   strcat(fileresv,fileres);
 1304:   if((ficresvij=fopen(fileresv,"w"))==NULL) {
 1305:     printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
 1306:   }
 1307:   printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
 1308: 
 1309: 
 1310:   fprintf(ficresvij,"# Covariances of life expectancies\n");
 1311:   fprintf(ficresvij,"# Age");
 1312:   for(i=1; i<=nlstate;i++)
 1313:     for(j=1; j<=nlstate;j++)
 1314:       fprintf(ficresvij," Cov(e%1d, e%1d)",i,j);
 1315:   fprintf(ficresvij,"\n");
 1316: 
 1317:   xp=vector(1,npar);
 1318:   dnewm=matrix(1,nlstate,1,npar);
 1319:   doldm=matrix(1,nlstate,1,nlstate);
 1320:   
 1321:   hstepm=1*YEARM; /* Every year of age */
 1322:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
 1323:   agelim = AGESUP;
 1324:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 1325:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 1326:     if (stepm >= YEARM) hstepm=1;
 1327:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 1328:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 1329:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
 1330:     gp=matrix(0,nhstepm,1,nlstate);
 1331:     gm=matrix(0,nhstepm,1,nlstate);
 1332: 
 1333:     for(theta=1; theta <=npar; theta++){
 1334:       for(i=1; i<=npar; i++){ /* Computes gradient */
 1335: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 1336:       }
 1337:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm);  
 1338:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl);
 1339:       for(j=1; j<= nlstate; j++){
 1340: 	for(h=0; h<=nhstepm; h++){
 1341: 	  for(i=1, gp[h][j]=0.;i<=nlstate;i++)
 1342: 	    gp[h][j] += prlim[i][i]*p3mat[i][j][h];
 1343: 	}
 1344:       }
 1345:     
 1346:       for(i=1; i<=npar; i++) /* Computes gradient */
 1347: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 1348:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm);  
 1349:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl);
 1350:       for(j=1; j<= nlstate; j++){
 1351: 	for(h=0; h<=nhstepm; h++){
 1352: 	  for(i=1, gm[h][j]=0.;i<=nlstate;i++)
 1353: 	    gm[h][j] += prlim[i][i]*p3mat[i][j][h];
 1354: 	}
 1355:       }
 1356:       for(j=1; j<= nlstate; j++)
 1357: 	for(h=0; h<=nhstepm; h++){
 1358: 	  gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
 1359: 	}
 1360:     } /* End theta */
 1361: 
 1362:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar);
 1363: 
 1364:     for(h=0; h<=nhstepm; h++)
 1365:       for(j=1; j<=nlstate;j++)
 1366: 	for(theta=1; theta <=npar; theta++)
 1367: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 1368: 
 1369:     for(i=1;i<=nlstate;i++)
 1370:       for(j=1;j<=nlstate;j++)
 1371: 	vareij[i][j][(int)age] =0.;
 1372:     for(h=0;h<=nhstepm;h++){
 1373:       for(k=0;k<=nhstepm;k++){
 1374: 	matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
 1375: 	matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
 1376: 	for(i=1;i<=nlstate;i++)
 1377: 	  for(j=1;j<=nlstate;j++)
 1378: 	    vareij[i][j][(int)age] += doldm[i][j];
 1379:       }
 1380:     }
 1381:     h=1;
 1382:     if (stepm >= YEARM) h=stepm/YEARM;
 1383:     fprintf(ficresvij,"%.0f ",age );
 1384:     for(i=1; i<=nlstate;i++)
 1385:       for(j=1; j<=nlstate;j++){
 1386: 	fprintf(ficresvij," %.4f", h*vareij[i][j][(int)age]);
 1387:       }
 1388:     fprintf(ficresvij,"\n");
 1389:     free_matrix(gp,0,nhstepm,1,nlstate);
 1390:     free_matrix(gm,0,nhstepm,1,nlstate);
 1391:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
 1392:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
 1393:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 1394:   } /* End age */
 1395:   fclose(ficresvij);
 1396:   free_vector(xp,1,npar);
 1397:   free_matrix(doldm,1,nlstate,1,npar);
 1398:   free_matrix(dnewm,1,nlstate,1,nlstate);
 1399: 
 1400: }
 1401: 
 1402: /************ Variance of prevlim ******************/
 1403: 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)
 1404: {
 1405:   /* Variance of health expectancies */
 1406:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
 1407:   double **newm;
 1408:   double **dnewm,**doldm;
 1409:   int i, j, nhstepm, hstepm;
 1410:   int k;
 1411:   FILE  *ficresvpl;
 1412:   char fileresvpl[FILENAMELENGTH];
 1413:   double *xp;
 1414:   double *gp, *gm;
 1415:   double **gradg, **trgradg;
 1416:   double age,agelim;
 1417:   int theta;
 1418: 
 1419:   strcpy(fileresvpl,"vpl");
 1420:   strcat(fileresvpl,fileres);
 1421:   if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
 1422:     printf("Problem with variance prev lim resultfile: %s\n", fileresvpl);
 1423:     exit(0);
 1424:   }
 1425:   printf("Computing Variance-covariance of Prevalence limit: file '%s' \n", fileresvpl);
 1426: 
 1427: 
 1428:   fprintf(ficresvpl,"# Standard deviation of prevalences limit\n");
 1429:   fprintf(ficresvpl,"# Age");
 1430:   for(i=1; i<=nlstate;i++)
 1431:       fprintf(ficresvpl," %1d-%1d",i,i);
 1432:   fprintf(ficresvpl,"\n");
 1433: 
 1434:   xp=vector(1,npar);
 1435:   dnewm=matrix(1,nlstate,1,npar);
 1436:   doldm=matrix(1,nlstate,1,nlstate);
 1437:   
 1438:   hstepm=1*YEARM; /* Every year of age */
 1439:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
 1440:   agelim = AGESUP;
 1441:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 1442:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 1443:     if (stepm >= YEARM) hstepm=1;
 1444:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 1445:     gradg=matrix(1,npar,1,nlstate);
 1446:     gp=vector(1,nlstate);
 1447:     gm=vector(1,nlstate);
 1448: 
 1449:     for(theta=1; theta <=npar; theta++){
 1450:       for(i=1; i<=npar; i++){ /* Computes gradient */
 1451: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 1452:       }
 1453:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl);
 1454:       for(i=1;i<=nlstate;i++)
 1455: 	gp[i] = prlim[i][i];
 1456:     
 1457:       for(i=1; i<=npar; i++) /* Computes gradient */
 1458: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 1459:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl);
 1460:       for(i=1;i<=nlstate;i++)
 1461: 	gm[i] = prlim[i][i];
 1462: 
 1463:       for(i=1;i<=nlstate;i++)
 1464: 	gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
 1465:     } /* End theta */
 1466: 
 1467:     trgradg =matrix(1,nlstate,1,npar);
 1468: 
 1469:     for(j=1; j<=nlstate;j++)
 1470:       for(theta=1; theta <=npar; theta++)
 1471: 	trgradg[j][theta]=gradg[theta][j];
 1472: 
 1473:     for(i=1;i<=nlstate;i++)
 1474:       varpl[i][(int)age] =0.;
 1475:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 1476:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 1477:     for(i=1;i<=nlstate;i++)
 1478:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
 1479: 
 1480:     fprintf(ficresvpl,"%.0f ",age );
 1481:     for(i=1; i<=nlstate;i++)
 1482:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
 1483:     fprintf(ficresvpl,"\n");
 1484:     free_vector(gp,1,nlstate);
 1485:     free_vector(gm,1,nlstate);
 1486:     free_matrix(gradg,1,npar,1,nlstate);
 1487:     free_matrix(trgradg,1,nlstate,1,npar);
 1488:   } /* End age */
 1489:   fclose(ficresvpl);
 1490:   free_vector(xp,1,npar);
 1491:   free_matrix(doldm,1,nlstate,1,npar);
 1492:   free_matrix(dnewm,1,nlstate,1,nlstate);
 1493: 
 1494: }
 1495: 
 1496: 
 1497: 
 1498: /***********************************************/
 1499: /**************** Main Program *****************/
 1500: /***********************************************/
 1501: 
 1502: /*int main(int argc, char *argv[])*/
 1503: int main()
 1504: {
 1505: 
 1506:   int i,j, k, n=MAXN,iter,m,size;
 1507:   double agedeb, agefin,hf;
 1508:   double agemin=1.e20, agemax=-1.e20;
 1509: 
 1510:   double fret;
 1511:   double **xi,tmp,delta;
 1512: 
 1513:   double dum; /* Dummy variable */
 1514:   double ***p3mat;
 1515:   int *indx;
 1516:   char line[MAXLINE], linepar[MAXLINE];
 1517:   char title[MAXLINE];
 1518:   char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
 1519:   char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH];
 1520:   char filerest[FILENAMELENGTH];
 1521:   char fileregp[FILENAMELENGTH];
 1522:   char path[80],pathc[80],pathcd[80],pathtot[80];
 1523:   int firstobs=1, lastobs=10;
 1524:   int sdeb, sfin; /* Status at beginning and end */
 1525:   int c,  h , cpt,l;
 1526:   int ju,jl, mi;
 1527:   int i1,j1, k1,jk,aa,bb, stepsize;
 1528:   int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,**adl,*tab;
 1529:   
 1530:   int hstepm, nhstepm;
 1531:   double bage, fage, age, agelim, agebase;
 1532:   double ftolpl=FTOL;
 1533:   double **prlim;
 1534:   double *severity;
 1535:   double ***param; /* Matrix of parameters */
 1536:   double  *p;
 1537:   double **matcov; /* Matrix of covariance */
 1538:   double ***delti3; /* Scale */
 1539:   double *delti; /* Scale */
 1540:   double ***eij, ***vareij;
 1541:   double **varpl; /* Variances of prevalence limits by age */
 1542:   double *epj, vepp;
 1543:   char version[80]="Imach version 0.64, May 2000, INED-EUROREVES ";
 1544:   char *alph[]={"a","a","b","c","d","e"}, str[4];
 1545:   char z[1]="c";
 1546: #include <sys/time.h>
 1547: #include <time.h>
 1548: 
 1549:   /* long total_usecs;
 1550:   struct timeval start_time, end_time;
 1551:   
 1552:   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
 1553: 
 1554: 
 1555:   printf("\nIMACH, Version 0.64");
 1556:   printf("\nEnter the parameter file name: ");
 1557: #define windows 1
 1558: #ifdef windows
 1559:   scanf("%s",pathtot);
 1560:   getcwd(pathcd, size);
 1561:   cut(path,optionfile,pathtot);
 1562:   chdir(path);
 1563:   replace(pathc,path);
 1564: #endif
 1565: #ifdef unix
 1566:   scanf("%s",optionfile);
 1567: #endif
 1568: 
 1569: /*-------- arguments in the command line --------*/
 1570: 
 1571:   strcpy(fileres,"r");
 1572:   strcat(fileres, optionfile);
 1573: 
 1574:   /*---------arguments file --------*/
 1575: 
 1576:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
 1577:     printf("Problem with optionfile %s\n",optionfile);
 1578:     goto end;
 1579:   }
 1580: 
 1581:   strcpy(filereso,"o");
 1582:   strcat(filereso,fileres);
 1583:   if((ficparo=fopen(filereso,"w"))==NULL) {
 1584:     printf("Problem with Output resultfile: %s\n", filereso);goto end;
 1585:   }
 1586: 
 1587: /*--------- index.htm --------*/
 1588: 
 1589:   if((fichtm=fopen("index.htm","w"))==NULL)    {
 1590:     printf("Problem with index.htm \n");goto end;
 1591:   }
 1592: 
 1593:  fprintf(fichtm,"<body><ul><li>Outputs files<br><br>\n
 1594:         - Observed prevalence in each state: <a href=\"p%s\">p%s</a> <br>\n
 1595: - Estimated parameters and the covariance matrix: <a href=\"%s\">%s</a> <br>
 1596:         - Stationary prevalence in each state: <a href=\"pl%s\">pl%s</a> <br>
 1597:         - Transition probabilities: <a href=\"pij%s\">pij%s</a><br>
 1598:         - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>
 1599:         - Life expectancies by age and initial health status: <a href=\"e%s\">e%s</a> <br>
 1600:         - Variances of life expectancies by age and initial health status: <a href=\"v%s\">v%s</a><br>
 1601:         - Health expectancies with their variances: <a href=\"t%s\">t%s</a> <br>
 1602:         - Standard deviation of stationary prevalences: <a href=\"vpl%s\">vpl%s</a> <br><br>",fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres);
 1603: 
 1604:  fprintf(fichtm," <li>Graphs<br> <br>");
 1605:  
 1606: for(cpt=1; cpt<nlstate;cpt++)
 1607:    fprintf(fichtm,"- Prevalence of disability: p%s1.gif<br>
 1608: <img src=\"p%s1.gif\"><br>",strtok(optionfile, "."),strtok(optionfile, "."),cpt);
 1609:  for(cpt=1; cpt<=nlstate;cpt++)
 1610:      fprintf(fichtm,"- Observed and stationary  prevalence (with confident
 1611: interval) in state (%d): v%s%d.gif <br>
 1612: <img src=\"v%s%d.gif\"><br>",cpt,strtok(optionfile, "."),cpt,strtok(optionfile, "."),cpt);
 1613:  
 1614:  for(cpt=1; cpt<=nlstate;cpt++)
 1615:      fprintf(fichtm,"- Health life expectancies by age and initial health state (%d): exp%s%d.gif <br>
 1616: <img src=\"ex%s%d.gif\"><br>",cpt,strtok(optionfile, "."),cpt,strtok(optionfile, "."),cpt);
 1617:    
 1618:  fprintf(fichtm,"- Total life expectancy by age and
 1619:         health expectancies in states (1) and (2): e%s.gif<br>
 1620: 	<img src=\"e%s.gif\"></li> </ul></body>",strtok(optionfile, "."),strtok(optionfile, "."));
 1621: 
 1622: 
 1623: fclose(fichtm);
 1624: 
 1625:   /* Reads comments: lines beginning with '#' */
 1626:   while((c=getc(ficpar))=='#' && c!= EOF){
 1627:     ungetc(c,ficpar);
 1628:     fgets(line, MAXLINE, ficpar);
 1629:     puts(line);
 1630:     fputs(line,ficparo);
 1631:   }
 1632:   ungetc(c,ficpar);
 1633: 
 1634:   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\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncov, &nlstate,&ndeath, &maxwav, &mle, &weightopt);
 1635:   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\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncov, nlstate,ndeath, maxwav, mle, weightopt);
 1636:   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\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncov,nlstate,ndeath,maxwav, mle, weightopt);
 1637:   
 1638:   nvar=ncov-1; /* Suppressing age as a basic covariate */
 1639:   
 1640:   /* Read guess parameters */
 1641:   /* Reads comments: lines beginning with '#' */
 1642:   while((c=getc(ficpar))=='#' && c!= EOF){
 1643:     ungetc(c,ficpar);
 1644:     fgets(line, MAXLINE, ficpar);
 1645:     puts(line);
 1646:     fputs(line,ficparo);
 1647:   }
 1648:   ungetc(c,ficpar);
 1649:   
 1650:   param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncov);
 1651:     for(i=1; i <=nlstate; i++)
 1652:     for(j=1; j <=nlstate+ndeath-1; j++){
 1653:       fscanf(ficpar,"%1d%1d",&i1,&j1);
 1654:       fprintf(ficparo,"%1d%1d",i1,j1);
 1655:       printf("%1d%1d",i,j);
 1656:       for(k=1; k<=ncov;k++){
 1657: 	fscanf(ficpar," %lf",&param[i][j][k]);
 1658: 	printf(" %lf",param[i][j][k]);
 1659: 	fprintf(ficparo," %lf",param[i][j][k]);
 1660:       }
 1661:       fscanf(ficpar,"\n");
 1662:       printf("\n");
 1663:       fprintf(ficparo,"\n");
 1664:     }
 1665:   
 1666:   npar= (nlstate+ndeath-1)*nlstate*ncov;
 1667:   p=param[1][1];
 1668:   
 1669:   /* Reads comments: lines beginning with '#' */
 1670:   while((c=getc(ficpar))=='#' && c!= EOF){
 1671:     ungetc(c,ficpar);
 1672:     fgets(line, MAXLINE, ficpar);
 1673:     puts(line);
 1674:     fputs(line,ficparo);
 1675:   }
 1676:   ungetc(c,ficpar);
 1677: 
 1678:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncov);
 1679:   delti=vector(1,npar); /* Scale of each paramater (output from hesscov) */
 1680:   for(i=1; i <=nlstate; i++){
 1681:     for(j=1; j <=nlstate+ndeath-1; j++){
 1682:       fscanf(ficpar,"%1d%1d",&i1,&j1);
 1683:       printf("%1d%1d",i,j);
 1684:       fprintf(ficparo,"%1d%1d",i1,j1);
 1685:       for(k=1; k<=ncov;k++){
 1686: 	fscanf(ficpar,"%le",&delti3[i][j][k]);
 1687: 	printf(" %le",delti3[i][j][k]);
 1688: 	fprintf(ficparo," %le",delti3[i][j][k]);
 1689:       }
 1690:       fscanf(ficpar,"\n");
 1691:       printf("\n");
 1692:       fprintf(ficparo,"\n");
 1693:     }
 1694:   }
 1695:   delti=delti3[1][1];
 1696:   
 1697:   /* Reads comments: lines beginning with '#' */
 1698:   while((c=getc(ficpar))=='#' && c!= EOF){
 1699:     ungetc(c,ficpar);
 1700:     fgets(line, MAXLINE, ficpar);
 1701:     puts(line);
 1702:     fputs(line,ficparo);
 1703:   }
 1704:   ungetc(c,ficpar);
 1705:   
 1706:   matcov=matrix(1,npar,1,npar);
 1707:   for(i=1; i <=npar; i++){
 1708:     fscanf(ficpar,"%s",&str);
 1709:     printf("%s",str);
 1710:     fprintf(ficparo,"%s",str);
 1711:     for(j=1; j <=i; j++){
 1712:       fscanf(ficpar," %le",&matcov[i][j]);
 1713:       printf(" %.5le",matcov[i][j]);
 1714:       fprintf(ficparo," %.5le",matcov[i][j]);
 1715:     }
 1716:     fscanf(ficpar,"\n");
 1717:     printf("\n");
 1718:     fprintf(ficparo,"\n");
 1719:   }
 1720:   for(i=1; i <=npar; i++)
 1721:     for(j=i+1;j<=npar;j++)
 1722:       matcov[i][j]=matcov[j][i];
 1723:    
 1724:   printf("\n");
 1725:   
 1726:   
 1727:   if(mle==1){
 1728:     /*-------- data file ----------*/
 1729:     if((ficres =fopen(fileres,"w"))==NULL) {
 1730:       printf("Problem with resultfile: %s\n", fileres);goto end;
 1731:     }
 1732:     fprintf(ficres,"#%s\n",version);
 1733:     
 1734:     if((fic=fopen(datafile,"r"))==NULL)    {
 1735:       printf("Problem with datafile: %s\n", datafile);goto end;
 1736:     }
 1737:     
 1738:     n= lastobs;
 1739:     severity = vector(1,maxwav);
 1740:     outcome=imatrix(1,maxwav+1,1,n);
 1741:     num=ivector(1,n);
 1742:     moisnais=vector(1,n);
 1743:     annais=vector(1,n);
 1744:     moisdc=vector(1,n);
 1745:     andc=vector(1,n);
 1746:     agedc=vector(1,n);
 1747:     cod=ivector(1,n);
 1748:     weight=vector(1,n);
 1749:     for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
 1750:     mint=matrix(1,maxwav,1,n);
 1751:     anint=matrix(1,maxwav,1,n);
 1752:     covar=matrix(1,NCOVMAX,1,n);
 1753:     s=imatrix(1,maxwav+1,1,n);
 1754:     adl=imatrix(1,maxwav+1,1,n);    
 1755:     tab=ivector(1,NCOVMAX);
 1756:     i=1; 
 1757:     while (fgets(line, MAXLINE, fic) != NULL)    {
 1758:       if ((i >= firstobs) && (i <lastobs)) {
 1759: sscanf(line,"%d %lf %lf %lf %lf/%lf %lf/%lf %lf/%lf %d %lf/%lf %d %lf/%lf %d %lf/%lf %d", &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]);
 1760: 	i=i+1;
 1761:       }
 1762:     } 
 1763:   imx=i-1; /* Number of individuals */
 1764: 
 1765:     fclose(fic);
 1766: 
 1767:     if (weightopt != 1) { /* Maximisation without weights*/
 1768:       for(i=1;i<=n;i++) weight[i]=1.0;
 1769:     }
 1770:     /*-calculation of age at interview from date of interview and age at death -*/
 1771:     agev=matrix(1,maxwav,1,imx);
 1772:     
 1773:     for (i=1; i<=imx; i++)  {
 1774:       agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
 1775:       for(m=1; (m<= maxwav); m++){
 1776: 	if(s[m][i] >0){
 1777: 	  if (s[m][i] == nlstate+1) {
 1778: 	    if(agedc[i]>0)
 1779: 	      agev[m][i]=agedc[i];
 1780: 	    else{
 1781: 	      printf("Warning negative age at death: %d line:%d\n",num[i],i);
 1782: 	      agev[m][i]=-1;
 1783: 	    }
 1784: 	  }
 1785: 	  else if(s[m][i] !=9){ /* Should no more exist */
 1786: 	    agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
 1787: 	    if(mint[m][i]==99 || anint[m][i]==9999)
 1788: 	      agev[m][i]=1;
 1789: 	    else if(agev[m][i] <agemin){ 
 1790: 	      agemin=agev[m][i];
 1791: 	      /*printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);*/
 1792: 	    }
 1793: 	    else if(agev[m][i] >agemax){
 1794: 	      agemax=agev[m][i];
 1795: 	     /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/
 1796: 	    }
 1797: 	    /*agev[m][i]=anint[m][i]-annais[i];*/
 1798: 	    /*	 agev[m][i] = age[i]+2*m;*/
 1799: 	  }
 1800: 	  else { /* =9 */
 1801: 	    agev[m][i]=1;
 1802: 	    s[m][i]=-1;
 1803: 	  }
 1804: 	}
 1805: 	else /*= 0 Unknown */
 1806: 	  agev[m][i]=1;
 1807:       }
 1808:     
 1809:     }
 1810:     for (i=1; i<=imx; i++)  {
 1811:       for(m=1; (m<= maxwav); m++){
 1812: 	if (s[m][i] > (nlstate+ndeath)) {
 1813: 	  printf("Error: Wrong value in nlstate or ndeath\n");	
 1814: 	  goto end;
 1815: 	}
 1816:       }
 1817:     }
 1818: 
 1819: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
 1820: 
 1821:     free_vector(severity,1,maxwav);
 1822:     free_imatrix(outcome,1,maxwav+1,1,n);
 1823:     free_vector(moisnais,1,n);
 1824:     free_vector(annais,1,n);
 1825:     free_matrix(mint,1,maxwav,1,n);
 1826:     free_matrix(anint,1,maxwav,1,n);
 1827:     free_vector(moisdc,1,n);
 1828:     free_vector(andc,1,n);
 1829: 
 1830:    
 1831:     wav=ivector(1,imx);
 1832:     dh=imatrix(1,lastpass-firstpass+1,1,imx);
 1833:     mw=imatrix(1,lastpass-firstpass+1,1,imx);
 1834:    
 1835:     /* Concatenates waves */
 1836:       concatwav(wav, dh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
 1837:     
 1838:    /* Calculates basic frequencies. Computes observed prevalence at single age
 1839:        and prints on file fileres'p'. */
 1840:       freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx); 
 1841: 
 1842:     pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 1843:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 1844:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 1845:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 1846:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
 1847:     
 1848:     /* For Powell, parameters are in a vector p[] starting at p[1]
 1849:        so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
 1850:     p=param[1][1]; /* *(*(*(param +1)+1)+0) */
 1851:     
 1852:     mlikeli(ficres,p, npar, ncov, nlstate, ftol, func);
 1853: 
 1854:     
 1855:     /*--------- results files --------------*/
 1856:     fprintf(ficres,"\ntitle=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncov=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncov, nlstate, ndeath, maxwav, mle,weightopt);
 1857:     
 1858:    jk=1;
 1859:    fprintf(ficres,"# Parameters\n");
 1860:    printf("# Parameters\n");
 1861:    for(i=1,jk=1; i <=nlstate; i++){
 1862:      for(k=1; k <=(nlstate+ndeath); k++){
 1863:        if (k != i) 
 1864: 	 {
 1865: 	   printf("%d%d ",i,k);
 1866: 	   fprintf(ficres,"%1d%1d ",i,k);
 1867: 	   for(j=1; j <=ncov; j++){
 1868: 	     printf("%f ",p[jk]);
 1869: 	     fprintf(ficres,"%f ",p[jk]);
 1870: 	     jk++; 
 1871: 	   }
 1872: 	   printf("\n");
 1873: 	   fprintf(ficres,"\n");
 1874: 	 }
 1875:      }
 1876:    }
 1877: 
 1878:     /* Computing hessian and covariance matrix */
 1879:     ftolhess=ftol; /* Usually correct */
 1880:     hesscov(matcov, p, npar, delti, ftolhess, func);
 1881:     fprintf(ficres,"# Scales\n");
 1882:     printf("# Scales\n");
 1883:      for(i=1,jk=1; i <=nlstate; i++){
 1884:       for(j=1; j <=nlstate+ndeath; j++){
 1885: 	if (j!=i) {
 1886: 	  fprintf(ficres,"%1d%1d",i,j);
 1887: 	  printf("%1d%1d",i,j);
 1888: 	  for(k=1; k<=ncov;k++){
 1889: 	    printf(" %.5e",delti[jk]);
 1890: 	    fprintf(ficres," %.5e",delti[jk]);
 1891: 	    jk++;
 1892: 	  }
 1893: 	  printf("\n");
 1894: 	  fprintf(ficres,"\n");
 1895: 	}
 1896:       }
 1897:       }
 1898:     
 1899:     k=1;
 1900:     fprintf(ficres,"# Covariance\n");
 1901:     printf("# Covariance\n");
 1902:     for(i=1;i<=npar;i++){
 1903:       /*  if (k>nlstate) k=1;
 1904:       i1=(i-1)/(ncov*nlstate)+1; 
 1905:       fprintf(ficres,"%s%d%d",alph[k],i1,tab[i]);
 1906:       printf("%s%d%d",alph[k],i1,tab[i]);*/
 1907:       fprintf(ficres,"%3d",i);
 1908:       printf("%3d",i);
 1909:       for(j=1; j<=i;j++){
 1910: 	fprintf(ficres," %.5e",matcov[i][j]);
 1911: 	printf(" %.5e",matcov[i][j]);
 1912:       }
 1913:       fprintf(ficres,"\n");
 1914:       printf("\n");
 1915:       k++;
 1916:     }
 1917:     
 1918:     while((c=getc(ficpar))=='#' && c!= EOF){
 1919:       ungetc(c,ficpar);
 1920:       fgets(line, MAXLINE, ficpar);
 1921:       puts(line);
 1922:       fputs(line,ficparo);
 1923:     }
 1924:     ungetc(c,ficpar);
 1925:   
 1926:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf\n",&agemin,&agemax, &bage, &fage);
 1927:     
 1928:     if (fage <= 2) {
 1929:       bage = agemin;
 1930:       fage = agemax;
 1931:     }
 1932: 
 1933:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
 1934:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f\n",agemin,agemax,bage,fage);
 1935: /*------------ gnuplot -------------*/
 1936: chdir(pathcd);
 1937:   if((ficgp=fopen("graph.gp","w"))==NULL) {
 1938:     printf("Problem with file graph.gp");goto end;
 1939:   }
 1940: #ifdef windows
 1941:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 1942: #endif
 1943:    /* 1eme*/
 1944: 
 1945:   for (cpt=1; cpt<= nlstate ; cpt ++) {
 1946: #ifdef windows
 1947:     fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \nset ter gif small size 400,300\nplot [%.f:%.f] \"vpl%s\" u 1:%d \"\%%lf",agemin,fage,fileres,cpt*2);
 1948: #endif
 1949: #ifdef unix
 1950: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \nplot [%.f:%.f] \"vpl%s\" u 1:%d \"\%%lf",agemin,fage,fileres,cpt*2);
 1951: #endif
 1952:     for (i=1; i<= nlstate ; i ++) fprintf(ficgp," \%%lf (\%%lf)");
 1953:     fprintf(ficgp,"\" t\"Stationary prevalence\" w l 0,\"vpl%s\" u 1:($%d+2*$%d) \"\%%lf",fileres,2*cpt,cpt*2+1);
 1954:     for (i=1; i<= nlstate ; i ++) fprintf(ficgp," \%%lf (\%%lf)");
 1955:   fprintf(ficgp,"\" t\"95\%% CI\" w l 1,\"vpl%s\" u 1:($%d-2*$%d) \"\%%lf",fileres,2*cpt,2*cpt+1); 
 1956:      for (i=1; i<= nlstate ; i ++) fprintf(ficgp," \%%lf (\%%lf)"); 
 1957:      fprintf(ficgp,"\" t\"\" w l 1,\"p%s\" u 1:($%d) t\"Observed prevalence \" w l 2",fileres,2+4*(cpt-1));
 1958: #ifdef unix
 1959: fprintf(ficgp,"\nset ter gif small size 400,300");
 1960: #endif
 1961: fprintf(ficgp,"\nset out \"v%s%d.gif\" \nreplot\n\n",strtok(optionfile, "."),cpt);
 1962:  
 1963:   }
 1964:   /*2 eme*/
 1965:  
 1966:   fprintf(ficgp,"set ylabel \"Years\" \nset ter gif small size 400,300\nplot [%.f:%.f] ",agemin,fage);
 1967:   for (i=1; i<= nlstate+1 ; i ++) {
 1968: k=2*i;
 1969:     fprintf(ficgp,"\"t%s\" u 1:%d \"\%%lf \%%lf (\%%lf) \%%lf (\%%lf)",fileres,k);
 1970:     for (j=1; j< nlstate ; j ++) fprintf(ficgp," \%%lf (\%%lf)");
 1971:     if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
 1972:     else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
 1973:     fprintf(ficgp,"\"t%s\" u 1:($%d-2*$%d) \"\%%lf \%%lf (\%%lf) \%%lf (\%%lf)",fileres,k,k+1);
 1974:     for (j=1; j< nlstate ; j ++) fprintf(ficgp," \%%lf (\%%lf)");
 1975:     fprintf(ficgp,"\" t\"\" w l 0,");
 1976: fprintf(ficgp,"\"t%s\" u 1:($%d+2*$%d) \"\%%lf \%%lf (\%%lf) \%%lf (\%%lf)",fileres,k,k+1);
 1977:     for (j=1; j< nlstate ; j ++) fprintf(ficgp," \%%lf (\%%lf)");
 1978:     if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");
 1979: else fprintf(ficgp,"\" t\"\" w l 0,");
 1980:   } 
 1981:   fprintf(ficgp,"\nset out \"e%s.gif\" \nreplot\n\n",strtok(optionfile, "."));
 1982: 
 1983:   /*3eme*/
 1984: for (cpt=1; cpt<= nlstate ; cpt ++) {
 1985:   k=2+nlstate*(cpt-1);
 1986:     fprintf(ficgp,"set ter gif small size 400,300\nplot [%.f:%.f] \"e%s\" u 1:%d t \"e%d1\" w l",agemin,fage,fileres,k,cpt);
 1987: for (i=1; i< nlstate ; i ++) {
 1988: fprintf(ficgp,",\"e%s\" u 1:%d t \"e%d%d\" w l",fileres,k+1,cpt,i+1);
 1989: } 
 1990: fprintf(ficgp,"\nset out \"ex%s%d.gif\" \nreplot\n\n",strtok(optionfile, "."),cpt);
 1991: }
 1992:  
 1993: /* CV preval stat */
 1994: for (cpt=1; cpt<nlstate ; cpt ++) {
 1995:     k=3;
 1996:     fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \nset ter gif small size 400,300\nplot [%.f:%.f] \"pij%s\" u 2:($%d/($%d",agemin,agemax,fileres,k+cpt,k);
 1997:     for (i=1; i< nlstate ; i ++)
 1998:       fprintf(ficgp,"+$%d",k+i);
 1999:     fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);
 2000:     
 2001:  l=3+(nlstate+ndeath)*cpt;
 2002:    fprintf(ficgp,",\"pij%s\" u 2:($%d/($%d",fileres,l+cpt,l);
 2003:  
 2004:    for (i=1; i< nlstate ; i ++) {
 2005:    l=3+(nlstate+ndeath)*cpt;
 2006:     fprintf(ficgp,"+$%d",l+i);
 2007:    }
 2008:   fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);
 2009:   
 2010:   
 2011:   fprintf(ficgp,"set out \"p%s%d.gif\" \nreplot\n\n",strtok(optionfile, "."),cpt);
 2012:   } 
 2013: 
 2014: 
 2015:   fclose(ficgp);
 2016:    
 2017: chdir(path);
 2018:     free_matrix(agev,1,maxwav,1,imx);
 2019:     free_ivector(wav,1,imx);
 2020:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
 2021:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
 2022:     
 2023:     free_imatrix(s,1,maxwav+1,1,n);
 2024:     
 2025:     
 2026:     free_ivector(num,1,n);
 2027:     free_vector(agedc,1,n);
 2028:     free_vector(weight,1,n);
 2029:     free_matrix(covar,1,NCOVMAX,1,n);
 2030:     fclose(ficparo);
 2031:     fclose(ficres);
 2032:   }
 2033: 
 2034:   /*________fin mle=1_________*/
 2035:   
 2036:   
 2037: 
 2038:   /* No more information from the sample is required now */
 2039:   /* Reads comments: lines beginning with '#' */
 2040:   while((c=getc(ficpar))=='#' && c!= EOF){
 2041:     ungetc(c,ficpar);
 2042:     fgets(line, MAXLINE, ficpar);
 2043:     puts(line);
 2044:     fputs(line,ficparo);
 2045:   }
 2046:   ungetc(c,ficpar);
 2047:   
 2048:   fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf\n",&agemin,&agemax, &bage, &fage);
 2049:   printf("agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f\n",agemin,agemax, bage, fage);
 2050:   fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f\n",agemin,agemax,bage,fage);
 2051: 
 2052:   /*--------------- Prevalence limit --------------*/
 2053:   
 2054:   strcpy(filerespl,"pl");
 2055:   strcat(filerespl,fileres);
 2056:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
 2057:     printf("Problem with Prev limit resultfile: %s\n", filerespl);goto end;
 2058:   }
 2059:   printf("Computing prevalence limit: result on file '%s' \n", filerespl);
 2060:   fprintf(ficrespl,"#Prevalence limit\n");
 2061:   fprintf(ficrespl,"#Age ");
 2062:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
 2063:   fprintf(ficrespl,"\n");
 2064:   
 2065:   prlim=matrix(1,nlstate,1,nlstate);
 2066:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 2067:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 2068:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 2069:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 2070:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
 2071:   
 2072:   agebase=agemin;
 2073:   agelim=agemax;
 2074:   ftolpl=1.e-10;
 2075:   for (age=agebase; age<=agelim; age++){
 2076:     prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl);
 2077:     fprintf(ficrespl,"%.0f",age );
 2078:     for(i=1; i<=nlstate;i++)
 2079:       fprintf(ficrespl," %.5f", prlim[i][i]);
 2080:     fprintf(ficrespl,"\n");
 2081:   }
 2082:   fclose(ficrespl);
 2083:   
 2084:   /*------------- h Pij x at various ages ------------*/
 2085:   
 2086:   strcpy(filerespij,"pij");  strcat(filerespij,fileres);
 2087:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
 2088:     printf("Problem with Pij resultfile: %s\n", filerespij);goto end;
 2089:   }
 2090:   printf("Computing pij: result on file '%s' \n", filerespij);
 2091:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 2092:   if (stepm<=24) stepsize=2;
 2093: 
 2094:   agelim=AGESUP;
 2095:   hstepm=stepsize*YEARM; /* Every year of age */
 2096:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
 2097:   for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
 2098:     nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 2099:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 2100:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 2101:     oldm=oldms;savm=savms;
 2102:     hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm);  
 2103:     fprintf(ficrespij,"# Age");
 2104:     for(i=1; i<=nlstate;i++)
 2105:       for(j=1; j<=nlstate+ndeath;j++)
 2106: 	fprintf(ficrespij," %1d-%1d",i,j);
 2107:     fprintf(ficrespij,"\n");
 2108:     for (h=0; h<=nhstepm; h++){
 2109:       fprintf(ficrespij,"%.0f %.0f",agedeb, agedeb+ h*hstepm/YEARM*stepm );
 2110:       for(i=1; i<=nlstate;i++)
 2111: 	for(j=1; j<=nlstate+ndeath;j++)
 2112: 	  fprintf(ficrespij," %.5f", p3mat[i][j][h]);
 2113:       fprintf(ficrespij,"\n");
 2114:     }
 2115:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 2116:     fprintf(ficrespij,"\n");
 2117:   }
 2118:   fclose(ficrespij);
 2119: 
 2120:   /*---------- Health expectancies and variances ------------*/
 2121:   
 2122:   eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 2123:   oldm=oldms;savm=savms;
 2124:   evsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm);
 2125:   
 2126:   vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 2127:   oldm=oldms;savm=savms;
 2128:   varevsij(fileres, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl);
 2129: 
 2130:   strcpy(filerest,"t");
 2131:   strcat(filerest,fileres);
 2132:   if((ficrest=fopen(filerest,"w"))==NULL) {
 2133:     printf("Problem with total LE resultfile: %s\n", filerest);goto end;
 2134:   }
 2135:   printf("Computing Total LEs with variances: file '%s' \n", filerest);
 2136:   fprintf(ficrest,"#Total LEs with variances: e.. (std) ");
 2137:   for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
 2138:   fprintf(ficrest,"\n");
 2139: 
 2140:   hf=1;
 2141:   if (stepm >= YEARM) hf=stepm/YEARM;
 2142:   epj=vector(1,nlstate+1);
 2143:   for(age=bage; age <=fage ;age++){
 2144:     prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl);
 2145:     fprintf(ficrest," %.0f",age);
 2146:     for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
 2147:       for(i=1, epj[j]=0.;i <=nlstate;i++) {
 2148: 	epj[j] += prlim[i][i]*hf*eij[i][j][(int)age];
 2149:       }
 2150:       epj[nlstate+1] +=epj[j];
 2151:     }
 2152:     for(i=1, vepp=0.;i <=nlstate;i++)
 2153:       for(j=1;j <=nlstate;j++)
 2154: 	vepp += vareij[i][j][(int)age];
 2155:     fprintf(ficrest," %.2f (%.2f)", epj[nlstate+1],hf*sqrt(vepp));
 2156:     for(j=1;j <=nlstate;j++){
 2157:       fprintf(ficrest," %.2f (%.2f)", epj[j],hf*sqrt(vareij[j][j][(int)age]));
 2158:     }
 2159:     fprintf(ficrest,"\n");
 2160:   }
 2161:   fclose(ficrest);
 2162:   fclose(ficpar);
 2163:   free_vector(epj,1,nlstate+1);
 2164: 
 2165:   /*------- Variance limit prevalence------*/   
 2166: 
 2167:   varpl=matrix(1,nlstate,(int) bage, (int) fage);
 2168:   oldm=oldms;savm=savms;
 2169:   varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl);
 2170:   
 2171:   
 2172:   free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
 2173:   
 2174:   free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 2175:   free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 2176:   
 2177:   
 2178:   free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
 2179:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
 2180:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
 2181:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
 2182:   
 2183:   free_matrix(matcov,1,npar,1,npar);
 2184:   free_vector(delti,1,npar);
 2185:   
 2186:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncov);
 2187: 
 2188:   printf("End of Imach\n");
 2189:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
 2190:   
 2191:   /* 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);*/
 2192:   /*printf("Total time was %d uSec.\n", total_usecs);*/
 2193:   /*------ End -----------*/
 2194: 
 2195:  end:
 2196: #ifdef windows
 2197:  chdir(pathcd);
 2198: #endif 
 2199:  system("gnuplot graph.gp");
 2200: 
 2201: #ifdef windows
 2202:   while (z[0] != 'q') {
 2203:     chdir(pathcd); 
 2204:     printf("\nType e to edit output files, c to start again, and q for exiting: ");
 2205:     scanf("%s",z);
 2206:     if (z[0] == 'c') system("./imach");
 2207:     else if (z[0] == 'e') {
 2208:       chdir(path);
 2209:       system("index.htm");
 2210:     }
 2211:     else if (z[0] == 'q') exit(0);
 2212:   }
 2213: #endif 
 2214: }
 2215: 

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