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

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

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