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

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

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