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

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

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