File:  [Local Repository] / imach / src / imach.c
Revision 1.96: download - view: text, annotated - select for diffs
Tue Jul 15 15:38:55 2003 UTC (20 years, 11 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
* imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
rewritten within the same printf. Workaround: many printfs.

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

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