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

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

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