File:  [Local Repository] / imach / src / imach.c
Revision 1.88: download - view: text, annotated - select for diffs
Mon Jun 23 17:54:56 2003 UTC (20 years, 11 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
* imach.c (Repository): Create a sub-directory where all the secondary files are. Only imach, htm, gp and r(imach) are on the main directory. Correct time and other things.

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

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