File:  [Local Repository] / imach / src / imach.c
Revision 1.65: download - view: text, annotated - select for diffs
Wed Dec 11 16:58:19 2002 UTC (21 years, 5 months ago) by lievre
Branches: MAIN
CVS tags: HEAD
Correction of bug related to the covariates

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

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