File:  [Local Repository] / imach / src / imach.c
Revision 1.116: download - view: text, annotated - select for diffs
Mon Mar 6 10:29:27 2006 UTC (18 years, 3 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
(Module): Variance-covariance wrong links and
varian-covariance of ej. is needed (Saito).

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

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