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

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

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