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

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

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