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

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

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