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

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

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