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

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

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