File:  [Local Repository] / imach / src / imach.c
Revision 1.101: download - view: text, annotated - select for diffs
Wed Sep 15 10:38:38 2004 UTC (19 years, 9 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
Fix on curr_time

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

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