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

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

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