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

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

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