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

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

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