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

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

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