File:  [Local Repository] / imach / src / imach.c
Revision 1.74: download - view: text, annotated - select for diffs
Fri May 2 18:51:41 2003 UTC (21 years ago) by brouard
Branches: MAIN
CVS tags: HEAD
Check memory allocation through valgrind on Linux and libnjamd .
So it is free of malloc bugs now!
Version 0.95

    1: /* $Id: imach.c,v 1.74 2003/05/02 18:51:41 brouard Exp $
    2:    Interpolated Markov Chain
    3: 
    4:   Short summary of the programme:
    5:   
    6:   This program computes Healthy Life Expectancies from
    7:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
    8:   first survey ("cross") where individuals from different ages are
    9:   interviewed on their health status or degree of disability (in the
   10:   case of a health survey which is our main interest) -2- at least a
   11:   second wave of interviews ("longitudinal") which measure each change
   12:   (if any) in individual health status.  Health expectancies are
   13:   computed from the time spent in each health state according to a
   14:   model. More health states you consider, more time is necessary to reach the
   15:   Maximum Likelihood of the parameters involved in the model.  The
   16:   simplest model is the multinomial logistic model where pij is the
   17:   probability to be observed in state j at the second wave
   18:   conditional to be observed in state i at the first wave. Therefore
   19:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
   20:   'age' is age and 'sex' is a covariate. If you want to have a more
   21:   complex model than "constant and age", you should modify the program
   22:   where the markup *Covariates have to be included here again* invites
   23:   you to do it.  More covariates you add, slower the
   24:   convergence.
   25: 
   26:   The advantage of this computer programme, compared to a simple
   27:   multinomial logistic model, is clear when the delay between waves is not
   28:   identical for each individual. Also, if a individual missed an
   29:   intermediate interview, the information is lost, but taken into
   30:   account using an interpolation or extrapolation.  
   31: 
   32:   hPijx is the probability to be observed in state i at age x+h
   33:   conditional to the observed state i at age x. The delay 'h' can be
   34:   split into an exact number (nh*stepm) of unobserved intermediate
   35:   states. This elementary transition (by month, quarter,
   36:   semester or year) is modelled as a multinomial logistic.  The hPx
   37:   matrix is simply the matrix product of nh*stepm elementary matrices
   38:   and the contribution of each individual to the likelihood is simply
   39:   hPijx.
   40: 
   41:   Also this programme outputs the covariance matrix of the parameters but also
   42:   of the life expectancies. It also computes the stable prevalence. 
   43:   
   44:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
   45:            Institut national d'études démographiques, Paris.
   46:   This software have been partly granted by Euro-REVES, a concerted action
   47:   from the European Union.
   48:   It is copyrighted identically to a GNU software product, ie programme and
   49:   software can be distributed freely for non commercial use. Latest version
   50:   can be accessed at http://euroreves.ined.fr/imach .
   51: 
   52:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
   53:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
   54:   
   55:   **********************************************************************/
   56: /*
   57:   main
   58:   read parameterfile
   59:   read datafile
   60:   concatwav
   61:   if (mle >= 1)
   62:     mlikeli
   63:   print results files
   64:   if mle==1 
   65:      computes hessian
   66:   read end of parameter file: agemin, agemax, bage, fage, estepm
   67:       begin-prev-date,...
   68:   open gnuplot file
   69:   open html file
   70:   stable prevalence
   71:    for age prevalim()
   72:   h Pij x
   73:   variance of p varprob
   74:   forecasting if prevfcast==1 prevforecast call prevalence()
   75:   health expectancies
   76:   Variance-covariance of DFLE
   77:   prevalence()
   78:    movingaverage()
   79:   varevsij() 
   80:   if popbased==1 varevsij(,popbased)
   81:   total life expectancies
   82:   Variance of stable prevalence
   83:  end
   84: */
   85: 
   86: 
   87: 
   88:  
   89: #include <math.h>
   90: #include <stdio.h>
   91: #include <stdlib.h>
   92: #include <unistd.h>
   93: 
   94: #define MAXLINE 256
   95: #define GNUPLOTPROGRAM "gnuplot"
   96: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
   97: #define FILENAMELENGTH 80
   98: /*#define DEBUG*/
   99: #define windows
  100: #define	GLOCK_ERROR_NOPATH		-1	/* empty path */
  101: #define	GLOCK_ERROR_GETCWD		-2	/* cannot get cwd */
  102: 
  103: #define MAXPARM 30 /* Maximum number of parameters for the optimization */
  104: #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncovmodel */
  105: 
  106: #define NINTERVMAX 8
  107: #define NLSTATEMAX 8 /* Maximum number of live states (for func) */
  108: #define NDEATHMAX 8 /* Maximum number of dead states (for func) */
  109: #define NCOVMAX 8 /* Maximum number of covariates */
  110: #define MAXN 20000
  111: #define YEARM 12. /* Number of months per year */
  112: #define AGESUP 130
  113: #define AGEBASE 40
  114: #ifdef windows
  115: #define DIRSEPARATOR '\\'
  116: #define ODIRSEPARATOR '/'
  117: #else
  118: #define DIRSEPARATOR '/'
  119: #define ODIRSEPARATOR '\\'
  120: #endif
  121: 
  122: char version[80]="Imach version 0.95, February 2003, INED-EUROREVES ";
  123: int erreur; /* Error number */
  124: int nvar;
  125: int cptcovn=0, cptcovage=0, cptcoveff=0,cptcov;
  126: int npar=NPARMAX;
  127: int nlstate=2; /* Number of live states */
  128: int ndeath=1; /* Number of dead states */
  129: int ncovmodel, ncovcol;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
  130: int popbased=0;
  131: 
  132: int *wav; /* Number of waves for this individuual 0 is possible */
  133: int maxwav; /* Maxim number of waves */
  134: int jmin, jmax; /* min, max spacing between 2 waves */
  135: int mle, weightopt;
  136: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
  137: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
  138: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
  139: 	   * wave mi and wave mi+1 is not an exact multiple of stepm. */
  140: double jmean; /* Mean space between 2 waves */
  141: double **oldm, **newm, **savm; /* Working pointers to matrices */
  142: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
  143: FILE *fic,*ficpar, *ficparo,*ficres,  *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
  144: FILE *ficlog;
  145: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
  146: FILE *ficresprobmorprev;
  147: FILE *fichtm; /* Html File */
  148: FILE *ficreseij;
  149: char filerese[FILENAMELENGTH];
  150: FILE  *ficresvij;
  151: char fileresv[FILENAMELENGTH];
  152: FILE  *ficresvpl;
  153: char fileresvpl[FILENAMELENGTH];
  154: char title[MAXLINE];
  155: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
  156: char optionfilext[10], optionfilefiname[FILENAMELENGTH], plotcmd[FILENAMELENGTH];
  157: 
  158: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
  159: char filelog[FILENAMELENGTH]; /* Log file */
  160: char filerest[FILENAMELENGTH];
  161: char fileregp[FILENAMELENGTH];
  162: char popfile[FILENAMELENGTH];
  163: 
  164: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH];
  165: 
  166: #define NR_END 1
  167: #define FREE_ARG char*
  168: #define FTOL 1.0e-10
  169: 
  170: #define NRANSI 
  171: #define ITMAX 200 
  172: 
  173: #define TOL 2.0e-4 
  174: 
  175: #define CGOLD 0.3819660 
  176: #define ZEPS 1.0e-10 
  177: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
  178: 
  179: #define GOLD 1.618034 
  180: #define GLIMIT 100.0 
  181: #define TINY 1.0e-20 
  182: 
  183: static double maxarg1,maxarg2;
  184: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
  185: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
  186:   
  187: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
  188: #define rint(a) floor(a+0.5)
  189: 
  190: static double sqrarg;
  191: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
  192: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
  193: 
  194: int imx; 
  195: int stepm;
  196: /* Stepm, step in month: minimum step interpolation*/
  197: 
  198: int estepm;
  199: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
  200: 
  201: int m,nb;
  202: int *num, firstpass=0, lastpass=4,*cod, *ncodemax, *Tage;
  203: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
  204: double **pmmij, ***probs;
  205: double dateintmean=0;
  206: 
  207: double *weight;
  208: int **s; /* Status */
  209: double *agedc, **covar, idx;
  210: int **nbcode, *Tcode, *Tvar, **codtab, **Tvard, *Tprod, cptcovprod, *Tvaraff;
  211: 
  212: double ftol=FTOL; /* Tolerance for computing Max Likelihood */
  213: double ftolhess; /* Tolerance for computing hessian */
  214: 
  215: /**************** split *************************/
  216: static	int split( char *path, char *dirc, char *name, char *ext, char *finame )
  217: {
  218:   char	*ss;				/* pointer */
  219:   int	l1, l2;				/* length counters */
  220: 
  221:   l1 = strlen(path );			/* length of path */
  222:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
  223:   ss= strrchr( path, DIRSEPARATOR );		/* find last / */
  224:   if ( ss == NULL ) {			/* no directory, so use current */
  225:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
  226:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
  227:     /* get current working directory */
  228:     /*    extern  char* getcwd ( char *buf , int len);*/
  229:     if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
  230:       return( GLOCK_ERROR_GETCWD );
  231:     }
  232:     strcpy( name, path );		/* we've got it */
  233:   } else {				/* strip direcotry from path */
  234:     ss++;				/* after this, the filename */
  235:     l2 = strlen( ss );			/* length of filename */
  236:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
  237:     strcpy( name, ss );		/* save file name */
  238:     strncpy( dirc, path, l1 - l2 );	/* now the directory */
  239:     dirc[l1-l2] = 0;			/* add zero */
  240:   }
  241:   l1 = strlen( dirc );			/* length of directory */
  242: #ifdef windows
  243:   if ( dirc[l1-1] != '\\' ) { dirc[l1] = '\\'; dirc[l1+1] = 0; }
  244: #else
  245:   if ( dirc[l1-1] != '/' ) { dirc[l1] = '/'; dirc[l1+1] = 0; }
  246: #endif
  247:   ss = strrchr( name, '.' );		/* find last / */
  248:   ss++;
  249:   strcpy(ext,ss);			/* save extension */
  250:   l1= strlen( name);
  251:   l2= strlen(ss)+1;
  252:   strncpy( finame, name, l1-l2);
  253:   finame[l1-l2]= 0;
  254:   return( 0 );				/* we're done */
  255: }
  256: 
  257: 
  258: /******************************************/
  259: 
  260: void replace(char *s, char*t)
  261: {
  262:   int i;
  263:   int lg=20;
  264:   i=0;
  265:   lg=strlen(t);
  266:   for(i=0; i<= lg; i++) {
  267:     (s[i] = t[i]);
  268:     if (t[i]== '\\') s[i]='/';
  269:   }
  270: }
  271: 
  272: int nbocc(char *s, char occ)
  273: {
  274:   int i,j=0;
  275:   int lg=20;
  276:   i=0;
  277:   lg=strlen(s);
  278:   for(i=0; i<= lg; i++) {
  279:   if  (s[i] == occ ) j++;
  280:   }
  281:   return j;
  282: }
  283: 
  284: void cutv(char *u,char *v, char*t, char occ)
  285: {
  286:   /* cuts string t into u and v where u is ended by char occ excluding it
  287:      and v is after occ excluding it too : ex cutv(u,v,"abcdef2ghi2j",2)
  288:      gives u="abcedf" and v="ghi2j" */
  289:   int i,lg,j,p=0;
  290:   i=0;
  291:   for(j=0; j<=strlen(t)-1; j++) {
  292:     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1;
  293:   }
  294: 
  295:   lg=strlen(t);
  296:   for(j=0; j<p; j++) {
  297:     (u[j] = t[j]);
  298:   }
  299:      u[p]='\0';
  300: 
  301:    for(j=0; j<= lg; j++) {
  302:     if (j>=(p+1))(v[j-p-1] = t[j]);
  303:   }
  304: }
  305: 
  306: /********************** nrerror ********************/
  307: 
  308: void nrerror(char error_text[])
  309: {
  310:   fprintf(stderr,"ERREUR ...\n");
  311:   fprintf(stderr,"%s\n",error_text);
  312:   exit(EXIT_FAILURE);
  313: }
  314: /*********************** vector *******************/
  315: double *vector(int nl, int nh)
  316: {
  317:   double *v;
  318:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
  319:   if (!v) nrerror("allocation failure in vector");
  320:   return v-nl+NR_END;
  321: }
  322: 
  323: /************************ free vector ******************/
  324: void free_vector(double*v, int nl, int nh)
  325: {
  326:   free((FREE_ARG)(v+nl-NR_END));
  327: }
  328: 
  329: /************************ivector *******************************/
  330: int *ivector(long nl,long nh)
  331: {
  332:   int *v;
  333:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
  334:   if (!v) nrerror("allocation failure in ivector");
  335:   return v-nl+NR_END;
  336: }
  337: 
  338: /******************free ivector **************************/
  339: void free_ivector(int *v, long nl, long nh)
  340: {
  341:   free((FREE_ARG)(v+nl-NR_END));
  342: }
  343: 
  344: /******************* imatrix *******************************/
  345: int **imatrix(long nrl, long nrh, long ncl, long nch) 
  346:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
  347: { 
  348:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
  349:   int **m; 
  350:   
  351:   /* allocate pointers to rows */ 
  352:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
  353:   if (!m) nrerror("allocation failure 1 in matrix()"); 
  354:   m += NR_END; 
  355:   m -= nrl; 
  356:   
  357:   
  358:   /* allocate rows and set pointers to them */ 
  359:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
  360:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
  361:   m[nrl] += NR_END; 
  362:   m[nrl] -= ncl; 
  363:   
  364:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
  365:   
  366:   /* return pointer to array of pointers to rows */ 
  367:   return m; 
  368: } 
  369: 
  370: /****************** free_imatrix *************************/
  371: void free_imatrix(m,nrl,nrh,ncl,nch)
  372:       int **m;
  373:       long nch,ncl,nrh,nrl; 
  374:      /* free an int matrix allocated by imatrix() */ 
  375: { 
  376:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
  377:   free((FREE_ARG) (m+nrl-NR_END)); 
  378: } 
  379: 
  380: /******************* matrix *******************************/
  381: double **matrix(long nrl, long nrh, long ncl, long nch)
  382: {
  383:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
  384:   double **m;
  385: 
  386:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
  387:   if (!m) nrerror("allocation failure 1 in matrix()");
  388:   m += NR_END;
  389:   m -= nrl;
  390: 
  391:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
  392:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
  393:   m[nrl] += NR_END;
  394:   m[nrl] -= ncl;
  395: 
  396:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
  397:   return m;
  398:   /* print *(*(m+1)+70) ou print m[1][70]; print m+1 or print &(m[1]) 
  399:    */
  400: }
  401: 
  402: /*************************free matrix ************************/
  403: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
  404: {
  405:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
  406:   free((FREE_ARG)(m+nrl-NR_END));
  407: }
  408: 
  409: /******************* ma3x *******************************/
  410: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
  411: {
  412:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
  413:   double ***m;
  414: 
  415:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
  416:   if (!m) nrerror("allocation failure 1 in matrix()");
  417:   m += NR_END;
  418:   m -= nrl;
  419: 
  420:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
  421:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
  422:   m[nrl] += NR_END;
  423:   m[nrl] -= ncl;
  424: 
  425:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
  426: 
  427:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
  428:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
  429:   m[nrl][ncl] += NR_END;
  430:   m[nrl][ncl] -= nll;
  431:   for (j=ncl+1; j<=nch; j++) 
  432:     m[nrl][j]=m[nrl][j-1]+nlay;
  433:   
  434:   for (i=nrl+1; i<=nrh; i++) {
  435:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
  436:     for (j=ncl+1; j<=nch; j++) 
  437:       m[i][j]=m[i][j-1]+nlay;
  438:   }
  439:   return m; 
  440:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
  441:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
  442:   */
  443: }
  444: 
  445: /*************************free ma3x ************************/
  446: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
  447: {
  448:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
  449:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
  450:   free((FREE_ARG)(m+nrl-NR_END));
  451: }
  452: 
  453: /***************** f1dim *************************/
  454: extern int ncom; 
  455: extern double *pcom,*xicom;
  456: extern double (*nrfunc)(double []); 
  457:  
  458: double f1dim(double x) 
  459: { 
  460:   int j; 
  461:   double f;
  462:   double *xt; 
  463:  
  464:   xt=vector(1,ncom); 
  465:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
  466:   f=(*nrfunc)(xt); 
  467:   free_vector(xt,1,ncom); 
  468:   return f; 
  469: } 
  470: 
  471: /*****************brent *************************/
  472: double brent(double ax, double bx, double cx, double (*f)(double), double tol, 	double *xmin) 
  473: { 
  474:   int iter; 
  475:   double a,b,d,etemp;
  476:   double fu,fv,fw,fx;
  477:   double ftemp;
  478:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
  479:   double e=0.0; 
  480:  
  481:   a=(ax < cx ? ax : cx); 
  482:   b=(ax > cx ? ax : cx); 
  483:   x=w=v=bx; 
  484:   fw=fv=fx=(*f)(x); 
  485:   for (iter=1;iter<=ITMAX;iter++) { 
  486:     xm=0.5*(a+b); 
  487:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
  488:     /*		if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
  489:     printf(".");fflush(stdout);
  490:     fprintf(ficlog,".");fflush(ficlog);
  491: #ifdef DEBUG
  492:     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);
  493:     fprintf(ficlog,"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);
  494:     /*		if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
  495: #endif
  496:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
  497:       *xmin=x; 
  498:       return fx; 
  499:     } 
  500:     ftemp=fu;
  501:     if (fabs(e) > tol1) { 
  502:       r=(x-w)*(fx-fv); 
  503:       q=(x-v)*(fx-fw); 
  504:       p=(x-v)*q-(x-w)*r; 
  505:       q=2.0*(q-r); 
  506:       if (q > 0.0) p = -p; 
  507:       q=fabs(q); 
  508:       etemp=e; 
  509:       e=d; 
  510:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
  511: 	d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
  512:       else { 
  513: 	d=p/q; 
  514: 	u=x+d; 
  515: 	if (u-a < tol2 || b-u < tol2) 
  516: 	  d=SIGN(tol1,xm-x); 
  517:       } 
  518:     } else { 
  519:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
  520:     } 
  521:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
  522:     fu=(*f)(u); 
  523:     if (fu <= fx) { 
  524:       if (u >= x) a=x; else b=x; 
  525:       SHFT(v,w,x,u) 
  526: 	SHFT(fv,fw,fx,fu) 
  527: 	} else { 
  528: 	  if (u < x) a=u; else b=u; 
  529: 	  if (fu <= fw || w == x) { 
  530: 	    v=w; 
  531: 	    w=u; 
  532: 	    fv=fw; 
  533: 	    fw=fu; 
  534: 	  } else if (fu <= fv || v == x || v == w) { 
  535: 	    v=u; 
  536: 	    fv=fu; 
  537: 	  } 
  538: 	} 
  539:   } 
  540:   nrerror("Too many iterations in brent"); 
  541:   *xmin=x; 
  542:   return fx; 
  543: } 
  544: 
  545: /****************** mnbrak ***********************/
  546: 
  547: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
  548: 	    double (*func)(double)) 
  549: { 
  550:   double ulim,u,r,q, dum;
  551:   double fu; 
  552:  
  553:   *fa=(*func)(*ax); 
  554:   *fb=(*func)(*bx); 
  555:   if (*fb > *fa) { 
  556:     SHFT(dum,*ax,*bx,dum) 
  557:       SHFT(dum,*fb,*fa,dum) 
  558:       } 
  559:   *cx=(*bx)+GOLD*(*bx-*ax); 
  560:   *fc=(*func)(*cx); 
  561:   while (*fb > *fc) { 
  562:     r=(*bx-*ax)*(*fb-*fc); 
  563:     q=(*bx-*cx)*(*fb-*fa); 
  564:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
  565:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); 
  566:     ulim=(*bx)+GLIMIT*(*cx-*bx); 
  567:     if ((*bx-u)*(u-*cx) > 0.0) { 
  568:       fu=(*func)(u); 
  569:     } else if ((*cx-u)*(u-ulim) > 0.0) { 
  570:       fu=(*func)(u); 
  571:       if (fu < *fc) { 
  572: 	SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
  573: 	  SHFT(*fb,*fc,fu,(*func)(u)) 
  574: 	  } 
  575:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { 
  576:       u=ulim; 
  577:       fu=(*func)(u); 
  578:     } else { 
  579:       u=(*cx)+GOLD*(*cx-*bx); 
  580:       fu=(*func)(u); 
  581:     } 
  582:     SHFT(*ax,*bx,*cx,u) 
  583:       SHFT(*fa,*fb,*fc,fu) 
  584:       } 
  585: } 
  586: 
  587: /*************** linmin ************************/
  588: 
  589: int ncom; 
  590: double *pcom,*xicom;
  591: double (*nrfunc)(double []); 
  592:  
  593: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
  594: { 
  595:   double brent(double ax, double bx, double cx, 
  596: 	       double (*f)(double), double tol, double *xmin); 
  597:   double f1dim(double x); 
  598:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
  599: 	      double *fc, double (*func)(double)); 
  600:   int j; 
  601:   double xx,xmin,bx,ax; 
  602:   double fx,fb,fa;
  603:  
  604:   ncom=n; 
  605:   pcom=vector(1,n); 
  606:   xicom=vector(1,n); 
  607:   nrfunc=func; 
  608:   for (j=1;j<=n;j++) { 
  609:     pcom[j]=p[j]; 
  610:     xicom[j]=xi[j]; 
  611:   } 
  612:   ax=0.0; 
  613:   xx=1.0; 
  614:   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); 
  615:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); 
  616: #ifdef DEBUG
  617:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
  618:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
  619: #endif
  620:   for (j=1;j<=n;j++) { 
  621:     xi[j] *= xmin; 
  622:     p[j] += xi[j]; 
  623:   } 
  624:   free_vector(xicom,1,n); 
  625:   free_vector(pcom,1,n); 
  626: } 
  627: 
  628: /*************** powell ************************/
  629: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
  630: 	    double (*func)(double [])) 
  631: { 
  632:   void linmin(double p[], double xi[], int n, double *fret, 
  633: 	      double (*func)(double [])); 
  634:   int i,ibig,j; 
  635:   double del,t,*pt,*ptt,*xit;
  636:   double fp,fptt;
  637:   double *xits;
  638:   pt=vector(1,n); 
  639:   ptt=vector(1,n); 
  640:   xit=vector(1,n); 
  641:   xits=vector(1,n); 
  642:   *fret=(*func)(p); 
  643:   for (j=1;j<=n;j++) pt[j]=p[j]; 
  644:   for (*iter=1;;++(*iter)) { 
  645:     fp=(*fret); 
  646:     ibig=0; 
  647:     del=0.0; 
  648:     printf("\nPowell iter=%d -2*LL=%.12f",*iter,*fret);
  649:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f",*iter,*fret);
  650:     for (i=1;i<=n;i++) 
  651:       printf(" %d %.12f",i, p[i]);
  652:     fprintf(ficlog," %d %.12f",i, p[i]);
  653:     printf("\n");
  654:     fprintf(ficlog,"\n");
  655:     for (i=1;i<=n;i++) { 
  656:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; 
  657:       fptt=(*fret); 
  658: #ifdef DEBUG
  659:       printf("fret=%lf \n",*fret);
  660:       fprintf(ficlog,"fret=%lf \n",*fret);
  661: #endif
  662:       printf("%d",i);fflush(stdout);
  663:       fprintf(ficlog,"%d",i);fflush(ficlog);
  664:       linmin(p,xit,n,fret,func); 
  665:       if (fabs(fptt-(*fret)) > del) { 
  666: 	del=fabs(fptt-(*fret)); 
  667: 	ibig=i; 
  668:       } 
  669: #ifdef DEBUG
  670:       printf("%d %.12e",i,(*fret));
  671:       fprintf(ficlog,"%d %.12e",i,(*fret));
  672:       for (j=1;j<=n;j++) {
  673: 	xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
  674: 	printf(" x(%d)=%.12e",j,xit[j]);
  675: 	fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
  676:       }
  677:       for(j=1;j<=n;j++) {
  678: 	printf(" p=%.12e",p[j]);
  679: 	fprintf(ficlog," p=%.12e",p[j]);
  680:       }
  681:       printf("\n");
  682:       fprintf(ficlog,"\n");
  683: #endif
  684:     } 
  685:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
  686: #ifdef DEBUG
  687:       int k[2],l;
  688:       k[0]=1;
  689:       k[1]=-1;
  690:       printf("Max: %.12e",(*func)(p));
  691:       fprintf(ficlog,"Max: %.12e",(*func)(p));
  692:       for (j=1;j<=n;j++) {
  693: 	printf(" %.12e",p[j]);
  694: 	fprintf(ficlog," %.12e",p[j]);
  695:       }
  696:       printf("\n");
  697:       fprintf(ficlog,"\n");
  698:       for(l=0;l<=1;l++) {
  699: 	for (j=1;j<=n;j++) {
  700: 	  ptt[j]=p[j]+(p[j]-pt[j])*k[l];
  701: 	  printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
  702: 	  fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
  703: 	}
  704: 	printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
  705: 	fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
  706:       }
  707: #endif
  708: 
  709: 
  710:       free_vector(xit,1,n); 
  711:       free_vector(xits,1,n); 
  712:       free_vector(ptt,1,n); 
  713:       free_vector(pt,1,n); 
  714:       return; 
  715:     } 
  716:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
  717:     for (j=1;j<=n;j++) { 
  718:       ptt[j]=2.0*p[j]-pt[j]; 
  719:       xit[j]=p[j]-pt[j]; 
  720:       pt[j]=p[j]; 
  721:     } 
  722:     fptt=(*func)(ptt); 
  723:     if (fptt < fp) { 
  724:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); 
  725:       if (t < 0.0) { 
  726: 	linmin(p,xit,n,fret,func); 
  727: 	for (j=1;j<=n;j++) { 
  728: 	  xi[j][ibig]=xi[j][n]; 
  729: 	  xi[j][n]=xit[j]; 
  730: 	}
  731: #ifdef DEBUG
  732: 	printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
  733: 	fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
  734: 	for(j=1;j<=n;j++){
  735: 	  printf(" %.12e",xit[j]);
  736: 	  fprintf(ficlog," %.12e",xit[j]);
  737: 	}
  738: 	printf("\n");
  739: 	fprintf(ficlog,"\n");
  740: #endif
  741:       }
  742:     } 
  743:   } 
  744: } 
  745: 
  746: /**** Prevalence limit (stable prevalence)  ****************/
  747: 
  748: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
  749: {
  750:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
  751:      matrix by transitions matrix until convergence is reached */
  752: 
  753:   int i, ii,j,k;
  754:   double min, max, maxmin, maxmax,sumnew=0.;
  755:   double **matprod2();
  756:   double **out, cov[NCOVMAX], **pmij();
  757:   double **newm;
  758:   double agefin, delaymax=50 ; /* Max number of years to converge */
  759: 
  760:   for (ii=1;ii<=nlstate+ndeath;ii++)
  761:     for (j=1;j<=nlstate+ndeath;j++){
  762:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
  763:     }
  764: 
  765:    cov[1]=1.;
  766:  
  767:  /* Even if hstepm = 1, at least one multiplication by the unit matrix */
  768:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
  769:     newm=savm;
  770:     /* Covariates have to be included here again */
  771:      cov[2]=agefin;
  772:   
  773:       for (k=1; k<=cptcovn;k++) {
  774: 	cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
  775: 	/*	printf("ij=%d k=%d Tvar[k]=%d nbcode=%d cov=%lf codtab[ij][Tvar[k]]=%d \n",ij,k, Tvar[k],nbcode[Tvar[k]][codtab[ij][Tvar[k]]],cov[2+k], codtab[ij][Tvar[k]]);*/
  776:       }
  777:       for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
  778:       for (k=1; k<=cptcovprod;k++)
  779: 	cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
  780: 
  781:       /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
  782:       /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
  783:       /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
  784:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
  785: 
  786:     savm=oldm;
  787:     oldm=newm;
  788:     maxmax=0.;
  789:     for(j=1;j<=nlstate;j++){
  790:       min=1.;
  791:       max=0.;
  792:       for(i=1; i<=nlstate; i++) {
  793: 	sumnew=0;
  794: 	for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
  795: 	prlim[i][j]= newm[i][j]/(1-sumnew);
  796: 	max=FMAX(max,prlim[i][j]);
  797: 	min=FMIN(min,prlim[i][j]);
  798:       }
  799:       maxmin=max-min;
  800:       maxmax=FMAX(maxmax,maxmin);
  801:     }
  802:     if(maxmax < ftolpl){
  803:       return prlim;
  804:     }
  805:   }
  806: }
  807: 
  808: /*************** transition probabilities ***************/ 
  809: 
  810: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
  811: {
  812:   double s1, s2;
  813:   /*double t34;*/
  814:   int i,j,j1, nc, ii, jj;
  815: 
  816:     for(i=1; i<= nlstate; i++){
  817:     for(j=1; j<i;j++){
  818:       for (nc=1, s2=0.;nc <=ncovmodel; nc++){
  819: 	/*s2 += param[i][j][nc]*cov[nc];*/
  820: 	s2 += x[(i-1)*nlstate*ncovmodel+(j-1)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
  821: 	/*printf("Int j<i s1=%.17e, s2=%.17e\n",s1,s2);*/
  822:       }
  823:       ps[i][j]=s2;
  824:       /*printf("s1=%.17e, s2=%.17e\n",s1,s2);*/
  825:     }
  826:     for(j=i+1; j<=nlstate+ndeath;j++){
  827:       for (nc=1, s2=0.;nc <=ncovmodel; nc++){
  828: 	s2 += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
  829: 	/*printf("Int j>i s1=%.17e, s2=%.17e %lx %lx\n",s1,s2,s1,s2);*/
  830:       }
  831:       ps[i][j]=s2;
  832:     }
  833:   }
  834:     /*ps[3][2]=1;*/
  835: 
  836:   for(i=1; i<= nlstate; i++){
  837:      s1=0;
  838:     for(j=1; j<i; j++)
  839:       s1+=exp(ps[i][j]);
  840:     for(j=i+1; j<=nlstate+ndeath; j++)
  841:       s1+=exp(ps[i][j]);
  842:     ps[i][i]=1./(s1+1.);
  843:     for(j=1; j<i; j++)
  844:       ps[i][j]= exp(ps[i][j])*ps[i][i];
  845:     for(j=i+1; j<=nlstate+ndeath; j++)
  846:       ps[i][j]= exp(ps[i][j])*ps[i][i];
  847:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
  848:   } /* end i */
  849: 
  850:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
  851:     for(jj=1; jj<= nlstate+ndeath; jj++){
  852:       ps[ii][jj]=0;
  853:       ps[ii][ii]=1;
  854:     }
  855:   }
  856: 
  857: 
  858:   /*   for(ii=1; ii<= nlstate+ndeath; ii++){
  859:     for(jj=1; jj<= nlstate+ndeath; jj++){
  860:      printf("%lf ",ps[ii][jj]);
  861:    }
  862:     printf("\n ");
  863:     }
  864:     printf("\n ");printf("%lf ",cov[2]);*/
  865: /*
  866:   for(i=1; i<= npar; i++) printf("%f ",x[i]);
  867:   goto end;*/
  868:     return ps;
  869: }
  870: 
  871: /**************** Product of 2 matrices ******************/
  872: 
  873: double **matprod2(double **out, double **in,long nrl, long nrh, long ncl, long nch, long ncolol, long ncoloh, double **b)
  874: {
  875:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
  876:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
  877:   /* in, b, out are matrice of pointers which should have been initialized 
  878:      before: only the contents of out is modified. The function returns
  879:      a pointer to pointers identical to out */
  880:   long i, j, k;
  881:   for(i=nrl; i<= nrh; i++)
  882:     for(k=ncolol; k<=ncoloh; k++)
  883:       for(j=ncl,out[i][k]=0.; j<=nch; j++)
  884: 	out[i][k] +=in[i][j]*b[j][k];
  885: 
  886:   return out;
  887: }
  888: 
  889: 
  890: /************* Higher Matrix Product ***************/
  891: 
  892: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
  893: {
  894:   /* Computes the transition matrix starting at age 'age' over 
  895:      'nhstepm*hstepm*stepm' months (i.e. until
  896:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
  897:      nhstepm*hstepm matrices. 
  898:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
  899:      (typically every 2 years instead of every month which is too big 
  900:      for the memory).
  901:      Model is determined by parameters x and covariates have to be 
  902:      included manually here. 
  903: 
  904:      */
  905: 
  906:   int i, j, d, h, k;
  907:   double **out, cov[NCOVMAX];
  908:   double **newm;
  909: 
  910:   /* Hstepm could be zero and should return the unit matrix */
  911:   for (i=1;i<=nlstate+ndeath;i++)
  912:     for (j=1;j<=nlstate+ndeath;j++){
  913:       oldm[i][j]=(i==j ? 1.0 : 0.0);
  914:       po[i][j][0]=(i==j ? 1.0 : 0.0);
  915:     }
  916:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
  917:   for(h=1; h <=nhstepm; h++){
  918:     for(d=1; d <=hstepm; d++){
  919:       newm=savm;
  920:       /* Covariates have to be included here again */
  921:       cov[1]=1.;
  922:       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
  923:       for (k=1; k<=cptcovn;k++) cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
  924:       for (k=1; k<=cptcovage;k++)
  925: 	cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
  926:       for (k=1; k<=cptcovprod;k++)
  927: 	cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
  928: 
  929: 
  930:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
  931:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
  932:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
  933: 		   pmij(pmmij,cov,ncovmodel,x,nlstate));
  934:       savm=oldm;
  935:       oldm=newm;
  936:     }
  937:     for(i=1; i<=nlstate+ndeath; i++)
  938:       for(j=1;j<=nlstate+ndeath;j++) {
  939: 	po[i][j][h]=newm[i][j];
  940: 	/*printf("i=%d j=%d h=%d po[i][j][h]=%f ",i,j,h,po[i][j][h]);
  941: 	 */
  942:       }
  943:   } /* end h */
  944:   return po;
  945: }
  946: 
  947: 
  948: /*************** log-likelihood *************/
  949: double func( double *x)
  950: {
  951:   int i, ii, j, k, mi, d, kk;
  952:   double l, ll[NLSTATEMAX], cov[NCOVMAX];
  953:   double **out;
  954:   double sw; /* Sum of weights */
  955:   double lli; /* Individual log likelihood */
  956:   int s1, s2;
  957:   double bbh, survp;
  958:   long ipmx;
  959:   /*extern weight */
  960:   /* We are differentiating ll according to initial status */
  961:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
  962:   /*for(i=1;i<imx;i++) 
  963:     printf(" %d\n",s[4][i]);
  964:   */
  965:   cov[1]=1.;
  966: 
  967:   for(k=1; k<=nlstate; k++) ll[k]=0.;
  968: 
  969:   if(mle==1){
  970:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
  971:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
  972:       for(mi=1; mi<= wav[i]-1; mi++){
  973: 	for (ii=1;ii<=nlstate+ndeath;ii++)
  974: 	  for (j=1;j<=nlstate+ndeath;j++){
  975: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
  976: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
  977: 	  }
  978: 	for(d=0; d<dh[mi][i]; d++){
  979: 	  newm=savm;
  980: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
  981: 	  for (kk=1; kk<=cptcovage;kk++) {
  982: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
  983: 	  }
  984: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
  985: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
  986: 	  savm=oldm;
  987: 	  oldm=newm;
  988: 	} /* end mult */
  989:       
  990: 	/*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
  991: 	/* But now since version 0.9 we anticipate for bias and large stepm.
  992: 	 * If stepm is larger than one month (smallest stepm) and if the exact delay 
  993: 	 * (in months) between two waves is not a multiple of stepm, we rounded to 
  994: 	 * the nearest (and in case of equal distance, to the lowest) interval but now
  995: 	 * we keep into memory the bias bh[mi][i] and also the previous matrix product
  996: 	 * (i.e to dh[mi][i]-1) saved in 'savm'. The we inter(extra)polate the
  997: 	 * probability in order to take into account the bias as a fraction of the way
  998: 	 * from savm to out if bh is neagtive or even beyond if bh is positive. bh varies
  999: 	 * -stepm/2 to stepm/2 .
 1000: 	 * For stepm=1 the results are the same as for previous versions of Imach.
 1001: 	 * For stepm > 1 the results are less biased than in previous versions. 
 1002: 	 */
 1003: 	s1=s[mw[mi][i]][i];
 1004: 	s2=s[mw[mi+1][i]][i];
 1005: 	bbh=(double)bh[mi][i]/(double)stepm; 
 1006: 	/* bias is positive if real duration
 1007: 	 * is higher than the multiple of stepm and negative otherwise.
 1008: 	 */
 1009: 	/* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
 1010: 	if( s2 > nlstate){ 
 1011: 	  /* i.e. if s2 is a death state and if the date of death is known then the contribution
 1012: 	     to the likelihood is the probability to die between last step unit time and current 
 1013: 	     step unit time, which is also the differences between probability to die before dh 
 1014: 	     and probability to die before dh-stepm . 
 1015: 	     In version up to 0.92 likelihood was computed
 1016: 	as if date of death was unknown. Death was treated as any other
 1017: 	health state: the date of the interview describes the actual state
 1018: 	and not the date of a change in health state. The former idea was
 1019: 	to consider that at each interview the state was recorded
 1020: 	(healthy, disable or death) and IMaCh was corrected; but when we
 1021: 	introduced the exact date of death then we should have modified
 1022: 	the contribution of an exact death to the likelihood. This new
 1023: 	contribution is smaller and very dependent of the step unit
 1024: 	stepm. It is no more the probability to die between last interview
 1025: 	and month of death but the probability to survive from last
 1026: 	interview up to one month before death multiplied by the
 1027: 	probability to die within a month. Thanks to Chris
 1028: 	Jackson for correcting this bug.  Former versions increased
 1029: 	mortality artificially. The bad side is that we add another loop
 1030: 	which slows down the processing. The difference can be up to 10%
 1031: 	lower mortality.
 1032: 	  */
 1033: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 1034: 	}else{
 1035: 	  lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 1036: 	  /*  lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*(savm[s1][s2])):log((1.+bbh)*out[s1][s2]));*/ /* linear interpolation */
 1037: 	} 
 1038: 	/*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
 1039: 	/*if(lli ==000.0)*/
 1040: 	/*printf("bbh= %f lli=%f savm=%f out=%f %d\n",bbh,lli,savm[s1][s2], out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]],i); */
 1041:   	ipmx +=1;
 1042: 	sw += weight[i];
 1043: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1044:       } /* end of wave */
 1045:     } /* end of individual */
 1046:   }  else if(mle==2){
 1047:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1048:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1049:       for(mi=1; mi<= wav[i]-1; mi++){
 1050: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1051: 	  for (j=1;j<=nlstate+ndeath;j++){
 1052: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1053: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1054: 	  }
 1055: 	for(d=0; d<=dh[mi][i]; d++){
 1056: 	  newm=savm;
 1057: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1058: 	  for (kk=1; kk<=cptcovage;kk++) {
 1059: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1060: 	  }
 1061: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1062: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1063: 	  savm=oldm;
 1064: 	  oldm=newm;
 1065: 	} /* end mult */
 1066:       
 1067: 	/*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
 1068: 	/* But now since version 0.9 we anticipate for bias and large stepm.
 1069: 	 * If stepm is larger than one month (smallest stepm) and if the exact delay 
 1070: 	 * (in months) between two waves is not a multiple of stepm, we rounded to 
 1071: 	 * the nearest (and in case of equal distance, to the lowest) interval but now
 1072: 	 * we keep into memory the bias bh[mi][i] and also the previous matrix product
 1073: 	 * (i.e to dh[mi][i]-1) saved in 'savm'. The we inter(extra)polate the
 1074: 	 * probability in order to take into account the bias as a fraction of the way
 1075: 	 * from savm to out if bh is neagtive or even beyond if bh is positive. bh varies
 1076: 	 * -stepm/2 to stepm/2 .
 1077: 	 * For stepm=1 the results are the same as for previous versions of Imach.
 1078: 	 * For stepm > 1 the results are less biased than in previous versions. 
 1079: 	 */
 1080: 	s1=s[mw[mi][i]][i];
 1081: 	s2=s[mw[mi+1][i]][i];
 1082: 	bbh=(double)bh[mi][i]/(double)stepm; 
 1083: 	/* bias is positive if real duration
 1084: 	 * is higher than the multiple of stepm and negative otherwise.
 1085: 	 */
 1086: 	lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*(savm[s1][s2])):log((1.+bbh)*out[s1][s2])); /* linear interpolation */
 1087: 	/* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
 1088: 	/*lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.-+bh)*out[s1][s2])); */ /* exponential interpolation */
 1089: 	/*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
 1090: 	/*if(lli ==000.0)*/
 1091: 	/*printf("bbh= %f lli=%f savm=%f out=%f %d\n",bbh,lli,savm[s1][s2], out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]],i); */
 1092: 	ipmx +=1;
 1093: 	sw += weight[i];
 1094: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1095:       } /* end of wave */
 1096:     } /* end of individual */
 1097:   }  else if(mle==3){  /* exponential inter-extrapolation */
 1098:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1099:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1100:       for(mi=1; mi<= wav[i]-1; mi++){
 1101: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1102: 	  for (j=1;j<=nlstate+ndeath;j++){
 1103: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1104: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1105: 	  }
 1106: 	for(d=0; d<dh[mi][i]; d++){
 1107: 	  newm=savm;
 1108: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1109: 	  for (kk=1; kk<=cptcovage;kk++) {
 1110: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1111: 	  }
 1112: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1113: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1114: 	  savm=oldm;
 1115: 	  oldm=newm;
 1116: 	} /* end mult */
 1117:       
 1118: 	/*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
 1119: 	/* But now since version 0.9 we anticipate for bias and large stepm.
 1120: 	 * If stepm is larger than one month (smallest stepm) and if the exact delay 
 1121: 	 * (in months) between two waves is not a multiple of stepm, we rounded to 
 1122: 	 * the nearest (and in case of equal distance, to the lowest) interval but now
 1123: 	 * we keep into memory the bias bh[mi][i] and also the previous matrix product
 1124: 	 * (i.e to dh[mi][i]-1) saved in 'savm'. The we inter(extra)polate the
 1125: 	 * probability in order to take into account the bias as a fraction of the way
 1126: 	 * from savm to out if bh is neagtive or even beyond if bh is positive. bh varies
 1127: 	 * -stepm/2 to stepm/2 .
 1128: 	 * For stepm=1 the results are the same as for previous versions of Imach.
 1129: 	 * For stepm > 1 the results are less biased than in previous versions. 
 1130: 	 */
 1131: 	s1=s[mw[mi][i]][i];
 1132: 	s2=s[mw[mi+1][i]][i];
 1133: 	bbh=(double)bh[mi][i]/(double)stepm; 
 1134: 	/* bias is positive if real duration
 1135: 	 * is higher than the multiple of stepm and negative otherwise.
 1136: 	 */
 1137: 	/* lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*(savm[s1][s2])):log((1.+bbh)*out[s1][s2])); */ /* linear interpolation */
 1138: 	lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2])); /* exponential inter-extrapolation */
 1139: 	/*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
 1140: 	/*if(lli ==000.0)*/
 1141: 	/*printf("bbh= %f lli=%f savm=%f out=%f %d\n",bbh,lli,savm[s1][s2], out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]],i); */
 1142: 	ipmx +=1;
 1143: 	sw += weight[i];
 1144: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1145:       } /* end of wave */
 1146:     } /* end of individual */
 1147:   }else{  /* ml=4 no inter-extrapolation */
 1148:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1149:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1150:       for(mi=1; mi<= wav[i]-1; mi++){
 1151: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1152: 	  for (j=1;j<=nlstate+ndeath;j++){
 1153: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1154: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1155: 	  }
 1156: 	for(d=0; d<dh[mi][i]; d++){
 1157: 	  newm=savm;
 1158: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1159: 	  for (kk=1; kk<=cptcovage;kk++) {
 1160: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1161: 	  }
 1162: 	
 1163: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1164: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1165: 	  savm=oldm;
 1166: 	  oldm=newm;
 1167: 	} /* end mult */
 1168:       
 1169: 	lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 1170: 	ipmx +=1;
 1171: 	sw += weight[i];
 1172: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1173:       } /* end of wave */
 1174:     } /* end of individual */
 1175:   } /* End of if */
 1176:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 1177:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 1178:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 1179:   return -l;
 1180: }
 1181: 
 1182: 
 1183: /*********** Maximum Likelihood Estimation ***************/
 1184: 
 1185: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
 1186: {
 1187:   int i,j, iter;
 1188:   double **xi;
 1189:   double fret;
 1190:   xi=matrix(1,npar,1,npar);
 1191:   for (i=1;i<=npar;i++)
 1192:     for (j=1;j<=npar;j++)
 1193:       xi[i][j]=(i==j ? 1.0 : 0.0);
 1194:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
 1195:   powell(p,xi,npar,ftol,&iter,&fret,func);
 1196: 
 1197:    printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));
 1198:   fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
 1199:   fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
 1200: 
 1201: }
 1202: 
 1203: /**** Computes Hessian and covariance matrix ***/
 1204: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
 1205: {
 1206:   double  **a,**y,*x,pd;
 1207:   double **hess;
 1208:   int i, j,jk;
 1209:   int *indx;
 1210: 
 1211:   double hessii(double p[], double delta, int theta, double delti[]);
 1212:   double hessij(double p[], double delti[], int i, int j);
 1213:   void lubksb(double **a, int npar, int *indx, double b[]) ;
 1214:   void ludcmp(double **a, int npar, int *indx, double *d) ;
 1215: 
 1216:   hess=matrix(1,npar,1,npar);
 1217: 
 1218:   printf("\nCalculation of the hessian matrix. Wait...\n");
 1219:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
 1220:   for (i=1;i<=npar;i++){
 1221:     printf("%d",i);fflush(stdout);
 1222:     fprintf(ficlog,"%d",i);fflush(ficlog);
 1223:     hess[i][i]=hessii(p,ftolhess,i,delti);
 1224:     /*printf(" %f ",p[i]);*/
 1225:     /*printf(" %lf ",hess[i][i]);*/
 1226:   }
 1227:   
 1228:   for (i=1;i<=npar;i++) {
 1229:     for (j=1;j<=npar;j++)  {
 1230:       if (j>i) { 
 1231: 	printf(".%d%d",i,j);fflush(stdout);
 1232: 	fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
 1233: 	hess[i][j]=hessij(p,delti,i,j);
 1234: 	hess[j][i]=hess[i][j];    
 1235: 	/*printf(" %lf ",hess[i][j]);*/
 1236:       }
 1237:     }
 1238:   }
 1239:   printf("\n");
 1240:   fprintf(ficlog,"\n");
 1241: 
 1242:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
 1243:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
 1244:   
 1245:   a=matrix(1,npar,1,npar);
 1246:   y=matrix(1,npar,1,npar);
 1247:   x=vector(1,npar);
 1248:   indx=ivector(1,npar);
 1249:   for (i=1;i<=npar;i++)
 1250:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
 1251:   ludcmp(a,npar,indx,&pd);
 1252: 
 1253:   for (j=1;j<=npar;j++) {
 1254:     for (i=1;i<=npar;i++) x[i]=0;
 1255:     x[j]=1;
 1256:     lubksb(a,npar,indx,x);
 1257:     for (i=1;i<=npar;i++){ 
 1258:       matcov[i][j]=x[i];
 1259:     }
 1260:   }
 1261: 
 1262:   printf("\n#Hessian matrix#\n");
 1263:   fprintf(ficlog,"\n#Hessian matrix#\n");
 1264:   for (i=1;i<=npar;i++) { 
 1265:     for (j=1;j<=npar;j++) { 
 1266:       printf("%.3e ",hess[i][j]);
 1267:       fprintf(ficlog,"%.3e ",hess[i][j]);
 1268:     }
 1269:     printf("\n");
 1270:     fprintf(ficlog,"\n");
 1271:   }
 1272: 
 1273:   /* Recompute Inverse */
 1274:   for (i=1;i<=npar;i++)
 1275:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
 1276:   ludcmp(a,npar,indx,&pd);
 1277: 
 1278:   /*  printf("\n#Hessian matrix recomputed#\n");
 1279: 
 1280:   for (j=1;j<=npar;j++) {
 1281:     for (i=1;i<=npar;i++) x[i]=0;
 1282:     x[j]=1;
 1283:     lubksb(a,npar,indx,x);
 1284:     for (i=1;i<=npar;i++){ 
 1285:       y[i][j]=x[i];
 1286:       printf("%.3e ",y[i][j]);
 1287:       fprintf(ficlog,"%.3e ",y[i][j]);
 1288:     }
 1289:     printf("\n");
 1290:     fprintf(ficlog,"\n");
 1291:   }
 1292:   */
 1293: 
 1294:   free_matrix(a,1,npar,1,npar);
 1295:   free_matrix(y,1,npar,1,npar);
 1296:   free_vector(x,1,npar);
 1297:   free_ivector(indx,1,npar);
 1298:   free_matrix(hess,1,npar,1,npar);
 1299: 
 1300: 
 1301: }
 1302: 
 1303: /*************** hessian matrix ****************/
 1304: double hessii( double x[], double delta, int theta, double delti[])
 1305: {
 1306:   int i;
 1307:   int l=1, lmax=20;
 1308:   double k1,k2;
 1309:   double p2[NPARMAX+1];
 1310:   double res;
 1311:   double delt, delts, nkhi=10.,nkhif=1., khi=1.e-4;
 1312:   double fx;
 1313:   int k=0,kmax=10;
 1314:   double l1;
 1315: 
 1316:   fx=func(x);
 1317:   for (i=1;i<=npar;i++) p2[i]=x[i];
 1318:   for(l=0 ; l <=lmax; l++){
 1319:     l1=pow(10,l);
 1320:     delts=delt;
 1321:     for(k=1 ; k <kmax; k=k+1){
 1322:       delt = delta*(l1*k);
 1323:       p2[theta]=x[theta] +delt;
 1324:       k1=func(p2)-fx;
 1325:       p2[theta]=x[theta]-delt;
 1326:       k2=func(p2)-fx;
 1327:       /*res= (k1-2.0*fx+k2)/delt/delt; */
 1328:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
 1329:       
 1330: #ifdef DEBUG
 1331:       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);
 1332:       fprintf(ficlog,"%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);
 1333: #endif
 1334:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
 1335:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
 1336: 	k=kmax;
 1337:       }
 1338:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
 1339: 	k=kmax; l=lmax*10.;
 1340:       }
 1341:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
 1342: 	delts=delt;
 1343:       }
 1344:     }
 1345:   }
 1346:   delti[theta]=delts;
 1347:   return res; 
 1348:   
 1349: }
 1350: 
 1351: double hessij( double x[], double delti[], int thetai,int thetaj)
 1352: {
 1353:   int i;
 1354:   int l=1, l1, lmax=20;
 1355:   double k1,k2,k3,k4,res,fx;
 1356:   double p2[NPARMAX+1];
 1357:   int k;
 1358: 
 1359:   fx=func(x);
 1360:   for (k=1; k<=2; k++) {
 1361:     for (i=1;i<=npar;i++) p2[i]=x[i];
 1362:     p2[thetai]=x[thetai]+delti[thetai]/k;
 1363:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
 1364:     k1=func(p2)-fx;
 1365:   
 1366:     p2[thetai]=x[thetai]+delti[thetai]/k;
 1367:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
 1368:     k2=func(p2)-fx;
 1369:   
 1370:     p2[thetai]=x[thetai]-delti[thetai]/k;
 1371:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
 1372:     k3=func(p2)-fx;
 1373:   
 1374:     p2[thetai]=x[thetai]-delti[thetai]/k;
 1375:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
 1376:     k4=func(p2)-fx;
 1377:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
 1378: #ifdef DEBUG
 1379:     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);
 1380:     fprintf(ficlog,"%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);
 1381: #endif
 1382:   }
 1383:   return res;
 1384: }
 1385: 
 1386: /************** Inverse of matrix **************/
 1387: void ludcmp(double **a, int n, int *indx, double *d) 
 1388: { 
 1389:   int i,imax,j,k; 
 1390:   double big,dum,sum,temp; 
 1391:   double *vv; 
 1392:  
 1393:   vv=vector(1,n); 
 1394:   *d=1.0; 
 1395:   for (i=1;i<=n;i++) { 
 1396:     big=0.0; 
 1397:     for (j=1;j<=n;j++) 
 1398:       if ((temp=fabs(a[i][j])) > big) big=temp; 
 1399:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
 1400:     vv[i]=1.0/big; 
 1401:   } 
 1402:   for (j=1;j<=n;j++) { 
 1403:     for (i=1;i<j;i++) { 
 1404:       sum=a[i][j]; 
 1405:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
 1406:       a[i][j]=sum; 
 1407:     } 
 1408:     big=0.0; 
 1409:     for (i=j;i<=n;i++) { 
 1410:       sum=a[i][j]; 
 1411:       for (k=1;k<j;k++) 
 1412: 	sum -= a[i][k]*a[k][j]; 
 1413:       a[i][j]=sum; 
 1414:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
 1415: 	big=dum; 
 1416: 	imax=i; 
 1417:       } 
 1418:     } 
 1419:     if (j != imax) { 
 1420:       for (k=1;k<=n;k++) { 
 1421: 	dum=a[imax][k]; 
 1422: 	a[imax][k]=a[j][k]; 
 1423: 	a[j][k]=dum; 
 1424:       } 
 1425:       *d = -(*d); 
 1426:       vv[imax]=vv[j]; 
 1427:     } 
 1428:     indx[j]=imax; 
 1429:     if (a[j][j] == 0.0) a[j][j]=TINY; 
 1430:     if (j != n) { 
 1431:       dum=1.0/(a[j][j]); 
 1432:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
 1433:     } 
 1434:   } 
 1435:   free_vector(vv,1,n);  /* Doesn't work */
 1436: ;
 1437: } 
 1438: 
 1439: void lubksb(double **a, int n, int *indx, double b[]) 
 1440: { 
 1441:   int i,ii=0,ip,j; 
 1442:   double sum; 
 1443:  
 1444:   for (i=1;i<=n;i++) { 
 1445:     ip=indx[i]; 
 1446:     sum=b[ip]; 
 1447:     b[ip]=b[i]; 
 1448:     if (ii) 
 1449:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
 1450:     else if (sum) ii=i; 
 1451:     b[i]=sum; 
 1452:   } 
 1453:   for (i=n;i>=1;i--) { 
 1454:     sum=b[i]; 
 1455:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
 1456:     b[i]=sum/a[i][i]; 
 1457:   } 
 1458: } 
 1459: 
 1460: /************ Frequencies ********************/
 1461: void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, int *Tvaraff, int **nbcode, int *ncodemax,double **mint,double **anint, double dateprev1,double dateprev2,double jprev1, double mprev1,double anprev1,double jprev2, double mprev2,double anprev2)
 1462: {  /* Some frequencies */
 1463:   
 1464:   int i, m, jk, k1,i1, j1, bool, z1,z2,j;
 1465:   int first;
 1466:   double ***freq; /* Frequencies */
 1467:   double *pp, **prop;
 1468:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
 1469:   FILE *ficresp;
 1470:   char fileresp[FILENAMELENGTH];
 1471:   
 1472:   pp=vector(1,nlstate);
 1473:   prop=matrix(1,nlstate,iagemin,iagemax+3);
 1474:   strcpy(fileresp,"p");
 1475:   strcat(fileresp,fileres);
 1476:   if((ficresp=fopen(fileresp,"w"))==NULL) {
 1477:     printf("Problem with prevalence resultfile: %s\n", fileresp);
 1478:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
 1479:     exit(0);
 1480:   }
 1481:   freq= ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);
 1482:   j1=0;
 1483:   
 1484:   j=cptcoveff;
 1485:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 1486: 
 1487:   first=1;
 1488: 
 1489:   for(k1=1; k1<=j;k1++){
 1490:     for(i1=1; i1<=ncodemax[k1];i1++){
 1491:       j1++;
 1492:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
 1493: 	scanf("%d", i);*/
 1494:       for (i=-1; i<=nlstate+ndeath; i++)  
 1495: 	for (jk=-1; jk<=nlstate+ndeath; jk++)  
 1496: 	  for(m=iagemin; m <= iagemax+3; m++)
 1497: 	    freq[i][jk][m]=0;
 1498: 
 1499:     for (i=1; i<=nlstate; i++)  
 1500:       for(m=iagemin; m <= iagemax+3; m++)
 1501: 	prop[i][m]=0;
 1502:       
 1503:       dateintsum=0;
 1504:       k2cpt=0;
 1505:       for (i=1; i<=imx; i++) {
 1506: 	bool=1;
 1507: 	if  (cptcovn>0) {
 1508: 	  for (z1=1; z1<=cptcoveff; z1++) 
 1509: 	    if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
 1510: 	      bool=0;
 1511: 	}
 1512: 	if (bool==1){
 1513: 	  for(m=firstpass; m<=lastpass; m++){
 1514: 	    k2=anint[m][i]+(mint[m][i]/12.);
 1515: 	    if ((k2>=dateprev1) && (k2<=dateprev2)) {
 1516: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 1517: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 1518: 	      if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
 1519: 	      if (m<lastpass) {
 1520: 		freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
 1521: 		freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
 1522: 	      }
 1523: 	      
 1524: 	      if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
 1525: 		dateintsum=dateintsum+k2;
 1526: 		k2cpt++;
 1527: 	      }
 1528: 	    }
 1529: 	  }
 1530: 	}
 1531:       }
 1532:        
 1533:       fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);
 1534: 
 1535:       if  (cptcovn>0) {
 1536: 	fprintf(ficresp, "\n#********** Variable "); 
 1537: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 1538: 	fprintf(ficresp, "**********\n#");
 1539:       }
 1540:       for(i=1; i<=nlstate;i++) 
 1541: 	fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
 1542:       fprintf(ficresp, "\n");
 1543:       
 1544:       for(i=iagemin; i <= iagemax+3; i++){
 1545: 	if(i==iagemax+3){
 1546: 	  fprintf(ficlog,"Total");
 1547: 	}else{
 1548: 	  if(first==1){
 1549: 	    first=0;
 1550: 	    printf("See log file for details...\n");
 1551: 	  }
 1552: 	  fprintf(ficlog,"Age %d", i);
 1553: 	}
 1554: 	for(jk=1; jk <=nlstate ; jk++){
 1555: 	  for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
 1556: 	    pp[jk] += freq[jk][m][i]; 
 1557: 	}
 1558: 	for(jk=1; jk <=nlstate ; jk++){
 1559: 	  for(m=-1, pos=0; m <=0 ; m++)
 1560: 	    pos += freq[jk][m][i];
 1561: 	  if(pp[jk]>=1.e-10){
 1562: 	    if(first==1){
 1563: 	    printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 1564: 	    }
 1565: 	    fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 1566: 	  }else{
 1567: 	    if(first==1)
 1568: 	      printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 1569: 	    fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 1570: 	  }
 1571: 	}
 1572: 
 1573: 	for(jk=1; jk <=nlstate ; jk++){
 1574: 	  for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
 1575: 	    pp[jk] += freq[jk][m][i];
 1576: 	}	
 1577: 	for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
 1578: 	  pos += pp[jk];
 1579: 	  posprop += prop[jk][i];
 1580: 	}
 1581: 	for(jk=1; jk <=nlstate ; jk++){
 1582: 	  if(pos>=1.e-5){
 1583: 	    if(first==1)
 1584: 	      printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 1585: 	    fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 1586: 	  }else{
 1587: 	    if(first==1)
 1588: 	      printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 1589: 	    fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 1590: 	  }
 1591: 	  if( i <= iagemax){
 1592: 	    if(pos>=1.e-5){
 1593: 	      fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
 1594: 	      probs[i][jk][j1]= pp[jk]/pos;
 1595: 	      /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
 1596: 	    }
 1597: 	    else
 1598: 	      fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
 1599: 	  }
 1600: 	}
 1601: 	
 1602: 	for(jk=-1; jk <=nlstate+ndeath; jk++)
 1603: 	  for(m=-1; m <=nlstate+ndeath; m++)
 1604: 	    if(freq[jk][m][i] !=0 ) {
 1605: 	    if(first==1)
 1606: 	      printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
 1607: 	      fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
 1608: 	    }
 1609: 	if(i <= iagemax)
 1610: 	  fprintf(ficresp,"\n");
 1611: 	if(first==1)
 1612: 	  printf("Others in log...\n");
 1613: 	fprintf(ficlog,"\n");
 1614:       }
 1615:     }
 1616:   }
 1617:   dateintmean=dateintsum/k2cpt; 
 1618:  
 1619:   fclose(ficresp);
 1620:   free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);
 1621:   free_vector(pp,1,nlstate);
 1622:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
 1623:   /* End of Freq */
 1624: }
 1625: 
 1626: /************ Prevalence ********************/
 1627: void prevalence(double agemin, double agemax, int **s, double **agev, int nlstate, int imx, int *Tvar, int **nbcode, int *ncodemax,double **mint,double **anint, double dateprev1,double dateprev2, int firstpass, int lastpass)
 1628: {  
 1629:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 1630:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 1631:      We still use firstpass and lastpass as another selection.
 1632:   */
 1633:  
 1634:   int i, m, jk, k1, i1, j1, bool, z1,z2,j;
 1635:   double ***freq; /* Frequencies */
 1636:   double *pp, **prop;
 1637:   double pos,posprop; 
 1638:   double  y2; /* in fractional years */
 1639:   int iagemin, iagemax;
 1640: 
 1641:   iagemin= (int) agemin;
 1642:   iagemax= (int) agemax;
 1643:   /*pp=vector(1,nlstate);*/
 1644:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
 1645:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
 1646:   j1=0;
 1647:   
 1648:   j=cptcoveff;
 1649:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 1650:   
 1651:   for(k1=1; k1<=j;k1++){
 1652:     for(i1=1; i1<=ncodemax[k1];i1++){
 1653:       j1++;
 1654:       
 1655:       for (i=1; i<=nlstate; i++)  
 1656: 	for(m=iagemin; m <= iagemax+3; m++)
 1657: 	  prop[i][m]=0.0;
 1658:      
 1659:       for (i=1; i<=imx; i++) { /* Each individual */
 1660: 	bool=1;
 1661: 	if  (cptcovn>0) {
 1662: 	  for (z1=1; z1<=cptcoveff; z1++) 
 1663: 	    if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
 1664: 	      bool=0;
 1665: 	} 
 1666: 	if (bool==1) { 
 1667: 	  for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
 1668: 	    y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
 1669: 	    if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
 1670: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 1671: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 1672: 	      if((int)agev[m][i] <iagemin || (int)agev[m][i] >iagemax+3) printf("Error on individual =%d agev[m][i]=%f m=%d\n",i, agev[m][i],m); 
 1673:  	      if (s[m][i]>0 && s[m][i]<=nlstate) { 
 1674: 		/*if(i>4620) printf(" i=%d m=%d s[m][i]=%d (int)agev[m][i]=%d weight[i]=%f prop=%f\n",i,m,s[m][i],(int)agev[m][m],weight[i],prop[s[m][i]][(int)agev[m][i]]);*/
 1675:  		prop[s[m][i]][(int)agev[m][i]] += weight[i];
 1676:  		prop[s[m][i]][iagemax+3] += weight[i]; 
 1677:  	      } 
 1678: 	    }
 1679: 	  } /* end selection of waves */
 1680: 	}
 1681:       }
 1682:       for(i=iagemin; i <= iagemax+3; i++){  
 1683: 	
 1684:  	for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
 1685:  	  posprop += prop[jk][i]; 
 1686:  	} 
 1687: 
 1688:  	for(jk=1; jk <=nlstate ; jk++){	    
 1689:  	  if( i <=  iagemax){ 
 1690:  	    if(posprop>=1.e-5){ 
 1691:  	      probs[i][jk][j1]= prop[jk][i]/posprop;
 1692:  	    } 
 1693:  	  } 
 1694:  	}/* end jk */ 
 1695:       }/* end i */ 
 1696:     } /* end i1 */
 1697:   } /* end k1 */
 1698:   
 1699:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
 1700:   /*free_vector(pp,1,nlstate);*/
 1701:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
 1702: }  /* End of prevalence */
 1703: 
 1704: /************* Waves Concatenation ***************/
 1705: 
 1706: void  concatwav(int wav[], int **dh, int **bh,  int **mw, int **s, double *agedc, double **agev, int  firstpass, int lastpass, int imx, int nlstate, int stepm)
 1707: {
 1708:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
 1709:      Death is a valid wave (if date is known).
 1710:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
 1711:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 1712:      and mw[mi+1][i]. dh depends on stepm.
 1713:      */
 1714: 
 1715:   int i, mi, m;
 1716:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
 1717:      double sum=0., jmean=0.;*/
 1718:   int first;
 1719:   int j, k=0,jk, ju, jl;
 1720:   double sum=0.;
 1721:   first=0;
 1722:   jmin=1e+5;
 1723:   jmax=-1;
 1724:   jmean=0.;
 1725:   for(i=1; i<=imx; i++){
 1726:     mi=0;
 1727:     m=firstpass;
 1728:     while(s[m][i] <= nlstate){
 1729:       if(s[m][i]>=1)
 1730: 	mw[++mi][i]=m;
 1731:       if(m >=lastpass)
 1732: 	break;
 1733:       else
 1734: 	m++;
 1735:     }/* end while */
 1736:     if (s[m][i] > nlstate){
 1737:       mi++;	/* Death is another wave */
 1738:       /* if(mi==0)  never been interviewed correctly before death */
 1739: 	 /* Only death is a correct wave */
 1740:       mw[mi][i]=m;
 1741:     }
 1742: 
 1743:     wav[i]=mi;
 1744:     if(mi==0){
 1745:       if(first==0){
 1746: 	printf("Warning, no any valid information for:%d line=%d and may be others, see log file\n",num[i],i);
 1747: 	first=1;
 1748:       }
 1749:       if(first==1){
 1750: 	fprintf(ficlog,"Warning, no any valid information for:%d line=%d\n",num[i],i);
 1751:       }
 1752:     } /* end mi==0 */
 1753:   }
 1754: 
 1755:   for(i=1; i<=imx; i++){
 1756:     for(mi=1; mi<wav[i];mi++){
 1757:       if (stepm <=0)
 1758: 	dh[mi][i]=1;
 1759:       else{
 1760: 	if (s[mw[mi+1][i]][i] > nlstate) {
 1761: 	  if (agedc[i] < 2*AGESUP) {
 1762: 	  j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
 1763: 	  if(j==0) j=1;  /* Survives at least one month after exam */
 1764: 	  k=k+1;
 1765: 	  if (j >= jmax) jmax=j;
 1766: 	  if (j <= jmin) jmin=j;
 1767: 	  sum=sum+j;
 1768: 	  /*if (j<0) printf("j=%d num=%d \n",j,i); */
 1769: 	  /*	  printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
 1770: 	  /*printf("%d %lf %d %d %d\n", i,agev[mw[mi][i]][i],j,s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);*/
 1771: 	  }
 1772: 	}
 1773: 	else{
 1774: 	  j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
 1775: 	  /*	  printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
 1776: 	  k=k+1;
 1777: 	  if (j >= jmax) jmax=j;
 1778: 	  else if (j <= jmin)jmin=j;
 1779: 	  /*	    if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
 1780: 	  /*printf("%d %lf %d %d %d\n", i,agev[mw[mi][i]][i],j,s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);*/
 1781: 	  sum=sum+j;
 1782: 	}
 1783: 	jk= j/stepm;
 1784: 	jl= j -jk*stepm;
 1785: 	ju= j -(jk+1)*stepm;
 1786: 	if(mle <=1){ 
 1787: 	  if(jl==0){
 1788: 	    dh[mi][i]=jk;
 1789: 	    bh[mi][i]=0;
 1790: 	  }else{ /* We want a negative bias in order to only have interpolation ie
 1791: 		  * at the price of an extra matrix product in likelihood */
 1792: 	    dh[mi][i]=jk+1;
 1793: 	    bh[mi][i]=ju;
 1794: 	  }
 1795: 	}else{
 1796: 	  if(jl <= -ju){
 1797: 	    dh[mi][i]=jk;
 1798: 	    bh[mi][i]=jl;	/* bias is positive if real duration
 1799: 				 * is higher than the multiple of stepm and negative otherwise.
 1800: 				 */
 1801: 	  }
 1802: 	  else{
 1803: 	    dh[mi][i]=jk+1;
 1804: 	    bh[mi][i]=ju;
 1805: 	  }
 1806: 	  if(dh[mi][i]==0){
 1807: 	    dh[mi][i]=1; /* At least one step */
 1808: 	    bh[mi][i]=ju; /* At least one step */
 1809: 	    /*  printf(" bh=%d ju=%d jl=%d dh=%d jk=%d stepm=%d %d\n",bh[mi][i],ju,jl,dh[mi][i],jk,stepm,i);*/
 1810: 	  }
 1811: 	}
 1812:       } /* end if mle */
 1813:     } /* end wave */
 1814:   }
 1815:   jmean=sum/k;
 1816:   printf("Delay (in months) between two waves Min=%d Max=%d Mean=%f\n\n ",jmin, jmax,jmean);
 1817:   fprintf(ficlog,"Delay (in months) between two waves Min=%d Max=%d Mean=%f\n\n ",jmin, jmax,jmean);
 1818:  }
 1819: 
 1820: /*********** Tricode ****************************/
 1821: void tricode(int *Tvar, int **nbcode, int imx)
 1822: {
 1823:   
 1824:   int Ndum[20],ij=1, k, j, i, maxncov=19;
 1825:   int cptcode=0;
 1826:   cptcoveff=0; 
 1827:  
 1828:   for (k=0; k<maxncov; k++) Ndum[k]=0;
 1829:   for (k=1; k<=7; k++) ncodemax[k]=0;
 1830: 
 1831:   for (j=1; j<=(cptcovn+2*cptcovprod); j++) {
 1832:     for (i=1; i<=imx; i++) { /*reads the data file to get the maximum 
 1833: 			       modality*/ 
 1834:       ij=(int)(covar[Tvar[j]][i]); /* ij is the modality of this individual*/
 1835:       Ndum[ij]++; /*store the modality */
 1836:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
 1837:       if (ij > cptcode) cptcode=ij; /* getting the maximum of covariable 
 1838: 				       Tvar[j]. If V=sex and male is 0 and 
 1839: 				       female is 1, then  cptcode=1.*/
 1840:     }
 1841: 
 1842:     for (i=0; i<=cptcode; i++) {
 1843:       if(Ndum[i]!=0) ncodemax[j]++; /* Nomber of modalities of the j th covariates. In fact ncodemax[j]=2 (dichotom. variables) but it can be more */
 1844:     }
 1845: 
 1846:     ij=1; 
 1847:     for (i=1; i<=ncodemax[j]; i++) {
 1848:       for (k=0; k<= maxncov; k++) {
 1849: 	if (Ndum[k] != 0) {
 1850: 	  nbcode[Tvar[j]][ij]=k; 
 1851: 	  /* store the modality in an array. k is a modality. If we have model=V1+V1*sex then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
 1852: 	  
 1853: 	  ij++;
 1854: 	}
 1855: 	if (ij > ncodemax[j]) break; 
 1856:       }  
 1857:     } 
 1858:   }  
 1859: 
 1860:  for (k=0; k< maxncov; k++) Ndum[k]=0;
 1861: 
 1862:  for (i=1; i<=ncovmodel-2; i++) { 
 1863:    /* Listing of all covariables in staement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
 1864:    ij=Tvar[i];
 1865:    Ndum[ij]++;
 1866:  }
 1867: 
 1868:  ij=1;
 1869:  for (i=1; i<= maxncov; i++) {
 1870:    if((Ndum[i]!=0) && (i<=ncovcol)){
 1871:      Tvaraff[ij]=i; /*For printing */
 1872:      ij++;
 1873:    }
 1874:  }
 1875:  
 1876:  cptcoveff=ij-1; /*Number of simple covariates*/
 1877: }
 1878: 
 1879: /*********** Health Expectancies ****************/
 1880: 
 1881: void evsij(char fileres[], double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int ij, int estepm,double delti[],double **matcov )
 1882: 
 1883: {
 1884:   /* Health expectancies */
 1885:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj;
 1886:   double age, agelim, hf;
 1887:   double ***p3mat,***varhe;
 1888:   double **dnewm,**doldm;
 1889:   double *xp;
 1890:   double **gp, **gm;
 1891:   double ***gradg, ***trgradg;
 1892:   int theta;
 1893: 
 1894:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
 1895:   xp=vector(1,npar);
 1896:   dnewm=matrix(1,nlstate*nlstate,1,npar);
 1897:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
 1898:   
 1899:   fprintf(ficreseij,"# Health expectancies\n");
 1900:   fprintf(ficreseij,"# Age");
 1901:   for(i=1; i<=nlstate;i++)
 1902:     for(j=1; j<=nlstate;j++)
 1903:       fprintf(ficreseij," %1d-%1d (SE)",i,j);
 1904:   fprintf(ficreseij,"\n");
 1905: 
 1906:   if(estepm < stepm){
 1907:     printf ("Problem %d lower than %d\n",estepm, stepm);
 1908:   }
 1909:   else  hstepm=estepm;   
 1910:   /* We compute the life expectancy from trapezoids spaced every estepm months
 1911:    * This is mainly to measure the difference between two models: for example
 1912:    * if stepm=24 months pijx are given only every 2 years and by summing them
 1913:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 1914:    * progression in between and thus overestimating or underestimating according
 1915:    * to the curvature of the survival function. If, for the same date, we 
 1916:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 1917:    * to compare the new estimate of Life expectancy with the same linear 
 1918:    * hypothesis. A more precise result, taking into account a more precise
 1919:    * curvature will be obtained if estepm is as small as stepm. */
 1920: 
 1921:   /* For example we decided to compute the life expectancy with the smallest unit */
 1922:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 1923:      nhstepm is the number of hstepm from age to agelim 
 1924:      nstepm is the number of stepm from age to agelin. 
 1925:      Look at hpijx to understand the reason of that which relies in memory size
 1926:      and note for a fixed period like estepm months */
 1927:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 1928:      survival function given by stepm (the optimization length). Unfortunately it
 1929:      means that if the survival funtion is printed only each two years of age and if
 1930:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 1931:      results. So we changed our mind and took the option of the best precision.
 1932:   */
 1933:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 1934: 
 1935:   agelim=AGESUP;
 1936:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 1937:     /* nhstepm age range expressed in number of stepm */
 1938:     nstepm=(int) rint((agelim-age)*YEARM/stepm); 
 1939:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 1940:     /* if (stepm >= YEARM) hstepm=1;*/
 1941:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 1942:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 1943:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
 1944:     gp=matrix(0,nhstepm,1,nlstate*nlstate);
 1945:     gm=matrix(0,nhstepm,1,nlstate*nlstate);
 1946: 
 1947:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
 1948:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
 1949:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, ij);  
 1950:  
 1951: 
 1952:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 1953: 
 1954:     /* Computing Variances of health expectancies */
 1955: 
 1956:      for(theta=1; theta <=npar; theta++){
 1957:       for(i=1; i<=npar; i++){ 
 1958: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 1959:       }
 1960:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 1961:   
 1962:       cptj=0;
 1963:       for(j=1; j<= nlstate; j++){
 1964: 	for(i=1; i<=nlstate; i++){
 1965: 	  cptj=cptj+1;
 1966: 	  for(h=0, gp[h][cptj]=0.; h<=nhstepm-1; h++){
 1967: 	    gp[h][cptj] = (p3mat[i][j][h]+p3mat[i][j][h+1])/2.;
 1968: 	  }
 1969: 	}
 1970:       }
 1971:      
 1972:      
 1973:       for(i=1; i<=npar; i++) 
 1974: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 1975:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 1976:       
 1977:       cptj=0;
 1978:       for(j=1; j<= nlstate; j++){
 1979: 	for(i=1;i<=nlstate;i++){
 1980: 	  cptj=cptj+1;
 1981: 	  for(h=0, gm[h][cptj]=0.; h<=nhstepm-1; h++){
 1982: 	    gm[h][cptj] = (p3mat[i][j][h]+p3mat[i][j][h+1])/2.;
 1983: 	  }
 1984: 	}
 1985:       }
 1986:       for(j=1; j<= nlstate*nlstate; j++)
 1987: 	for(h=0; h<=nhstepm-1; h++){
 1988: 	  gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
 1989: 	}
 1990:      } 
 1991:    
 1992: /* End theta */
 1993: 
 1994:      trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
 1995: 
 1996:      for(h=0; h<=nhstepm-1; h++)
 1997:       for(j=1; j<=nlstate*nlstate;j++)
 1998: 	for(theta=1; theta <=npar; theta++)
 1999: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 2000:      
 2001: 
 2002:      for(i=1;i<=nlstate*nlstate;i++)
 2003:       for(j=1;j<=nlstate*nlstate;j++)
 2004: 	varhe[i][j][(int)age] =0.;
 2005: 
 2006:      printf("%d|",(int)age);fflush(stdout);
 2007:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 2008:      for(h=0;h<=nhstepm-1;h++){
 2009:       for(k=0;k<=nhstepm-1;k++){
 2010: 	matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
 2011: 	matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
 2012: 	for(i=1;i<=nlstate*nlstate;i++)
 2013: 	  for(j=1;j<=nlstate*nlstate;j++)
 2014: 	    varhe[i][j][(int)age] += doldm[i][j]*hf*hf;
 2015:       }
 2016:     }
 2017:     /* Computing expectancies */
 2018:     for(i=1; i<=nlstate;i++)
 2019:       for(j=1; j<=nlstate;j++)
 2020: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 2021: 	  eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
 2022: 	  
 2023: /* if((int)age==70)printf("i=%2d,j=%2d,h=%2d,age=%3d,%9.4f,%9.4f,%9.4f\n",i,j,h,(int)age,p3mat[i][j][h],hf,eij[i][j][(int)age]);*/
 2024: 
 2025: 	}
 2026: 
 2027:     fprintf(ficreseij,"%3.0f",age );
 2028:     cptj=0;
 2029:     for(i=1; i<=nlstate;i++)
 2030:       for(j=1; j<=nlstate;j++){
 2031: 	cptj++;
 2032: 	fprintf(ficreseij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[cptj][cptj][(int)age]) );
 2033:       }
 2034:     fprintf(ficreseij,"\n");
 2035:    
 2036:     free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
 2037:     free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
 2038:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
 2039:     free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
 2040:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 2041:   }
 2042:   printf("\n");
 2043:   fprintf(ficlog,"\n");
 2044: 
 2045:   free_vector(xp,1,npar);
 2046:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
 2047:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
 2048:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
 2049: }
 2050: 
 2051: /************ Variance ******************/
 2052: void varevsij(char optionfilefiname[], double ***vareij, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int ij, int estepm, int cptcov, int cptcod, int popbased, int mobilav)
 2053: {
 2054:   /* Variance of health expectancies */
 2055:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
 2056:   /* double **newm;*/
 2057:   double **dnewm,**doldm;
 2058:   double **dnewmp,**doldmp;
 2059:   int i, j, nhstepm, hstepm, h, nstepm ;
 2060:   int k, cptcode;
 2061:   double *xp;
 2062:   double **gp, **gm;  /* for var eij */
 2063:   double ***gradg, ***trgradg; /*for var eij */
 2064:   double **gradgp, **trgradgp; /* for var p point j */
 2065:   double *gpp, *gmp; /* for var p point j */
 2066:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
 2067:   double ***p3mat;
 2068:   double age,agelim, hf;
 2069:   double ***mobaverage;
 2070:   int theta;
 2071:   char digit[4];
 2072:   char digitp[25];
 2073: 
 2074:   char fileresprobmorprev[FILENAMELENGTH];
 2075: 
 2076:   if(popbased==1){
 2077:     if(mobilav!=0)
 2078:       strcpy(digitp,"-populbased-mobilav-");
 2079:     else strcpy(digitp,"-populbased-nomobil-");
 2080:   }
 2081:   else 
 2082:     strcpy(digitp,"-stablbased-");
 2083: 
 2084:   if (mobilav!=0) {
 2085:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 2086:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 2087:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 2088:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 2089:     }
 2090:   }
 2091: 
 2092:   strcpy(fileresprobmorprev,"prmorprev"); 
 2093:   sprintf(digit,"%-d",ij);
 2094:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
 2095:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
 2096:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
 2097:   strcat(fileresprobmorprev,fileres);
 2098:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
 2099:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
 2100:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
 2101:   }
 2102:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 2103:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 2104:   fprintf(ficresprobmorprev,"# probabilities of dying before estepm=%d months for people of exact age and weighted probabilities w1*p1j+w2*p2j+... stand dev in()\n",estepm);
 2105:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
 2106:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 2107:     fprintf(ficresprobmorprev," p.%-d SE",j);
 2108:     for(i=1; i<=nlstate;i++)
 2109:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
 2110:   }  
 2111:   fprintf(ficresprobmorprev,"\n");
 2112:   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) {
 2113:     printf("Problem with gnuplot file: %s\n", optionfilegnuplot);
 2114:     fprintf(ficlog,"Problem with gnuplot file: %s\n", optionfilegnuplot);
 2115:     exit(0);
 2116:   }
 2117:   else{
 2118:     fprintf(ficgp,"\n# Routine varevsij");
 2119:   }
 2120:   if((fichtm=fopen(optionfilehtm,"a"))==NULL) {
 2121:     printf("Problem with html file: %s\n", optionfilehtm);
 2122:     fprintf(ficlog,"Problem with html file: %s\n", optionfilehtm);
 2123:     exit(0);
 2124:   }
 2125:   else{
 2126:     fprintf(fichtm,"\n<li><h4> Computing probabilities of dying over estepm months as a weighted average (i.e global mortality independent of initial healh state)</h4></li>\n");
 2127:     fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
 2128:   }
 2129:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 2130: 
 2131:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are the stable prevalence in health states i\n");
 2132:   fprintf(ficresvij,"# Age");
 2133:   for(i=1; i<=nlstate;i++)
 2134:     for(j=1; j<=nlstate;j++)
 2135:       fprintf(ficresvij," Cov(e%1d, e%1d)",i,j);
 2136:   fprintf(ficresvij,"\n");
 2137: 
 2138:   xp=vector(1,npar);
 2139:   dnewm=matrix(1,nlstate,1,npar);
 2140:   doldm=matrix(1,nlstate,1,nlstate);
 2141:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
 2142:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 2143: 
 2144:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
 2145:   gpp=vector(nlstate+1,nlstate+ndeath);
 2146:   gmp=vector(nlstate+1,nlstate+ndeath);
 2147:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 2148:   
 2149:   if(estepm < stepm){
 2150:     printf ("Problem %d lower than %d\n",estepm, stepm);
 2151:   }
 2152:   else  hstepm=estepm;   
 2153:   /* For example we decided to compute the life expectancy with the smallest unit */
 2154:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 2155:      nhstepm is the number of hstepm from age to agelim 
 2156:      nstepm is the number of stepm from age to agelin. 
 2157:      Look at hpijx to understand the reason of that which relies in memory size
 2158:      and note for a fixed period like k years */
 2159:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 2160:      survival function given by stepm (the optimization length). Unfortunately it
 2161:      means that if the survival funtion is printed every two years of age and if
 2162:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 2163:      results. So we changed our mind and took the option of the best precision.
 2164:   */
 2165:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 2166:   agelim = AGESUP;
 2167:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 2168:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 2169:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 2170:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 2171:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
 2172:     gp=matrix(0,nhstepm,1,nlstate);
 2173:     gm=matrix(0,nhstepm,1,nlstate);
 2174: 
 2175: 
 2176:     for(theta=1; theta <=npar; theta++){
 2177:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
 2178: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 2179:       }
 2180:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 2181:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 2182: 
 2183:       if (popbased==1) {
 2184: 	if(mobilav ==0){
 2185: 	  for(i=1; i<=nlstate;i++)
 2186: 	    prlim[i][i]=probs[(int)age][i][ij];
 2187: 	}else{ /* mobilav */ 
 2188: 	  for(i=1; i<=nlstate;i++)
 2189: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 2190: 	}
 2191:       }
 2192:   
 2193:       for(j=1; j<= nlstate; j++){
 2194: 	for(h=0; h<=nhstepm; h++){
 2195: 	  for(i=1, gp[h][j]=0.;i<=nlstate;i++)
 2196: 	    gp[h][j] += prlim[i][i]*p3mat[i][j][h];
 2197: 	}
 2198:       }
 2199:       /* This for computing probability of death (h=1 means
 2200:          computed over hstepm matrices product = hstepm*stepm months) 
 2201:          as a weighted average of prlim.
 2202:       */
 2203:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 2204: 	for(i=1,gpp[j]=0.; i<= nlstate; i++)
 2205: 	  gpp[j] += prlim[i][i]*p3mat[i][j][1];
 2206:       }    
 2207:       /* end probability of death */
 2208: 
 2209:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
 2210: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 2211:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 2212:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 2213:  
 2214:       if (popbased==1) {
 2215: 	if(mobilav ==0){
 2216: 	  for(i=1; i<=nlstate;i++)
 2217: 	    prlim[i][i]=probs[(int)age][i][ij];
 2218: 	}else{ /* mobilav */ 
 2219: 	  for(i=1; i<=nlstate;i++)
 2220: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 2221: 	}
 2222:       }
 2223: 
 2224:       for(j=1; j<= nlstate; j++){
 2225: 	for(h=0; h<=nhstepm; h++){
 2226: 	  for(i=1, gm[h][j]=0.;i<=nlstate;i++)
 2227: 	    gm[h][j] += prlim[i][i]*p3mat[i][j][h];
 2228: 	}
 2229:       }
 2230:       /* This for computing probability of death (h=1 means
 2231:          computed over hstepm matrices product = hstepm*stepm months) 
 2232:          as a weighted average of prlim.
 2233:       */
 2234:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 2235: 	for(i=1,gmp[j]=0.; i<= nlstate; i++)
 2236:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
 2237:       }    
 2238:       /* end probability of death */
 2239: 
 2240:       for(j=1; j<= nlstate; j++) /* vareij */
 2241: 	for(h=0; h<=nhstepm; h++){
 2242: 	  gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
 2243: 	}
 2244: 
 2245:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
 2246: 	gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
 2247:       }
 2248: 
 2249:     } /* End theta */
 2250: 
 2251:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
 2252: 
 2253:     for(h=0; h<=nhstepm; h++) /* veij */
 2254:       for(j=1; j<=nlstate;j++)
 2255: 	for(theta=1; theta <=npar; theta++)
 2256: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 2257: 
 2258:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
 2259:       for(theta=1; theta <=npar; theta++)
 2260: 	trgradgp[j][theta]=gradgp[theta][j];
 2261:   
 2262: 
 2263:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 2264:     for(i=1;i<=nlstate;i++)
 2265:       for(j=1;j<=nlstate;j++)
 2266: 	vareij[i][j][(int)age] =0.;
 2267: 
 2268:     for(h=0;h<=nhstepm;h++){
 2269:       for(k=0;k<=nhstepm;k++){
 2270: 	matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
 2271: 	matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
 2272: 	for(i=1;i<=nlstate;i++)
 2273: 	  for(j=1;j<=nlstate;j++)
 2274: 	    vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
 2275:       }
 2276:     }
 2277:   
 2278:     /* pptj */
 2279:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
 2280:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
 2281:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
 2282:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
 2283: 	varppt[j][i]=doldmp[j][i];
 2284:     /* end ppptj */
 2285:     /*  x centered again */
 2286:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
 2287:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
 2288:  
 2289:     if (popbased==1) {
 2290:       if(mobilav ==0){
 2291: 	for(i=1; i<=nlstate;i++)
 2292: 	  prlim[i][i]=probs[(int)age][i][ij];
 2293:       }else{ /* mobilav */ 
 2294: 	for(i=1; i<=nlstate;i++)
 2295: 	  prlim[i][i]=mobaverage[(int)age][i][ij];
 2296:       }
 2297:     }
 2298:              
 2299:     /* This for computing probability of death (h=1 means
 2300:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
 2301:        as a weighted average of prlim.
 2302:     */
 2303:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
 2304:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
 2305: 	gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
 2306:     }    
 2307:     /* end probability of death */
 2308: 
 2309:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
 2310:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 2311:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
 2312:       for(i=1; i<=nlstate;i++){
 2313: 	fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
 2314:       }
 2315:     } 
 2316:     fprintf(ficresprobmorprev,"\n");
 2317: 
 2318:     fprintf(ficresvij,"%.0f ",age );
 2319:     for(i=1; i<=nlstate;i++)
 2320:       for(j=1; j<=nlstate;j++){
 2321: 	fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
 2322:       }
 2323:     fprintf(ficresvij,"\n");
 2324:     free_matrix(gp,0,nhstepm,1,nlstate);
 2325:     free_matrix(gm,0,nhstepm,1,nlstate);
 2326:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
 2327:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
 2328:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 2329:   } /* End age */
 2330:   free_vector(gpp,nlstate+1,nlstate+ndeath);
 2331:   free_vector(gmp,nlstate+1,nlstate+ndeath);
 2332:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
 2333:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 2334:   fprintf(ficgp,"\nset noparametric;set nolabel; set ter png small;set size 0.65, 0.65");
 2335:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
 2336:   fprintf(ficgp,"\n set log y; set nolog x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
 2337: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
 2338: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
 2339: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
 2340:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l 1 ",fileresprobmorprev);
 2341:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95\%% interval\" w l 2 ",fileresprobmorprev);
 2342:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l 2 ",fileresprobmorprev);
 2343:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",fileresprobmorprev,fileresprobmorprev);
 2344:   fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months. <br> <img src=\"varmuptjgr%s%s%s.png\"> <br>\n", estepm,digitp,optionfilefiname,digit);
 2345:   /*  fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months and then divided by estepm and multiplied by %.0f in order to have the probability to die over a year <br> <img src=\"varmuptjgr%s%s.png\"> <br>\n", stepm,YEARM,digitp,digit);
 2346: */
 2347:   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit);
 2348: 
 2349:   free_vector(xp,1,npar);
 2350:   free_matrix(doldm,1,nlstate,1,nlstate);
 2351:   free_matrix(dnewm,1,nlstate,1,npar);
 2352:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 2353:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
 2354:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 2355:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 2356:   fclose(ficresprobmorprev);
 2357:   fclose(ficgp);
 2358:   fclose(fichtm);
 2359: }  
 2360: 
 2361: /************ Variance of prevlim ******************/
 2362: 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)
 2363: {
 2364:   /* Variance of prevalence limit */
 2365:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
 2366:   double **newm;
 2367:   double **dnewm,**doldm;
 2368:   int i, j, nhstepm, hstepm;
 2369:   int k, cptcode;
 2370:   double *xp;
 2371:   double *gp, *gm;
 2372:   double **gradg, **trgradg;
 2373:   double age,agelim;
 2374:   int theta;
 2375:    
 2376:   fprintf(ficresvpl,"# Standard deviation of stable prevalences \n");
 2377:   fprintf(ficresvpl,"# Age");
 2378:   for(i=1; i<=nlstate;i++)
 2379:       fprintf(ficresvpl," %1d-%1d",i,i);
 2380:   fprintf(ficresvpl,"\n");
 2381: 
 2382:   xp=vector(1,npar);
 2383:   dnewm=matrix(1,nlstate,1,npar);
 2384:   doldm=matrix(1,nlstate,1,nlstate);
 2385:   
 2386:   hstepm=1*YEARM; /* Every year of age */
 2387:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
 2388:   agelim = AGESUP;
 2389:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 2390:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 2391:     if (stepm >= YEARM) hstepm=1;
 2392:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 2393:     gradg=matrix(1,npar,1,nlstate);
 2394:     gp=vector(1,nlstate);
 2395:     gm=vector(1,nlstate);
 2396: 
 2397:     for(theta=1; theta <=npar; theta++){
 2398:       for(i=1; i<=npar; i++){ /* Computes gradient */
 2399: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 2400:       }
 2401:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 2402:       for(i=1;i<=nlstate;i++)
 2403: 	gp[i] = prlim[i][i];
 2404:     
 2405:       for(i=1; i<=npar; i++) /* Computes gradient */
 2406: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 2407:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 2408:       for(i=1;i<=nlstate;i++)
 2409: 	gm[i] = prlim[i][i];
 2410: 
 2411:       for(i=1;i<=nlstate;i++)
 2412: 	gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
 2413:     } /* End theta */
 2414: 
 2415:     trgradg =matrix(1,nlstate,1,npar);
 2416: 
 2417:     for(j=1; j<=nlstate;j++)
 2418:       for(theta=1; theta <=npar; theta++)
 2419: 	trgradg[j][theta]=gradg[theta][j];
 2420: 
 2421:     for(i=1;i<=nlstate;i++)
 2422:       varpl[i][(int)age] =0.;
 2423:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 2424:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 2425:     for(i=1;i<=nlstate;i++)
 2426:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
 2427: 
 2428:     fprintf(ficresvpl,"%.0f ",age );
 2429:     for(i=1; i<=nlstate;i++)
 2430:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
 2431:     fprintf(ficresvpl,"\n");
 2432:     free_vector(gp,1,nlstate);
 2433:     free_vector(gm,1,nlstate);
 2434:     free_matrix(gradg,1,npar,1,nlstate);
 2435:     free_matrix(trgradg,1,nlstate,1,npar);
 2436:   } /* End age */
 2437: 
 2438:   free_vector(xp,1,npar);
 2439:   free_matrix(doldm,1,nlstate,1,npar);
 2440:   free_matrix(dnewm,1,nlstate,1,nlstate);
 2441: 
 2442: }
 2443: 
 2444: /************ Variance of one-step probabilities  ******************/
 2445: void varprob(char optionfilefiname[], double **matcov, double x[], double delti[], int nlstate, double bage, double fage, int ij, int *Tvar, int **nbcode, int *ncodemax)
 2446: {
 2447:   int i, j=0,  i1, k1, l1, t, tj;
 2448:   int k2, l2, j1,  z1;
 2449:   int k=0,l, cptcode;
 2450:   int first=1, first1;
 2451:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
 2452:   double **dnewm,**doldm;
 2453:   double *xp;
 2454:   double *gp, *gm;
 2455:   double **gradg, **trgradg;
 2456:   double **mu;
 2457:   double age,agelim, cov[NCOVMAX];
 2458:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
 2459:   int theta;
 2460:   char fileresprob[FILENAMELENGTH];
 2461:   char fileresprobcov[FILENAMELENGTH];
 2462:   char fileresprobcor[FILENAMELENGTH];
 2463: 
 2464:   double ***varpij;
 2465: 
 2466:   strcpy(fileresprob,"prob"); 
 2467:   strcat(fileresprob,fileres);
 2468:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
 2469:     printf("Problem with resultfile: %s\n", fileresprob);
 2470:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
 2471:   }
 2472:   strcpy(fileresprobcov,"probcov"); 
 2473:   strcat(fileresprobcov,fileres);
 2474:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
 2475:     printf("Problem with resultfile: %s\n", fileresprobcov);
 2476:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
 2477:   }
 2478:   strcpy(fileresprobcor,"probcor"); 
 2479:   strcat(fileresprobcor,fileres);
 2480:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
 2481:     printf("Problem with resultfile: %s\n", fileresprobcor);
 2482:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
 2483:   }
 2484:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 2485:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 2486:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 2487:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 2488:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 2489:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 2490:   
 2491:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
 2492:   fprintf(ficresprob,"# Age");
 2493:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
 2494:   fprintf(ficresprobcov,"# Age");
 2495:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
 2496:   fprintf(ficresprobcov,"# Age");
 2497: 
 2498: 
 2499:   for(i=1; i<=nlstate;i++)
 2500:     for(j=1; j<=(nlstate+ndeath);j++){
 2501:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
 2502:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
 2503:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
 2504:     }  
 2505:  /* fprintf(ficresprob,"\n");
 2506:   fprintf(ficresprobcov,"\n");
 2507:   fprintf(ficresprobcor,"\n");
 2508:  */
 2509:  xp=vector(1,npar);
 2510:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 2511:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 2512:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
 2513:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
 2514:   first=1;
 2515:   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) {
 2516:     printf("Problem with gnuplot file: %s\n", optionfilegnuplot);
 2517:     fprintf(ficlog,"Problem with gnuplot file: %s\n", optionfilegnuplot);
 2518:     exit(0);
 2519:   }
 2520:   else{
 2521:     fprintf(ficgp,"\n# Routine varprob");
 2522:   }
 2523:   if((fichtm=fopen(optionfilehtm,"a"))==NULL) {
 2524:     printf("Problem with html file: %s\n", optionfilehtm);
 2525:     fprintf(ficlog,"Problem with html file: %s\n", optionfilehtm);
 2526:     exit(0);
 2527:   }
 2528:   else{
 2529:     fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
 2530:     fprintf(fichtm,"\n");
 2531: 
 2532:     fprintf(fichtm,"\n<li><h4> Computing matrix of variance-covariance of step probabilities</h4></li>\n");
 2533:     fprintf(fichtm,"\nWe have drawn ellipsoids of confidence around the p<inf>ij</inf>, p<inf>kl</inf> to understand the covariance between two incidences. They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
 2534:     fprintf(fichtm,"\n<br> We have drawn x'cov<sup>-1</sup>x = 4 where x is the column vector (pij,pkl). It means that if pij and pkl where uncorrelated the (2X2) matrix would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 standard deviations wide on each axis. <br> When both incidences are correlated we diagonalised the inverse of the covariance matrix and made the appropriate rotation.<br> \n");
 2535: 
 2536:   }
 2537: 
 2538:   cov[1]=1;
 2539:   tj=cptcoveff;
 2540:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
 2541:   j1=0;
 2542:   for(t=1; t<=tj;t++){
 2543:     for(i1=1; i1<=ncodemax[t];i1++){ 
 2544:       j1++;
 2545:       if  (cptcovn>0) {
 2546: 	fprintf(ficresprob, "\n#********** Variable "); 
 2547: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 2548: 	fprintf(ficresprob, "**********\n#\n");
 2549: 	fprintf(ficresprobcov, "\n#********** Variable "); 
 2550: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 2551: 	fprintf(ficresprobcov, "**********\n#\n");
 2552: 	
 2553: 	fprintf(ficgp, "\n#********** Variable "); 
 2554: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 2555: 	fprintf(ficgp, "**********\n#\n");
 2556: 	
 2557: 	
 2558: 	fprintf(fichtm, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
 2559: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 2560: 	fprintf(fichtm, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
 2561: 	
 2562: 	fprintf(ficresprobcor, "\n#********** Variable ");    
 2563: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 2564: 	fprintf(ficresprobcor, "**********\n#");    
 2565:       }
 2566:       
 2567:       for (age=bage; age<=fage; age ++){ 
 2568: 	cov[2]=age;
 2569: 	for (k=1; k<=cptcovn;k++) {
 2570: 	  cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];
 2571: 	}
 2572: 	for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
 2573: 	for (k=1; k<=cptcovprod;k++)
 2574: 	  cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 2575: 	
 2576: 	gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
 2577: 	trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 2578: 	gp=vector(1,(nlstate)*(nlstate+ndeath));
 2579: 	gm=vector(1,(nlstate)*(nlstate+ndeath));
 2580:     
 2581: 	for(theta=1; theta <=npar; theta++){
 2582: 	  for(i=1; i<=npar; i++)
 2583: 	    xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
 2584: 	  
 2585: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 2586: 	  
 2587: 	  k=0;
 2588: 	  for(i=1; i<= (nlstate); i++){
 2589: 	    for(j=1; j<=(nlstate+ndeath);j++){
 2590: 	      k=k+1;
 2591: 	      gp[k]=pmmij[i][j];
 2592: 	    }
 2593: 	  }
 2594: 	  
 2595: 	  for(i=1; i<=npar; i++)
 2596: 	    xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
 2597:     
 2598: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 2599: 	  k=0;
 2600: 	  for(i=1; i<=(nlstate); i++){
 2601: 	    for(j=1; j<=(nlstate+ndeath);j++){
 2602: 	      k=k+1;
 2603: 	      gm[k]=pmmij[i][j];
 2604: 	    }
 2605: 	  }
 2606:      
 2607: 	  for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
 2608: 	    gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
 2609: 	}
 2610: 
 2611: 	for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
 2612: 	  for(theta=1; theta <=npar; theta++)
 2613: 	    trgradg[j][theta]=gradg[theta][j];
 2614: 	
 2615: 	matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
 2616: 	matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
 2617: 	free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
 2618: 	free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
 2619: 	free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 2620: 	free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 2621: 
 2622: 	pmij(pmmij,cov,ncovmodel,x,nlstate);
 2623: 	
 2624: 	k=0;
 2625: 	for(i=1; i<=(nlstate); i++){
 2626: 	  for(j=1; j<=(nlstate+ndeath);j++){
 2627: 	    k=k+1;
 2628: 	    mu[k][(int) age]=pmmij[i][j];
 2629: 	  }
 2630: 	}
 2631:      	for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
 2632: 	  for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
 2633: 	    varpij[i][j][(int)age] = doldm[i][j];
 2634: 
 2635: 	/*printf("\n%d ",(int)age);
 2636: 	  for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 2637: 	  printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 2638: 	  fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 2639: 	  }*/
 2640: 
 2641: 	fprintf(ficresprob,"\n%d ",(int)age);
 2642: 	fprintf(ficresprobcov,"\n%d ",(int)age);
 2643: 	fprintf(ficresprobcor,"\n%d ",(int)age);
 2644: 
 2645: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
 2646: 	  fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
 2647: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 2648: 	  fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
 2649: 	  fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
 2650: 	}
 2651: 	i=0;
 2652: 	for (k=1; k<=(nlstate);k++){
 2653:  	  for (l=1; l<=(nlstate+ndeath);l++){ 
 2654:  	    i=i++;
 2655: 	    fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
 2656: 	    fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
 2657: 	    for (j=1; j<=i;j++){
 2658: 	      fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
 2659: 	      fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
 2660: 	    }
 2661: 	  }
 2662: 	}/* end of loop for state */
 2663:       } /* end of loop for age */
 2664: 
 2665:       /* Confidence intervalle of pij  */
 2666:       /*
 2667: 	fprintf(ficgp,"\nset noparametric;unset label");
 2668: 	fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
 2669: 	fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
 2670: 	fprintf(fichtm,"\n<br>Probability with  confidence intervals expressed in year<sup>-1</sup> :<a href=\"pijgr%s.png\">pijgr%s.png</A>, ",optionfilefiname,optionfilefiname);
 2671: 	fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
 2672: 	fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
 2673: 	fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
 2674:       */
 2675: 
 2676:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
 2677:       first1=1;
 2678:       for (k2=1; k2<=(nlstate);k2++){
 2679: 	for (l2=1; l2<=(nlstate+ndeath);l2++){ 
 2680: 	  if(l2==k2) continue;
 2681: 	  j=(k2-1)*(nlstate+ndeath)+l2;
 2682: 	  for (k1=1; k1<=(nlstate);k1++){
 2683: 	    for (l1=1; l1<=(nlstate+ndeath);l1++){ 
 2684: 	      if(l1==k1) continue;
 2685: 	      i=(k1-1)*(nlstate+ndeath)+l1;
 2686: 	      if(i<=j) continue;
 2687: 	      for (age=bage; age<=fage; age ++){ 
 2688: 		if ((int)age %5==0){
 2689: 		  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
 2690: 		  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
 2691: 		  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
 2692: 		  mu1=mu[i][(int) age]/stepm*YEARM ;
 2693: 		  mu2=mu[j][(int) age]/stepm*YEARM;
 2694: 		  c12=cv12/sqrt(v1*v2);
 2695: 		  /* Computing eigen value of matrix of covariance */
 2696: 		  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 2697: 		  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 2698: 		  /* Eigen vectors */
 2699: 		  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
 2700: 		  /*v21=sqrt(1.-v11*v11); *//* error */
 2701: 		  v21=(lc1-v1)/cv12*v11;
 2702: 		  v12=-v21;
 2703: 		  v22=v11;
 2704: 		  tnalp=v21/v11;
 2705: 		  if(first1==1){
 2706: 		    first1=0;
 2707: 		    printf("%d %d%d-%d%d mu %.4e %.4e Var %.4e %.4e cor %.3f cov %.4e Eig %.3e %.3e 1stv %.3f %.3f tang %.3f\nOthers in log...\n",(int) age,k1,l1,k2,l2,mu1,mu2,v1,v2,c12,cv12,lc1,lc2,v11,v21,tnalp);
 2708: 		  }
 2709: 		  fprintf(ficlog,"%d %d%d-%d%d mu %.4e %.4e Var %.4e %.4e cor %.3f cov %.4e Eig %.3e %.3e 1stv %.3f %.3f tan %.3f\n",(int) age,k1,l1,k2,l2,mu1,mu2,v1,v2,c12,cv12,lc1,lc2,v11,v21,tnalp);
 2710: 		  /*printf(fignu*/
 2711: 		  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
 2712: 		  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
 2713: 		  if(first==1){
 2714: 		    first=0;
 2715:  		    fprintf(ficgp,"\nset parametric;unset label");
 2716: 		    fprintf(ficgp,"\nset log y;set log x; set xlabel \"p%1d%1d (year-1)\";set ylabel \"p%1d%1d (year-1)\"",k1,l1,k2,l2);
 2717: 		    fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
 2718: 		    fprintf(fichtm,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup> :<a href=\"varpijgr%s%d%1d%1d-%1d%1d.png\">varpijgr%s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,optionfilefiname, j1,k1,l1,k2,l2,optionfilefiname, j1,k1,l1,k2,l2);
 2719: 		    fprintf(fichtm,"\n<br><img src=\"varpijgr%s%d%1d%1d-%1d%1d.png\"> ",optionfilefiname, j1,k1,l1,k2,l2);
 2720: 		    fprintf(fichtm,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
 2721: 		    fprintf(ficgp,"\nset out \"varpijgr%s%d%1d%1d-%1d%1d.png\"",optionfilefiname, j1,k1,l1,k2,l2);
 2722: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 2723: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 2724: 		    fprintf(ficgp,"\nplot [-pi:pi] %11.3e+ %.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)), %11.3e +%.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)) not",\
 2725: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 2726: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 2727: 		  }else{
 2728: 		    first=0;
 2729: 		    fprintf(fichtm," %d (%.3f),",(int) age, c12);
 2730: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 2731: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 2732: 		    fprintf(ficgp,"\nreplot %11.3e+ %.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)), %11.3e +%.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)) not",\
 2733: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 2734: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 2735: 		  }/* if first */
 2736: 		} /* age mod 5 */
 2737: 	      } /* end loop age */
 2738: 	      fprintf(ficgp,"\nset out \"varpijgr%s%d%1d%1d-%1d%1d.png\";replot;",optionfilefiname, j1,k1,l1,k2,l2);
 2739: 	      first=1;
 2740: 	    } /*l12 */
 2741: 	  } /* k12 */
 2742: 	} /*l1 */
 2743:       }/* k1 */
 2744:     } /* loop covariates */
 2745:   }
 2746:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
 2747:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
 2748:   free_vector(xp,1,npar);
 2749:   fclose(ficresprob);
 2750:   fclose(ficresprobcov);
 2751:   fclose(ficresprobcor);
 2752:   fclose(ficgp);
 2753:   fclose(fichtm);
 2754: }
 2755: 
 2756: 
 2757: /******************* Printing html file ***********/
 2758: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
 2759: 		  int lastpass, int stepm, int weightopt, char model[],\
 2760: 		  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
 2761: 		  int popforecast, int estepm ,\
 2762: 		  double jprev1, double mprev1,double anprev1, \
 2763: 		  double jprev2, double mprev2,double anprev2){
 2764:   int jj1, k1, i1, cpt;
 2765:   /*char optionfilehtm[FILENAMELENGTH];*/
 2766:   if((fichtm=fopen(optionfilehtm,"a"))==NULL)    {
 2767:     printf("Problem with %s \n",optionfilehtm), exit(0);
 2768:     fprintf(ficlog,"Problem with %s \n",optionfilehtm), exit(0);
 2769:   }
 2770: 
 2771:    fprintf(fichtm,"<ul><li><h4>Result files (first order: no variance)</h4>\n
 2772:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"p%s\">p%s</a> <br>\n
 2773:  - Estimated transition probabilities over %d (stepm) months: <a href=\"pij%s\">pij%s</a><br>\n
 2774:  - Stable prevalence in each health state: <a href=\"pl%s\">pl%s</a> <br>\n
 2775:  - Life expectancies by age and initial health status (estepm=%2d months): 
 2776:    <a href=\"e%s\">e%s</a> <br>\n</li>", \
 2777:   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,fileres,fileres,stepm,fileres,fileres,fileres,fileres,estepm,fileres,fileres);
 2778: 
 2779: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
 2780: 
 2781:  m=cptcoveff;
 2782:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 2783: 
 2784:  jj1=0;
 2785:  for(k1=1; k1<=m;k1++){
 2786:    for(i1=1; i1<=ncodemax[k1];i1++){
 2787:      jj1++;
 2788:      if (cptcovn > 0) {
 2789:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 2790:        for (cpt=1; cpt<=cptcoveff;cpt++) 
 2791: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
 2792:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 2793:      }
 2794:      /* Pij */
 2795:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months before: pe%s%d1.png<br>
 2796: <img src=\"pe%s%d1.png\">",stepm,strtok(optionfile, "."),jj1,strtok(optionfile, "."),jj1);     
 2797:      /* Quasi-incidences */
 2798:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too: pe%s%d2.png<br>
 2799: <img src=\"pe%s%d2.png\">",stepm,strtok(optionfile, "."),jj1,strtok(optionfile, "."),jj1); 
 2800:        /* Stable prevalence in each health state */
 2801:        for(cpt=1; cpt<nlstate;cpt++){
 2802: 	 fprintf(fichtm,"<br>- Stable prevalence in each health state : p%s%d%d.png<br>
 2803: <img src=\"p%s%d%d.png\">",strtok(optionfile, "."),cpt,jj1,strtok(optionfile, "."),cpt,jj1);
 2804:        }
 2805:      for(cpt=1; cpt<=nlstate;cpt++) {
 2806:         fprintf(fichtm,"\n<br>- Health life expectancies by age and initial health state (%d): exp%s%d%d.png <br>
 2807: <img src=\"exp%s%d%d.png\">",cpt,strtok(optionfile, "."),cpt,jj1,strtok(optionfile, "."),cpt,jj1);
 2808:      }
 2809:      fprintf(fichtm,"\n<br>- Total life expectancy by age and
 2810: health expectancies in states (1) and (2): e%s%d.png<br>
 2811: <img src=\"e%s%d.png\">",strtok(optionfile, "."),jj1,strtok(optionfile, "."),jj1);
 2812:    } /* end i1 */
 2813:  }/* End k1 */
 2814:  fprintf(fichtm,"</ul>");
 2815: 
 2816: 
 2817:  fprintf(fichtm,"\n<br><li><h4> Result files (second order: variances)</h4>\n
 2818:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n
 2819:  - Variance of one-step probabilities: <a href=\"prob%s\">prob%s</a> <br>\n
 2820:  - Variance-covariance of one-step probabilities: <a href=\"probcov%s\">probcov%s</a> <br>\n
 2821:  - Correlation matrix of one-step probabilities: <a href=\"probcor%s\">probcor%s</a> <br>\n
 2822:  - Variances and covariances of life expectancies by age and initial health status (estepm=%d months): <a href=\"v%s\">v%s</a><br>\n 
 2823:  - Health expectancies with their variances (no covariance): <a href=\"t%s\">t%s</a> <br>\n
 2824:  - Standard deviation of stable prevalences: <a href=\"vpl%s\">vpl%s</a> <br>\n",rfileres,rfileres,fileres,fileres,fileres,fileres,fileres,fileres, estepm, fileres,fileres,fileres,fileres,fileres,fileres);
 2825: 
 2826:  if(popforecast==1) fprintf(fichtm,"\n
 2827:  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n
 2828:  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n
 2829: 	<br>",fileres,fileres,fileres,fileres);
 2830:  else 
 2831:    fprintf(fichtm,"\n No population forecast: popforecast = %d (instead of 1) or stepm = %d (instead of 1) or model=%s (instead of .)<br><br></li>\n",popforecast, stepm, model);
 2832: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
 2833: 
 2834:  m=cptcoveff;
 2835:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 2836: 
 2837:  jj1=0;
 2838:  for(k1=1; k1<=m;k1++){
 2839:    for(i1=1; i1<=ncodemax[k1];i1++){
 2840:      jj1++;
 2841:      if (cptcovn > 0) {
 2842:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 2843:        for (cpt=1; cpt<=cptcoveff;cpt++) 
 2844: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
 2845:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 2846:      }
 2847:      for(cpt=1; cpt<=nlstate;cpt++) {
 2848:        fprintf(fichtm,"<br>- Observed and stationary prevalence (with confident
 2849: interval) in state (%d): v%s%d%d.png <br>
 2850: <img src=\"v%s%d%d.png\">",cpt,strtok(optionfile, "."),cpt,jj1,strtok(optionfile, "."),cpt,jj1);  
 2851:      }
 2852:    } /* end i1 */
 2853:  }/* End k1 */
 2854:  fprintf(fichtm,"</ul>");
 2855: fclose(fichtm);
 2856: }
 2857: 
 2858: /******************* Gnuplot file **************/
 2859: void printinggnuplot(char fileres[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 2860: 
 2861:   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
 2862:   int ng;
 2863:   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) {
 2864:     printf("Problem with file %s",optionfilegnuplot);
 2865:     fprintf(ficlog,"Problem with file %s",optionfilegnuplot);
 2866:   }
 2867: 
 2868:   /*#ifdef windows */
 2869:     fprintf(ficgp,"cd \"%s\" \n",pathc);
 2870:     /*#endif */
 2871: m=pow(2,cptcoveff);
 2872:   
 2873:  /* 1eme*/
 2874:   for (cpt=1; cpt<= nlstate ; cpt ++) {
 2875:    for (k1=1; k1<= m ; k1 ++) {
 2876:      fprintf(ficgp,"\nset out \"v%s%d%d.png\" \n",strtok(optionfile, "."),cpt,k1);
 2877:      fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] \"vpl%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,fileres,k1-1,k1-1);
 2878: 
 2879:      for (i=1; i<= nlstate ; i ++) {
 2880:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
 2881:        else fprintf(ficgp," \%%*lf (\%%*lf)");
 2882:      }
 2883:      fprintf(ficgp,"\" t\"Stable prevalence\" w l 0,\"vpl%s\" every :::%d::%d u 1:($2+1.96*$3) \"\%%lf",fileres,k1-1,k1-1);
 2884:      for (i=1; i<= nlstate ; i ++) {
 2885:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
 2886:        else fprintf(ficgp," \%%*lf (\%%*lf)");
 2887:      } 
 2888:      fprintf(ficgp,"\" t\"95\%% CI\" w l 1,\"vpl%s\" every :::%d::%d u 1:($2-1.96*$3) \"\%%lf",fileres,k1-1,k1-1); 
 2889:      for (i=1; i<= nlstate ; i ++) {
 2890:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
 2891:        else fprintf(ficgp," \%%*lf (\%%*lf)");
 2892:      }  
 2893:      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));
 2894:    }
 2895:   }
 2896:   /*2 eme*/
 2897:   
 2898:   for (k1=1; k1<= m ; k1 ++) { 
 2899:     fprintf(ficgp,"\nset out \"e%s%d.png\" \n",strtok(optionfile, "."),k1);
 2900:     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] ",ageminpar,fage);
 2901:     
 2902:     for (i=1; i<= nlstate+1 ; i ++) {
 2903:       k=2*i;
 2904:       fprintf(ficgp,"\"t%s\" every :::%d::%d u 1:2 \"\%%lf",fileres,k1-1,k1-1);
 2905:       for (j=1; j<= nlstate+1 ; j ++) {
 2906: 	if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
 2907: 	else fprintf(ficgp," \%%*lf (\%%*lf)");
 2908:       }   
 2909:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
 2910:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
 2911:       fprintf(ficgp,"\"t%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",fileres,k1-1,k1-1);
 2912:       for (j=1; j<= nlstate+1 ; j ++) {
 2913: 	if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
 2914: 	else fprintf(ficgp," \%%*lf (\%%*lf)");
 2915:       }   
 2916:       fprintf(ficgp,"\" t\"\" w l 0,");
 2917:       fprintf(ficgp,"\"t%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",fileres,k1-1,k1-1);
 2918:       for (j=1; j<= nlstate+1 ; j ++) {
 2919: 	if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
 2920: 	else fprintf(ficgp," \%%*lf (\%%*lf)");
 2921:       }   
 2922:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");
 2923:       else fprintf(ficgp,"\" t\"\" w l 0,");
 2924:     }
 2925:   }
 2926:   
 2927:   /*3eme*/
 2928:   
 2929:   for (k1=1; k1<= m ; k1 ++) { 
 2930:     for (cpt=1; cpt<= nlstate ; cpt ++) {
 2931:       k=2+nlstate*(2*cpt-2);
 2932:       fprintf(ficgp,"\nset out \"exp%s%d%d.png\" \n",strtok(optionfile, "."),cpt,k1);
 2933:       fprintf(ficgp,"set ter png small\nset size 0.65,0.65\nplot [%.f:%.f] \"e%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",ageminpar,fage,fileres,k1-1,k1-1,k,cpt);
 2934:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 2935: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 2936: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 2937: 	fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 2938: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 2939: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 2940: 	
 2941:       */
 2942:       for (i=1; i< nlstate ; i ++) {
 2943: 	fprintf(ficgp," ,\"e%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",fileres,k1-1,k1-1,k+2*i,cpt,i+1);
 2944: 	
 2945:       } 
 2946:     }
 2947:   }
 2948:   
 2949:   /* CV preval stat */
 2950:   for (k1=1; k1<= m ; k1 ++) { 
 2951:     for (cpt=1; cpt<nlstate ; cpt ++) {
 2952:       k=3;
 2953:       fprintf(ficgp,"\nset out \"p%s%d%d.png\" \n",strtok(optionfile, "."),cpt,k1);
 2954:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] \"pij%s\" u ($1==%d ? ($3):1/0):($%d/($%d",ageminpar,agemaxpar,fileres,k1,k+cpt+1,k+1);
 2955:       
 2956:       for (i=1; i< nlstate ; i ++)
 2957: 	fprintf(ficgp,"+$%d",k+i+1);
 2958:       fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);
 2959:       
 2960:       l=3+(nlstate+ndeath)*cpt;
 2961:       fprintf(ficgp,",\"pij%s\" u ($1==%d ? ($3):1/0):($%d/($%d",fileres,k1,l+cpt+1,l+1);
 2962:       for (i=1; i< nlstate ; i ++) {
 2963: 	l=3+(nlstate+ndeath)*cpt;
 2964: 	fprintf(ficgp,"+$%d",l+i+1);
 2965:       }
 2966:       fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);   
 2967:     } 
 2968:   }  
 2969:   
 2970:   /* proba elementaires */
 2971:   for(i=1,jk=1; i <=nlstate; i++){
 2972:     for(k=1; k <=(nlstate+ndeath); k++){
 2973:       if (k != i) {
 2974: 	for(j=1; j <=ncovmodel; j++){
 2975: 	  fprintf(ficgp,"p%d=%f ",jk,p[jk]);
 2976: 	  jk++; 
 2977: 	  fprintf(ficgp,"\n");
 2978: 	}
 2979:       }
 2980:     }
 2981:    }
 2982: 
 2983:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
 2984:      for(jk=1; jk <=m; jk++) {
 2985:        fprintf(ficgp,"\nset out \"pe%s%d%d.png\" \n",strtok(optionfile, "."),jk,ng); 
 2986:        if (ng==2)
 2987: 	 fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
 2988:        else
 2989: 	 fprintf(ficgp,"\nset title \"Probability\"\n");
 2990:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
 2991:        i=1;
 2992:        for(k2=1; k2<=nlstate; k2++) {
 2993: 	 k3=i;
 2994: 	 for(k=1; k<=(nlstate+ndeath); k++) {
 2995: 	   if (k != k2){
 2996: 	     if(ng==2)
 2997: 	       fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
 2998: 	     else
 2999: 	       fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
 3000: 	     ij=1;
 3001: 	     for(j=3; j <=ncovmodel; j++) {
 3002: 	       if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
 3003: 		 fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
 3004: 		 ij++;
 3005: 	       }
 3006: 	       else
 3007: 		 fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
 3008: 	     }
 3009: 	     fprintf(ficgp,")/(1");
 3010: 	     
 3011: 	     for(k1=1; k1 <=nlstate; k1++){   
 3012: 	       fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
 3013: 	       ij=1;
 3014: 	       for(j=3; j <=ncovmodel; j++){
 3015: 		 if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
 3016: 		   fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
 3017: 		   ij++;
 3018: 		 }
 3019: 		 else
 3020: 		   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
 3021: 	       }
 3022: 	       fprintf(ficgp,")");
 3023: 	     }
 3024: 	     fprintf(ficgp,") t \"p%d%d\" ", k2,k);
 3025: 	     if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
 3026: 	     i=i+ncovmodel;
 3027: 	   }
 3028: 	 } /* end k */
 3029:        } /* end k2 */
 3030:      } /* end jk */
 3031:    } /* end ng */
 3032:    fclose(ficgp); 
 3033: }  /* end gnuplot */
 3034: 
 3035: 
 3036: /*************** Moving average **************/
 3037: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
 3038: 
 3039:   int i, cpt, cptcod;
 3040:   int modcovmax =1;
 3041:   int mobilavrange, mob;
 3042:   double age;
 3043: 
 3044:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
 3045: 			   a covariate has 2 modalities */
 3046:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
 3047: 
 3048:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
 3049:     if(mobilav==1) mobilavrange=5; /* default */
 3050:     else mobilavrange=mobilav;
 3051:     for (age=bage; age<=fage; age++)
 3052:       for (i=1; i<=nlstate;i++)
 3053: 	for (cptcod=1;cptcod<=modcovmax;cptcod++)
 3054: 	  mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
 3055:     /* We keep the original values on the extreme ages bage, fage and for 
 3056:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
 3057:        we use a 5 terms etc. until the borders are no more concerned. 
 3058:     */ 
 3059:     for (mob=3;mob <=mobilavrange;mob=mob+2){
 3060:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
 3061: 	for (i=1; i<=nlstate;i++){
 3062: 	  for (cptcod=1;cptcod<=modcovmax;cptcod++){
 3063: 	    mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
 3064: 	      for (cpt=1;cpt<=(mob-1)/2;cpt++){
 3065: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
 3066: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
 3067: 	      }
 3068: 	    mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
 3069: 	  }
 3070: 	}
 3071:       }/* end age */
 3072:     }/* end mob */
 3073:   }else return -1;
 3074:   return 0;
 3075: }/* End movingaverage */
 3076: 
 3077: 
 3078: /************** Forecasting ******************/
 3079: prevforecast(char fileres[], double anproj1, double mproj1, double jproj1, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double anproj2, double p[], int cptcoveff){
 3080:   /* proj1, year, month, day of starting projection 
 3081:      agemin, agemax range of age
 3082:      dateprev1 dateprev2 range of dates during which prevalence is computed
 3083:      anproj2 year of en of projection (same day and month as proj1).
 3084:   */
 3085:   int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;
 3086:   int *popage;
 3087:   double agec; /* generic age */
 3088:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
 3089:   double *popeffectif,*popcount;
 3090:   double ***p3mat;
 3091:   double ***mobaverage;
 3092:   char fileresf[FILENAMELENGTH];
 3093: 
 3094:   agelim=AGESUP;
 3095:   prevalence(ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 3096:  
 3097:   strcpy(fileresf,"f"); 
 3098:   strcat(fileresf,fileres);
 3099:   if((ficresf=fopen(fileresf,"w"))==NULL) {
 3100:     printf("Problem with forecast resultfile: %s\n", fileresf);
 3101:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
 3102:   }
 3103:   printf("Computing forecasting: result on file '%s' \n", fileresf);
 3104:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
 3105: 
 3106:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 3107: 
 3108:   if (mobilav!=0) {
 3109:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3110:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 3111:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 3112:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 3113:     }
 3114:   }
 3115: 
 3116:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 3117:   if (stepm<=12) stepsize=1;
 3118:   if(estepm < stepm){
 3119:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3120:   }
 3121:   else  hstepm=estepm;   
 3122: 
 3123:   hstepm=hstepm/stepm; 
 3124:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
 3125:                                fractional in yp1 */
 3126:   anprojmean=yp;
 3127:   yp2=modf((yp1*12),&yp);
 3128:   mprojmean=yp;
 3129:   yp1=modf((yp2*30.5),&yp);
 3130:   jprojmean=yp;
 3131:   if(jprojmean==0) jprojmean=1;
 3132:   if(mprojmean==0) jprojmean=1;
 3133: 
 3134:   i1=cptcoveff;
 3135:   if (cptcovn < 1){i1=1;}
 3136:   
 3137:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
 3138:   
 3139:   fprintf(ficresf,"#****** Routine prevforecast **\n");
 3140: 
 3141:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
 3142:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 3143:       k=k+1;
 3144:       fprintf(ficresf,"\n#******");
 3145:       for(j=1;j<=cptcoveff;j++) {
 3146: 	fprintf(ficresf," V%d=%d, hpijx=probability over h years, hp.jx is weighted by observed prev ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 3147:       }
 3148:       fprintf(ficresf,"******\n");
 3149:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
 3150:       for(j=1; j<=nlstate+ndeath;j++){ 
 3151: 	for(i=1; i<=nlstate;i++) 	      
 3152:           fprintf(ficresf," p%d%d",i,j);
 3153: 	fprintf(ficresf," p.%d",j);
 3154:       }
 3155:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
 3156: 	fprintf(ficresf,"\n");
 3157: 	fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
 3158: 
 3159:      	for (agec=fage; agec>=(ageminpar-1); agec--){ 
 3160: 	  nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
 3161: 	  nhstepm = nhstepm/hstepm; 
 3162: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3163: 	  oldm=oldms;savm=savms;
 3164: 	  hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
 3165: 	
 3166: 	  for (h=0; h<=nhstepm; h++){
 3167: 	    if (h==(int) (YEARM*yearp)) {
 3168:               fprintf(ficresf,"\n");
 3169:               for(j=1;j<=cptcoveff;j++) 
 3170:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 3171: 	      fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
 3172: 	    } 
 3173: 	    for(j=1; j<=nlstate+ndeath;j++) {
 3174: 	      ppij=0.;
 3175: 	      for(i=1; i<=nlstate;i++) {
 3176: 		if (mobilav==1) 
 3177: 		  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
 3178: 		else {
 3179: 		  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
 3180: 		}
 3181: 		if (h==(int)(YEARM*yearp))
 3182: 		  fprintf(ficresf," %.3f", p3mat[i][j][h]);
 3183: 	      }
 3184: 	      if (h==(int)(YEARM*yearp)){
 3185: 		fprintf(ficresf," %.3f", ppij);
 3186: 	      }
 3187: 	    }
 3188: 	  }
 3189: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3190: 	}
 3191:       }
 3192:     }
 3193:   }
 3194:        
 3195:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3196: 
 3197:   fclose(ficresf);
 3198: }
 3199: 
 3200: /************** Forecasting *****not tested NB*************/
 3201: populforecast(char fileres[], double anpyram,double mpyram,double jpyram,double ageminpar, double agemax,double dateprev1, double dateprev2, int mobilav, double agedeb, double fage, int popforecast, char popfile[], double anpyram1,double p[], int i2){
 3202:   
 3203:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
 3204:   int *popage;
 3205:   double calagedatem, agelim, kk1, kk2;
 3206:   double *popeffectif,*popcount;
 3207:   double ***p3mat,***tabpop,***tabpopprev;
 3208:   double ***mobaverage;
 3209:   char filerespop[FILENAMELENGTH];
 3210: 
 3211:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3212:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3213:   agelim=AGESUP;
 3214:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
 3215:   
 3216:   prevalence(ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 3217:   
 3218:   
 3219:   strcpy(filerespop,"pop"); 
 3220:   strcat(filerespop,fileres);
 3221:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
 3222:     printf("Problem with forecast resultfile: %s\n", filerespop);
 3223:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
 3224:   }
 3225:   printf("Computing forecasting: result on file '%s' \n", filerespop);
 3226:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
 3227: 
 3228:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 3229: 
 3230:   if (mobilav!=0) {
 3231:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3232:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 3233:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 3234:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 3235:     }
 3236:   }
 3237: 
 3238:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 3239:   if (stepm<=12) stepsize=1;
 3240:   
 3241:   agelim=AGESUP;
 3242:   
 3243:   hstepm=1;
 3244:   hstepm=hstepm/stepm; 
 3245:   
 3246:   if (popforecast==1) {
 3247:     if((ficpop=fopen(popfile,"r"))==NULL) {
 3248:       printf("Problem with population file : %s\n",popfile);exit(0);
 3249:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
 3250:     } 
 3251:     popage=ivector(0,AGESUP);
 3252:     popeffectif=vector(0,AGESUP);
 3253:     popcount=vector(0,AGESUP);
 3254:     
 3255:     i=1;   
 3256:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
 3257:    
 3258:     imx=i;
 3259:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
 3260:   }
 3261: 
 3262:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
 3263:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 3264:       k=k+1;
 3265:       fprintf(ficrespop,"\n#******");
 3266:       for(j=1;j<=cptcoveff;j++) {
 3267: 	fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 3268:       }
 3269:       fprintf(ficrespop,"******\n");
 3270:       fprintf(ficrespop,"# Age");
 3271:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
 3272:       if (popforecast==1)  fprintf(ficrespop," [Population]");
 3273:       
 3274:       for (cpt=0; cpt<=0;cpt++) { 
 3275: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 3276: 	
 3277:      	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 3278: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 3279: 	  nhstepm = nhstepm/hstepm; 
 3280: 	  
 3281: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3282: 	  oldm=oldms;savm=savms;
 3283: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 3284: 	
 3285: 	  for (h=0; h<=nhstepm; h++){
 3286: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 3287: 	      fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 3288: 	    } 
 3289: 	    for(j=1; j<=nlstate+ndeath;j++) {
 3290: 	      kk1=0.;kk2=0;
 3291: 	      for(i=1; i<=nlstate;i++) {	      
 3292: 		if (mobilav==1) 
 3293: 		  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
 3294: 		else {
 3295: 		  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
 3296: 		}
 3297: 	      }
 3298: 	      if (h==(int)(calagedatem+12*cpt)){
 3299: 		tabpop[(int)(agedeb)][j][cptcod]=kk1;
 3300: 		  /*fprintf(ficrespop," %.3f", kk1);
 3301: 		    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
 3302: 	      }
 3303: 	    }
 3304: 	    for(i=1; i<=nlstate;i++){
 3305: 	      kk1=0.;
 3306: 		for(j=1; j<=nlstate;j++){
 3307: 		  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
 3308: 		}
 3309: 		  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
 3310: 	    }
 3311: 
 3312: 	    if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
 3313: 	      fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
 3314: 	  }
 3315: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3316: 	}
 3317:       }
 3318:  
 3319:   /******/
 3320: 
 3321:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
 3322: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 3323: 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 3324: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 3325: 	  nhstepm = nhstepm/hstepm; 
 3326: 	  
 3327: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3328: 	  oldm=oldms;savm=savms;
 3329: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 3330: 	  for (h=0; h<=nhstepm; h++){
 3331: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 3332: 	      fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 3333: 	    } 
 3334: 	    for(j=1; j<=nlstate+ndeath;j++) {
 3335: 	      kk1=0.;kk2=0;
 3336: 	      for(i=1; i<=nlstate;i++) {	      
 3337: 		kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];	
 3338: 	      }
 3339: 	      if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);	
 3340: 	    }
 3341: 	  }
 3342: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3343: 	}
 3344:       }
 3345:    } 
 3346:   }
 3347:  
 3348:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3349: 
 3350:   if (popforecast==1) {
 3351:     free_ivector(popage,0,AGESUP);
 3352:     free_vector(popeffectif,0,AGESUP);
 3353:     free_vector(popcount,0,AGESUP);
 3354:   }
 3355:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3356:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3357:   fclose(ficrespop);
 3358: }
 3359: 
 3360: /***********************************************/
 3361: /**************** Main Program *****************/
 3362: /***********************************************/
 3363: 
 3364: int main(int argc, char *argv[])
 3365: {
 3366:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
 3367:   int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;
 3368:   double agedeb, agefin,hf;
 3369:   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
 3370: 
 3371:   double fret;
 3372:   double **xi,tmp,delta;
 3373: 
 3374:   double dum; /* Dummy variable */
 3375:   double ***p3mat;
 3376:   double ***mobaverage;
 3377:   int *indx;
 3378:   char line[MAXLINE], linepar[MAXLINE];
 3379:   char path[80],pathc[80],pathcd[80],pathtot[80],model[80];
 3380:   int firstobs=1, lastobs=10;
 3381:   int sdeb, sfin; /* Status at beginning and end */
 3382:   int c,  h , cpt,l;
 3383:   int ju,jl, mi;
 3384:   int i1,j1, k1,k2,k3,jk,aa,bb, stepsize, ij;
 3385:   int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,*tab; 
 3386:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
 3387:   int mobilav=0,popforecast=0;
 3388:   int hstepm, nhstepm;
 3389:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
 3390:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
 3391: 
 3392:   double bage, fage, age, agelim, agebase;
 3393:   double ftolpl=FTOL;
 3394:   double **prlim;
 3395:   double *severity;
 3396:   double ***param; /* Matrix of parameters */
 3397:   double  *p;
 3398:   double **matcov; /* Matrix of covariance */
 3399:   double ***delti3; /* Scale */
 3400:   double *delti; /* Scale */
 3401:   double ***eij, ***vareij;
 3402:   double **varpl; /* Variances of prevalence limits by age */
 3403:   double *epj, vepp;
 3404:   double kk1, kk2;
 3405:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
 3406: 
 3407:   char *alph[]={"a","a","b","c","d","e"}, str[4];
 3408: 
 3409: 
 3410:   char z[1]="c", occ;
 3411: #include <sys/time.h>
 3412: #include <time.h>
 3413:   char stra[80], strb[80], strc[80], strd[80],stre[80],modelsav[80];
 3414:  
 3415:   /* long total_usecs;
 3416:      struct timeval start_time, end_time;
 3417:   
 3418:      gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
 3419:   getcwd(pathcd, size);
 3420: 
 3421:   printf("\n%s",version);
 3422:   if(argc <=1){
 3423:     printf("\nEnter the parameter file name: ");
 3424:     scanf("%s",pathtot);
 3425:   }
 3426:   else{
 3427:     strcpy(pathtot,argv[1]);
 3428:   }
 3429:   /*if(getcwd(pathcd, 80)!= NULL)printf ("Error pathcd\n");*/
 3430:   /*cygwin_split_path(pathtot,path,optionfile);
 3431:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
 3432:   /* cutv(path,optionfile,pathtot,'\\');*/
 3433: 
 3434:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
 3435:   printf("pathtot=%s, path=%s, optionfile=%s optionfilext=%s optionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
 3436:   chdir(path);
 3437:   replace(pathc,path);
 3438: 
 3439:   /*-------- arguments in the command line --------*/
 3440: 
 3441:   /* Log file */
 3442:   strcat(filelog, optionfilefiname);
 3443:   strcat(filelog,".log");    /* */
 3444:   if((ficlog=fopen(filelog,"w"))==NULL)    {
 3445:     printf("Problem with logfile %s\n",filelog);
 3446:     goto end;
 3447:   }
 3448:   fprintf(ficlog,"Log filename:%s\n",filelog);
 3449:   fprintf(ficlog,"\n%s",version);
 3450:   fprintf(ficlog,"\nEnter the parameter file name: ");
 3451:   fprintf(ficlog,"pathtot=%s, path=%s, optionfile=%s optionfilext=%s optionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
 3452:   fflush(ficlog);
 3453: 
 3454:   /* */
 3455:   strcpy(fileres,"r");
 3456:   strcat(fileres, optionfilefiname);
 3457:   strcat(fileres,".txt");    /* Other files have txt extension */
 3458: 
 3459:   /*---------arguments file --------*/
 3460: 
 3461:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
 3462:     printf("Problem with optionfile %s\n",optionfile);
 3463:     fprintf(ficlog,"Problem with optionfile %s\n",optionfile);
 3464:     goto end;
 3465:   }
 3466: 
 3467:   strcpy(filereso,"o");
 3468:   strcat(filereso,fileres);
 3469:   if((ficparo=fopen(filereso,"w"))==NULL) {
 3470:     printf("Problem with Output resultfile: %s\n", filereso);
 3471:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
 3472:     goto end;
 3473:   }
 3474: 
 3475:   /* Reads comments: lines beginning with '#' */
 3476:   while((c=getc(ficpar))=='#' && c!= EOF){
 3477:     ungetc(c,ficpar);
 3478:     fgets(line, MAXLINE, ficpar);
 3479:     puts(line);
 3480:     fputs(line,ficparo);
 3481:   }
 3482:   ungetc(c,ficpar);
 3483: 
 3484:   fscanf(ficpar,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d model=%s\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncovcol, &nlstate,&ndeath, &maxwav, &mle, &weightopt,model);
 3485:   printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt,model);
 3486:   fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
 3487:   while((c=getc(ficpar))=='#' && c!= EOF){
 3488:     ungetc(c,ficpar);
 3489:     fgets(line, MAXLINE, ficpar);
 3490:     puts(line);
 3491:     fputs(line,ficparo);
 3492:   }
 3493:   ungetc(c,ficpar);
 3494:   
 3495:    
 3496:   covar=matrix(0,NCOVMAX,1,n); 
 3497:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement*/
 3498:   if (strlen(model)>1) cptcovn=nbocc(model,'+')+1;
 3499: 
 3500:   ncovmodel=2+cptcovn; /*Number of variables = cptcovn + intercept + age */
 3501:   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
 3502:   
 3503:   /* Read guess parameters */
 3504:   /* Reads comments: lines beginning with '#' */
 3505:   while((c=getc(ficpar))=='#' && c!= EOF){
 3506:     ungetc(c,ficpar);
 3507:     fgets(line, MAXLINE, ficpar);
 3508:     puts(line);
 3509:     fputs(line,ficparo);
 3510:   }
 3511:   ungetc(c,ficpar);
 3512:   
 3513:   param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 3514:   for(i=1; i <=nlstate; i++)
 3515:     for(j=1; j <=nlstate+ndeath-1; j++){
 3516:       fscanf(ficpar,"%1d%1d",&i1,&j1);
 3517:       fprintf(ficparo,"%1d%1d",i1,j1);
 3518:       if(mle==1)
 3519: 	printf("%1d%1d",i,j);
 3520:       fprintf(ficlog,"%1d%1d",i,j);
 3521:       for(k=1; k<=ncovmodel;k++){
 3522: 	fscanf(ficpar," %lf",&param[i][j][k]);
 3523: 	if(mle==1){
 3524: 	  printf(" %lf",param[i][j][k]);
 3525: 	  fprintf(ficlog," %lf",param[i][j][k]);
 3526: 	}
 3527: 	else
 3528: 	  fprintf(ficlog," %lf",param[i][j][k]);
 3529: 	fprintf(ficparo," %lf",param[i][j][k]);
 3530:       }
 3531:       fscanf(ficpar,"\n");
 3532:       if(mle==1)
 3533: 	printf("\n");
 3534:       fprintf(ficlog,"\n");
 3535:       fprintf(ficparo,"\n");
 3536:     }
 3537:   
 3538:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
 3539: 
 3540:   p=param[1][1];
 3541:   
 3542:   /* Reads comments: lines beginning with '#' */
 3543:   while((c=getc(ficpar))=='#' && c!= EOF){
 3544:     ungetc(c,ficpar);
 3545:     fgets(line, MAXLINE, ficpar);
 3546:     puts(line);
 3547:     fputs(line,ficparo);
 3548:   }
 3549:   ungetc(c,ficpar);
 3550: 
 3551:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 3552:   /* delti=vector(1,npar); *//* Scale of each paramater (output from hesscov) */
 3553:   for(i=1; i <=nlstate; i++){
 3554:     for(j=1; j <=nlstate+ndeath-1; j++){
 3555:       fscanf(ficpar,"%1d%1d",&i1,&j1);
 3556:       printf("%1d%1d",i,j);
 3557:       fprintf(ficparo,"%1d%1d",i1,j1);
 3558:       for(k=1; k<=ncovmodel;k++){
 3559: 	fscanf(ficpar,"%le",&delti3[i][j][k]);
 3560: 	printf(" %le",delti3[i][j][k]);
 3561: 	fprintf(ficparo," %le",delti3[i][j][k]);
 3562:       }
 3563:       fscanf(ficpar,"\n");
 3564:       printf("\n");
 3565:       fprintf(ficparo,"\n");
 3566:     }
 3567:   }
 3568:   delti=delti3[1][1];
 3569: 
 3570: 
 3571:   /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
 3572:   
 3573:   /* Reads comments: lines beginning with '#' */
 3574:   while((c=getc(ficpar))=='#' && c!= EOF){
 3575:     ungetc(c,ficpar);
 3576:     fgets(line, MAXLINE, ficpar);
 3577:     puts(line);
 3578:     fputs(line,ficparo);
 3579:   }
 3580:   ungetc(c,ficpar);
 3581:   
 3582:   matcov=matrix(1,npar,1,npar);
 3583:   for(i=1; i <=npar; i++){
 3584:     fscanf(ficpar,"%s",&str);
 3585:     if(mle==1)
 3586:       printf("%s",str);
 3587:     fprintf(ficlog,"%s",str);
 3588:     fprintf(ficparo,"%s",str);
 3589:     for(j=1; j <=i; j++){
 3590:       fscanf(ficpar," %le",&matcov[i][j]);
 3591:       if(mle==1){
 3592: 	printf(" %.5le",matcov[i][j]);
 3593: 	fprintf(ficlog," %.5le",matcov[i][j]);
 3594:       }
 3595:       else
 3596: 	fprintf(ficlog," %.5le",matcov[i][j]);
 3597:       fprintf(ficparo," %.5le",matcov[i][j]);
 3598:     }
 3599:     fscanf(ficpar,"\n");
 3600:     if(mle==1)
 3601:       printf("\n");
 3602:     fprintf(ficlog,"\n");
 3603:     fprintf(ficparo,"\n");
 3604:   }
 3605:   for(i=1; i <=npar; i++)
 3606:     for(j=i+1;j<=npar;j++)
 3607:       matcov[i][j]=matcov[j][i];
 3608:    
 3609:   if(mle==1)
 3610:     printf("\n");
 3611:   fprintf(ficlog,"\n");
 3612: 
 3613: 
 3614:   /*-------- Rewriting paramater file ----------*/
 3615:   strcpy(rfileres,"r");    /* "Rparameterfile */
 3616:   strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
 3617:   strcat(rfileres,".");    /* */
 3618:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
 3619:   if((ficres =fopen(rfileres,"w"))==NULL) {
 3620:     printf("Problem writing new parameter file: %s\n", fileres);goto end;
 3621:     fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
 3622:   }
 3623:   fprintf(ficres,"#%s\n",version);
 3624:     
 3625:   /*-------- data file ----------*/
 3626:   if((fic=fopen(datafile,"r"))==NULL)    {
 3627:     printf("Problem with datafile: %s\n", datafile);goto end;
 3628:     fprintf(ficlog,"Problem with datafile: %s\n", datafile);goto end;
 3629:   }
 3630: 
 3631:   n= lastobs;
 3632:   severity = vector(1,maxwav);
 3633:   outcome=imatrix(1,maxwav+1,1,n);
 3634:   num=ivector(1,n);
 3635:   moisnais=vector(1,n);
 3636:   annais=vector(1,n);
 3637:   moisdc=vector(1,n);
 3638:   andc=vector(1,n);
 3639:   agedc=vector(1,n);
 3640:   cod=ivector(1,n);
 3641:   weight=vector(1,n);
 3642:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
 3643:   mint=matrix(1,maxwav,1,n);
 3644:   anint=matrix(1,maxwav,1,n);
 3645:   s=imatrix(1,maxwav+1,1,n);
 3646:   tab=ivector(1,NCOVMAX);
 3647:   ncodemax=ivector(1,8);
 3648: 
 3649:   i=1;
 3650:   while (fgets(line, MAXLINE, fic) != NULL)    {
 3651:     if ((i >= firstobs) && (i <=lastobs)) {
 3652: 	
 3653:       for (j=maxwav;j>=1;j--){
 3654: 	cutv(stra, strb,line,' '); s[j][i]=atoi(strb); 
 3655: 	strcpy(line,stra);
 3656: 	cutv(stra, strb,line,'/'); anint[j][i]=(double)(atoi(strb)); strcpy(line,stra);
 3657: 	cutv(stra, strb,line,' '); mint[j][i]=(double)(atoi(strb)); strcpy(line,stra);
 3658:       }
 3659: 	
 3660:       cutv(stra, strb,line,'/'); andc[i]=(double)(atoi(strb)); strcpy(line,stra);
 3661:       cutv(stra, strb,line,' '); moisdc[i]=(double)(atoi(strb)); strcpy(line,stra);
 3662: 
 3663:       cutv(stra, strb,line,'/'); annais[i]=(double)(atoi(strb)); strcpy(line,stra);
 3664:       cutv(stra, strb,line,' '); moisnais[i]=(double)(atoi(strb)); strcpy(line,stra);
 3665: 
 3666:       cutv(stra, strb,line,' '); weight[i]=(double)(atoi(strb)); strcpy(line,stra);
 3667:       for (j=ncovcol;j>=1;j--){
 3668: 	cutv(stra, strb,line,' '); covar[j][i]=(double)(atoi(strb)); strcpy(line,stra);
 3669:       } 
 3670:       num[i]=atol(stra);
 3671: 	
 3672:       /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
 3673: 	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;}*/
 3674: 
 3675:       i=i+1;
 3676:     }
 3677:   }
 3678:   /* printf("ii=%d", ij);
 3679:      scanf("%d",i);*/
 3680:   imx=i-1; /* Number of individuals */
 3681: 
 3682:   /* for (i=1; i<=imx; i++){
 3683:     if ((s[1][i]==3) && (s[2][i]==2)) s[2][i]=3;
 3684:     if ((s[2][i]==3) && (s[3][i]==2)) s[3][i]=3;
 3685:     if ((s[3][i]==3) && (s[4][i]==2)) s[4][i]=3;
 3686:     }*/
 3687:    /*  for (i=1; i<=imx; i++){
 3688:      if (s[4][i]==9)  s[4][i]=-1; 
 3689:      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]));}*/
 3690:   
 3691:  for (i=1; i<=imx; i++)
 3692:  
 3693:    /*if ((s[3][i]==3) ||  (s[4][i]==3)) weight[i]=0.08;
 3694:      else weight[i]=1;*/
 3695: 
 3696:   /* Calculation of the number of parameter from char model*/
 3697:   Tvar=ivector(1,15); /* stores the number n of the covariates in Vm+Vn at 1 and m at 2 */
 3698:   Tprod=ivector(1,15); 
 3699:   Tvaraff=ivector(1,15); 
 3700:   Tvard=imatrix(1,15,1,2);
 3701:   Tage=ivector(1,15);      
 3702:    
 3703:   if (strlen(model) >1){ /* If there is at least 1 covariate */
 3704:     j=0, j1=0, k1=1, k2=1;
 3705:     j=nbocc(model,'+'); /* j=Number of '+' */
 3706:     j1=nbocc(model,'*'); /* j1=Number of '*' */
 3707:     cptcovn=j+1; 
 3708:     cptcovprod=j1; /*Number of products */
 3709:     
 3710:     strcpy(modelsav,model); 
 3711:     if ((strcmp(model,"age")==0) || (strcmp(model,"age*age")==0)){
 3712:       printf("Error. Non available option model=%s ",model);
 3713:       fprintf(ficlog,"Error. Non available option model=%s ",model);
 3714:       goto end;
 3715:     }
 3716:     
 3717:     /* This loop fills the array Tvar from the string 'model'.*/
 3718: 
 3719:     for(i=(j+1); i>=1;i--){
 3720:       cutv(stra,strb,modelsav,'+'); /* keeps in strb after the last + */ 
 3721:       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
 3722:       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
 3723:       /*scanf("%d",i);*/
 3724:       if (strchr(strb,'*')) {  /* Model includes a product */
 3725: 	cutv(strd,strc,strb,'*'); /* strd*strc  Vm*Vn (if not *age)*/
 3726: 	if (strcmp(strc,"age")==0) { /* Vn*age */
 3727: 	  cptcovprod--;
 3728: 	  cutv(strb,stre,strd,'V');
 3729: 	  Tvar[i]=atoi(stre); /* computes n in Vn and stores in Tvar*/
 3730: 	  cptcovage++;
 3731: 	    Tage[cptcovage]=i;
 3732: 	    /*printf("stre=%s ", stre);*/
 3733: 	}
 3734: 	else if (strcmp(strd,"age")==0) { /* or age*Vn */
 3735: 	  cptcovprod--;
 3736: 	  cutv(strb,stre,strc,'V');
 3737: 	  Tvar[i]=atoi(stre);
 3738: 	  cptcovage++;
 3739: 	  Tage[cptcovage]=i;
 3740: 	}
 3741: 	else {  /* Age is not in the model */
 3742: 	  cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n*/
 3743: 	  Tvar[i]=ncovcol+k1;
 3744: 	  cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */
 3745: 	  Tprod[k1]=i;
 3746: 	  Tvard[k1][1]=atoi(strc); /* m*/
 3747: 	  Tvard[k1][2]=atoi(stre); /* n */
 3748: 	  Tvar[cptcovn+k2]=Tvard[k1][1];
 3749: 	  Tvar[cptcovn+k2+1]=Tvard[k1][2]; 
 3750: 	  for (k=1; k<=lastobs;k++) 
 3751: 	    covar[ncovcol+k1][k]=covar[atoi(stre)][k]*covar[atoi(strc)][k];
 3752: 	  k1++;
 3753: 	  k2=k2+2;
 3754: 	}
 3755:       }
 3756:       else { /* no more sum */
 3757: 	/*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
 3758:        /*  scanf("%d",i);*/
 3759:       cutv(strd,strc,strb,'V');
 3760:       Tvar[i]=atoi(strc);
 3761:       }
 3762:       strcpy(modelsav,stra);  
 3763:       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
 3764: 	scanf("%d",i);*/
 3765:     } /* end of loop + */
 3766:   } /* end model */
 3767:   
 3768:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
 3769:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
 3770: 
 3771:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
 3772:   printf("cptcovprod=%d ", cptcovprod);
 3773:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
 3774: 
 3775:   scanf("%d ",i);
 3776:   fclose(fic);*/
 3777: 
 3778:     /*  if(mle==1){*/
 3779:   if (weightopt != 1) { /* Maximisation without weights*/
 3780:     for(i=1;i<=n;i++) weight[i]=1.0;
 3781:   }
 3782:     /*-calculation of age at interview from date of interview and age at death -*/
 3783:   agev=matrix(1,maxwav,1,imx);
 3784: 
 3785:   for (i=1; i<=imx; i++) {
 3786:     for(m=2; (m<= maxwav); m++) {
 3787:       if ((mint[m][i]== 99) && (s[m][i] <= nlstate)){
 3788: 	anint[m][i]=9999;
 3789: 	s[m][i]=-1;
 3790:       }
 3791:       if(moisdc[i]==99 && andc[i]==9999 & s[m][i]>nlstate) s[m][i]=-1;
 3792:     }
 3793:   }
 3794: 
 3795:   for (i=1; i<=imx; i++)  {
 3796:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
 3797:     for(m=firstpass; (m<= lastpass); m++){
 3798:       if(s[m][i] >0){
 3799: 	if (s[m][i] >= nlstate+1) {
 3800: 	  if(agedc[i]>0)
 3801: 	    if(moisdc[i]!=99 && andc[i]!=9999)
 3802: 	      agev[m][i]=agedc[i];
 3803: 	  /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
 3804: 	    else {
 3805: 	      if (andc[i]!=9999){
 3806: 		printf("Warning negative age at death: %d line:%d\n",num[i],i);
 3807: 		fprintf(ficlog,"Warning negative age at death: %d line:%d\n",num[i],i);
 3808: 		agev[m][i]=-1;
 3809: 	      }
 3810: 	    }
 3811: 	}
 3812: 	else if(s[m][i] !=9){ /* Standard case, age in fractional
 3813: 				 years but with the precision of a
 3814: 				 month */
 3815: 	  agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
 3816: 	  if(mint[m][i]==99 || anint[m][i]==9999)
 3817: 	    agev[m][i]=1;
 3818: 	  else if(agev[m][i] <agemin){ 
 3819: 	    agemin=agev[m][i];
 3820: 	    /*printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);*/
 3821: 	  }
 3822: 	  else if(agev[m][i] >agemax){
 3823: 	    agemax=agev[m][i];
 3824: 	    /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/
 3825: 	  }
 3826: 	  /*agev[m][i]=anint[m][i]-annais[i];*/
 3827: 	  /*	 agev[m][i] = age[i]+2*m;*/
 3828: 	}
 3829: 	else { /* =9 */
 3830: 	  agev[m][i]=1;
 3831: 	  s[m][i]=-1;
 3832: 	}
 3833:       }
 3834:       else /*= 0 Unknown */
 3835: 	agev[m][i]=1;
 3836:     }
 3837:     
 3838:   }
 3839:   for (i=1; i<=imx; i++)  {
 3840:     for(m=firstpass; (m<=lastpass); m++){
 3841:       if (s[m][i] > (nlstate+ndeath)) {
 3842: 	printf("Error: on wave %d of individual %d status %d > (nlstate+ndeath)=(%d+%d)=%d\n",m,i,s[m][i],nlstate, ndeath, nlstate+ndeath);	
 3843: 	fprintf(ficlog,"Error: on wave %d of individual %d status %d > (nlstate+ndeath)=(%d+%d)=%d\n",m,i,s[m][i],nlstate, ndeath, nlstate+ndeath);	
 3844: 	goto end;
 3845:       }
 3846:     }
 3847:   }
 3848: 
 3849:   /*for (i=1; i<=imx; i++){
 3850:   for (m=firstpass; (m<lastpass); m++){
 3851:      printf("%d %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
 3852: }
 3853: 
 3854: }*/
 3855: 
 3856:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
 3857:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax); 
 3858: 
 3859:   free_vector(severity,1,maxwav);
 3860:   free_imatrix(outcome,1,maxwav+1,1,n);
 3861:   free_vector(moisnais,1,n);
 3862:   free_vector(annais,1,n);
 3863:   /* free_matrix(mint,1,maxwav,1,n);
 3864:      free_matrix(anint,1,maxwav,1,n);*/
 3865:   free_vector(moisdc,1,n);
 3866:   free_vector(andc,1,n);
 3867: 
 3868:    
 3869:   wav=ivector(1,imx);
 3870:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
 3871:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
 3872:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
 3873:    
 3874:   /* Concatenates waves */
 3875:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
 3876: 
 3877:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
 3878: 
 3879:   Tcode=ivector(1,100);
 3880:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
 3881:   ncodemax[1]=1;
 3882:   if (cptcovn > 0) tricode(Tvar,nbcode,imx);
 3883:       
 3884:   codtab=imatrix(1,100,1,10); /* Cross tabulation to get the order of 
 3885: 				 the estimations*/
 3886:   h=0;
 3887:   m=pow(2,cptcoveff);
 3888:  
 3889:   for(k=1;k<=cptcoveff; k++){
 3890:     for(i=1; i <=(m/pow(2,k));i++){
 3891:       for(j=1; j <= ncodemax[k]; j++){
 3892: 	for(cpt=1; cpt <=(m/pow(2,cptcoveff+1-k)); cpt++){
 3893: 	  h++;
 3894: 	  if (h>m) h=1;codtab[h][k]=j;codtab[h][Tvar[k]]=j;
 3895: 	  /*  printf("h=%d k=%d j=%d codtab[h][k]=%d tvar[k]=%d \n",h, k,j,codtab[h][k],Tvar[k]);*/
 3896: 	} 
 3897:       }
 3898:     }
 3899:   } 
 3900:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
 3901:      codtab[1][2]=1;codtab[2][2]=2; */
 3902:   /* for(i=1; i <=m ;i++){ 
 3903:      for(k=1; k <=cptcovn; k++){
 3904:      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
 3905:      }
 3906:      printf("\n");
 3907:      }
 3908:      scanf("%d",i);*/
 3909:     
 3910:   /* Calculates basic frequencies. Computes observed prevalence at single age
 3911:      and prints on file fileres'p'. */
 3912: 
 3913:     pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 3914:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 3915:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 3916:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 3917:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
 3918:     
 3919:    
 3920:   /* For Powell, parameters are in a vector p[] starting at p[1]
 3921:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
 3922:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
 3923: 
 3924:   if(mle>=1){ /* Could be 1 or 2 */
 3925:     mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
 3926:   }
 3927:     
 3928:   /*--------- results files --------------*/
 3929:   fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle= 0 weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate, ndeath, maxwav, weightopt,model);
 3930:   
 3931: 
 3932:   jk=1;
 3933:   fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 3934:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 3935:   fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 3936:   for(i=1,jk=1; i <=nlstate; i++){
 3937:     for(k=1; k <=(nlstate+ndeath); k++){
 3938:       if (k != i) 
 3939: 	{
 3940: 	  printf("%d%d ",i,k);
 3941: 	  fprintf(ficlog,"%d%d ",i,k);
 3942: 	  fprintf(ficres,"%1d%1d ",i,k);
 3943: 	  for(j=1; j <=ncovmodel; j++){
 3944: 	    printf("%f ",p[jk]);
 3945: 	    fprintf(ficlog,"%f ",p[jk]);
 3946: 	    fprintf(ficres,"%f ",p[jk]);
 3947: 	    jk++; 
 3948: 	  }
 3949: 	  printf("\n");
 3950: 	  fprintf(ficlog,"\n");
 3951: 	  fprintf(ficres,"\n");
 3952: 	}
 3953:     }
 3954:   }
 3955:   if(mle==1){
 3956:     /* Computing hessian and covariance matrix */
 3957:     ftolhess=ftol; /* Usually correct */
 3958:     hesscov(matcov, p, npar, delti, ftolhess, func);
 3959:   }
 3960:   fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
 3961:   printf("# Scales (for hessian or gradient estimation)\n");
 3962:   fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
 3963:   for(i=1,jk=1; i <=nlstate; i++){
 3964:     for(j=1; j <=nlstate+ndeath; j++){
 3965:       if (j!=i) {
 3966: 	fprintf(ficres,"%1d%1d",i,j);
 3967: 	printf("%1d%1d",i,j);
 3968: 	fprintf(ficlog,"%1d%1d",i,j);
 3969: 	for(k=1; k<=ncovmodel;k++){
 3970: 	  printf(" %.5e",delti[jk]);
 3971: 	  fprintf(ficlog," %.5e",delti[jk]);
 3972: 	  fprintf(ficres," %.5e",delti[jk]);
 3973: 	  jk++;
 3974: 	}
 3975: 	printf("\n");
 3976: 	fprintf(ficlog,"\n");
 3977: 	fprintf(ficres,"\n");
 3978:       }
 3979:     }
 3980:   }
 3981:    
 3982:   fprintf(ficres,"# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");
 3983:   if(mle==1)
 3984:     printf("# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");
 3985:   fprintf(ficlog,"# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");
 3986:   for(i=1,k=1;i<=npar;i++){
 3987:     /*  if (k>nlstate) k=1;
 3988: 	i1=(i-1)/(ncovmodel*nlstate)+1; 
 3989: 	fprintf(ficres,"%s%d%d",alph[k],i1,tab[i]);
 3990: 	printf("%s%d%d",alph[k],i1,tab[i]);
 3991:     */
 3992:     fprintf(ficres,"%3d",i);
 3993:     if(mle==1)
 3994:       printf("%3d",i);
 3995:     fprintf(ficlog,"%3d",i);
 3996:     for(j=1; j<=i;j++){
 3997:       fprintf(ficres," %.5e",matcov[i][j]);
 3998:       if(mle==1)
 3999: 	printf(" %.5e",matcov[i][j]);
 4000:       fprintf(ficlog," %.5e",matcov[i][j]);
 4001:     }
 4002:     fprintf(ficres,"\n");
 4003:     if(mle==1)
 4004:       printf("\n");
 4005:     fprintf(ficlog,"\n");
 4006:     k++;
 4007:   }
 4008:    
 4009:   while((c=getc(ficpar))=='#' && c!= EOF){
 4010:     ungetc(c,ficpar);
 4011:     fgets(line, MAXLINE, ficpar);
 4012:     puts(line);
 4013:     fputs(line,ficparo);
 4014:   }
 4015:   ungetc(c,ficpar);
 4016: 
 4017:   estepm=0;
 4018:   fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
 4019:   if (estepm==0 || estepm < stepm) estepm=stepm;
 4020:   if (fage <= 2) {
 4021:     bage = ageminpar;
 4022:     fage = agemaxpar;
 4023:   }
 4024:    
 4025:   fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
 4026:   fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
 4027:   fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
 4028:    
 4029:   while((c=getc(ficpar))=='#' && c!= EOF){
 4030:     ungetc(c,ficpar);
 4031:     fgets(line, MAXLINE, ficpar);
 4032:     puts(line);
 4033:     fputs(line,ficparo);
 4034:   }
 4035:   ungetc(c,ficpar);
 4036:   
 4037:   fscanf(ficpar,"begin-prev-date=%lf/%lf/%lf end-prev-date=%lf/%lf/%lf mov_average=%d\n",&jprev1, &mprev1,&anprev1,&jprev2, &mprev2,&anprev2,&mobilav);
 4038:   fprintf(ficparo,"begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
 4039:   fprintf(ficres,"begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
 4040:   printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
 4041:   fprintf(ficlog,"begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
 4042:    
 4043:   while((c=getc(ficpar))=='#' && c!= EOF){
 4044:     ungetc(c,ficpar);
 4045:     fgets(line, MAXLINE, ficpar);
 4046:     puts(line);
 4047:     fputs(line,ficparo);
 4048:   }
 4049:   ungetc(c,ficpar);
 4050:  
 4051: 
 4052:   dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
 4053:   dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
 4054: 
 4055:   fscanf(ficpar,"pop_based=%d\n",&popbased);
 4056:   fprintf(ficparo,"pop_based=%d\n",popbased);   
 4057:   fprintf(ficres,"pop_based=%d\n",popbased);   
 4058:   
 4059:   while((c=getc(ficpar))=='#' && c!= EOF){
 4060:     ungetc(c,ficpar);
 4061:     fgets(line, MAXLINE, ficpar);
 4062:     puts(line);
 4063:     fputs(line,ficparo);
 4064:   }
 4065:   ungetc(c,ficpar);
 4066: 
 4067:   fscanf(ficpar,"prevforecast=%d starting-proj-date=%lf/%lf/%lf final-proj-date=%lf/%lf/%lf mobil_average=%d\n",&prevfcast,&jproj1,&mproj1,&anproj1,&jproj2,&mproj2,&anproj2,&mobilavproj);
 4068:   fprintf(ficparo,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);
 4069:   printf("prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);
 4070:   fprintf(ficlog,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);
 4071:   fprintf(ficres,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);
 4072:   /* day and month of proj2 are not used but only year anproj2.*/
 4073: 
 4074:   while((c=getc(ficpar))=='#' && c!= EOF){
 4075:     ungetc(c,ficpar);
 4076:     fgets(line, MAXLINE, ficpar);
 4077:     puts(line);
 4078:     fputs(line,ficparo);
 4079:   }
 4080:   ungetc(c,ficpar);
 4081: 
 4082:   fscanf(ficpar,"popforecast=%d popfile=%s popfiledate=%lf/%lf/%lf last-popfiledate=%lf/%lf/%lf\n",&popforecast,popfile,&jpyram,&mpyram,&anpyram,&jpyram1,&mpyram1,&anpyram1);
 4083:   fprintf(ficparo,"popforecast=%d popfile=%s popfiledate=%.lf/%.lf/%.lf last-popfiledate=%.lf/%.lf/%.lf\n",popforecast,popfile,jpyram,mpyram,anpyram,jpyram1,mpyram1,anpyram1);
 4084:   fprintf(ficres,"popforecast=%d popfile=%s popfiledate=%.lf/%.lf/%.lf last-popfiledate=%.lf/%.lf/%.lf\n",popforecast,popfile,jpyram,mpyram,anpyram,jpyram1,mpyram1,anpyram1);
 4085: 
 4086:   probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4087:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);
 4088: 
 4089:   /*------------ gnuplot -------------*/
 4090:   strcpy(optionfilegnuplot,optionfilefiname);
 4091:   strcat(optionfilegnuplot,".gp");
 4092:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
 4093:     printf("Problem with file %s",optionfilegnuplot);
 4094:   }
 4095:   else{
 4096:     fprintf(ficgp,"\n# %s\n", version); 
 4097:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
 4098:     fprintf(ficgp,"set missing 'NaNq'\n");
 4099:   }
 4100:   fclose(ficgp);
 4101:   printinggnuplot(fileres, ageminpar,agemaxpar,fage, pathc,p);
 4102:   /*--------- index.htm --------*/
 4103: 
 4104:   strcpy(optionfilehtm,optionfile);
 4105:   strcat(optionfilehtm,".htm");
 4106:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
 4107:     printf("Problem with %s \n",optionfilehtm), exit(0);
 4108:   }
 4109: 
 4110:   fprintf(fichtm,"<body> <font size=\"2\">%s </font> <hr size=\"2\" color=\"#EC5E5E\"> \n
 4111: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n
 4112: \n
 4113: Total number of observations=%d <br>\n
 4114: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n
 4115: <hr  size=\"2\" color=\"#EC5E5E\">
 4116:  <ul><li><h4>Parameter files</h4>\n
 4117:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n
 4118:  - Log file of the run: <a href=\"%s\">%s</a><br>\n
 4119:  - Gnuplot file name: <a href=\"%s\">%s</a></ul>\n",version,title,datafile,firstpass,lastpass,stepm, weightopt,model,imx,jmin,jmax,jmean,fileres,fileres,filelog,filelog,optionfilegnuplot,optionfilegnuplot);
 4120:    fclose(fichtm);
 4121: 
 4122:   printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
 4123:  
 4124:   /*------------ free_vector  -------------*/
 4125:   chdir(path);
 4126:  
 4127:   free_ivector(wav,1,imx);
 4128:   free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
 4129:   free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
 4130:   free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
 4131:   free_ivector(num,1,n);
 4132:   free_vector(agedc,1,n);
 4133:   /*free_matrix(covar,0,NCOVMAX,1,n);*/
 4134:   /*free_matrix(covar,1,NCOVMAX,1,n);*/
 4135:   fclose(ficparo);
 4136:   fclose(ficres);
 4137: 
 4138: 
 4139:   /*--------------- Prevalence limit  (stable prevalence) --------------*/
 4140:   
 4141:   strcpy(filerespl,"pl");
 4142:   strcat(filerespl,fileres);
 4143:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
 4144:     printf("Problem with stable prevalence resultfile: %s\n", filerespl);goto end;
 4145:     fprintf(ficlog,"Problem with stable prevalence resultfile: %s\n", filerespl);goto end;
 4146:   }
 4147:   printf("Computing stable prevalence: result on file '%s' \n", filerespl);
 4148:   fprintf(ficlog,"Computing stable prevalence: result on file '%s' \n", filerespl);
 4149:   fprintf(ficrespl,"#Stable prevalence \n");
 4150:   fprintf(ficrespl,"#Age ");
 4151:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
 4152:   fprintf(ficrespl,"\n");
 4153:   
 4154:   prlim=matrix(1,nlstate,1,nlstate);
 4155: 
 4156:   agebase=ageminpar;
 4157:   agelim=agemaxpar;
 4158:   ftolpl=1.e-10;
 4159:   i1=cptcoveff;
 4160:   if (cptcovn < 1){i1=1;}
 4161: 
 4162:   for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 4163:     for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 4164:       k=k+1;
 4165:       /*printf("cptcov=%d cptcod=%d codtab=%d nbcode=%d\n",cptcov, cptcod,Tcode[cptcode],codtab[cptcod][cptcov]);*/
 4166:       fprintf(ficrespl,"\n#******");
 4167:       printf("\n#******");
 4168:       fprintf(ficlog,"\n#******");
 4169:       for(j=1;j<=cptcoveff;j++) {
 4170: 	fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4171: 	printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4172: 	fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4173:       }
 4174:       fprintf(ficrespl,"******\n");
 4175:       printf("******\n");
 4176:       fprintf(ficlog,"******\n");
 4177: 	
 4178:       for (age=agebase; age<=agelim; age++){
 4179: 	prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
 4180: 	fprintf(ficrespl,"%.0f ",age );
 4181:         for(j=1;j<=cptcoveff;j++)
 4182:  	  fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4183: 	for(i=1; i<=nlstate;i++)
 4184: 	  fprintf(ficrespl," %.5f", prlim[i][i]);
 4185: 	fprintf(ficrespl,"\n");
 4186:       }
 4187:     }
 4188:   }
 4189:   fclose(ficrespl);
 4190: 
 4191:   /*------------- h Pij x at various ages ------------*/
 4192:   
 4193:   strcpy(filerespij,"pij");  strcat(filerespij,fileres);
 4194:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
 4195:     printf("Problem with Pij resultfile: %s\n", filerespij);goto end;
 4196:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij);goto end;
 4197:   }
 4198:   printf("Computing pij: result on file '%s' \n", filerespij);
 4199:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
 4200:   
 4201:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 4202:   /*if (stepm<=24) stepsize=2;*/
 4203: 
 4204:   agelim=AGESUP;
 4205:   hstepm=stepsize*YEARM; /* Every year of age */
 4206:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
 4207: 
 4208:   /* hstepm=1;   aff par mois*/
 4209: 
 4210:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
 4211:   for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 4212:     for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 4213:       k=k+1;
 4214:       fprintf(ficrespij,"\n#****** ");
 4215:       for(j=1;j<=cptcoveff;j++) 
 4216: 	fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4217:       fprintf(ficrespij,"******\n");
 4218: 	
 4219:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
 4220: 	nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 4221: 	nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 4222: 
 4223: 	/*	  nhstepm=nhstepm*YEARM; aff par mois*/
 4224: 
 4225: 	p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4226: 	oldm=oldms;savm=savms;
 4227: 	hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 4228: 	fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
 4229: 	for(i=1; i<=nlstate;i++)
 4230: 	  for(j=1; j<=nlstate+ndeath;j++)
 4231: 	    fprintf(ficrespij," %1d-%1d",i,j);
 4232: 	fprintf(ficrespij,"\n");
 4233: 	for (h=0; h<=nhstepm; h++){
 4234: 	  fprintf(ficrespij,"%d %3.f %3.f",k,agedeb, agedeb+ h*hstepm/YEARM*stepm );
 4235: 	  for(i=1; i<=nlstate;i++)
 4236: 	    for(j=1; j<=nlstate+ndeath;j++)
 4237: 	      fprintf(ficrespij," %.5f", p3mat[i][j][h]);
 4238: 	  fprintf(ficrespij,"\n");
 4239: 	}
 4240: 	free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4241: 	fprintf(ficrespij,"\n");
 4242:       }
 4243:     }
 4244:   }
 4245: 
 4246:   varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax);
 4247: 
 4248:   fclose(ficrespij);
 4249: 
 4250: 
 4251:   /*---------- Forecasting ------------------*/
 4252:   /*if((stepm == 1) && (strcmp(model,".")==0)){*/
 4253:   if(prevfcast==1){
 4254:     /*    if(stepm ==1){*/
 4255:       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
 4256:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
 4257: /*      }  */
 4258: /*      else{ */
 4259: /*        erreur=108; */
 4260: /*        printf("Warning %d!! You can only forecast the prevalences if the optimization\n  has been performed with stepm = 1 (month) instead of %d or model=. instead of '%s'\n", erreur, stepm, model); */
 4261: /*        fprintf(ficlog,"Warning %d!! You can only forecast the prevalences if the optimization\n  has been performed with stepm = 1 (month) instead of %d or model=. instead of '%s'\n", erreur, stepm, model); */
 4262: /*      } */
 4263:   }
 4264:   
 4265: 
 4266:   /*---------- Health expectancies and variances ------------*/
 4267: 
 4268:   strcpy(filerest,"t");
 4269:   strcat(filerest,fileres);
 4270:   if((ficrest=fopen(filerest,"w"))==NULL) {
 4271:     printf("Problem with total LE resultfile: %s\n", filerest);goto end;
 4272:     fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
 4273:   }
 4274:   printf("Computing Total LEs with variances: file '%s' \n", filerest); 
 4275:   fprintf(ficlog,"Computing Total LEs with variances: file '%s' \n", filerest); 
 4276: 
 4277: 
 4278:   strcpy(filerese,"e");
 4279:   strcat(filerese,fileres);
 4280:   if((ficreseij=fopen(filerese,"w"))==NULL) {
 4281:     printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 4282:     fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 4283:   }
 4284:   printf("Computing Health Expectancies: result on file '%s' \n", filerese);
 4285:   fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
 4286: 
 4287:   strcpy(fileresv,"v");
 4288:   strcat(fileresv,fileres);
 4289:   if((ficresvij=fopen(fileresv,"w"))==NULL) {
 4290:     printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
 4291:     fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
 4292:   }
 4293:   printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
 4294:   fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
 4295: 
 4296:   /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
 4297:   prevalence(agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 4298:   /*  printf("ageminpar=%f, agemax=%f, s[lastpass][imx]=%d, agev[lastpass][imx]=%f, nlstate=%d, imx=%d,  mint[lastpass][imx]=%f, anint[lastpass][imx]=%f,dateprev1=%f, dateprev2=%f, firstpass=%d, lastpass=%d\n",\
 4299: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
 4300:   */
 4301: 
 4302:   if (mobilav!=0) {
 4303:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4304:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 4305:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 4306:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 4307:     }
 4308:   }
 4309: 
 4310:   for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 4311:     for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 4312:       k=k+1; 
 4313:       fprintf(ficrest,"\n#****** ");
 4314:       for(j=1;j<=cptcoveff;j++) 
 4315: 	fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4316:       fprintf(ficrest,"******\n");
 4317: 
 4318:       fprintf(ficreseij,"\n#****** ");
 4319:       for(j=1;j<=cptcoveff;j++) 
 4320: 	fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4321:       fprintf(ficreseij,"******\n");
 4322: 
 4323:       fprintf(ficresvij,"\n#****** ");
 4324:       for(j=1;j<=cptcoveff;j++) 
 4325: 	fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4326:       fprintf(ficresvij,"******\n");
 4327: 
 4328:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 4329:       oldm=oldms;savm=savms;
 4330:       evsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov);  
 4331:  
 4332:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 4333:       oldm=oldms;savm=savms;
 4334:       varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,0, mobilav);
 4335:       if(popbased==1){
 4336: 	varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,popbased,mobilav);
 4337:       }
 4338: 
 4339:  
 4340:       fprintf(ficrest,"#Total LEs with variances: e.. (std) ");
 4341:       for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
 4342:       fprintf(ficrest,"\n");
 4343: 
 4344:       epj=vector(1,nlstate+1);
 4345:       for(age=bage; age <=fage ;age++){
 4346: 	prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
 4347: 	if (popbased==1) {
 4348: 	  if(mobilav ==0){
 4349: 	    for(i=1; i<=nlstate;i++)
 4350: 	      prlim[i][i]=probs[(int)age][i][k];
 4351: 	  }else{ /* mobilav */ 
 4352: 	    for(i=1; i<=nlstate;i++)
 4353: 	      prlim[i][i]=mobaverage[(int)age][i][k];
 4354: 	  }
 4355: 	}
 4356: 	
 4357: 	fprintf(ficrest," %4.0f",age);
 4358: 	for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
 4359: 	  for(i=1, epj[j]=0.;i <=nlstate;i++) {
 4360: 	    epj[j] += prlim[i][i]*eij[i][j][(int)age];
 4361: 	    /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
 4362: 	  }
 4363: 	  epj[nlstate+1] +=epj[j];
 4364: 	}
 4365: 
 4366: 	for(i=1, vepp=0.;i <=nlstate;i++)
 4367: 	  for(j=1;j <=nlstate;j++)
 4368: 	    vepp += vareij[i][j][(int)age];
 4369: 	fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
 4370: 	for(j=1;j <=nlstate;j++){
 4371: 	  fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
 4372: 	}
 4373: 	fprintf(ficrest,"\n");
 4374:       }
 4375:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 4376:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 4377:       free_vector(epj,1,nlstate+1);
 4378:     }
 4379:   }
 4380:   free_vector(weight,1,n);
 4381:   free_imatrix(Tvard,1,15,1,2);
 4382:   free_imatrix(s,1,maxwav+1,1,n);
 4383:   free_matrix(anint,1,maxwav,1,n); 
 4384:   free_matrix(mint,1,maxwav,1,n);
 4385:   free_ivector(cod,1,n);
 4386:   free_ivector(tab,1,NCOVMAX);
 4387:   fclose(ficreseij);
 4388:   fclose(ficresvij);
 4389:   fclose(ficrest);
 4390:   fclose(ficpar);
 4391:   
 4392:   /*------- Variance of stable prevalence------*/   
 4393: 
 4394:   strcpy(fileresvpl,"vpl");
 4395:   strcat(fileresvpl,fileres);
 4396:   if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
 4397:     printf("Problem with variance of stable prevalence  resultfile: %s\n", fileresvpl);
 4398:     exit(0);
 4399:   }
 4400:   printf("Computing Variance-covariance of stable prevalence: file '%s' \n", fileresvpl);
 4401: 
 4402:   for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 4403:     for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 4404:       k=k+1;
 4405:       fprintf(ficresvpl,"\n#****** ");
 4406:       for(j=1;j<=cptcoveff;j++) 
 4407: 	fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4408:       fprintf(ficresvpl,"******\n");
 4409:       
 4410:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
 4411:       oldm=oldms;savm=savms;
 4412:       varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k);
 4413:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
 4414:     }
 4415:   }
 4416: 
 4417:   fclose(ficresvpl);
 4418: 
 4419:   /*---------- End : free ----------------*/
 4420:   free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
 4421:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
 4422:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
 4423:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
 4424:   
 4425:   free_matrix(covar,0,NCOVMAX,1,n);
 4426:   free_matrix(matcov,1,npar,1,npar);
 4427:   /*free_vector(delti,1,npar);*/
 4428:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 4429:   free_matrix(agev,1,maxwav,1,imx);
 4430:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
 4431:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4432:   free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4433: 
 4434:   free_ivector(ncodemax,1,8);
 4435:   free_ivector(Tvar,1,15);
 4436:   free_ivector(Tprod,1,15);
 4437:   free_ivector(Tvaraff,1,15);
 4438:   free_ivector(Tage,1,15);
 4439:   free_ivector(Tcode,1,100);
 4440: 
 4441:   /*  fclose(fichtm);*/
 4442:   /*  fclose(ficgp);*/ /* ALready done */
 4443:   
 4444: 
 4445:   if(erreur >0){
 4446:     printf("End of Imach with error or warning %d\n",erreur);
 4447:     fprintf(ficlog,"End of Imach with error or warning %d\n",erreur);
 4448:   }else{
 4449:    printf("End of Imach\n");
 4450:    fprintf(ficlog,"End of Imach\n");
 4451:   }
 4452:   printf("See log file on %s\n",filelog);
 4453:   fclose(ficlog);
 4454:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
 4455:   
 4456:   /* 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);*/
 4457:   /*printf("Total time was %d uSec.\n", total_usecs);*/
 4458:   /*------ End -----------*/
 4459: 
 4460:   end:
 4461: #ifdef windows
 4462:   /* chdir(pathcd);*/
 4463: #endif 
 4464:  /*system("wgnuplot graph.plt");*/
 4465:  /*system("../gp37mgw/wgnuplot graph.plt");*/
 4466:  /*system("cd ../gp37mgw");*/
 4467:  /* system("..\\gp37mgw\\wgnuplot graph.plt");*/
 4468:   strcpy(plotcmd,GNUPLOTPROGRAM);
 4469:   strcat(plotcmd," ");
 4470:   strcat(plotcmd,optionfilegnuplot);
 4471:   printf("Starting: %s\n",plotcmd);fflush(stdout);
 4472:   system(plotcmd);
 4473: 
 4474:  /*#ifdef windows*/
 4475:   while (z[0] != 'q') {
 4476:     /* chdir(path); */
 4477:     printf("\nType e to edit output files, g to graph again, c to start again, and q for exiting: ");
 4478:     scanf("%s",z);
 4479:     if (z[0] == 'c') system("./imach");
 4480:     else if (z[0] == 'e') system(optionfilehtm);
 4481:     else if (z[0] == 'g') system(plotcmd);
 4482:     else if (z[0] == 'q') exit(0);
 4483:   }
 4484:   /*#endif */
 4485: }
 4486: 
 4487: 

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