File:  [Local Repository] / imach / src / imach.c
Revision 1.115: download - view: text, annotated - select for diffs
Mon Feb 27 12:17:45 2006 UTC (18 years, 2 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
(Module): One freematrix added in mlikeli! 0.98c

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

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