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

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

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