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

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

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