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

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

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