Annotation of imach/src/imach.c, revision 1.102

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

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