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

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

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