File:  [Local Repository] / imach / src / imach.c
Revision 1.107: download - view: text, annotated - select for diffs
Thu Jan 19 16:20:37 2006 UTC (18 years, 4 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
Test existence of gnuplot in imach path

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

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