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

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

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