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

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

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