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

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

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