Annotation of imach096d/src/imach.c, revision 1.79

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

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